github.com/caos/orbos@v1.5.14-0.20221103111702-e6cd0cea7ad4/internal/utils/clientgo/clientgo.go (about) 1 package clientgo 2 3 import ( 4 "errors" 5 "fmt" 6 "os" 7 "path/filepath" 8 9 "github.com/caos/orbos/mntr" 10 "k8s.io/client-go/kubernetes" 11 "k8s.io/client-go/rest" 12 "k8s.io/client-go/tools/clientcmd" 13 ) 14 15 func GetClusterConfig(monitor mntr.Monitor, path string) (*rest.Config, error) { 16 17 monitor.Debug("trying to use in-cluster kube client") 18 if cfg, err := getInClusterConfig(); err == nil { 19 monitor.Debug("using in-cluster kube client") 20 return cfg, nil 21 } 22 23 if path != "" { 24 if cfg, err := getOutClusterConfigPath(path); err == nil { 25 return cfg, nil 26 } 27 monitor.Info(fmt.Sprintf("no kubeconfig found at path %s", path)) 28 } 29 30 if cfg, err := getOutClusterConfig(); err == nil { 31 return cfg, nil 32 } 33 34 monitor.Info(fmt.Sprintf("no kubeconfig found at path %s", "$HOME/.kube/config")) 35 36 err := errors.New("no kubeconfig found") 37 monitor.Error(err) 38 return nil, err 39 } 40 func getOutClusterConfigPath(path string) (*rest.Config, error) { 41 // use the current context in kubeconfig 42 config, err := clientcmd.BuildConfigFromFlags("", path) 43 return config, nonNilErrorf("creating out-cluster config failed: %w", err) 44 } 45 46 func getOutClusterConfig() (*rest.Config, error) { 47 kubeconfig := filepath.Join(homeDir(), ".kube", "config") 48 49 // use the current context in kubeconfig 50 config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) 51 return config, nonNilErrorf("creating out-cluster config failed: %w", err) 52 } 53 54 func homeDir() string { 55 if h := os.Getenv("HOME"); h != "" { 56 return h 57 } 58 return os.Getenv("USERPROFILE") // windows 59 } 60 61 func getInClusterConfig() (*rest.Config, error) { 62 // creates the in-cluster config 63 config, err := rest.InClusterConfig() 64 return config, nonNilErrorf("creating in-cluster config failed: %w", err) 65 } 66 67 func getClientSet(config *rest.Config) (*kubernetes.Clientset, error) { 68 // creates the clientset 69 clientset, err := kubernetes.NewForConfig(config) 70 return clientset, nonNilErrorf("creating clientset failed: %w", err) 71 } 72 73 func nonNilErrorf(format string, err error, val ...interface{}) error { 74 if err == nil { 75 return nil 76 } 77 78 return fmt.Errorf(format, append([]interface{}{err}, val...)) 79 }