forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.go
1327 lines (1133 loc) · 31.2 KB
/
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
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package influxql
import (
"encoding/binary"
"errors"
"fmt"
"hash/fnv"
"math"
"sort"
"strings"
"time"
)
// how many values we will map before emitting
const emitBatchSize = 1000
// DB represents an interface for creating transactions.
type DB interface {
Begin() (Tx, error)
}
// Tx represents a transaction.
// The Tx must be opened before being used.
type Tx interface {
// Opens and closes the transaction.
Open() error
Close() error
// SetNow sets the current time to be used throughout the transaction.
SetNow(time.Time)
// Creates a list of iterators for a simple select statement.
//
// The statement must adhere to the following rules:
// 1. It can only have a single VarRef field.
// 2. It can only have a single source measurement.
CreateIterators(*SelectStatement) ([]Iterator, error)
// DecodeValues is for use in a raw data query
DecodeValues(fieldIDs []uint8, timestamp int64, data []byte) []interface{}
// FieldIDs will take an array of fields and return the id associated with each
FieldIDs(fields []*Field) ([]uint8, error)
}
// Iterator represents a forward-only iterator over a set of points.
type Iterator interface {
// Tags returns the encoded dimensional tag values.
Tags() string
// Next returns the next value from the iterator.
Next() (key int64, data []byte, value interface{})
}
// Planner represents an object for creating execution plans.
type Planner struct {
DB DB
// Returns the current time. Defaults to time.Now().
Now func() time.Time
}
// NewPlanner returns a new instance of Planner.
func NewPlanner(db DB) *Planner {
return &Planner{
DB: db,
Now: time.Now,
}
}
// Plan creates an execution plan for the given SelectStatement and returns an Executor.
func (p *Planner) Plan(stmt *SelectStatement) (*Executor, error) {
now := p.Now().UTC()
// Clone the statement to be planned.
// Replace instances of "now()" with the current time.
stmt = stmt.Clone()
stmt.Condition = Reduce(stmt.Condition, &nowValuer{Now: now})
// Begin an unopened transaction.
tx, err := p.DB.Begin()
if err != nil {
return nil, err
}
// Create the executor.
e := newExecutor(tx, stmt)
// Determine group by tag keys.
interval, tags, err := stmt.Dimensions.Normalize()
if err != nil {
return nil, err
}
e.interval = interval
e.tags = tags
// Generate a processor for each field.
e.processors = make([]Processor, 0)
if v, ok := stmt.Fields[0].Expr.(*VarRef); ok { // this is a raw query so we handle it differently
proc, err := p.planRawQuery(e, v)
if err != nil {
return nil, err
}
e.processors = append(e.processors, proc)
} else {
for _, f := range stmt.Fields {
p, err := p.planField(e, f)
if err != nil {
return nil, err
}
e.processors = append(e.processors, p)
}
}
return e, nil
}
func (p *Planner) planField(e *Executor, f *Field) (Processor, error) {
return p.planExpr(e, f.Expr)
}
func (p *Planner) planExpr(e *Executor, expr Expr) (Processor, error) {
switch expr := expr.(type) {
case *VarRef:
return nil, errors.New("query has a raw field mixed with an aggregate in the select")
case *Call:
return p.planCall(e, expr)
case *BinaryExpr:
return p.planBinaryExpr(e, expr)
case *ParenExpr:
return p.planExpr(e, expr.Expr)
case *NumberLiteral:
return newLiteralProcessor(expr.Val), nil
case *StringLiteral:
return newLiteralProcessor(expr.Val), nil
case *BooleanLiteral:
return newLiteralProcessor(expr.Val), nil
case *TimeLiteral:
return newLiteralProcessor(expr.Val), nil
case *DurationLiteral:
return newLiteralProcessor(expr.Val), nil
}
panic("unreachable")
}
// planCall generates a processor for a function call.
func (p *Planner) planRawQuery(e *Executor, v *VarRef) (Processor, error) {
stmt := e.stmt
stmt.RawQuery = true
// Retrieve a list of iterators for the substatement.
itrs, err := e.tx.CreateIterators(stmt)
if err != nil {
return nil, err
}
// Verify that all the fields exist
if _, err := e.tx.FieldIDs(e.stmt.Fields); err != nil {
return nil, err
}
// Create mapper and reducer.
mappers := make([]*Mapper, len(itrs))
for i, itr := range itrs {
mappers[i] = NewMapper(MapRawQuery, itr, e.interval)
}
r := NewReducer(ReduceRawQuery, mappers)
r.name = lastIdent(stmt.Source.(*Measurement).Name)
r.isRawQuery = true
return r, nil
}
// planCall generates a processor for a function call.
func (p *Planner) planCall(e *Executor, c *Call) (Processor, error) {
// Ensure there is a single argument.
if c.Name == "percentile" {
if len(c.Args) != 2 {
return nil, fmt.Errorf("expected two arguments for percentile()")
}
} else if len(c.Args) != 1 {
return nil, fmt.Errorf("expected one argument for %s()", c.Name)
}
// Ensure the argument is a variable reference.
ref, ok := c.Args[0].(*VarRef)
if !ok {
return nil, fmt.Errorf("expected field argument in %s()", c.Name)
}
// Convert the statement to a simplified substatement for the single field.
stmt, err := e.stmt.Substatement(ref)
if err != nil {
return nil, err
}
// Retrieve a list of iterators for the substatement.
itrs, err := e.tx.CreateIterators(stmt)
if err != nil {
return nil, err
}
// Retrieve map & reduce functions by name.
var mapFn MapFunc
var reduceFn ReduceFunc
switch strings.ToLower(c.Name) {
case "count":
mapFn, reduceFn = MapCount, ReduceSum
case "sum":
mapFn, reduceFn = MapSum, ReduceSum
case "mean":
mapFn, reduceFn = MapMean, ReduceMean
case "min":
mapFn, reduceFn = MapMin, ReduceMin
case "max":
mapFn, reduceFn = MapMax, ReduceMax
case "spread":
mapFn, reduceFn = MapSpread, ReduceSpread
case "stddev":
mapFn, reduceFn = MapStddev, ReduceStddev
case "first":
mapFn, reduceFn = MapFirst, ReduceFirst
case "last":
mapFn, reduceFn = MapLast, ReduceLast
case "percentile":
lit, ok := c.Args[1].(*NumberLiteral)
if !ok {
return nil, fmt.Errorf("expected float argument in percentile()")
}
mapFn, reduceFn = MapEcho, ReducePercentile(lit.Val)
default:
return nil, fmt.Errorf("function not found: %q", c.Name)
}
// Create mapper and reducer.
mappers := make([]*Mapper, len(itrs))
for i, itr := range itrs {
mappers[i] = NewMapper(mapFn, itr, e.interval)
}
r := NewReducer(reduceFn, mappers)
r.name = lastIdent(stmt.Source.(*Measurement).Name)
return r, nil
}
// planBinaryExpr generates a processor for a binary expression.
// A binary expression represents a join operator between two processors.
func (p *Planner) planBinaryExpr(e *Executor, expr *BinaryExpr) (Processor, error) {
// Create processor for LHS.
lhs, err := p.planExpr(e, expr.LHS)
if err != nil {
return nil, fmt.Errorf("lhs: %s", err)
}
// Create processor for RHS.
rhs, err := p.planExpr(e, expr.RHS)
if err != nil {
return nil, fmt.Errorf("rhs: %s", err)
}
// Combine processors.
return newBinaryExprEvaluator(e, expr.Op, lhs, rhs), nil
}
// Executor represents the implementation of Executor.
// It executes all reducers and combines their result into a row.
type Executor struct {
tx Tx // transaction
stmt *SelectStatement // original statement
processors []Processor // per-field processors
interval time.Duration // group by interval
tags []string // dimensional tag keys
}
// newExecutor returns an executor associated with a transaction and statement.
func newExecutor(tx Tx, stmt *SelectStatement) *Executor {
return &Executor{
tx: tx,
stmt: stmt,
}
}
// Execute begins execution of the query and returns a channel to receive rows.
func (e *Executor) Execute() (<-chan *Row, error) {
// Open transaction.
if err := e.tx.Open(); err != nil {
return nil, err
}
// Initialize processors.
for _, p := range e.processors {
p.Process()
}
// Create output channel and stream data in a separate goroutine.
out := make(chan *Row, 0)
go e.execute(out)
return out, nil
}
// execute runs in a separate separate goroutine and streams data from processors.
func (e *Executor) execute(out chan *Row) {
// Ensure the transaction closes after execution.
defer e.tx.Close()
// TODO: Support multi-value rows.
// Initialize map of rows by encoded tagset.
rows := make(map[string]*Row)
var fieldIDs []uint8
isRaw := e.processors[0].IsRawQuery()
if isRaw {
fieldIDs, _ = e.tx.FieldIDs(e.stmt.Fields)
}
// Combine values from each processor.
loop:
for {
// Retrieve values from processors and write them to the approprite
// row based on their tagset.
for i, p := range e.processors {
// Retrieve data from the processor.
m, ok := <-p.C()
if !ok {
break loop
}
// Set values on returned row.
for k, v := range m {
// Lookup row values and populate data.
row, values := e.createRowValuesIfNotExists(rows, e.processors[0].Name(), k.Timestamp, k.Values)
if isRaw {
vv := v.([]*rawQueryMapOutput)
vals := make([][]interface{}, len(vv))
for i, val := range vv {
vals[i] = e.tx.DecodeValues(fieldIDs, val.timestamp, val.data)
}
row.Values = vals
} else {
values[i+1] = v
}
}
}
}
// Normalize rows and values.
// Convert all times to timestamps
a := make(Rows, 0, len(rows))
for _, row := range rows {
for _, values := range row.Values {
t := time.Unix(0, values[0].(int64))
values[0] = t.UTC()
}
a = append(a, row)
}
sort.Sort(a)
// Send rows to the channel.
for _, row := range a {
out <- row
}
// Mark the end of the output channel.
close(out)
}
// creates a new value set if one does not already exist for a given tagset + timestamp.
func (e *Executor) createRowValuesIfNotExists(rows map[string]*Row, name string, timestamp int64, tagset string) (*Row, []interface{}) {
// TODO: Add "name" to lookup key.
// Find row by tagset.
var row *Row
if row = rows[tagset]; row == nil {
row = &Row{Name: name}
// Create tag map.
row.Tags = make(map[string]string)
for i, v := range UnmarshalStrings([]byte(tagset)) {
row.Tags[e.tags[i]] = v
}
// Create column names.
row.Columns = make([]string, 1, len(e.stmt.Fields)+1)
row.Columns[0] = "time"
for i, f := range e.stmt.Fields {
name := f.Name()
if name == "" {
name = fmt.Sprintf("col%d", i)
}
row.Columns = append(row.Columns, name)
}
// Save to lookup.
rows[tagset] = row
}
// If no values exist or last value doesn't match the timestamp then create new.
if len(row.Values) == 0 || row.Values[len(row.Values)-1][0] != timestamp {
values := make([]interface{}, len(e.processors)+1)
values[0] = timestamp
row.Values = append(row.Values, values)
}
return row, row.Values[len(row.Values)-1]
}
// Mapper represents an object for processing iterators.
type Mapper struct {
fn MapFunc // map function
itr Iterator // iterators
interval int64 // grouping interval
}
// NewMapper returns a new instance of Mapper with a given function and interval.
func NewMapper(fn MapFunc, itr Iterator, interval time.Duration) *Mapper {
return &Mapper{
fn: fn,
itr: itr,
interval: interval.Nanoseconds(),
}
}
// Map executes the mapper's function against the iterator.
// Returns a nil emitter if no data was found.
func (m *Mapper) Map() *Emitter {
e := NewEmitter(1)
go m.run(e)
return e
}
func (m *Mapper) run(e *Emitter) {
// Close emitter when we're done.
defer func() { _ = e.Close() }()
// Wrap iterator with buffer.
bufItr := &bufIterator{itr: m.itr}
// Determine the start time.
var tmin int64
if m.interval > 0 {
// Align start time to interval.
tmin, _, _ = bufItr.Peek()
tmin -= (tmin % m.interval)
}
for {
// Set the upper bound of the interval.
if m.interval > 0 {
bufItr.tmax = tmin + m.interval - 1
}
// Exit if there was only one interval or no more data is available.
if bufItr.EOF() {
break
}
// Execute the map function.
m.fn(bufItr, e, tmin)
// Move the interval forward.
tmin += m.interval
}
}
// bufIterator represents a buffer iterator.
type bufIterator struct {
itr Iterator // underlying iterator
tmax int64 // maximum key
buf struct {
key int64
data []byte
value interface{}
}
buffered bool
}
// Tags returns the encoded dimensional values for the iterator.
func (i *bufIterator) Tags() string { return i.itr.Tags() }
// Next returns the next key/value pair from the iterator.
func (i *bufIterator) Next() (key int64, data []byte, value interface{}) {
// Read the key/value pair off the buffer or underlying iterator.
if i.buffered {
i.buffered = false
} else {
i.buf.key, i.buf.data, i.buf.value = i.itr.Next()
}
key, data, value = i.buf.key, i.buf.data, i.buf.value
// If key is greater than tmax then put it back on the buffer.
if i.tmax != 0 && key > i.tmax {
i.buffered = true
return 0, nil, nil
}
return key, data, value
}
// Peek returns the next key/value pair but does not move the iterator forward.
func (i *bufIterator) Peek() (key int64, data []byte, value interface{}) {
key, data, value = i.Next()
i.buffered = true
return
}
// EOF returns true if there is no more data in the underlying iterator.
func (i *bufIterator) EOF() bool { i.Peek(); return i.buf.key == 0 }
// MapFunc represents a function used for mapping iterators.
type MapFunc func(Iterator, *Emitter, int64)
// MapCount computes the number of values in an iterator.
func MapCount(itr Iterator, e *Emitter, tmin int64) {
n := 0
for k, _, _ := itr.Next(); k != 0; k, _, _ = itr.Next() {
n++
}
e.Emit(Key{tmin, itr.Tags()}, float64(n))
}
// MapSum computes the summation of values in an iterator.
func MapSum(itr Iterator, e *Emitter, tmin int64) {
n := float64(0)
for k, _, v := itr.Next(); k != 0; k, _, v = itr.Next() {
n += v.(float64)
}
e.Emit(Key{tmin, itr.Tags()}, n)
}
// Processor represents an object for joining reducer output.
type Processor interface {
Process()
Name() string
C() <-chan map[Key]interface{}
IsRawQuery() bool
}
// Reducer represents an object for processing mapper output.
// Implements processor.
type Reducer struct {
name string
fn ReduceFunc // reduce function
mappers []*Mapper // child mappersf
isRawQuery bool
c <-chan map[Key]interface{}
}
// NewReducer returns a new instance of reducer.
func NewReducer(fn ReduceFunc, mappers []*Mapper) *Reducer {
return &Reducer{
fn: fn,
mappers: mappers,
}
}
// C returns the output channel.
func (r *Reducer) C() <-chan map[Key]interface{} { return r.c }
// Name returns the source name.
func (r *Reducer) Name() string { return r.name }
// Process processes the Reducer.
func (r *Reducer) Process() { r.Reduce() }
func (r *Reducer) IsRawQuery() bool {
return r.isRawQuery
}
// Reduce executes the reducer's function against all output from the mappers.
func (r *Reducer) Reduce() *Emitter {
inputs := make([]<-chan map[Key]interface{}, len(r.mappers))
for i, m := range r.mappers {
inputs[i] = m.Map().C()
}
e := NewEmitter(1)
r.c = e.C()
go r.run(e, inputs)
return e
}
func (r *Reducer) run(e *Emitter, inputs []<-chan map[Key]interface{}) {
// Close emitter when we're done.
defer func() { _ = e.Close() }()
// Buffer all the inputs.
bufInputs := make([]*bufInput, len(inputs))
for i, input := range inputs {
bufInputs[i] = &bufInput{c: input}
}
// Stream data from the inputs and reduce.
for {
// Read all data from the inputers with the same timestamp.
timestamp := int64(0)
for _, bufInput := range bufInputs {
rec := bufInput.peek()
if rec == nil {
continue
}
if timestamp == 0 || rec.Key.Timestamp < timestamp {
timestamp = rec.Key.Timestamp
}
}
data := make(map[Key][]interface{})
for _, bufInput := range bufInputs {
for {
rec := bufInput.read()
if rec == nil {
break
}
if rec.Key.Timestamp != timestamp {
bufInput.unread(rec)
break
}
data[rec.Key] = append(data[rec.Key], rec.Value)
}
}
if len(data) == 0 {
break
}
// Sort keys.
keys := make(keySlice, 0, len(data))
for k := range data {
keys = append(keys, k)
}
sort.Sort(keys)
// Reduce each key.
for _, k := range keys {
r.fn(k, data[k], e)
}
}
}
type bufInput struct {
buf *Record
c <-chan map[Key]interface{}
}
func (i *bufInput) read() *Record {
if i.buf != nil {
rec := i.buf
i.buf = nil
return rec
}
m, _ := <-i.c
return mapToRecord(m)
}
func (i *bufInput) unread(rec *Record) { i.buf = rec }
func (i *bufInput) peek() *Record {
rec := i.read()
i.unread(rec)
return rec
}
type Record struct {
Key Key
Value interface{}
}
func mapToRecord(m map[Key]interface{}) *Record {
for k, v := range m {
return &Record{k, v}
}
return nil
}
// ReduceFunc represents a function used for reducing mapper output.
type ReduceFunc func(Key, []interface{}, *Emitter)
// ReduceSum computes the sum of values for each key.
func ReduceSum(key Key, values []interface{}, e *Emitter) {
var n float64
for _, v := range values {
n += v.(float64)
}
e.Emit(key, n)
}
// MapMean computes the count and sum of values in an iterator to be combined by the reducer.
func MapMean(itr Iterator, e *Emitter, tmin int64) {
out := &meanMapOutput{}
for k, _, v := itr.Next(); k != 0; k, _, v = itr.Next() {
out.Count++
out.Sum += v.(float64)
}
if out.Count > 0 {
e.Emit(Key{tmin, itr.Tags()}, out)
}
}
type meanMapOutput struct {
Count int
Sum float64
}
// ReduceMean computes the mean of values for each key.
func ReduceMean(key Key, values []interface{}, e *Emitter) {
out := &meanMapOutput{}
for _, v := range values {
val := v.(*meanMapOutput)
out.Count += val.Count
out.Sum += val.Sum
}
if out.Count > 0 {
e.Emit(key, out.Sum/float64(out.Count))
}
}
// MapMin collects the values to pass to the reducer
func MapMin(itr Iterator, e *Emitter, tmin int64) {
var min float64
pointsYielded := false
for k, _, v := itr.Next(); k != 0; k, _, v = itr.Next() {
val := v.(float64)
// Initialize min
if !pointsYielded {
min = val
pointsYielded = true
}
min = math.Min(min, val)
}
if pointsYielded {
e.Emit(Key{tmin, itr.Tags()}, min)
}
}
// ReduceMin computes the min of value.
func ReduceMin(key Key, values []interface{}, e *Emitter) {
var min float64
pointsYielded := false
for _, v := range values {
val := v.(float64)
// Initialize min
if !pointsYielded {
min = val
pointsYielded = true
}
m := math.Min(min, val)
min = m
}
if pointsYielded {
e.Emit(key, min)
}
}
// MapMax collects the values to pass to the reducer
func MapMax(itr Iterator, e *Emitter, tmax int64) {
var max float64
pointsYielded := false
for k, _, v := itr.Next(); k != 0; k, _, v = itr.Next() {
val := v.(float64)
// Initialize max
if !pointsYielded {
max = val
pointsYielded = true
}
max = math.Max(max, val)
}
if pointsYielded {
e.Emit(Key{tmax, itr.Tags()}, max)
}
}
// ReduceMax computes the max of value.
func ReduceMax(key Key, values []interface{}, e *Emitter) {
var max float64
pointsYielded := false
for _, v := range values {
val := v.(float64)
// Initialize max
if !pointsYielded {
max = val
pointsYielded = true
}
max = math.Max(max, val)
}
if pointsYielded {
e.Emit(key, max)
}
}
type spreadMapOutput struct {
Min, Max float64
}
// MapSpread collects the values to pass to the reducer
func MapSpread(itr Iterator, e *Emitter, tmax int64) {
var out spreadMapOutput
pointsYielded := false
for k, _, v := itr.Next(); k != 0; k, _, v = itr.Next() {
val := v.(float64)
// Initialize
if !pointsYielded {
out.Max = val
out.Min = val
pointsYielded = true
}
out.Max = math.Max(out.Max, val)
out.Min = math.Min(out.Min, val)
}
if pointsYielded {
e.Emit(Key{tmax, itr.Tags()}, out)
}
}
// ReduceSpread computes the spread of values.
func ReduceSpread(key Key, values []interface{}, e *Emitter) {
var result spreadMapOutput
pointsYielded := false
for _, v := range values {
val := v.(spreadMapOutput)
// Initialize
if !pointsYielded {
result.Max = val.Max
result.Min = val.Min
pointsYielded = true
}
result.Max = math.Max(result.Max, val.Max)
result.Min = math.Min(result.Min, val.Min)
}
if pointsYielded {
e.Emit(key, result.Max-result.Min)
}
}
// MapStddev collects the values to pass to the reducer
func MapStddev(itr Iterator, e *Emitter, tmax int64) {
var values []float64
for k, _, v := itr.Next(); k != 0; k, _, v = itr.Next() {
values = append(values, v.(float64))
// Emit in batches.
// unbounded emission of data can lead to excessive memory use
// or other potential performance problems.
if len(values) == emitBatchSize {
e.Emit(Key{tmax, itr.Tags()}, values)
values = []float64{}
}
}
if len(values) > 0 {
e.Emit(Key{tmax, itr.Tags()}, values)
}
}
// ReduceStddev computes the stddev of values.
func ReduceStddev(key Key, values []interface{}, e *Emitter) {
var data []float64
// Collect all the data points
for _, value := range values {
data = append(data, value.([]float64)...)
}
// If no data, leave
if len(data) == 0 {
return
}
// If we only have one data point, the std dev is undefined
if len(data) == 1 {
e.Emit(key, "undefined")
return
}
// Get the sum
var sum float64
for _, v := range data {
sum += v
}
// Get the mean
mean := sum / float64(len(data))
// Get the variance
var variance float64
for _, v := range data {
dif := v - mean
sq := math.Pow(dif, 2)
variance += sq
}
variance = variance / float64(len(data)-1)
stddev := math.Sqrt(variance)
e.Emit(key, stddev)
}
type firstLastMapOutput struct {
Time int64
Val interface{}
}
// MapFirst collects the values to pass to the reducer
func MapFirst(itr Iterator, e *Emitter, tmax int64) {
out := firstLastMapOutput{}
pointsYielded := false
for k, _, v := itr.Next(); k != 0; k, _, v = itr.Next() {
// Initialize first
if !pointsYielded {
out.Time = k
out.Val = v
pointsYielded = true
}
if k < out.Time {
out.Time = k
out.Val = v
}
}
if pointsYielded {
e.Emit(Key{tmax, itr.Tags()}, out)
}
}
// ReduceFirst computes the first of value.
func ReduceFirst(key Key, values []interface{}, e *Emitter) {
out := firstLastMapOutput{}
pointsYielded := false
for _, v := range values {
val := v.(firstLastMapOutput)
// Initialize first
if !pointsYielded {
out.Time = val.Time
out.Val = val.Val
pointsYielded = true
}
if val.Time < out.Time {
out.Time = val.Time
out.Val = val.Val
}
}
if pointsYielded {
e.Emit(key, out.Val)
}
}
// MapLast collects the values to pass to the reducer
func MapLast(itr Iterator, e *Emitter, tmax int64) {
out := firstLastMapOutput{}
pointsYielded := false
for k, _, v := itr.Next(); k != 0; k, _, v = itr.Next() {
// Initialize last
if !pointsYielded {
out.Time = k
out.Val = v
pointsYielded = true
}
if k > out.Time {
out.Time = k
out.Val = v
}
}
if pointsYielded {
e.Emit(Key{tmax, itr.Tags()}, out)
}
}
// ReduceLast computes the last of value.
func ReduceLast(key Key, values []interface{}, e *Emitter) {
out := firstLastMapOutput{}
pointsYielded := false
for _, v := range values {
val := v.(firstLastMapOutput)
// Initialize last
if !pointsYielded {
out.Time = val.Time
out.Val = val.Val
pointsYielded = true
}
if val.Time > out.Time {
out.Time = val.Time
out.Val = val.Val
}
}
if pointsYielded {
e.Emit(key, out.Val)
}
}
// MapEcho emits the data points for each group by interval
func MapEcho(itr Iterator, e *Emitter, tmin int64) {
var values []interface{}