-
Notifications
You must be signed in to change notification settings - Fork 177
/
queryparser.go
312 lines (298 loc) · 10.6 KB
/
queryparser.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
// Copyright (c) 2021-2024 SigScalr, Inc.
//
// This file is part of SigLens Observability Solution
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package otsdbquery
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/cespare/xxhash"
dtu "github.com/siglens/siglens/pkg/common/dtypeutils"
rutils "github.com/siglens/siglens/pkg/readerUtils"
"github.com/siglens/siglens/pkg/segment"
"github.com/siglens/siglens/pkg/segment/structs"
segutils "github.com/siglens/siglens/pkg/segment/utils"
toputils "github.com/siglens/siglens/pkg/utils"
log "github.com/sirupsen/logrus"
"github.com/valyala/fasthttp"
)
func MetricsQueryParser(ctx *fasthttp.RequestCtx, myid uint64) {
var httpResp toputils.HttpServerResponse
queryReq := ctx.QueryArgs()
startStr := string(queryReq.Peek("start"))
endStr := string(queryReq.Peek("end"))
m := string(queryReq.Peek("m"))
mQRequest, err := ParseRequest(startStr, endStr, m, myid)
if err != nil {
ctx.SetStatusCode(fasthttp.StatusBadRequest)
httpResp.Message = err.Error()
httpResp.StatusCode = fasthttp.StatusBadRequest
toputils.WriteResponse(ctx, httpResp)
return
}
qid := rutils.GetNextQid()
segment.LogMetricsQuery("metrics query parser", mQRequest, qid)
mQRequest.MetricsQuery.OrgId = myid
res := segment.ExecuteMetricsQuery(&mQRequest.MetricsQuery, &mQRequest.TimeRange, qid)
mQResponse, err := res.GetOTSDBResults(&mQRequest.MetricsQuery)
if err != nil {
ctx.SetStatusCode(fasthttp.StatusBadRequest)
httpResp.Message = err.Error()
httpResp.StatusCode = fasthttp.StatusBadRequest
toputils.WriteResponse(ctx, httpResp)
return
}
toputils.WriteJsonResponse(ctx, &mQResponse)
ctx.SetContentType(toputils.ContentJson)
ctx.SetStatusCode(fasthttp.StatusOK)
}
func ParseRequest(startStr string, endStr string, m string, myid uint64) (*structs.MetricsQueryRequest, error) {
if startStr == "" || m == "" {
return nil, fmt.Errorf("Invalid query - missing 'start' or 'm' parameter")
}
start, err := parseTime(startStr)
if err != nil {
log.Errorf("MetricsQueryParser: Unable to parse Start time: %v. Error: %+v", startStr, err)
return nil, fmt.Errorf("Unable to parse Start time. Error: %+v", err)
}
var end uint32
if endStr == "" {
end = uint32(time.Now().Unix())
} else {
end, err = parseTime(endStr)
if err != nil {
log.Errorf("MetricsQueryParser: Unable to parse End time: %v. Error: %+v", endStr, err)
return nil, fmt.Errorf("Unable to parse End time. Error: %+v", err)
}
}
metricName, hashedMName, tags, err := parseMetricTag(m)
if err != nil {
log.Errorf("MetricsQueryParser: Unable to parse Metrics Tag: %v. Error: %+v", m, err)
return nil, fmt.Errorf("Unable to parse Metrics Tag. Error: %+v", err)
}
aggregator, downsampler, err := parseAggregatorDownsampler(m)
if err != nil {
return nil, fmt.Errorf("Unable to parse Aggregator and/or Downsampler. Error: %+v", err)
}
metricQueryRequest := &structs.MetricsQueryRequest{
MetricsQuery: structs.MetricsQuery{
MetricName: metricName,
HashedMName: hashedMName,
TagsFilters: tags,
Aggregator: structs.Aggregation{AggregatorFunction: aggregator},
Downsampler: downsampler,
OrgId: myid,
},
TimeRange: dtu.MetricsTimeRange{
StartEpochSec: start,
EndEpochSec: end,
},
}
return metricQueryRequest, nil
}
func parseTime(timeStr string) (uint32, error) {
if strings.HasSuffix(timeStr, "-ago") {
var duration time.Duration
durationStr := strings.TrimSuffix(timeStr, "-ago")
unit := durationStr[len(durationStr)-1]
durationNum, err := strconv.Atoi(strings.TrimSuffix(durationStr, string(unit)))
if err != nil {
log.Errorf("parseTime: invalid time format: %s. Error: %v", timeStr, err)
return 0, err
}
switch unit {
case 's':
duration = time.Duration(durationNum) * time.Second
case 'm':
duration = time.Duration(durationNum) * time.Minute
case 'h':
duration = time.Duration(durationNum) * time.Hour
case 'd':
duration = time.Duration(durationNum) * 24 * time.Hour
case 'w':
duration = time.Duration(durationNum) * 7 * 24 * time.Hour
case 'n':
duration = time.Duration(durationNum) * 30 * 24 * time.Hour
case 'y':
duration = time.Duration(durationNum) * 365 * 24 * time.Hour
default:
log.Errorf("parseTime: invalid time format: %s", timeStr)
return 0, fmt.Errorf("invalid time format: %s", timeStr)
}
return uint32(time.Now().Add(-duration).Unix()), nil
}
// if it is not a relative time, parse as absolute time
var t time.Time
var err error
// unixtime
if unixTime, err := strconv.ParseInt(timeStr, 10, 64); err == nil {
if toputils.IsTimeInMilli(uint64(unixTime)) {
return uint32(unixTime / 1e3), nil
}
return uint32(unixTime), nil
}
//absolute time formats
timeStr = absoluteTimeFormat(timeStr)
formats := []string{
"2006-01-02 15:04:05",
"2006-01-02",
}
for _, format := range formats {
t, err = time.Parse(format, timeStr)
if err == nil {
break
}
}
if err != nil {
log.Errorf("parseTime: invalid time format: %s. Error: %v", timeStr, err)
return 0, err
}
return uint32(t.Unix()), nil
}
func absoluteTimeFormat(timeStr string) string {
if strings.Contains(timeStr, "-") && strings.Count(timeStr, "-") == 1 {
timeStr = strings.Replace(timeStr, "-", " ", 1)
}
timeStr = strings.Replace(timeStr, "/", "-", 2)
if strings.Contains(timeStr, ":") {
if strings.Count(timeStr, ":") < 2 {
timeStr += ":00"
}
}
return timeStr
}
func parseMetricTag(m string) (string, uint64, []*structs.TagsFilter, error) {
logicalOperator := segutils.And
metricStart := strings.LastIndex(m, ":") + 1
metricEnd := strings.Index(m, "{")
if metricEnd == -1 {
metricEnd = len(m)
}
metric := m[metricStart:metricEnd]
hashedMName := xxhash.Sum64String(metric)
tagsStart := strings.Index(m, "{")
tagsEnd := strings.Index(m, "}")
if tagsStart == -1 || tagsEnd == -1 {
log.Errorf("parseMetricTag: invalid query format, either tasgStart or tagsEnd was -1 for m: %s", m)
return metric, hashedMName, nil, fmt.Errorf("invalid query format, either tasgStart or tagsEnd was -1 for m: %s", m)
}
tagsStr := m[tagsStart+1 : tagsEnd]
listOfTags := strings.Split(tagsStr, ",")
tags := make([]*structs.TagsFilter, 0)
var val interface{}
var key, multipleTagValues string
var hashedTagVal uint64
for _, tag := range listOfTags {
pair := strings.Split(tag, "=")
if len(pair) != 2 {
log.Errorf("parseMetricTag: invalid tag format, len(pair)=%v was not 2 for tag: %s", len(pair), tag)
return metric, hashedMName, nil, fmt.Errorf("invalid tag format, len(pair)=%v was not 2 for tag: %s", len(pair), tag)
}
key, multipleTagValues = strings.TrimSpace(pair[0]), strings.TrimSpace(pair[1])
valuesList := strings.Split(multipleTagValues, "|")
if len(valuesList) > 1 {
logicalOperator = segutils.Or
}
for _, val = range valuesList {
switch v := val.(type) {
case string:
if (strings.HasPrefix(v, `"`) && strings.HasSuffix(v, `"`) && len(v) > 1) ||
(strings.HasPrefix(v, `'`) && strings.HasSuffix(v, `'`) && len(v) > 1) {
v = v[1 : len(v)-1]
val = v
}
hashedTagVal = xxhash.Sum64String(v)
case int64:
hashedTagVal = uint64(v)
case float64:
hashedTagVal = uint64(v)
case uint64:
hashedTagVal = v
default:
log.Errorf("parseMetricTag: invalid tag value type %T for value %v", val, val)
return metric, hashedMName, nil, fmt.Errorf("parseMetricTag: invalid tag value type %v", val)
}
tags = append(tags, &structs.TagsFilter{
TagKey: key,
RawTagValue: val,
HashTagValue: hashedTagVal,
LogicalOperator: logicalOperator,
})
}
}
return metric, hashedMName, tags, nil
}
func parseAggregatorDownsampler(m string) (segutils.AggregateFunctions, structs.Downsampler, error) {
aggregaterDownsamplerList := strings.Split(m, ":")
aggregator := segutils.Sum
downsamplerStr := ""
var ok bool
var aggregatorMapping = map[string]segutils.AggregateFunctions{
"count": segutils.Count,
"avg": segutils.Avg,
"min": segutils.Min,
"max": segutils.Max,
"sum": segutils.Sum,
"cardinality": segutils.Cardinality,
"quantile": segutils.Quantile,
}
agg := structs.Aggregation{AggregatorFunction: aggregatorMapping["avg"]}
downsampler := structs.Downsampler{Interval: 1, Unit: "m", Aggregator: agg}
if len(aggregaterDownsamplerList) >= 2 {
aggregator, ok = aggregatorMapping[aggregaterDownsamplerList[0]]
if !ok {
log.Errorf("parseAggregatorDownsampler: unsupported aggregator function: %s", aggregaterDownsamplerList[0])
return segutils.Sum, downsampler, fmt.Errorf("unsupported aggregator function: %s", aggregaterDownsamplerList[0])
}
if len(aggregaterDownsamplerList) > 2 {
downsamplerStr = aggregaterDownsamplerList[1]
}
}
if downsamplerStr != "" {
downsampleComp := strings.Split(downsamplerStr, "-")
if len(downsampleComp) == 1 {
log.Errorf("parseAggregatorDownsampler: invalid downsampler format for %s", downsamplerStr)
return aggregator, downsampler, fmt.Errorf("invalid downsampler format for %s", downsamplerStr)
}
downsampler.Aggregator = structs.Aggregation{AggregatorFunction: aggregatorMapping[downsampleComp[1]]}
downsamplerIntervalUnit := downsampleComp[0]
var intervalStr string
var unit string
for i, c := range downsamplerIntervalUnit {
if c >= '0' && c <= '9' {
intervalStr += string(c)
} else if c == 'c' && i == len(downsamplerIntervalUnit)-1 {
downsampler.CFlag = true
break
} else {
unit += string(c)
}
}
if len(intervalStr) == 0 || len(unit) == 0 {
log.Errorf("parseAggregatorDownsampler: invalid downsampler(no interval or unit) format for %s", downsamplerStr)
return aggregator, downsampler, fmt.Errorf("invalid downsampler format for %s", downsamplerStr)
}
interval, err := strconv.Atoi(intervalStr)
if err != nil {
log.Errorf("parseAggregatorDownsampler: invalid interval in downsampler %s. Error: %v", downsamplerStr, err)
return aggregator, downsampler, fmt.Errorf("invalid interval in downsampler")
}
downsampler.Interval = interval
downsampler.Unit = unit
}
return aggregator, downsampler, nil
}