-
Notifications
You must be signed in to change notification settings - Fork 451
/
read_common.go
286 lines (246 loc) · 8.39 KB
/
read_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
// 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 native
import (
"context"
"math"
"net/http"
"github.com/m3db/m3/src/query/api/v1/handler/prometheus"
"github.com/m3db/m3/src/query/api/v1/options"
"github.com/m3db/m3/src/query/block"
"github.com/m3db/m3/src/query/executor"
"github.com/m3db/m3/src/query/models"
"github.com/m3db/m3/src/query/parser/promql"
"github.com/m3db/m3/src/query/storage"
"github.com/m3db/m3/src/query/ts"
xerrors "github.com/m3db/m3/src/x/errors"
xhttp "github.com/m3db/m3/src/x/net/http"
xopentracing "github.com/m3db/m3/src/x/opentracing"
opentracinglog "github.com/opentracing/opentracing-go/log"
"github.com/uber-go/tally"
)
type promReadMetrics struct {
fetchSuccess tally.Counter
fetchErrorsServer tally.Counter
fetchErrorsClient tally.Counter
fetchTimerSuccess tally.Timer
returnedDataMetrics PromReadReturnedDataMetrics
}
// PromReadReturnedDataMetrics are metrics on the data returned from prom reads.
type PromReadReturnedDataMetrics struct {
FetchSeries tally.Histogram
FetchDatapoints tally.Histogram
}
func newPromReadMetrics(scope tally.Scope) promReadMetrics {
return promReadMetrics{
fetchSuccess: scope.Counter("fetch.success"),
fetchErrorsServer: scope.Tagged(map[string]string{"code": "5XX"}).
Counter("fetch.errors"),
fetchErrorsClient: scope.Tagged(map[string]string{"code": "4XX"}).
Counter("fetch.errors"),
fetchTimerSuccess: scope.Timer("fetch.success.latency"),
returnedDataMetrics: NewPromReadReturnedDataMetrics(scope),
}
}
// NewPromReadReturnedDataMetrics returns metrics for returned data.
func NewPromReadReturnedDataMetrics(scope tally.Scope) PromReadReturnedDataMetrics {
seriesBuckets := append(tally.ValueBuckets{0}, tally.MustMakeExponentialValueBuckets(1, 2, 16)...)
datapointBuckets := append(tally.ValueBuckets{0}, tally.MustMakeExponentialValueBuckets(100, 2, 16)...)
return PromReadReturnedDataMetrics{
FetchSeries: scope.Histogram("fetch.series", seriesBuckets),
FetchDatapoints: scope.Histogram("fetch.datapoints", datapointBuckets),
}
}
func (m *promReadMetrics) incError(err error) {
if xhttp.IsClientError(err) {
m.fetchErrorsClient.Inc(1)
} else {
m.fetchErrorsServer.Inc(1)
}
}
// ReadResponse is the response that gets returned to the user
type ReadResponse struct {
Results []ts.Series `json:"results,omitempty"`
}
// ReadResult is a result from a remote read.
type ReadResult struct {
Series []*ts.Series
Meta block.ResultMetadata
BlockType block.BlockType
}
// ParseRequest parses the given request.
func ParseRequest(
ctx context.Context,
r *http.Request,
instantaneous bool,
opts options.HandlerOptions,
) (context.Context, ParsedOptions, error) {
ctx, parsed, err := parseRequest(ctx, r, instantaneous, opts)
if err != nil {
// All parsing of requests should result in an invalid params error.
return nil, ParsedOptions{}, xerrors.NewInvalidParamsError(err)
}
return ctx, parsed, nil
}
func parseRequest(
ctx context.Context,
r *http.Request,
instantaneous bool,
opts options.HandlerOptions,
) (context.Context, ParsedOptions, error) {
ctx, fetchOpts, err := opts.FetchOptionsBuilder().NewFetchOptions(ctx, r)
if err != nil {
return nil, ParsedOptions{}, err
}
queryOpts := &executor.QueryOptions{
QueryContextOptions: models.QueryContextOptions{
LimitMaxTimeseries: fetchOpts.SeriesLimit,
LimitMaxDocs: fetchOpts.DocsLimit,
LimitMaxReturnedSeries: fetchOpts.ReturnedSeriesLimit,
LimitMaxReturnedDatapoints: fetchOpts.ReturnedDatapointsLimit,
LimitMaxReturnedSeriesMetadata: fetchOpts.ReturnedSeriesMetadataLimit,
Instantaneous: instantaneous,
},
}
restrictOpts := fetchOpts.RestrictQueryOptions.GetRestrictByType()
if restrictOpts != nil {
restrict := &models.RestrictFetchTypeQueryContextOptions{
MetricsType: uint(restrictOpts.MetricsType),
StoragePolicy: restrictOpts.StoragePolicy,
}
queryOpts.QueryContextOptions.RestrictFetchType = restrict
}
var (
engine = opts.Engine()
params models.RequestParams
)
if instantaneous {
params, err = parseInstantaneousParams(r, engine.Options(), fetchOpts)
} else {
params, err = parseParams(r, engine.Options(), fetchOpts)
}
if err != nil {
return nil, ParsedOptions{}, err
}
return ctx, ParsedOptions{
QueryOpts: queryOpts,
FetchOpts: fetchOpts,
Params: params,
}, nil
}
// ParsedOptions are parsed options for the query.
type ParsedOptions struct {
QueryOpts *executor.QueryOptions
FetchOpts *storage.FetchOptions
Params models.RequestParams
}
func read(
ctx context.Context,
parsed ParsedOptions,
handlerOpts options.HandlerOptions,
) (ReadResult, error) {
var (
opts = parsed.QueryOpts
fetchOpts = parsed.FetchOpts
params = parsed.Params
tagOpts = handlerOpts.TagOptions()
engine = handlerOpts.Engine()
)
sp := xopentracing.SpanFromContextOrNoop(ctx)
sp.LogFields(
opentracinglog.String("params.query", params.Query),
xopentracing.Time("params.start", params.Start.ToTime()),
xopentracing.Time("params.end", params.End.ToTime()),
xopentracing.Time("params.now", params.Now),
xopentracing.Duration("params.step", params.Step),
)
emptyResult := ReadResult{
Meta: block.NewResultMetadata(),
BlockType: block.BlockEmpty,
}
// TODO: Capture timing
parseOpts := engine.Options().ParseOptions()
parser, err := promql.Parse(params.Query, params.Step, tagOpts, parseOpts)
if err != nil {
return emptyResult, xerrors.NewInvalidParamsError(err)
}
bl, err := engine.ExecuteExpr(ctx, parser, opts, fetchOpts, params)
if err != nil {
return emptyResult, err
}
resultMeta := bl.Meta().ResultMetadata
it, err := bl.StepIter()
if err != nil {
return emptyResult, err
}
seriesMeta := it.SeriesMeta()
numSeries := len(seriesMeta)
bounds := bl.Meta().Bounds
// Initialize data slices.
data := make([]ts.FixedResolutionMutableValues, 0, numSeries)
for i := 0; i < numSeries; i++ {
data = append(data, ts.NewFixedStepValues(bounds.StepSize, bounds.Steps(),
math.NaN(), bounds.Start))
}
stepIndex := 0
for it.Next() {
step := it.Current()
for seriesIndex, v := range step.Values() {
mutableValuesForSeries := data[seriesIndex]
mutableValuesForSeries.SetValueAt(stepIndex, v)
}
stepIndex++
}
if err := it.Err(); err != nil {
return emptyResult, err
}
seriesList := make([]*ts.Series, 0, len(data))
for i, values := range data {
var (
meta = seriesMeta[i]
tags = meta.Tags.AddTags(bl.Meta().Tags.Tags)
series = ts.NewSeries(meta.Name, values, tags)
)
seriesList = append(seriesList, series)
}
if err := bl.Close(); err != nil {
return emptyResult, err
}
seriesList = prometheus.FilterSeriesByOptions(seriesList, fetchOpts)
blockType := bl.Info().Type()
return ReadResult{
Series: seriesList,
Meta: resultMeta,
BlockType: blockType,
}, nil
}
// ReturnedDataLimited are parsed options for the query.
type ReturnedDataLimited struct {
Series int
Datapoints int
// Total series is the total number of series which maybe be >= Series.
// Truncation happens at the series-level to avoid presenting partial series
// and so this value is useful for indicating how many series would have
// been rendered without limiting either series or datapoints.
TotalSeries int
// Limited signals that the results returned were
// limited by either series or datapoint limits.
Limited bool
}