diff --git a/cmd/cnivpctl/common.go b/cmd/cnivpctl/common.go index a0b6666..7ad682f 100644 --- a/cmd/cnivpctl/common.go +++ b/cmd/cnivpctl/common.go @@ -17,7 +17,6 @@ import ( "context" "fmt" "os" - "path" "strconv" "sync" "time" @@ -34,17 +33,22 @@ import ( "github.com/ucloud/uk8s-cni-vpc/rpc" ) +var preferredConfigPaths = []string{ + "$HOME/.kube/config", + "/etc/kubernetes/cnivpc.kubeconfig", + "/etc/kubernetes/kubelet.kubeconfig", +} + func kubeConfig() (*rest.Config, error) { configPath := os.Getenv("KUBECONFIG") if configPath == "" { - homeDir, err := os.UserHomeDir() - if err != nil { - return nil, fmt.Errorf("Get home dir error: %v", err) - } - configPath = path.Join(homeDir, ".kube", "config") - _, err = os.Stat(configPath) - if err != nil { - configPath = "/etc/kubernetes/kubelet.kubeconfig" + for _, path := range preferredConfigPaths { + path = os.ExpandEnv(path) + _, err := os.Stat(path) + if err == nil { + configPath = path + break + } } } diff --git a/pkg/ipamd/svc.go b/pkg/ipamd/svc.go index 1b81d0c..a4ad967 100644 --- a/pkg/ipamd/svc.go +++ b/pkg/ipamd/svc.go @@ -78,10 +78,15 @@ type ipamServer struct { } func Start() error { - kubeClient, err := kubeclient.GetNodeClient() + kubeConfig, err := kubeclient.GetConfig() if err != nil { return err } + kubeClient, err := kubernetes.NewForConfig(kubeConfig) + if err != nil { + return err + } + crdClient, err := kubeclient.GetCRD() if err != nil { return err diff --git a/pkg/kubeclient/client.go b/pkg/kubeclient/client.go index ced46d4..a53519f 100644 --- a/pkg/kubeclient/client.go +++ b/pkg/kubeclient/client.go @@ -14,7 +14,9 @@ package kubeclient import ( + "errors" "fmt" + "os" "sync" "k8s.io/client-go/kubernetes" @@ -81,12 +83,27 @@ func GetCRD() (*crdclientset.Clientset, error) { return crd, err } -const nodeKubeConfigPath = "/etc/kubernetes/kubelet.kubeconfig" +var nodeKubeConfigPaths = []string{ + "/etc/kubernetes/cnivpc.kubeconfig", + "/etc/kubernetes/kubelet.kubeconfig", +} func GetNodeClient() (*kubernetes.Clientset, error) { - cfg, err := clientcmd.BuildConfigFromFlags("", nodeKubeConfigPath) - if err != nil { - return nil, fmt.Errorf("failed to read kube config: %v", err) + for _, path := range nodeKubeConfigPaths { + _, err := os.Stat(path) + if os.IsNotExist(err) { + continue + } + if err != nil { + return nil, err + } + + cfg, err := clientcmd.BuildConfigFromFlags("", path) + if err != nil { + return nil, fmt.Errorf("failed to read kube config: %v", err) + } + return kubernetes.NewForConfig(cfg) } - return kubernetes.NewForConfig(cfg) + + return nil, errors.New("no available kubeconfig in node") }