func()

in receiver/elasticapmreceiver/agentcfg.go [46:111]


func (r *elasticAPMReceiver) newElasticAPMConfigsHandler(ctx context.Context, host component.Host) http.HandlerFunc {
	mapBodyError := func(err string) map[string]string {
		return map[string]string{"error": err}
	}

	// write a json response and log any encoding error
	encodeJsonLogError := func(w http.ResponseWriter, data any) {
		w.Header().Set(ContentType, "application/json")
		err := json.NewEncoder(w).Encode(data)
		if err != nil {
			r.settings.Logger.Error(fmt.Sprintf("error encoding json response: %s", err.Error()))
		}
	}

	// servers where the Kibana/ES connection is not enabled (server responds with 403)
	// https://github.com/elastic/apm/blob/main/specs/agents/configuration.md#dealing-with-errors
	if r.fetcherFactory == nil {
		r.settings.Logger.Warn("no agent configuration fetcher available")

		return func(w http.ResponseWriter, req *http.Request) {
			w.WriteHeader(http.StatusForbidden)
			encodeJsonLogError(w, mapBodyError("remote configuration fetcher not enabled"))
		}
	}

	fetcher, err := r.fetcherFactory(ctx, host)
	if err != nil {
		r.settings.Logger.Error(fmt.Sprintf("could not start agent configuration fetcher: %s", err.Error()))

		// servers where the Kibana/ES connection is enabled, but unavailable (server responds with 503)
		return func(w http.ResponseWriter, req *http.Request) {
			w.WriteHeader(http.StatusServiceUnavailable)
			encodeJsonLogError(w, mapBodyError(err.Error()))
		}
	}

	return func(w http.ResponseWriter, req *http.Request) {
		query, queryErr := buildQuery(req)
		if queryErr != nil {
			w.WriteHeader(http.StatusBadRequest)
			encodeJsonLogError(w, mapBodyError(queryErr.Error()))
			return
		}

		result, err := fetcher.Fetch(req.Context(), query)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			encodeJsonLogError(w, mapBodyError(err.Error()))
			return
		}

		// configuration successfully fetched
		w.Header().Set(CacheControl, fmt.Sprintf("max-age=%v, must-revalidate", r.cfg.AgentConfig.CacheDuration.Seconds()))
		w.Header().Set(Etag, fmt.Sprintf("%q", result.Source.Etag))
		w.Header().Set(AccessControlExposeHeaders, Etag)

		if result.Source.Etag == query.Etag {
			// c.Result.SetDefault(request.IDResponseValidNotModified)
			w.WriteHeader(http.StatusNotModified)
		} else {
			// c.Result.SetWithBody(request.IDResponseValidOK, result.Source.Settings)
			w.WriteHeader(http.StatusOK)
			encodeJsonLogError(w, result.Source.Settings)
		}
	}
}