From 0b23ab480f1d6307957cea8c76a7d17c060bc662 Mon Sep 17 00:00:00 2001 From: YuMin Kim Date: Tue, 17 Nov 2026 02:05:50 +0900 Subject: [PATCH 1/2] Querier: log requests handled by the internal querier router in single binary mode Signed-off-by: YuMin Kim --- CHANGELOG.md | 1 + pkg/cortex/modules.go | 36 +++++++++++++++++++++++++----------- pkg/cortex/modules_test.go | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f32e39e4efe..c00492261a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ * [ENHANCEMENT] Upgrade promql-engine to latest. #7841 * [ENHANCEMENT] Ruler: Add new limit `-ruler.list-rules-max-rules` on the total number of rules returned by the Prometheus ListRules API. Responses exceeding the limit are truncated on a rule group boundary and return a `groupNextToken` for retrieving the remaining groups. A rule group is never split, so a single group larger than the limit is still returned whole. Defaults to 0, which is unlimited. #7785 * [ENHANCEMENT] Compactor: Add the `cortex_compactor_oldest_level_1_block_offset_seconds` metric, reporting per tenant how long ago the oldest level 1 block still listed in the bucket index was uploaded. Blocks marked for deletion or for no compaction are excluded. The bucket index entry now carries the block's compaction level; an entry written before this reports an unknown level and is skipped. #7959 +* [BUGFIX] Querier: Log requests handled by the internal querier router when the querier runs together with the query-frontend or query-scheduler (including `-target=all`), as a standalone querier does. #7940 * [BUGFIX] Update prometheus alertmanager version to v0.34.1 to apply upstream inhibit rule bug fixes. #7877 * [BUGFIX] Tenant Federation: Fix regex tenant federation not working in single binary mode, and failing with `multiple org IDs present` when a matched tenant ID contains regex metacharacters and also matches other tenants as a regex. #7869 * [BUGFIX] Query Frontend: Fix the data selection time window computed for an instant query sent without a `time` parameter. The default evaluation time was passed to `util.ParseTimeParam` in milliseconds, but that helper formats the default and parses it as seconds, so the value overflowed `UnixNano()` and wrapped to a timestamp decades away from `now`. This made the `data_select_min_time` and `data_select_max_time` query stats wrong, and stopped the `time_window` query attribute of query priority and query rejection from matching such queries correctly. #7880 diff --git a/pkg/cortex/modules.go b/pkg/cortex/modules.go index d787a6b2429..c6d3e0b1f0c 100644 --- a/pkg/cortex/modules.go +++ b/pkg/cortex/modules.go @@ -9,6 +9,7 @@ import ( "net/http" "runtime" "runtime/debug" + "strings" "github.com/go-kit/log/level" "github.com/opentracing-contrib/go-stdlib/nethttp" @@ -27,6 +28,8 @@ import ( "github.com/thanos-io/thanos/pkg/discovery/dns" "github.com/thanos-io/thanos/pkg/querysharding" httpgrpc_server "github.com/weaveworks/common/httpgrpc/server" + "github.com/weaveworks/common/logging" + "github.com/weaveworks/common/middleware" "github.com/weaveworks/common/server" "github.com/cortexproject/cortex/pkg/alertmanager" @@ -359,6 +362,27 @@ func (t *Cortex) initTenantFederation() (serv services.Service, err error) { return nil, nil } +// wrapInternalQuerierRouter adds the middlewares that the querier would otherwise get from the external HTTP server. +func (t *Cortex) wrapInternalQuerierRouter(router http.Handler) http.Handler { + // Add a middleware to extract the trace context and add a header. + router = nethttp.MiddlewareFunc(opentracing.GlobalTracer(), router.ServeHTTP, nethttp.OperationNameFunc(func(r *http.Request) string { + return "internalQuerier" + })) + + // Log requests like the external HTTP server does for a standalone querier. It is wrapped inside the + // auth middleware, so that the log lines carry the tenant ID. + logMiddleware := middleware.NewLogMiddleware(logging.GoKit(util_log.Logger), t.Cfg.Server.LogRequestHeaders, t.Cfg.Server.LogRequestAtInfoLevel, nil, strings.Split(t.Cfg.Server.LogRequestExcludeHeadersList, ",")) + logMiddleware.DisableRequestSuccessLog = t.Cfg.Server.DisableRequestSuccessLog + router = logMiddleware.Wrap(router) + + // If queries are processed using the external HTTP Server, we need wrap the internal querier with + // HTTP router with middleware to parse the tenant ID from the HTTP header and inject it into the + // request context. + router = t.API.AuthMiddleware.Wrap(router) + + return t.API.HTTPHeaderMiddleware.Wrap(router) +} + // initQuerier registers an internal HTTP router with a Prometheus API backed by the // Cortex Queryable. Then it does one of the following: // @@ -442,17 +466,7 @@ func (t *Cortex) initQuerier() (serv services.Service, err error) { t.Cfg.Worker.FrontendAddress = address } - // Add a middleware to extract the trace context and add a header. - internalQuerierRouter = nethttp.MiddlewareFunc(opentracing.GlobalTracer(), internalQuerierRouter.ServeHTTP, nethttp.OperationNameFunc(func(r *http.Request) string { - return "internalQuerier" - })) - - // If queries are processed using the external HTTP Server, we need wrap the internal querier with - // HTTP router with middleware to parse the tenant ID from the HTTP header and inject it into the - // request context. - internalQuerierRouter = t.API.AuthMiddleware.Wrap(internalQuerierRouter) - - internalQuerierRouter = t.API.HTTPHeaderMiddleware.Wrap(internalQuerierRouter) + internalQuerierRouter = t.wrapInternalQuerierRouter(internalQuerierRouter) } // If neither frontend address or scheduler address is configured, no worker is needed. diff --git a/pkg/cortex/modules_test.go b/pkg/cortex/modules_test.go index 697c2ec56cc..3605b2ce828 100644 --- a/pkg/cortex/modules_test.go +++ b/pkg/cortex/modules_test.go @@ -1,8 +1,10 @@ package cortex import ( + "bytes" "context" "maps" + "net/http" "net/http/httptest" "os" "reflect" @@ -10,16 +12,20 @@ import ( "strings" "testing" + "github.com/go-kit/log" "github.com/gorilla/mux" "github.com/prometheus/prometheus/promql/parser" prom_storage "github.com/prometheus/prometheus/storage" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/weaveworks/common/middleware" "github.com/weaveworks/common/server" + "github.com/cortexproject/cortex/pkg/api" "github.com/cortexproject/cortex/pkg/configs" "github.com/cortexproject/cortex/pkg/cortexpb" "github.com/cortexproject/cortex/pkg/util/flagext" + util_log "github.com/cortexproject/cortex/pkg/util/log" ) func changeTargetConfig(c *Config) { @@ -438,3 +444,31 @@ func setAllSecrets(v reflect.Value, sentinel string) { } } } + +func TestWrapInternalQuerierRouter_LogsRequests(t *testing.T) { + buf := &bytes.Buffer{} + origLogger := util_log.Logger + util_log.Logger = log.NewLogfmtLogger(log.NewSyncWriter(buf)) + t.Cleanup(func() { util_log.Logger = origLogger }) + + cfg := newDefaultConfig() + cfg.Server.LogRequestAtInfoLevel = true + c := &Cortex{ + Cfg: *cfg, + API: &api.API{ + AuthMiddleware: middleware.AuthenticateUser, + HTTPHeaderMiddleware: &api.HTTPHeaderMiddleware{}, + }, + } + + handler := c.wrapInternalQuerierRouter(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/query?query=up", nil) + req.Header.Set("X-Scope-OrgID", "tenant-1") + handler.ServeHTTP(httptest.NewRecorder(), req) + + assert.Contains(t, buf.String(), "GET /api/v1/query?query=up") + assert.Contains(t, buf.String(), "tenant-1") +} From 150252497018389731e143fed082d6062622590d Mon Sep 17 00:00:00 2001 From: YuMin Kim Date: Thu, 19 Nov 2026 11:33:54 +0900 Subject: [PATCH 2/2] Querier: run tracing before the request log of the internal querier router The log middleware reads the trace ID from the request context, so it has to be wrapped inside the tracing middleware, as in the external HTTP server. Signed-off-by: YuMin Kim --- pkg/cortex/modules.go | 13 +++++++------ pkg/cortex/modules_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/pkg/cortex/modules.go b/pkg/cortex/modules.go index c6d3e0b1f0c..bf78e1e5d60 100644 --- a/pkg/cortex/modules.go +++ b/pkg/cortex/modules.go @@ -364,17 +364,18 @@ func (t *Cortex) initTenantFederation() (serv services.Service, err error) { // wrapInternalQuerierRouter adds the middlewares that the querier would otherwise get from the external HTTP server. func (t *Cortex) wrapInternalQuerierRouter(router http.Handler) http.Handler { - // Add a middleware to extract the trace context and add a header. - router = nethttp.MiddlewareFunc(opentracing.GlobalTracer(), router.ServeHTTP, nethttp.OperationNameFunc(func(r *http.Request) string { - return "internalQuerier" - })) - // Log requests like the external HTTP server does for a standalone querier. It is wrapped inside the - // auth middleware, so that the log lines carry the tenant ID. + // auth middleware, so that the log lines carry the tenant ID, and inside the tracing middleware, so + // that they carry the trace ID. logMiddleware := middleware.NewLogMiddleware(logging.GoKit(util_log.Logger), t.Cfg.Server.LogRequestHeaders, t.Cfg.Server.LogRequestAtInfoLevel, nil, strings.Split(t.Cfg.Server.LogRequestExcludeHeadersList, ",")) logMiddleware.DisableRequestSuccessLog = t.Cfg.Server.DisableRequestSuccessLog router = logMiddleware.Wrap(router) + // Add a middleware to extract the trace context and add a header. + router = nethttp.MiddlewareFunc(opentracing.GlobalTracer(), router.ServeHTTP, nethttp.OperationNameFunc(func(r *http.Request) string { + return "internalQuerier" + })) + // If queries are processed using the external HTTP Server, we need wrap the internal querier with // HTTP router with middleware to parse the tenant ID from the HTTP header and inject it into the // request context. diff --git a/pkg/cortex/modules_test.go b/pkg/cortex/modules_test.go index 3605b2ce828..638e801b74e 100644 --- a/pkg/cortex/modules_test.go +++ b/pkg/cortex/modules_test.go @@ -14,10 +14,12 @@ import ( "github.com/go-kit/log" "github.com/gorilla/mux" + "github.com/opentracing/opentracing-go" "github.com/prometheus/prometheus/promql/parser" prom_storage "github.com/prometheus/prometheus/storage" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/uber/jaeger-client-go" "github.com/weaveworks/common/middleware" "github.com/weaveworks/common/server" @@ -472,3 +474,38 @@ func TestWrapInternalQuerierRouter_LogsRequests(t *testing.T) { assert.Contains(t, buf.String(), "GET /api/v1/query?query=up") assert.Contains(t, buf.String(), "tenant-1") } + +func TestWrapInternalQuerierRouter_LogCarriesTraceID(t *testing.T) { + buf := &bytes.Buffer{} + origLogger := util_log.Logger + util_log.Logger = log.NewLogfmtLogger(log.NewSyncWriter(buf)) + t.Cleanup(func() { util_log.Logger = origLogger }) + + tracer, closer := jaeger.NewTracer("test", jaeger.NewConstSampler(true), jaeger.NewNullReporter()) + t.Cleanup(func() { _ = closer.Close() }) + origTracer := opentracing.GlobalTracer() + opentracing.SetGlobalTracer(tracer) + t.Cleanup(func() { opentracing.SetGlobalTracer(origTracer) }) + + cfg := newDefaultConfig() + cfg.Server.LogRequestAtInfoLevel = true + c := &Cortex{ + Cfg: *cfg, + API: &api.API{ + AuthMiddleware: middleware.AuthenticateUser, + HTTPHeaderMiddleware: &api.HTTPHeaderMiddleware{}, + }, + } + + // The request has no incoming span, so a trace ID in the log line proves that + // the tracing middleware runs before the log middleware. + handler := c.wrapInternalQuerierRouter(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/query?query=up", nil) + req.Header.Set("X-Scope-OrgID", "tenant-1") + handler.ServeHTTP(httptest.NewRecorder(), req) + + assert.Contains(t, buf.String(), "traceID=") +}