mirror of
https://github.com/k3s-io/k3s.git
synced 2024-06-07 19:41:36 +00:00
73df2d806b
* Update embedded kube-router Signed-off-by: dereknola <derek.nola@suse.com>
67 lines
2.1 KiB
Go
67 lines
2.1 KiB
Go
// Apache License v2.0 (copyright Cloud Native Labs & Rancher Labs)
|
|
// - modified from https://github.com/cloudnativelabs/kube-router/blob/73b1b03b32c5755b240f6c077bb097abe3888314/pkg/utils/node.go
|
|
|
|
// +build !windows
|
|
|
|
package utils
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"os"
|
|
|
|
apiv1 "k8s.io/api/core/v1"
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
"k8s.io/client-go/kubernetes"
|
|
)
|
|
|
|
// GetNodeObject returns the node API object for the node
|
|
func GetNodeObject(clientset kubernetes.Interface, hostnameOverride string) (*apiv1.Node, error) {
|
|
// assuming kube-router is running as pod, first check env NODE_NAME
|
|
nodeName := os.Getenv("NODE_NAME")
|
|
if nodeName != "" {
|
|
node, err := clientset.CoreV1().Nodes().Get(context.Background(), nodeName, metav1.GetOptions{})
|
|
if err == nil {
|
|
return node, nil
|
|
}
|
|
}
|
|
|
|
// if env NODE_NAME is not set then check if node is register with hostname
|
|
hostName, _ := os.Hostname()
|
|
node, err := clientset.CoreV1().Nodes().Get(context.Background(), hostName, metav1.GetOptions{})
|
|
if err == nil {
|
|
return node, nil
|
|
}
|
|
|
|
// if env NODE_NAME is not set and node is not registered with hostname, then use host name override
|
|
if hostnameOverride != "" {
|
|
node, err = clientset.CoreV1().Nodes().Get(context.Background(), hostnameOverride, metav1.GetOptions{})
|
|
if err == nil {
|
|
return node, nil
|
|
}
|
|
}
|
|
|
|
return nil, fmt.Errorf("failed to identify the node by NODE_NAME, hostname or --hostname-override")
|
|
}
|
|
|
|
// GetNodeIP returns the most valid external facing IP address for a node.
|
|
// Order of preference:
|
|
// 1. NodeInternalIP
|
|
// 2. NodeExternalIP (Only set on cloud providers usually)
|
|
func GetNodeIP(node *apiv1.Node) (net.IP, error) {
|
|
addresses := node.Status.Addresses
|
|
addressMap := make(map[apiv1.NodeAddressType][]apiv1.NodeAddress)
|
|
for i := range addresses {
|
|
addressMap[addresses[i].Type] = append(addressMap[addresses[i].Type], addresses[i])
|
|
}
|
|
if addresses, ok := addressMap[apiv1.NodeInternalIP]; ok {
|
|
return net.ParseIP(addresses[0].Address), nil
|
|
}
|
|
if addresses, ok := addressMap[apiv1.NodeExternalIP]; ok {
|
|
return net.ParseIP(addresses[0].Address), nil
|
|
}
|
|
return nil, errors.New("host IP unknown")
|
|
}
|