-
Notifications
You must be signed in to change notification settings - Fork 458
/
Copy pathcommon.go
431 lines (354 loc) · 10.4 KB
/
common.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
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Copyright (c) 2018 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package prometheus
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
"github.com/m3db/m3/src/query/errors"
"github.com/m3db/m3/src/query/models"
xpromql "github.com/m3db/m3/src/query/parser/promql"
"github.com/m3db/m3/src/query/storage"
"github.com/m3db/m3/src/query/util"
"github.com/m3db/m3/src/query/util/json"
xhttp "github.com/m3db/m3/src/x/net/http"
"github.com/golang/snappy"
"github.com/gorilla/mux"
"github.com/prometheus/prometheus/promql"
)
const (
// NameReplace is the parameter that gets replaced
NameReplace = "name"
queryParam = "query"
filterNameTagsParam = "tag"
errFormatStr = "error parsing param: %s, error: %v"
maxTimeout = 5 * time.Minute
)
var (
matchValues = []byte(".*")
)
// TimeoutOpts stores options related to various timeout configurations
type TimeoutOpts struct {
FetchTimeout time.Duration
}
// ParsePromCompressedRequest parses a snappy compressed request from Prometheus
func ParsePromCompressedRequest(r *http.Request) ([]byte, *xhttp.ParseError) {
body := r.Body
if r.Body == nil {
err := fmt.Errorf("empty request body")
return nil, xhttp.NewParseError(err, http.StatusBadRequest)
}
defer body.Close()
compressed, err := ioutil.ReadAll(body)
if err != nil {
return nil, xhttp.NewParseError(err, http.StatusInternalServerError)
}
if len(compressed) == 0 {
return nil, xhttp.NewParseError(fmt.Errorf("empty request body"), http.StatusBadRequest)
}
reqBuf, err := snappy.Decode(nil, compressed)
if err != nil {
return nil, xhttp.NewParseError(err, http.StatusBadRequest)
}
return reqBuf, nil
}
// ParseRequestTimeout parses the input request timeout with a default
func ParseRequestTimeout(r *http.Request, configFetchTimeout time.Duration) (time.Duration, error) {
timeout := r.Header.Get("timeout")
if timeout == "" {
return configFetchTimeout, nil
}
duration, err := time.ParseDuration(timeout)
if err != nil {
return 0, fmt.Errorf("%s: invalid 'timeout': %v", xhttp.ErrInvalidParams, err)
}
if duration > maxTimeout {
return 0, fmt.Errorf("%s: invalid 'timeout': greater than %v", xhttp.ErrInvalidParams, maxTimeout)
}
return duration, nil
}
// ParseTagCompletionParamsToQuery parses all params from the GET request
func ParseTagCompletionParamsToQuery(
r *http.Request,
) (*storage.CompleteTagsQuery, *xhttp.ParseError) {
tagQuery := storage.CompleteTagsQuery{}
query, err := parseTagCompletionQuery(r)
if err != nil {
return nil, xhttp.NewParseError(fmt.Errorf(errFormatStr, queryParam, err), http.StatusBadRequest)
}
matchers, err := models.MatchersFromString(query)
if err != nil {
return nil, xhttp.NewParseError(err, http.StatusBadRequest)
}
tagQuery.TagMatchers = matchers
// If there is a result type field present, parse it and set
// complete name only parameter appropriately. Otherwise, default
// to returning both completed tag names and values
if result := r.FormValue("result"); result != "" {
switch result {
case "default":
tagQuery.CompleteNameOnly = false
case "tagNamesOnly":
tagQuery.CompleteNameOnly = true
default:
return nil, xhttp.NewParseError(errors.ErrInvalidResultParamError, http.StatusBadRequest)
}
}
filterNameTags := r.Form[filterNameTagsParam]
tagQuery.FilterNameTags = make([][]byte, len(filterNameTags))
for i, f := range filterNameTags {
tagQuery.FilterNameTags[i] = []byte(f)
}
return &tagQuery, nil
}
func parseTagCompletionQuery(r *http.Request) (string, error) {
queries, ok := r.URL.Query()[queryParam]
if !ok || len(queries) == 0 || queries[0] == "" {
return "", errors.ErrNoQueryFound
}
// TODO: currently, we only support one target at a time
if len(queries) > 1 {
return "", errors.ErrBatchQuery
}
return queries[0], nil
}
func parseTimeWithDefault(
r *http.Request,
key string,
defaultTime time.Time,
) (time.Time, error) {
if t := r.FormValue(key); t != "" {
return util.ParseTimeString(t)
}
return defaultTime, nil
}
// ParseSeriesMatchQuery parses all params from the GET request
func ParseSeriesMatchQuery(
r *http.Request,
tagOptions models.TagOptions,
) (*storage.SeriesMatchQuery, *xhttp.ParseError) {
r.ParseForm()
matcherValues := r.Form["match[]"]
if len(matcherValues) == 0 {
return nil, xhttp.NewParseError(errors.ErrInvalidMatchers, http.StatusBadRequest)
}
start, err := parseTimeWithDefault(r, "start", time.Now().Add(time.Hour*24*-40))
if err != nil {
return nil, xhttp.NewParseError(err, http.StatusBadRequest)
}
end, err := parseTimeWithDefault(r, "end", time.Now())
if err != nil {
return nil, xhttp.NewParseError(err, http.StatusBadRequest)
}
tagMatchers := make([]models.Matchers, len(matcherValues))
for i, s := range matcherValues {
promMatchers, err := promql.ParseMetricSelector(s)
if err != nil {
return nil, xhttp.NewParseError(err, http.StatusBadRequest)
}
matchers, err := xpromql.LabelMatchersToModelMatcher(promMatchers, tagOptions)
if err != nil {
return nil, xhttp.NewParseError(err, http.StatusBadRequest)
}
tagMatchers[i] = matchers
}
return &storage.SeriesMatchQuery{
TagMatchers: tagMatchers,
Start: start,
End: end,
}, nil
}
// ParseTagValuesToQuery parses a tag values request to a complete tags query
func ParseTagValuesToQuery(
r *http.Request,
) (*storage.CompleteTagsQuery, error) {
vars := mux.Vars(r)
name, ok := vars[NameReplace]
if !ok || len(name) == 0 {
return nil, errors.ErrNoName
}
nameBytes := []byte(name)
return &storage.CompleteTagsQuery{
CompleteNameOnly: false,
FilterNameTags: [][]byte{nameBytes},
TagMatchers: models.Matchers{
models.Matcher{
Type: models.MatchRegexp,
Name: nameBytes,
Value: matchValues,
},
},
}, nil
}
func renderNameOnlyTagCompletionResultsJSON(
w io.Writer,
results []storage.CompletedTag,
) error {
jw := json.NewWriter(w)
jw.BeginArray()
for _, tag := range results {
jw.WriteString(string(tag.Name))
}
jw.EndArray()
return jw.Close()
}
func renderDefaultTagCompletionResultsJSON(
w io.Writer,
results []storage.CompletedTag,
) error {
jw := json.NewWriter(w)
jw.BeginObject()
jw.BeginObjectField("hits")
jw.WriteInt(len(results))
jw.BeginObjectField("tags")
jw.BeginArray()
for _, tag := range results {
jw.BeginObject()
jw.BeginObjectField("key")
jw.WriteString(string(tag.Name))
jw.BeginObjectField("values")
jw.BeginArray()
for _, value := range tag.Values {
jw.WriteString(string(value))
}
jw.EndArray()
jw.EndObject()
}
jw.EndArray()
jw.EndObject()
return jw.Close()
}
// RenderTagCompletionResultsJSON renders tag completion results to json format
func RenderTagCompletionResultsJSON(
w io.Writer,
result *storage.CompleteTagsResult,
) error {
results := result.CompletedTags
if result.CompleteNameOnly {
return renderNameOnlyTagCompletionResultsJSON(w, results)
}
return renderDefaultTagCompletionResultsJSON(w, results)
}
// RenderTagValuesResultsJSON renders tag values results to json format
func RenderTagValuesResultsJSON(
w io.Writer,
result *storage.CompleteTagsResult,
) error {
if result.CompleteNameOnly {
return errors.ErrNamesOnly
}
tagCount := len(result.CompletedTags)
if tagCount > 1 {
return errors.ErrMultipleResults
}
jw := json.NewWriter(w)
jw.BeginObject()
jw.BeginObjectField("status")
jw.WriteString("success")
jw.BeginObjectField("data")
jw.BeginArray()
// if no tags found, return empty array
if tagCount == 0 {
jw.EndArray()
jw.EndObject()
return jw.Close()
}
values := result.CompletedTags[0].Values
for _, value := range values {
jw.WriteString(string(value))
}
jw.EndArray()
jw.EndObject()
return jw.Close()
}
type tag struct {
name string
value string
}
func writeTagsHelper(
jw *json.Writer,
completedTags []storage.CompletedTag,
tags []tag,
) {
if len(completedTags) == 0 {
jw.BeginObject()
for _, tag := range tags {
jw.BeginObjectField(tag.name)
jw.WriteString(tag.value)
}
jw.EndObject()
return
}
firstResult := completedTags[0]
name := string(firstResult.Name)
copiedTags := make([]tag, len(tags)+1)
copy(copiedTags, tags)
for _, value := range firstResult.Values {
copiedTags[len(tags)] = tag{name: name, value: string(value)}
writeTagsHelper(jw, completedTags[1:], copiedTags)
}
}
func writeTags(
jw *json.Writer,
results []*storage.CompleteTagsResult,
) {
for _, result := range results {
jw.BeginArray()
tags := result.CompletedTags
if len(tags) > 0 {
writeTagsHelper(jw, result.CompletedTags, nil)
}
jw.EndArray()
}
}
// RenderSeriesMatchResultsJSON renders series match results to json format
func RenderSeriesMatchResultsJSON(
w io.Writer,
results []*storage.CompleteTagsResult,
) error {
jw := json.NewWriter(w)
jw.BeginObject()
jw.BeginObjectField("status")
jw.WriteString("success")
jw.BeginObjectField("data")
writeTags(jw, results)
jw.EndObject()
return jw.Close()
}
// PromResp represents Prometheus's query response
type PromResp struct {
Status string `json:"status"`
Data struct {
ResultType string `json:"resultType"`
Result []struct {
Metric map[string]string `json:"metric"`
// todo(braskin): use `Datapoints` instead of interface{} in values
// Values is [float, string]
Values [][]interface{} `json:"values"`
} `json:"result"`
} `json:"data"`
}
// PromDebug represents the input and output that are used in the debug endpoint
type PromDebug struct {
Input PromResp `json:"input"`
Results PromResp `json:"results"`
}