loader.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package kubeconfig
  2. import (
  3. "context"
  4. "fmt"
  5. v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  6. "k8s.io/client-go/kubernetes"
  7. _ "k8s.io/client-go/plugin/pkg/client/auth"
  8. "k8s.io/client-go/rest"
  9. "k8s.io/client-go/tools/clientcmd"
  10. )
  11. // LoadKubeconfig attempts to load a kubeconfig based on default locations.
  12. // If a path is passed in then only that path is checked and will error
  13. // if not found
  14. func LoadKubeconfig(path string) (*rest.Config, error) {
  15. // Use the default load order: KUBECONFIG env > $HOME/.kube/config > In cluster config
  16. loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
  17. if path != "" {
  18. loadingRules.ExplicitPath = path
  19. }
  20. loader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
  21. config, err := loader.ClientConfig()
  22. if err != nil {
  23. return nil, fmt.Errorf("loading kubeconfig: %w", err)
  24. }
  25. config.UserAgent = "opencost"
  26. // use protobuf for faster serialization instead of default json
  27. // https://kubernetes.io/docs/reference/using-api/api-concepts/#alternate-representations-of-resources
  28. config.AcceptContentTypes = "application/vnd.kubernetes.protobuf,application/json"
  29. config.ContentType = "application/vnd.kubernetes.protobuf"
  30. return config, nil
  31. }
  32. // LoadKubeClient accepts a path to a kubeconfig to load and returns the clientset
  33. func LoadKubeClient(path string) (*kubernetes.Clientset, error) {
  34. config, err := LoadKubeconfig(path)
  35. if err != nil {
  36. return nil, err
  37. }
  38. return kubernetes.NewForConfig(config)
  39. }
  40. func GetClusterUID(client kubernetes.Interface) (string, error) {
  41. ns, err := client.CoreV1().Namespaces().Get(context.Background(), "kube-system", v1.GetOptions{})
  42. if err != nil {
  43. return "", fmt.Errorf("error getting 'kube-system' namespace: %w", err)
  44. }
  45. uid := string(ns.ObjectMeta.UID)
  46. if uid == "" {
  47. return "", fmt.Errorf("uid field in 'kube-system' namespace is empty")
  48. }
  49. return uid, nil
  50. }