Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 26 additions & 11 deletions pkg/cortex/modules.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"runtime"
"runtime/debug"
"strings"

"github.com/go-kit/log/level"
"github.com/opentracing-contrib/go-stdlib/nethttp"
Expand All @@ -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"
Expand Down Expand Up @@ -359,6 +362,28 @@ 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 {
// 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, 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can tracing run before the logger? Otherwise this log can miss the query's trace ID.


// 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.
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:
//
Expand Down Expand Up @@ -442,17 +467,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.
Expand Down
71 changes: 71 additions & 0 deletions pkg/cortex/modules_test.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,33 @@
package cortex

import (
"bytes"
"context"
"maps"
"net/http"
"net/http/httptest"
"os"
"reflect"
"regexp"
"strings"
"testing"

"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"

"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) {
Expand Down Expand Up @@ -438,3 +446,66 @@ 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")
}

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=")
}