forked from thanos-io/thanos
/
queryrange_codec.go
264 lines (225 loc) · 8.1 KB
/
queryrange_codec.go
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
// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
package queryfrontend
import (
"bytes"
"context"
"math"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/cortexproject/cortex/pkg/querier/queryrange"
cortexutil "github.com/cortexproject/cortex/pkg/util"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql/parser"
"github.com/weaveworks/common/httpgrpc"
queryv1 "github.com/thanos-io/thanos/pkg/api/query"
"github.com/thanos-io/thanos/pkg/store/storepb"
)
const (
// Name of the cache control header.
cacheControlHeader = "Cache-Control"
// Value that cacheControlHeader has if the response indicates that the results should not be cached.
noStoreValue = "no-store"
)
var (
errEndBeforeStart = httpgrpc.Errorf(http.StatusBadRequest, "end timestamp must not be before start time")
errNegativeStep = httpgrpc.Errorf(http.StatusBadRequest, "zero or negative query resolution step widths are not accepted. Try a positive integer")
errStepTooSmall = httpgrpc.Errorf(http.StatusBadRequest, "exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)")
errCannotParse = "cannot parse parameter %s"
)
// queryRangeCodec is used to encode/decode Thanos query range requests and responses.
type queryRangeCodec struct {
queryrange.Codec
partialResponse bool
}
// NewThanosQueryRangeCodec initializes a queryRangeCodec.
func NewThanosQueryRangeCodec(partialResponse bool) *queryRangeCodec {
return &queryRangeCodec{
Codec: queryrange.PrometheusCodec,
partialResponse: partialResponse,
}
}
func (c queryRangeCodec) DecodeRequest(_ context.Context, r *http.Request, forwardHeaders []string) (queryrange.Request, error) {
var (
result ThanosQueryRangeRequest
err error
)
result.Start, err = cortexutil.ParseTime(r.FormValue("start"))
if err != nil {
return nil, err
}
result.End, err = cortexutil.ParseTime(r.FormValue("end"))
if err != nil {
return nil, err
}
if result.End < result.Start {
return nil, errEndBeforeStart
}
result.Step, err = parseDurationMillis(r.FormValue("step"))
if err != nil {
return nil, err
}
if result.Step <= 0 {
return nil, errNegativeStep
}
// For safety, limit the number of returned points per timeseries.
// This is sufficient for 60s resolution for a week or 1h resolution for a year.
if (result.End-result.Start)/result.Step > 11000 {
return nil, errStepTooSmall
}
result.Dedup, err = parseEnableDedupParam(r.FormValue(queryv1.DedupParam))
if err != nil {
return nil, err
}
if r.FormValue(queryv1.MaxSourceResolutionParam) == "auto" {
result.AutoDownsampling = true
result.MaxSourceResolution = result.Step / 5
} else {
result.MaxSourceResolution, err = parseDownsamplingParamMillis(r.FormValue(queryv1.MaxSourceResolutionParam))
if err != nil {
return nil, err
}
}
result.PartialResponse, err = parsePartialResponseParam(r.FormValue(queryv1.PartialResponseParam), c.partialResponse)
if err != nil {
return nil, err
}
if len(r.Form[queryv1.ReplicaLabelsParam]) > 0 {
result.ReplicaLabels = r.Form[queryv1.ReplicaLabelsParam]
}
result.StoreMatchers, err = parseMatchersParam(r.Form, queryv1.StoreMatcherParam)
if err != nil {
return nil, err
}
result.Query = r.FormValue("query")
result.Path = r.URL.Path
for _, value := range r.Header.Values(cacheControlHeader) {
if strings.Contains(value, noStoreValue) {
result.CachingOptions.Disabled = true
break
}
}
for _, header := range forwardHeaders {
for h, hv := range r.Header {
if strings.EqualFold(h, header) {
result.Headers = append(result.Headers, &RequestHeader{Name: h, Values: hv})
break
}
}
}
return &result, nil
}
func (c queryRangeCodec) EncodeRequest(ctx context.Context, r queryrange.Request) (*http.Request, error) {
thanosReq, ok := r.(*ThanosQueryRangeRequest)
if !ok {
return nil, httpgrpc.Errorf(http.StatusBadRequest, "invalid request format")
}
params := url.Values{
"start": []string{encodeTime(thanosReq.Start)},
"end": []string{encodeTime(thanosReq.End)},
"step": []string{encodeDurationMillis(thanosReq.Step)},
"query": []string{thanosReq.Query},
queryv1.DedupParam: []string{strconv.FormatBool(thanosReq.Dedup)},
queryv1.PartialResponseParam: []string{strconv.FormatBool(thanosReq.PartialResponse)},
queryv1.ReplicaLabelsParam: thanosReq.ReplicaLabels,
}
if thanosReq.AutoDownsampling {
params[queryv1.MaxSourceResolutionParam] = []string{"auto"}
} else if thanosReq.MaxSourceResolution != 0 {
// Add this param only if it is set. Set to 0 will impact
// auto-downsampling in the querier.
params[queryv1.MaxSourceResolutionParam] = []string{encodeDurationMillis(thanosReq.MaxSourceResolution)}
}
if len(thanosReq.StoreMatchers) > 0 {
params[queryv1.StoreMatcherParam] = matchersToStringSlice(thanosReq.StoreMatchers)
}
req, err := http.NewRequest(http.MethodPost, thanosReq.Path, bytes.NewBufferString(params.Encode()))
if err != nil {
return nil, httpgrpc.Errorf(http.StatusBadRequest, "error creating request: %s", err.Error())
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
for _, hv := range thanosReq.Headers {
for _, v := range hv.Values {
req.Header.Add(hv.Name, v)
}
}
return req.WithContext(ctx), nil
}
func parseDurationMillis(s string) (int64, error) {
if d, err := strconv.ParseFloat(s, 64); err == nil {
ts := d * float64(time.Second/time.Millisecond)
if ts > float64(math.MaxInt64) || ts < float64(math.MinInt64) {
return 0, httpgrpc.Errorf(http.StatusBadRequest, "cannot parse %q to a valid duration. It overflows int64", s)
}
return int64(ts), nil
}
if d, err := model.ParseDuration(s); err == nil {
return int64(d) / int64(time.Millisecond/time.Nanosecond), nil
}
return 0, httpgrpc.Errorf(http.StatusBadRequest, "cannot parse %q to a valid duration", s)
}
func parseEnableDedupParam(s string) (bool, error) {
enableDeduplication := true
if s != "" {
var err error
enableDeduplication, err = strconv.ParseBool(s)
if err != nil {
return enableDeduplication, httpgrpc.Errorf(http.StatusBadRequest, errCannotParse, queryv1.DedupParam)
}
}
return enableDeduplication, nil
}
func parseDownsamplingParamMillis(s string) (int64, error) {
var maxSourceResolution int64
if s != "" {
var err error
maxSourceResolution, err = parseDurationMillis(s)
if err != nil {
return maxSourceResolution, httpgrpc.Errorf(http.StatusBadRequest, errCannotParse, queryv1.MaxSourceResolutionParam)
}
}
if maxSourceResolution < 0 {
return 0, httpgrpc.Errorf(http.StatusBadRequest, "negative max_source_resolution is not accepted. Try a positive integer")
}
return maxSourceResolution, nil
}
func parsePartialResponseParam(s string, defaultEnablePartialResponse bool) (bool, error) {
if s != "" {
var err error
defaultEnablePartialResponse, err = strconv.ParseBool(s)
if err != nil {
return defaultEnablePartialResponse, httpgrpc.Errorf(http.StatusBadRequest, errCannotParse, queryv1.PartialResponseParam)
}
}
return defaultEnablePartialResponse, nil
}
func parseMatchersParam(ss url.Values, matcherParam string) ([][]*labels.Matcher, error) {
matchers := make([][]*labels.Matcher, 0, len(ss[matcherParam]))
for _, s := range ss[matcherParam] {
ms, err := parser.ParseMetricSelector(s)
if err != nil {
return nil, httpgrpc.Errorf(http.StatusBadRequest, errCannotParse, matcherParam)
}
matchers = append(matchers, ms)
}
return matchers, nil
}
func encodeTime(t int64) string {
f := float64(t) / 1.0e3
return strconv.FormatFloat(f, 'f', -1, 64)
}
func encodeDurationMillis(d int64) string {
return strconv.FormatFloat(float64(d)/float64(time.Second/time.Millisecond), 'f', -1, 64)
}
// matchersToStringSlice converts storeMatchers to string slice.
func matchersToStringSlice(storeMatchers [][]*labels.Matcher) []string {
res := make([]string, 0, len(storeMatchers))
for _, storeMatcher := range storeMatchers {
res = append(res, storepb.PromMatchersToString(storeMatcher...))
}
return res
}