| 34 | const agentTokenKey = "BUILDKITE_AGENT_TOKEN" |
| 35 | |
| 36 | func Run(ctx context.Context, logger *slog.Logger, k8sClient kubernetes.Interface, cfg *config.Config) { |
| 37 | httpMuxes := make(map[string]*http.ServeMux) |
| 38 | |
| 39 | if cfg.ProfilerAddress != "" { |
| 40 | logger.Info("profiler listening for requests") |
| 41 | // Specifically set the mux to DefaultServeMux, because the pprof |
| 42 | // handlers are registered there. |
| 43 | httpMuxes[cfg.ProfilerAddress] = http.DefaultServeMux |
| 44 | } |
| 45 | if cfg.PrometheusPort > 0 { |
| 46 | logger.Info("prometheus metrics handler listening for requests") |
| 47 | addr := ":" + strconv.Itoa(int(cfg.PrometheusPort)) |
| 48 | // If PrometheusAddress == ProfilerAddress, the mux will already be set |
| 49 | // to DefaultServeMux. |
| 50 | // If PrometheusAddress != ProfilerAddress, we don't want to |
| 51 | // expose pprof handlers on this mux, so make a new mux. |
| 52 | mux := httpMuxes[addr] |
| 53 | if mux == nil { |
| 54 | mux = http.NewServeMux() |
| 55 | } |
| 56 | mux.Handle("GET /metrics", promhttp.Handler()) |
| 57 | httpMuxes[addr] = mux |
| 58 | } |
| 59 | |
| 60 | for addr, mux := range httpMuxes { |
| 61 | go func() { |
| 62 | svr := &http.Server{ |
| 63 | Addr: addr, |
| 64 | ReadHeaderTimeout: 2 * time.Second, |
| 65 | Handler: mux, |
| 66 | } |
| 67 | logger.Error("http server exited", "error", svr.ListenAndServe()) |
| 68 | }() |
| 69 | } |
| 70 | |
| 71 | // Agent token required to query for jobs. |
| 72 | agentToken, err := fetchAgentToken(ctx, logger, k8sClient, cfg.Namespace, cfg.AgentTokenSecret) |
| 73 | if err != nil { |
| 74 | logger.Error("Couldn't get agent token from secret", "error", err) |
| 75 | return |
| 76 | } |
| 77 | |
| 78 | agentEndpoint := "" |
| 79 | if cfg.AgentConfig != nil && cfg.AgentConfig.Endpoint != nil { |
| 80 | agentEndpoint = *cfg.AgentConfig.Endpoint |
| 81 | } |
| 82 | |
| 83 | agentTags, tagErrs := agenttags.TagMapFromTags(cfg.Tags) |
| 84 | if err := errors.Join(tagErrs...); err != nil { |
| 85 | logger.Error("Couldn't process the configured agent tags", "error", err) |
| 86 | return |
| 87 | } |
| 88 | |
| 89 | queue := cmp.Or(cfg.Queue, agentTags["queue"]) |
| 90 | if queue == "" { |
| 91 | logger.Info("Listening to the default queue for the given cluster. To listen to a specific queue, set the `queue` configuration option, or set the `queue` tag in the `tags` configuration option.") |
| 92 | queue = stacksapi.DefaultQueue |
| 93 | } |