Skip to content

Commit

Permalink
feat(kubeclient): update default kubeconfig path to fit uk8s 1.28 (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
fioncat authored Dec 18, 2024
1 parent a407d31 commit 41c5b94
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 15 deletions.
22 changes: 13 additions & 9 deletions cmd/cnivpctl/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
"context"
"fmt"
"os"
"path"
"strconv"
"sync"
"time"
Expand All @@ -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
}
}
}

Expand Down
7 changes: 6 additions & 1 deletion pkg/ipamd/svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 22 additions & 5 deletions pkg/kubeclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
package kubeclient

import (
"errors"
"fmt"
"os"
"sync"

"k8s.io/client-go/kubernetes"
Expand Down Expand Up @@ -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")
}

0 comments on commit 41c5b94

Please sign in to comment.