client.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package client
  2. import (
  3. "context"
  4. "github.com/argoproj/argo-workflows/v3/pkg/apiclient"
  5. "github.com/argoproj/argo-workflows/v3/pkg/apiclient/workflow"
  6. "github.com/argoproj/argo-workflows/v3/pkg/apiclient/workflowtemplate"
  7. "github.com/pkg/errors"
  8. log "github.com/sirupsen/logrus"
  9. "k8s.io/client-go/tools/clientcmd"
  10. "os"
  11. "sync"
  12. )
  13. var LogLevel string
  14. var watchWorkflowTokenMap sync.Map
  15. type Client struct {
  16. ctx context.Context
  17. client apiclient.Client
  18. workflowTemplateService workflowtemplate.WorkflowTemplateServiceClient
  19. workflowService workflow.WorkflowServiceClient
  20. workflowWatcherManager *workflowWatcherManager
  21. }
  22. func NewClient(kubeConfigEnv string, opts ...Option) (*Client, error) {
  23. options := new(Options)
  24. for _, opt := range opts {
  25. opt(options)
  26. }
  27. level, err := log.ParseLevel(options.logLevel)
  28. if err != nil {
  29. level = log.ErrorLevel
  30. }
  31. log.SetLevel(level)
  32. err = os.Setenv("KUBECONFIG", kubeConfigEnv)
  33. if err != nil {
  34. return nil, errors.New(err.Error())
  35. }
  36. apiClientCtx, apiClient, err := apiclient.NewClientFromOpts(apiclient.Opts{
  37. ArgoServerOpts: apiclient.ArgoServerOpts{},
  38. ClientConfigSupplier: func() clientcmd.ClientConfig {
  39. return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(clientcmd.NewDefaultClientConfigLoadingRules(), nil)
  40. },
  41. Context: context.Background(),
  42. })
  43. if err != nil {
  44. return nil, errors.New(err.Error())
  45. }
  46. workflowTemplateService, err := apiClient.NewWorkflowTemplateServiceClient()
  47. if err != nil {
  48. return nil, errors.New(err.Error())
  49. }
  50. return &Client{
  51. ctx: apiClientCtx,
  52. client: apiClient,
  53. workflowTemplateService: workflowTemplateService,
  54. workflowService: apiClient.NewWorkflowServiceClient(),
  55. workflowWatcherManager: newWorkflowWatcherManager(),
  56. }, nil
  57. }
  58. func Destroy(c *Client) {
  59. if c == nil {
  60. return
  61. }
  62. c.unregisterAllWorkflowWatchers()
  63. c.ctx.Done()
  64. c.client = nil
  65. c.workflowTemplateService = nil
  66. c.workflowService = nil
  67. }