| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package k8s_state |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | |
| 10 | "k8s.io/client-go/kubernetes" |
| 11 | "k8s.io/client-go/rest" |
| 12 | "k8s.io/client-go/tools/clientcmd" |
| 13 | |
| 14 | _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" |
| 15 | |
| 16 | "github.com/mattn/go-isatty" |
| 17 | ) |
| 18 | |
| 19 | const ( |
| 20 | envKubeServiceHost = "KUBERNETES_SERVICE_HOST" |
| 21 | envKubeServicePort = "KUBERNETES_SERVICE_PORT" |
| 22 | ) |
| 23 | |
| 24 | func newKubeClient() (kubernetes.Interface, error) { |
| 25 | if os.Getenv(envKubeServiceHost) != "" && os.Getenv(envKubeServicePort) != "" { |
| 26 | return newKubeClientInCluster() |
| 27 | } |
| 28 | if isatty.IsTerminal(os.Stdout.Fd()) { |
| 29 | return newKubeClientOutOfCluster() |
| 30 | } |
| 31 | return nil, errors.New("can not create Kubernetes client: not inside a cluster") |
| 32 | } |
| 33 | |
| 34 | func newKubeClientInCluster() (*kubernetes.Clientset, error) { |
| 35 | config, err := rest.InClusterConfig() |
| 36 | if err != nil { |
| 37 | return nil, err |
| 38 | } |
| 39 | config.UserAgent = "Netdata/kube-state" |
| 40 | return kubernetes.NewForConfig(config) |
| 41 | } |
| 42 | |
| 43 | func newKubeClientOutOfCluster() (*kubernetes.Clientset, error) { |
| 44 | home := homeDir() |
| 45 | if home == "" { |
| 46 | return nil, errors.New("couldn't find home directory") |
| 47 | } |
| 48 | |
| 49 | configPath := filepath.Join(home, ".kube", "config") |
| 50 | config, err := clientcmd.BuildConfigFromFlags("", configPath) |
| 51 | if err != nil { |
| 52 | return nil, err |
| 53 | } |
| 54 | |
| 55 | config.UserAgent = "Netdata/kube-state" |
| 56 | return kubernetes.NewForConfig(config) |
| 57 | } |
| 58 | |
| 59 | func homeDir() string { |
| 60 | if h := os.Getenv("HOME"); h != "" { |
| 61 | return h |
| 62 | } |
| 63 | return os.Getenv("USERPROFILE") // windows |
| 64 | } |