-
Notifications
You must be signed in to change notification settings - Fork 2k
/
remote_engine.go
380 lines (329 loc) · 9.62 KB
/
remote_engine.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
// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
package query
import (
"context"
"io"
"math"
"strings"
"sync"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql"
"github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/prometheus/util/annotations"
"github.com/prometheus/prometheus/util/stats"
"github.com/thanos-io/promql-engine/api"
"github.com/thanos-io/thanos/pkg/api/query/querypb"
"github.com/thanos-io/thanos/pkg/info/infopb"
"github.com/thanos-io/thanos/pkg/store/labelpb"
"github.com/thanos-io/thanos/pkg/store/storepb/prompb"
)
// Opts are the options for a PromQL query.
type Opts struct {
AutoDownsample bool
ReplicaLabels []string
Timeout time.Duration
EnablePartialResponse bool
}
// Client is a query client that executes PromQL queries.
type Client struct {
querypb.QueryClient
address string
tsdbInfos infopb.TSDBInfos
}
// NewClient creates a new Client.
func NewClient(queryClient querypb.QueryClient, address string, tsdbInfos infopb.TSDBInfos) Client {
return Client{
QueryClient: queryClient,
address: address,
tsdbInfos: tsdbInfos,
}
}
func (c Client) GetAddress() string { return c.address }
func (c Client) LabelSets() []labels.Labels {
return c.tsdbInfos.LabelSets()
}
type remoteEndpoints struct {
logger log.Logger
getClients func() []Client
opts Opts
}
func NewRemoteEndpoints(logger log.Logger, getClients func() []Client, opts Opts) api.RemoteEndpoints {
return remoteEndpoints{
logger: logger,
getClients: getClients,
opts: opts,
}
}
func (r remoteEndpoints) Engines() []api.RemoteEngine {
clients := r.getClients()
engines := make([]api.RemoteEngine, len(clients))
for i := range clients {
engines[i] = NewRemoteEngine(r.logger, clients[i], r.opts)
}
return engines
}
type remoteEngine struct {
opts Opts
logger log.Logger
client Client
mintOnce sync.Once
mint int64
maxtOnce sync.Once
maxt int64
labelSetsOnce sync.Once
labelSets []labels.Labels
}
func NewRemoteEngine(logger log.Logger, queryClient Client, opts Opts) *remoteEngine {
return &remoteEngine{
logger: logger,
client: queryClient,
opts: opts,
}
}
// MinT returns the minimum timestamp that is safe to query in the remote engine.
// In order to calculate it, we find the highest min time for each label set, and we return
// the lowest of those values.
// Calculating the MinT this way makes remote queries resilient to cases where one tsdb replica would delete
// a block due to retention before other replicas did the same.
// See https://github.com/thanos-io/promql-engine/issues/187.
func (r *remoteEngine) MinT() int64 {
r.mintOnce.Do(func() {
var (
hashBuf = make([]byte, 0, 128)
highestMintByLabelSet = make(map[uint64]int64)
)
for _, lset := range r.infosWithoutReplicaLabels() {
key, _ := labelpb.ZLabelsToPromLabels(lset.Labels.Labels).HashWithoutLabels(hashBuf)
lsetMinT, ok := highestMintByLabelSet[key]
if !ok {
highestMintByLabelSet[key] = lset.MinTime
continue
}
if lset.MinTime > lsetMinT {
highestMintByLabelSet[key] = lset.MinTime
}
}
var mint int64 = math.MaxInt64
for _, m := range highestMintByLabelSet {
if m < mint {
mint = m
}
}
r.mint = mint
})
return r.mint
}
func (r *remoteEngine) MaxT() int64 {
r.maxtOnce.Do(func() {
r.maxt = r.client.tsdbInfos.MaxT()
})
return r.maxt
}
func (r *remoteEngine) LabelSets() []labels.Labels {
r.labelSetsOnce.Do(func() {
r.labelSets = r.infosWithoutReplicaLabels().LabelSets()
})
return r.labelSets
}
func (r *remoteEngine) infosWithoutReplicaLabels() infopb.TSDBInfos {
replicaLabelSet := make(map[string]struct{})
for _, lbl := range r.opts.ReplicaLabels {
replicaLabelSet[lbl] = struct{}{}
}
// Strip replica labels from the result.
infos := make(infopb.TSDBInfos, 0, len(r.client.tsdbInfos))
var builder labels.ScratchBuilder
for _, info := range r.client.tsdbInfos {
builder.Reset()
for _, lbl := range info.Labels.Labels {
if _, ok := replicaLabelSet[lbl.Name]; ok {
continue
}
builder.Add(lbl.Name, lbl.Value)
}
infos = append(infos, infopb.NewTSDBInfo(
info.MinTime,
info.MaxTime,
labelpb.ZLabelsFromPromLabels(builder.Labels())),
)
}
return infos
}
func (r *remoteEngine) NewRangeQuery(_ context.Context, _ promql.QueryOpts, plan api.RemoteQuery, start, end time.Time, interval time.Duration) (promql.Query, error) {
return &remoteQuery{
logger: r.logger,
client: r.client,
opts: r.opts,
plan: plan,
start: start,
end: end,
interval: interval,
}, nil
}
func (r *remoteEngine) NewInstantQuery(_ context.Context, _ promql.QueryOpts, plan api.RemoteQuery, ts time.Time) (promql.Query, error) {
return &remoteQuery{
logger: r.logger,
client: r.client,
opts: r.opts,
plan: plan,
start: ts,
end: ts,
interval: 0,
}, nil
}
type remoteQuery struct {
logger log.Logger
client Client
opts Opts
plan api.RemoteQuery
start time.Time
end time.Time
interval time.Duration
cancel context.CancelFunc
}
func (r *remoteQuery) Exec(ctx context.Context) *promql.Result {
start := time.Now()
qctx, cancel := context.WithCancel(ctx)
r.cancel = cancel
defer cancel()
var maxResolution int64
if r.opts.AutoDownsample {
maxResolution = int64(r.interval.Seconds() / 5)
}
plan, err := querypb.NewJSONEncodedPlan(r.plan)
if err != nil {
level.Warn(r.logger).Log("msg", "Failed to encode query plan", "err", err)
}
// Instant query.
if r.start == r.end {
request := &querypb.QueryRequest{
Query: r.plan.String(),
QueryPlan: plan,
TimeSeconds: r.start.Unix(),
TimeoutSeconds: int64(r.opts.Timeout.Seconds()),
EnablePartialResponse: r.opts.EnablePartialResponse,
// TODO (fpetkovski): Allow specifying these parameters at query time.
// This will likely require a change in the remote engine interface.
ReplicaLabels: r.opts.ReplicaLabels,
MaxResolutionSeconds: maxResolution,
EnableDedup: true,
}
qry, err := r.client.Query(qctx, request)
if err != nil {
return &promql.Result{Err: err}
}
var (
result = make(promql.Vector, 0)
warnings annotations.Annotations
builder = labels.NewScratchBuilder(8)
)
for {
msg, err := qry.Recv()
if err == io.EOF {
break
}
if err != nil {
return &promql.Result{Err: err}
}
if warn := msg.GetWarnings(); warn != "" {
warnings.Add(errors.New(warn))
continue
}
ts := msg.GetTimeseries()
builder.Reset()
for _, l := range ts.Labels {
builder.Add(strings.Clone(l.Name), strings.Clone(l.Value))
}
// Point might have a different timestamp, force it to the evaluation
// timestamp as that is when we ran the evaluation.
// See https://github.com/prometheus/prometheus/blob/b727e69b7601b069ded5c34348dca41b80988f4b/promql/engine.go#L693-L699
if len(ts.Histograms) > 0 {
result = append(result, promql.Sample{Metric: builder.Labels(), H: prompb.FromProtoHistogram(ts.Histograms[0]), T: r.start.UnixMilli()})
} else {
result = append(result, promql.Sample{Metric: builder.Labels(), F: ts.Samples[0].Value, T: r.start.UnixMilli()})
}
}
return &promql.Result{
Value: result,
Warnings: warnings,
}
}
request := &querypb.QueryRangeRequest{
Query: r.plan.String(),
QueryPlan: plan,
StartTimeSeconds: r.start.Unix(),
EndTimeSeconds: r.end.Unix(),
IntervalSeconds: int64(r.interval.Seconds()),
TimeoutSeconds: int64(r.opts.Timeout.Seconds()),
EnablePartialResponse: r.opts.EnablePartialResponse,
// TODO (fpetkovski): Allow specifying these parameters at query time.
// This will likely require a change in the remote engine interface.
ReplicaLabels: r.opts.ReplicaLabels,
MaxResolutionSeconds: maxResolution,
EnableDedup: true,
}
qry, err := r.client.QueryRange(qctx, request)
if err != nil {
return &promql.Result{Err: err}
}
var (
result = make(promql.Matrix, 0)
warnings annotations.Annotations
builder = labels.NewScratchBuilder(8)
)
for {
msg, err := qry.Recv()
if err == io.EOF {
break
}
if err != nil {
return &promql.Result{Err: err}
}
if warn := msg.GetWarnings(); warn != "" {
warnings.Add(errors.New(warn))
continue
}
ts := msg.GetTimeseries()
if ts == nil {
continue
}
builder.Reset()
for _, l := range ts.Labels {
builder.Add(strings.Clone(l.Name), strings.Clone(l.Value))
}
series := promql.Series{
Metric: builder.Labels(),
Floats: make([]promql.FPoint, 0, len(ts.Samples)),
Histograms: make([]promql.HPoint, 0, len(ts.Histograms)),
}
for _, s := range ts.Samples {
series.Floats = append(series.Floats, promql.FPoint{
T: s.Timestamp,
F: s.Value,
})
}
for _, hp := range ts.Histograms {
series.Histograms = append(series.Histograms, promql.HPoint{
T: hp.Timestamp,
H: prompb.FloatHistogramProtoToFloatHistogram(hp),
})
}
result = append(result, series)
}
level.Debug(r.logger).Log("msg", "Executed query", "query", r.plan.String(), "time", time.Since(start))
return &promql.Result{Value: result, Warnings: warnings}
}
func (r *remoteQuery) Close() { r.Cancel() }
func (r *remoteQuery) Statement() parser.Statement { return nil }
func (r *remoteQuery) Stats() *stats.Statistics { return nil }
func (r *remoteQuery) Cancel() {
if r.cancel != nil {
r.cancel()
}
}
func (r *remoteQuery) String() string { return r.plan.String() }