| 55 | } |
| 56 | |
| 57 | func NewAgentClient(ctx context.Context, opts AgentClientOpts) (*AgentClient, error) { |
| 58 | if opts.Endpoint == "" { |
| 59 | opts.Endpoint = "https://agent.buildkite.com/v3" |
| 60 | } |
| 61 | |
| 62 | if opts.ClusterID == "" { |
| 63 | opts.ClusterID = "unclustered" |
| 64 | } |
| 65 | |
| 66 | if opts.HTTPTimeout == 0 { |
| 67 | opts.HTTPTimeout = DefaultHTTPTimeout |
| 68 | } |
| 69 | |
| 70 | endpointURL, err := url.Parse(opts.Endpoint) |
| 71 | if err != nil { |
| 72 | return nil, err |
| 73 | } |
| 74 | |
| 75 | client := &AgentClient{ |
| 76 | endpoint: endpointURL, |
| 77 | clusterID: opts.ClusterID, |
| 78 | queue: opts.Queue, |
| 79 | logger: opts.Logger, |
| 80 | } |
| 81 | |
| 82 | clientOpts := []stacksapi.ClientOpt{ |
| 83 | stacksapi.WithLogger(opts.Logger.With("component", "stacksapi")), |
| 84 | stacksapi.WithBaseURL(endpointURL), |
| 85 | stacksapi.WithHTTPClient(&http.Client{ |
| 86 | Timeout: opts.HTTPTimeout, |
| 87 | }), |
| 88 | stacksapi.PrependToUserAgent("agent-stack-k8s/" + version.Version()), |
| 89 | } |
| 90 | if opts.LogHTTPPayloads { |
| 91 | clientOpts = append(clientOpts, stacksapi.LogHTTPPayloads()) |
| 92 | } |
| 93 | |
| 94 | client.stacksAPIClient, err = stacksapi.NewClient(opts.Token, clientOpts...) |
| 95 | if err != nil { |
| 96 | return nil, fmt.Errorf("couldn't create Buildkite Stacks API client: %w", err) |
| 97 | } |
| 98 | |
| 99 | stackKey := opts.StackID |
| 100 | if stackKey == "" { |
| 101 | stackKey = "agent-stack-k8s" |
| 102 | } |
| 103 | |
| 104 | client.notificationBatcher = newNotificationBatcher(stackKey, client.stacksAPIClient, opts.Logger) |
| 105 | stack, _, err := client.stacksAPIClient.RegisterStack(ctx, stacksapi.RegisterStackRequest{ |
| 106 | Type: stacksapi.StackTypeKubernetes, |
| 107 | QueueKey: opts.Queue, |
| 108 | Key: stackKey, |
| 109 | Metadata: map[string]string{}, |
| 110 | }) |
| 111 | if err != nil { |
| 112 | return nil, fmt.Errorf("registering stack with Buildkite Stacks API: %w", err) |
| 113 | } |
| 114 | |