-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathhandler.go
More file actions
348 lines (298 loc) · 11 KB
/
handler.go
File metadata and controls
348 lines (298 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright (c) The Cortex Authors.
// Licensed under the Apache License 2.0.
package transport
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"maps"
"net/http"
"net/url"
"strconv"
"strings"
"syscall"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/weaveworks/common/httpgrpc"
"github.com/weaveworks/common/httpgrpc/server"
querier_stats "github.com/thanos-io/thanos/internal/cortex/querier/stats"
"github.com/thanos-io/thanos/internal/cortex/tenant"
"github.com/thanos-io/thanos/internal/cortex/util"
util_log "github.com/thanos-io/thanos/internal/cortex/util/log"
)
const (
// StatusClientClosedRequest is the status code for when a client request cancellation of an http request
StatusClientClosedRequest = 499
ServiceTimingHeaderName = "Server-Timing"
)
var (
errCanceled = httpgrpc.Errorf(StatusClientClosedRequest, "%s", context.Canceled.Error())
errDeadlineExceeded = httpgrpc.Errorf(http.StatusGatewayTimeout, "%s", context.DeadlineExceeded.Error())
errRequestEntityTooLarge = httpgrpc.Errorf(http.StatusRequestEntityTooLarge, "http: request body too large")
)
// Config for a Handler.
type HandlerConfig struct {
LogQueriesLongerThan time.Duration `yaml:"log_queries_longer_than"`
MaxBodySize int64 `yaml:"max_body_size"`
QueryStatsEnabled bool `yaml:"query_stats_enabled"`
SlowQueryLogsUserHeader string `yaml:"slow_query_logs_user_header"`
}
// Handler accepts queries and forwards them to RoundTripper. It can log slow queries,
// but all other logic is inside the RoundTripper.
type Handler struct {
cfg HandlerConfig
log log.Logger
roundTripper http.RoundTripper
// Metrics.
querySeconds *prometheus.CounterVec
querySeries *prometheus.CounterVec
queryBytes *prometheus.CounterVec
activeUsers *util.ActiveUsersCleanupService
}
// NewHandler creates a new frontend handler.
func NewHandler(cfg HandlerConfig, roundTripper http.RoundTripper, log log.Logger, reg prometheus.Registerer) http.Handler {
h := &Handler{
cfg: cfg,
log: log,
roundTripper: roundTripper,
}
if cfg.QueryStatsEnabled {
h.querySeconds = promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_query_seconds_total",
Help: "Total amount of wall clock time spend processing queries.",
}, []string{"user"})
h.querySeries = promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_query_fetched_series_total",
Help: "Number of series fetched to execute a query.",
}, []string{"user"})
h.queryBytes = promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "cortex_query_fetched_chunks_bytes_total",
Help: "Size of all chunks fetched to execute a query in bytes.",
}, []string{"user"})
h.activeUsers = util.NewActiveUsersCleanupWithDefaultValues(func(user string) {
h.querySeconds.DeleteLabelValues(user)
h.querySeries.DeleteLabelValues(user)
h.queryBytes.DeleteLabelValues(user)
})
// If cleaner stops or fail, we will simply not clean the metrics for inactive users.
_ = h.activeUsers.StartAsync(context.Background())
}
return h
}
func (f *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var (
stats *querier_stats.Stats
resp *http.Response
)
// Initialise the stats in the context and make sure it's propagated
// down the request chain.
if f.cfg.QueryStatsEnabled {
var ctx context.Context
stats, ctx = querier_stats.ContextWithEmptyStats(r.Context())
r = r.WithContext(ctx)
}
defer func() {
_ = r.Body.Close()
}()
// Buffer the body for later use to track slow queries.
var buf bytes.Buffer
r.Body = http.MaxBytesReader(w, r.Body, f.cfg.MaxBodySize)
r.Body = io.NopCloser(io.TeeReader(r.Body, &buf))
startTime := time.Now()
// Ensure we log slow queries and query statistics regardless of how the request completes.
defer func() {
f.reportQueryStatsAndSlowQueries(r, w.Header(), buf, startTime, stats)
}()
var err error
resp, err = f.roundTripper.RoundTrip(r)
if err != nil {
writeError(w, err)
return
}
hs := w.Header()
maps.Copy(hs, resp.Header)
if f.cfg.QueryStatsEnabled {
writeServiceTimingHeader(time.Since(startTime), hs, stats)
}
w.WriteHeader(resp.StatusCode)
// log copy response body error so that we will know even though success response code returned
bytesCopied, err := io.Copy(w, resp.Body)
if err != nil && !errors.Is(err, syscall.EPIPE) {
level.Error(util_log.WithContext(r.Context(), f.log)).Log("msg", "write response body error", "bytesCopied", bytesCopied, "err", err)
}
}
// reportQueryStatsAndSlowQueries handles logging of slow queries and query statistics.
func (f *Handler) reportQueryStatsAndSlowQueries(r *http.Request, responseHeaders http.Header, buf bytes.Buffer, startTime time.Time, stats *querier_stats.Stats) {
queryResponseTime := time.Since(startTime)
shouldReportSlowQuery := f.cfg.LogQueriesLongerThan != 0 &&
queryResponseTime > f.cfg.LogQueriesLongerThan &&
isQueryEndpoint(r.URL.Path)
if shouldReportSlowQuery || f.cfg.QueryStatsEnabled {
queryString := f.parseRequestQueryString(r, buf)
if shouldReportSlowQuery {
f.reportSlowQuery(r, responseHeaders, queryString, queryResponseTime, stats)
}
if f.cfg.QueryStatsEnabled {
f.reportQueryStats(r, queryString, queryResponseTime, stats)
}
}
}
// isQueryEndpoint returns true if the path is any of the Prometheus HTTP API,
// query-related endpoints.
// Example: /api/v1/query, /api/v1/query_range, /api/v1/series, /api/v1/label, /api/v1/labels
func isQueryEndpoint(path string) bool {
return strings.Contains(path, "/api/v1")
}
// reportSlowQuery reports slow queries.
func (f *Handler) reportSlowQuery(
r *http.Request,
responseHeaders http.Header,
queryString url.Values,
queryResponseTime time.Duration,
stats *querier_stats.Stats,
) {
// NOTE(GiedriusS): see https://github.com/grafana/grafana/pull/60301 for more info.
grafanaDashboardUID := "-"
if dashboardUID := r.Header.Get("X-Dashboard-Uid"); dashboardUID != "" {
grafanaDashboardUID = dashboardUID
}
grafanaPanelID := "-"
if panelID := r.Header.Get("X-Panel-Id"); panelID != "" {
grafanaPanelID = panelID
}
thanosTraceID := "-"
if traceID := responseHeaders.Get("X-Thanos-Trace-Id"); traceID != "" {
thanosTraceID = traceID
}
var remoteUser string
// Prefer reading remote user from header. Fall back to the value of basic authentication.
if f.cfg.SlowQueryLogsUserHeader != "" {
remoteUser = r.Header.Get(f.cfg.SlowQueryLogsUserHeader)
} else {
remoteUser, _, _ = r.BasicAuth()
}
logMessage := append([]any{
"msg", "slow query detected",
"method", r.Method,
"host", r.Host,
"path", r.URL.Path,
"remote_user", remoteUser,
"remote_addr", r.RemoteAddr,
"time_taken", queryResponseTime.String(),
"grafana_dashboard_uid", grafanaDashboardUID,
"grafana_panel_id", grafanaPanelID,
"trace_id", thanosTraceID,
}, formatQueryString(queryString)...)
logMessage = addQueryRangeToLogMessage(logMessage, queryString)
logMessage = f.addStatsToLogMessage(logMessage, stats)
level.Info(util_log.WithContext(r.Context(), f.log)).Log(logMessage...)
}
func (f *Handler) reportQueryStats(r *http.Request, queryString url.Values, queryResponseTime time.Duration, stats *querier_stats.Stats) {
tenantIDs, err := tenant.TenantIDs(r.Context())
if err != nil {
return
}
userID := tenant.JoinTenantIDs(tenantIDs)
wallTime := stats.LoadWallTime()
numSeries := stats.LoadFetchedSeries()
numBytes := stats.LoadFetchedChunkBytes()
remoteUser, _, _ := r.BasicAuth()
// Track stats.
f.querySeconds.WithLabelValues(userID).Add(wallTime.Seconds())
f.querySeries.WithLabelValues(userID).Add(float64(numSeries))
f.queryBytes.WithLabelValues(userID).Add(float64(numBytes))
f.activeUsers.UpdateUserTimestamp(userID, time.Now())
// Log stats.
logMessage := append([]any{
"msg", "query stats",
"component", "query-frontend",
"method", r.Method,
"path", r.URL.Path,
"remote_user", remoteUser,
"remote_addr", r.RemoteAddr,
"response_time", queryResponseTime,
"query_wall_time_seconds", wallTime.Seconds(),
"fetched_series_count", numSeries,
"fetched_chunks_bytes", numBytes,
}, formatQueryString(queryString)...)
logMessage = f.addStatsToLogMessage(logMessage, stats)
logMessage = addQueryRangeToLogMessage(logMessage, queryString)
level.Info(util_log.WithContext(r.Context(), f.log)).Log(logMessage...)
}
func (f *Handler) parseRequestQueryString(r *http.Request, bodyBuf bytes.Buffer) url.Values {
// Use previously buffered body.
r.Body = io.NopCloser(&bodyBuf)
// Ensure the form has been parsed so all the parameters are present
err := r.ParseForm()
if err != nil {
level.Warn(util_log.WithContext(r.Context(), f.log)).Log("msg", "unable to parse request form", "err", err)
return nil
}
return r.Form
}
func formatQueryString(queryString url.Values) (fields []any) {
for k, v := range queryString {
fields = append(fields, fmt.Sprintf("param_%s", k), strings.Join(v, ","))
}
return fields
}
func (f *Handler) addStatsToLogMessage(message []any, stats *querier_stats.Stats) []any {
if stats != nil {
message = append(message, "peak_samples", stats.LoadPeakSamples())
message = append(message, "total_samples_loaded", stats.LoadTotalSamples())
}
return message
}
func addQueryRangeToLogMessage(logMessage []any, queryString url.Values) []any {
queryRange := extractQueryRange(queryString)
if queryRange != time.Duration(0) {
logMessage = append(logMessage, "query_range_hours", int(queryRange.Hours()))
logMessage = append(logMessage, "query_range_human", queryRange.String())
}
return logMessage
}
// extractQueryRange extracts query range from query string.
// If start and end are not provided or are invalid, it returns a duration with zero-value.
func extractQueryRange(queryString url.Values) time.Duration {
startStr := queryString.Get("start")
endStr := queryString.Get("end")
var queryRange = time.Duration(0)
if startStr != "" && endStr != "" {
start, serr := util.ParseTime(startStr)
end, eerr := util.ParseTime(endStr)
if serr == nil && eerr == nil {
queryRange = time.Duration(end-start) * time.Millisecond
}
}
return queryRange
}
func writeError(w http.ResponseWriter, err error) {
switch err {
case context.Canceled:
err = errCanceled
case context.DeadlineExceeded:
err = errDeadlineExceeded
default:
if util.IsRequestBodyTooLarge(err) {
err = errRequestEntityTooLarge
}
}
server.WriteError(w, err)
}
func writeServiceTimingHeader(queryResponseTime time.Duration, headers http.Header, stats *querier_stats.Stats) {
if stats != nil {
parts := make([]string, 0)
parts = append(parts, statsValue("querier_wall_time", stats.LoadWallTime()))
parts = append(parts, statsValue("response_time", queryResponseTime))
headers.Set(ServiceTimingHeaderName, strings.Join(parts, ", "))
}
}
func statsValue(name string, d time.Duration) string {
durationInMs := strconv.FormatFloat(float64(d)/float64(time.Millisecond), 'f', -1, 64)
return name + ";dur=" + durationInMs
}