client.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package kube
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/coroot/coroot-node-agent/kube/transfer"
  6. "github.com/sirupsen/logrus"
  7. "k8s.io/client-go/kubernetes"
  8. "k8s.io/client-go/rest"
  9. "strings"
  10. )
  11. var CwK8sClient *transfer.CwK8sClient
  12. func GetKubeClient() (*transfer.CwK8sClient, error) {
  13. if CwK8sClient == nil {
  14. return CwK8sClient, fmt.Errorf("K8sClient is nil")
  15. }
  16. return CwK8sClient, nil
  17. }
  18. func NewKubeClient() (*transfer.CwK8sClient, error) {
  19. if CwK8sClient != nil {
  20. return CwK8sClient, nil
  21. }
  22. ctx := context.Background()
  23. config, err := rest.InClusterConfig()
  24. if err != nil {
  25. return nil, err
  26. }
  27. config.TLSClientConfig.Insecure = false
  28. // creates the clientset
  29. clientset, err := kubernetes.NewForConfig(config)
  30. if err != nil {
  31. logrus.WithError(err).Error("[kube] connect init error")
  32. return nil, err
  33. }
  34. cwk8sclient := transfer.NewCwK8sClient(ctx, clientset)
  35. go cwk8sclient.InformerSharedfactory.Start(make(chan struct{}, 0))
  36. CwK8sClient = cwk8sclient
  37. logrus.Info("[kube] connect init success")
  38. return cwk8sclient, nil
  39. }
  40. func GetWorkload(ns, pod string) (string, error) {
  41. client, err := GetKubeClient()
  42. if err != nil {
  43. return "", err
  44. }
  45. podsItems, err := client.InformerSharedfactory.Core().V1().Pods().Lister().Pods(ns).Get(pod)
  46. if err != nil {
  47. return "", err
  48. }
  49. if len(podsItems.ObjectMeta.OwnerReferences) > 0 {
  50. ownerReferences := podsItems.ObjectMeta.OwnerReferences[0]
  51. kind := ownerReferences.Kind
  52. workload := ownerReferences.Name
  53. switch kind {
  54. case "ReplicaSet":
  55. lastDash := strings.LastIndex(workload, "-")
  56. if lastDash != -1 {
  57. workload = workload[:lastDash]
  58. }
  59. }
  60. return workload, nil
  61. }
  62. return "", fmt.Errorf("workload not found")
  63. }