forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
batch.go
522 lines (466 loc) · 10.4 KB
/
batch.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
package kapacitor
import (
"bytes"
"fmt"
"sync"
"time"
"github.com/gorhill/cronexpr"
"github.com/influxdata/influxdb/influxql"
"github.com/influxdata/kapacitor/edge"
"github.com/influxdata/kapacitor/expvar"
"github.com/influxdata/kapacitor/influxdb"
"github.com/influxdata/kapacitor/pipeline"
"github.com/pkg/errors"
)
const (
statsBatchesQueried = "batches_queried"
statsPointsQueried = "points_queried"
)
type BatchNode struct {
node
s *pipeline.BatchNode
idx int
}
func newBatchNode(et *ExecutingTask, n *pipeline.BatchNode, d NodeDiagnostic) (*BatchNode, error) {
sn := &BatchNode{
node: node{Node: n, et: et, diag: d},
s: n,
}
return sn, nil
}
func (n *BatchNode) linkChild(c Node) error {
// add child
if n.Provides() != c.Wants() {
return fmt.Errorf("cannot add child mismatched edges: %s -> %s", n.Provides(), c.Wants())
}
n.children = append(n.children, c)
// add parent
c.addParent(n)
return nil
}
func (n *BatchNode) addParentEdge(in edge.StatsEdge) {
// Pass edges down to children
n.children[n.idx].addParentEdge(in)
n.idx++
}
func (n *BatchNode) start([]byte) {
}
func (n *BatchNode) Wait() error {
return nil
}
// Return list of databases and retention policies
// the batcher will query.
func (n *BatchNode) DBRPs() ([]DBRP, error) {
var dbrps []DBRP
for _, b := range n.children {
d, err := b.(*QueryNode).DBRPs()
if err != nil {
return nil, err
}
dbrps = append(dbrps, d...)
}
return dbrps, nil
}
func (n *BatchNode) Count() int {
return len(n.children)
}
func (n *BatchNode) Start() {
for _, b := range n.children {
b.(*QueryNode).Start()
}
}
func (n *BatchNode) Abort() {
for _, b := range n.children {
b.(*QueryNode).Abort()
}
}
type BatchQueries struct {
Queries []*Query
Cluster string
GroupByMeasurement bool
}
func (n *BatchNode) Queries(start, stop time.Time) ([]BatchQueries, error) {
queries := make([]BatchQueries, len(n.children))
for i, b := range n.children {
qn := b.(*QueryNode)
qs, err := qn.Queries(start, stop)
if err != nil {
return nil, err
}
queries[i] = BatchQueries{
Queries: qs,
Cluster: qn.Cluster(),
GroupByMeasurement: qn.GroupByMeasurement(),
}
}
return queries, nil
}
// Do not add the source batch node to the dot output
// since its not really an edge.
func (n *BatchNode) edot(*bytes.Buffer, bool) {}
func (n *BatchNode) collectedCount() (count int64) {
for _, child := range n.children {
count += child.collectedCount()
}
return
}
type QueryNode struct {
node
b *pipeline.QueryNode
query *Query
ticker ticker
queryMu sync.Mutex
queryErr chan error
closing chan struct{}
aborting chan struct{}
batchesQueried *expvar.Int
pointsQueried *expvar.Int
byName bool
}
func newQueryNode(et *ExecutingTask, n *pipeline.QueryNode, d NodeDiagnostic) (*QueryNode, error) {
bn := &QueryNode{
node: node{Node: n, et: et, diag: d},
b: n,
closing: make(chan struct{}),
aborting: make(chan struct{}),
byName: n.GroupByMeasurementFlag,
}
bn.node.runF = bn.runBatch
bn.node.stopF = bn.stopBatch
// Create query
q, err := NewQuery(n.QueryStr)
if err != nil {
return nil, err
}
bn.query = q
// Add in dimensions
err = bn.query.Dimensions(n.Dimensions)
if err != nil {
return nil, err
}
// Set offset alignment
if n.AlignGroupFlag {
bn.query.AlignGroup()
}
// Set fill
switch fill := n.Fill.(type) {
case string:
switch fill {
case "null":
bn.query.Fill(influxql.NullFill, nil)
case "none":
bn.query.Fill(influxql.NoFill, nil)
case "previous":
bn.query.Fill(influxql.PreviousFill, nil)
case "linear":
bn.query.Fill(influxql.LinearFill, nil)
default:
return nil, fmt.Errorf("unexpected fill option %s", fill)
}
case int64, float64:
bn.query.Fill(influxql.NumberFill, fill)
}
// Determine schedule
if n.Every != 0 && n.Cron != "" {
return nil, errors.New("must not set both 'every' and 'cron' properties")
}
switch {
case n.Every != 0:
bn.ticker = newTimeTicker(n.Every, n.AlignFlag)
case n.Cron != "":
var err error
bn.ticker, err = newCronTicker(n.Cron)
if err != nil {
return nil, err
}
default:
return nil, errors.New("must define one of 'every' or 'cron'")
}
return bn, nil
}
func (n *QueryNode) GroupByMeasurement() bool {
return n.byName
}
// Return list of databases and retention policies
// the batcher will query.
func (n *QueryNode) DBRPs() ([]DBRP, error) {
return n.query.DBRPs()
}
func (n *QueryNode) Start() {
n.queryMu.Lock()
defer n.queryMu.Unlock()
n.queryErr = make(chan error, 1)
go func() {
n.queryErr <- n.doQuery(n.ins[0])
}()
}
func (n *QueryNode) Abort() {
close(n.aborting)
}
func (n *QueryNode) Cluster() string {
return n.b.Cluster
}
func (n *QueryNode) Queries(start, stop time.Time) ([]*Query, error) {
now := time.Now()
if stop.IsZero() {
stop = now
}
// Crons are sensitive to timezones.
// Make sure we are using local time.
current := start.Local()
queries := make([]*Query, 0)
for {
current = n.ticker.Next(current)
if current.IsZero() || current.After(stop) {
break
}
qstop := current.Add(-1 * n.b.Offset)
if qstop.After(now) {
break
}
q, err := n.query.Clone()
if err != nil {
return nil, err
}
q.SetStartTime(qstop.Add(-1 * n.b.Period))
q.SetStopTime(qstop)
queries = append(queries, q)
}
return queries, nil
}
// Query InfluxDB and collect batches on batch collector.
func (n *QueryNode) doQuery(in edge.Edge) error {
defer in.Close()
n.batchesQueried = &expvar.Int{}
n.pointsQueried = &expvar.Int{}
n.statMap.Set(statsBatchesQueried, n.batchesQueried)
n.statMap.Set(statsPointsQueried, n.pointsQueried)
if n.et.tm.InfluxDBService == nil {
return errors.New("InfluxDB not configured, cannot query InfluxDB for batch query")
}
con, err := n.et.tm.InfluxDBService.NewNamedClient(n.b.Cluster)
if err != nil {
return errors.Wrap(err, "failed to get InfluxDB client")
}
tickC := n.ticker.Start()
for {
select {
case <-n.closing:
return nil
case <-n.aborting:
return errors.New("batch doQuery aborted")
case now := <-tickC:
n.timer.Start()
// Update times for query
stop := now.Add(-1 * n.b.Offset)
n.query.SetStartTime(stop.Add(-1 * n.b.Period))
n.query.SetStopTime(stop)
qStr := n.query.String()
n.diag.StartingBatchQuery(qStr)
// Execute query
q := influxdb.Query{
Command: qStr,
}
resp, err := con.Query(q)
if err != nil {
n.diag.Error("error executing query", err)
n.timer.Stop()
break
}
// Collect batches
for _, res := range resp.Results {
batches, err := edge.ResultToBufferedBatches(res, n.byName)
if err != nil {
n.diag.Error("failed to understand query result", err)
continue
}
for _, bch := range batches {
// Set stop time based off query bounds
if bch.Begin().Time().IsZero() || !n.query.IsGroupedByTime() {
bch.Begin().SetTime(stop)
}
n.batchesQueried.Add(1)
n.pointsQueried.Add(int64(len(bch.Points())))
n.timer.Pause()
if err := in.Collect(bch); err != nil {
return err
}
n.timer.Resume()
}
}
n.timer.Stop()
}
}
}
func (n *QueryNode) runBatch([]byte) error {
errC := make(chan error, 1)
go func() {
defer func() {
err := recover()
if err != nil {
errC <- fmt.Errorf("%v", err)
}
}()
for bt, ok := n.ins[0].Emit(); ok; bt, ok = n.ins[0].Emit() {
for _, child := range n.outs {
err := child.Collect(bt)
if err != nil {
errC <- err
return
}
}
}
errC <- nil
}()
var queryErr error
n.queryMu.Lock()
if n.queryErr != nil {
n.queryMu.Unlock()
select {
case queryErr = <-n.queryErr:
case <-n.aborting:
queryErr = errors.New("batch queryErr aborted")
}
} else {
n.queryMu.Unlock()
}
var err error
select {
case err = <-errC:
case <-n.aborting:
err = errors.New("batch run aborted")
}
if queryErr != nil {
return queryErr
}
return err
}
func (n *QueryNode) stopBatch() {
if n.ticker != nil {
n.ticker.Stop()
}
close(n.closing)
}
type ticker interface {
Start() <-chan time.Time
Stop()
// Return the next time the ticker will tick after now.
Next(now time.Time) time.Time
}
type timeTicker struct {
every time.Duration
align bool
alignChan chan time.Time
stopping chan struct{}
ticker *time.Ticker
mu sync.Mutex
wg sync.WaitGroup
}
func newTimeTicker(every time.Duration, align bool) *timeTicker {
t := &timeTicker{
align: align,
every: every,
}
if align {
t.alignChan = make(chan time.Time)
t.stopping = make(chan struct{})
}
return t
}
func (t *timeTicker) Start() <-chan time.Time {
t.mu.Lock()
defer t.mu.Unlock()
if t.alignChan != nil {
t.wg.Add(1)
go func() {
defer t.wg.Done()
// Sleep until we are roughly aligned
now := time.Now()
next := now.Truncate(t.every).Add(t.every)
after := time.NewTicker(next.Sub(now))
select {
case <-after.C:
after.Stop()
case <-t.stopping:
after.Stop()
return
}
t.ticker = time.NewTicker(t.every)
// Send first event since we waited for it explicitly
t.alignChan <- next
for {
select {
case <-t.stopping:
return
case now := <-t.ticker.C:
now = now.Round(t.every)
t.alignChan <- now
}
}
}()
return t.alignChan
} else {
t.ticker = time.NewTicker(t.every)
return t.ticker.C
}
}
func (t *timeTicker) Stop() {
t.mu.Lock()
defer t.mu.Unlock()
if t.ticker != nil {
t.ticker.Stop()
}
if t.alignChan != nil {
close(t.stopping)
}
t.wg.Wait()
}
func (t *timeTicker) Next(now time.Time) time.Time {
next := now.Add(t.every)
if t.align {
next = next.Round(t.every)
}
return next
}
type cronTicker struct {
expr *cronexpr.Expression
ticker chan time.Time
closing chan struct{}
wg sync.WaitGroup
}
func newCronTicker(cronExpr string) (*cronTicker, error) {
expr, err := cronexpr.Parse(cronExpr)
if err != nil {
return nil, err
}
return &cronTicker{
expr: expr,
ticker: make(chan time.Time),
closing: make(chan struct{}),
}, nil
}
func (c *cronTicker) Start() <-chan time.Time {
c.wg.Add(1)
go func() {
defer c.wg.Done()
for {
now := time.Now()
next := c.expr.Next(now)
diff := next.Sub(now)
select {
case <-time.After(diff):
c.ticker <- next
case <-c.closing:
return
}
}
}()
return c.ticker
}
func (c *cronTicker) Stop() {
close(c.closing)
c.wg.Wait()
}
func (c *cronTicker) Next(now time.Time) time.Time {
return c.expr.Next(now)
}