client.go 1.8 KB

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