forked from robyoung/go-whisper
-
Notifications
You must be signed in to change notification settings - Fork 9
/
whisper.go
1121 lines (967 loc) · 28.1 KB
/
whisper.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 whisper implements Graphite's Whisper database format
*/
package whisper
import (
"encoding/binary"
"errors"
"fmt"
"math"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
const (
IntSize = 4
FloatSize = 4
Float64Size = 8
PointSize = 12
MetadataSize = 16
ArchiveInfoSize = 12
)
const (
Seconds = 1
Minutes = 60
Hours = 3600
Days = 86400
Weeks = 86400 * 7
Years = 86400 * 365
)
type AggregationMethod int
const (
Average AggregationMethod = iota + 1
Sum
Last
Max
Min
)
type Options struct {
Sparse bool
}
func unitMultiplier(s string) (int, error) {
switch {
case strings.HasPrefix(s, "s"):
return Seconds, nil
case strings.HasPrefix(s, "m"):
return Minutes, nil
case strings.HasPrefix(s, "h"):
return Hours, nil
case strings.HasPrefix(s, "d"):
return Days, nil
case strings.HasPrefix(s, "w"):
return Weeks, nil
case strings.HasPrefix(s, "y"):
return Years, nil
}
return 0, fmt.Errorf("Invalid unit multiplier [%v]", s)
}
var retentionRegexp *regexp.Regexp = regexp.MustCompile("^(\\d+)([smhdwy]+)$")
func parseRetentionPart(retentionPart string) (int, error) {
part, err := strconv.ParseInt(retentionPart, 10, 32)
if err == nil {
return int(part), nil
}
if !retentionRegexp.MatchString(retentionPart) {
return 0, fmt.Errorf("%v", retentionPart)
}
matches := retentionRegexp.FindStringSubmatch(retentionPart)
value, err := strconv.ParseInt(matches[1], 10, 32)
if err != nil {
panic(fmt.Sprintf("Regex on %v is borked, %v cannot be parsed as int", retentionPart, matches[1]))
}
multiplier, err := unitMultiplier(matches[2])
return multiplier * int(value), err
}
/*
Parse a retention definition as you would find in the storage-schemas.conf of a Carbon install.
Note that this only parses a single retention definition, if you have multiple definitions (separated by a comma)
you will have to split them yourself.
ParseRetentionDef("10s:14d") Retention{10, 120960}
See: http://graphite.readthedocs.org/en/1.0/config-carbon.html#storage-schemas-conf
*/
func ParseRetentionDef(retentionDef string) (*Retention, error) {
parts := strings.Split(retentionDef, ":")
if len(parts) != 2 {
return nil, fmt.Errorf("Not enough parts in retentionDef [%v]", retentionDef)
}
precision, err := parseRetentionPart(parts[0])
if err != nil {
return nil, fmt.Errorf("Failed to parse precision: %v", err)
}
points, err := parseRetentionPart(parts[1])
if err != nil {
return nil, fmt.Errorf("Failed to parse points: %v", err)
}
points /= precision
return &Retention{precision, points}, err
}
func ParseRetentionDefs(retentionDefs string) (Retentions, error) {
retentions := make(Retentions, 0)
for _, retentionDef := range strings.Split(retentionDefs, ",") {
retention, err := ParseRetentionDef(retentionDef)
if err != nil {
return nil, err
}
retentions = append(retentions, retention)
}
return retentions, nil
}
/*
Represents a Whisper database file.
*/
type Whisper struct {
file *os.File
// Metadata
aggregationMethod AggregationMethod
maxRetention int
xFilesFactor float32
archives []*archiveInfo
}
// Wrappers for whisper.file operations
func (whisper *Whisper) fileWriteAt(b []byte, off int64) error {
_, err := whisper.file.WriteAt(b, off)
return err
}
// Wrappers for file.ReadAt operations
func (whisper *Whisper) fileReadAt(b []byte, off int64) error {
_, err := whisper.file.ReadAt(b, off)
return err
}
/*
Create a new Whisper database file and write it's header.
*/
func Create(path string, retentions Retentions, aggregationMethod AggregationMethod, xFilesFactor float32) (whisper *Whisper, err error) {
return CreateWithOptions(path, retentions, aggregationMethod, xFilesFactor, &Options{
Sparse: false,
})
}
// CreateWithOptions is more customizable create function
func CreateWithOptions(path string, retentions Retentions, aggregationMethod AggregationMethod, xFilesFactor float32, options *Options) (whisper *Whisper, err error) {
if options == nil {
options = &Options{}
}
sort.Sort(retentionsByPrecision{retentions})
if err = validateRetentions(retentions); err != nil {
return nil, err
}
_, err = os.Stat(path)
if err == nil {
return nil, os.ErrExist
}
file, err := os.Create(path)
if err != nil {
return nil, err
}
whisper = new(Whisper)
// Set the metadata
whisper.file = file
whisper.aggregationMethod = aggregationMethod
whisper.xFilesFactor = xFilesFactor
for _, retention := range retentions {
if retention.MaxRetention() > whisper.maxRetention {
whisper.maxRetention = retention.MaxRetention()
}
}
// Set the archive info
offset := MetadataSize + (ArchiveInfoSize * len(retentions))
whisper.archives = make([]*archiveInfo, 0, len(retentions))
for _, retention := range retentions {
whisper.archives = append(whisper.archives, &archiveInfo{*retention, offset})
offset += retention.Size()
}
err = whisper.writeHeader()
if err != nil {
return nil, err
}
// pre-allocate file size, fallocate proved slower
if options.Sparse {
if _, err = whisper.file.Seek(int64(whisper.Size()-1), 0); err != nil {
return nil, err
}
if _, err = whisper.file.Write([]byte{0}); err != nil {
return nil, err
}
} else {
remaining := whisper.Size() - whisper.MetadataSize()
chunkSize := 16384
zeros := make([]byte, chunkSize)
for remaining > chunkSize {
if _, err = whisper.file.Write(zeros); err != nil {
return nil, err
}
remaining -= chunkSize
}
if _, err = whisper.file.Write(zeros[:remaining]); err != nil {
return nil, err
}
}
// whisper.file.Sync()
return whisper, nil
}
func validateRetentions(retentions Retentions) error {
if len(retentions) == 0 {
return fmt.Errorf("No retentions")
}
for i, retention := range retentions {
if i == len(retentions)-1 {
break
}
nextRetention := retentions[i+1]
if !(retention.secondsPerPoint < nextRetention.secondsPerPoint) {
return fmt.Errorf("A Whisper database may not be configured having two archives with the same precision (archive%v: %v, archive%v: %v)", i, retention, i+1, nextRetention)
}
if mod(nextRetention.secondsPerPoint, retention.secondsPerPoint) != 0 {
return fmt.Errorf("Higher precision archives' precision must evenly divide all lower precision archives' precision (archive%v: %v, archive%v: %v)", i, retention.secondsPerPoint, i+1, nextRetention.secondsPerPoint)
}
if retention.MaxRetention() >= nextRetention.MaxRetention() {
return fmt.Errorf("Lower precision archives must cover larger time intervals than higher precision archives (archive%v: %v seconds, archive%v: %v seconds)", i, retention.MaxRetention(), i+1, nextRetention.MaxRetention())
}
if retention.numberOfPoints < (nextRetention.secondsPerPoint / retention.secondsPerPoint) {
return fmt.Errorf("Each archive must have at least enough points to consolidate to the next archive (archive%v consolidates %v of archive%v's points but it has only %v total points)", i+1, nextRetention.secondsPerPoint/retention.secondsPerPoint, i, retention.numberOfPoints)
}
}
return nil
}
/*
Open an existing Whisper database and read it's header
*/
func Open(path string) (whisper *Whisper, err error) {
file, err := os.OpenFile(path, os.O_RDWR, 0666)
if err != nil {
return
}
defer func() {
if err != nil {
whisper = nil
file.Close()
}
}()
whisper = new(Whisper)
whisper.file = file
offset := 0
// read the metadata
b := make([]byte, MetadataSize)
readed, err := file.Read(b)
if err != nil {
err = fmt.Errorf("Unable to read header: %s", err.Error())
return
}
if readed != MetadataSize {
err = fmt.Errorf("Unable to read header: EOF")
return
}
a := unpackInt(b[offset : offset+IntSize])
if a > 1024 { // support very old format. File starts with lastUpdate and has only average aggregation method
whisper.aggregationMethod = Average
} else {
whisper.aggregationMethod = AggregationMethod(a)
}
offset += IntSize
whisper.maxRetention = unpackInt(b[offset : offset+IntSize])
offset += IntSize
whisper.xFilesFactor = unpackFloat32(b[offset : offset+FloatSize])
offset += FloatSize
archiveCount := unpackInt(b[offset : offset+IntSize])
offset += IntSize
// read the archive info
b = make([]byte, ArchiveInfoSize)
whisper.archives = make([]*archiveInfo, 0)
for i := 0; i < archiveCount; i++ {
readed, err = file.Read(b)
if err != nil || readed != ArchiveInfoSize {
err = fmt.Errorf("Unable to read archive %d metadata", i)
return
}
whisper.archives = append(whisper.archives, unpackArchiveInfo(b))
}
return whisper, nil
}
func (whisper *Whisper) writeHeader() (err error) {
b := make([]byte, whisper.MetadataSize())
i := 0
i += packInt(b, int(whisper.aggregationMethod), i)
i += packInt(b, whisper.maxRetention, i)
i += packFloat32(b, whisper.xFilesFactor, i)
i += packInt(b, len(whisper.archives), i)
for _, archive := range whisper.archives {
i += packInt(b, archive.offset, i)
i += packInt(b, archive.secondsPerPoint, i)
i += packInt(b, archive.numberOfPoints, i)
}
_, err = whisper.file.Write(b)
return err
}
/*
Close the whisper file
*/
func (whisper *Whisper) Close() {
whisper.file.Close()
}
/*
Calculate the total number of bytes the Whisper file should be according to the metadata.
*/
func (whisper *Whisper) Size() int {
size := whisper.MetadataSize()
for _, archive := range whisper.archives {
size += archive.Size()
}
return size
}
/*
Calculate the number of bytes the metadata section will be.
*/
func (whisper *Whisper) MetadataSize() int {
return MetadataSize + (ArchiveInfoSize * len(whisper.archives))
}
/* Return aggregation method */
func (whisper *Whisper) AggregationMethod() string {
aggr := "unknown"
switch whisper.aggregationMethod {
case Average:
aggr = "Average"
case Sum:
aggr = "Sum"
case Last:
aggr = "Last"
case Max:
aggr = "Max"
case Min:
aggr = "Min"
}
return aggr
}
/* Return max retention in seconds */
func (whisper *Whisper) MaxRetention() int {
return whisper.maxRetention
}
/* Return xFilesFactor */
func (whisper *Whisper) XFilesFactor() float32 {
return whisper.xFilesFactor
}
/* Return retentions */
func (whisper *Whisper) Retentions() []Retention {
ret := make([]Retention, 0, 4)
for _, archive := range whisper.archives {
ret = append(ret, archive.Retention)
}
return ret
}
/*
Update a value in the database.
If the timestamp is in the future or outside of the maximum retention it will
fail immediately.
*/
func (whisper *Whisper) Update(value float64, timestamp int) (err error) {
// recover panics and return as error
defer func() {
if e := recover(); e != nil {
err = errors.New(e.(string))
}
}()
diff := int(time.Now().Unix()) - timestamp
if !(diff < whisper.maxRetention && diff >= 0) {
return fmt.Errorf("Timestamp not covered by any archives in this database")
}
var archive *archiveInfo
var lowerArchives []*archiveInfo
var i int
for i, archive = range whisper.archives {
if archive.MaxRetention() < diff {
continue
}
lowerArchives = whisper.archives[i+1:] // TODO: investigate just returning the positions
break
}
myInterval := timestamp - mod(timestamp, archive.secondsPerPoint)
point := dataPoint{myInterval, value}
_, err = whisper.file.WriteAt(point.Bytes(), whisper.getPointOffset(myInterval, archive))
if err != nil {
return err
}
higher := archive
for _, lower := range lowerArchives {
propagated, err := whisper.propagate(myInterval, higher, lower)
if err != nil {
return err
} else if !propagated {
break
}
higher = lower
}
return nil
}
func reversePoints(points []*TimeSeriesPoint) {
size := len(points)
end := size / 2
for i := 0; i < end; i++ {
points[i], points[size-i-1] = points[size-i-1], points[i]
}
}
func (whisper *Whisper) UpdateMany(points []*TimeSeriesPoint) (err error) {
// recover panics and return as error
defer func() {
if e := recover(); e != nil {
err = errors.New(e.(string))
}
}()
// sort the points, newest first
reversePoints(points)
sort.Stable(timeSeriesPointsNewestFirst{points})
now := int(time.Now().Unix()) // TODO: danger of 2030 something overflow
var currentPoints []*TimeSeriesPoint
for _, archive := range whisper.archives {
currentPoints, points = extractPoints(points, now, archive.MaxRetention())
if len(currentPoints) == 0 {
continue
}
// reverse currentPoints
reversePoints(currentPoints)
err = whisper.archiveUpdateMany(archive, currentPoints)
if err != nil {
return
}
if len(points) == 0 { // nothing left to do
break
}
}
return
}
func (whisper *Whisper) archiveUpdateMany(archive *archiveInfo, points []*TimeSeriesPoint) error {
alignedPoints := alignPoints(archive, points)
intervals, packedBlocks := packSequences(archive, alignedPoints)
baseInterval := whisper.getBaseInterval(archive)
if baseInterval == 0 {
baseInterval = intervals[0]
}
for i := range intervals {
myOffset := archive.PointOffset(baseInterval, intervals[i])
bytesBeyond := int(myOffset-archive.End()) + len(packedBlocks[i])
if bytesBeyond > 0 {
pos := len(packedBlocks[i]) - bytesBeyond
err := whisper.fileWriteAt(packedBlocks[i][:pos], myOffset)
if err != nil {
return err
}
err = whisper.fileWriteAt(packedBlocks[i][pos:], archive.Offset())
if err != nil {
return err
}
} else {
err := whisper.fileWriteAt(packedBlocks[i], myOffset)
if err != nil {
return err
}
}
}
higher := archive
lowerArchives := whisper.lowerArchives(archive)
for _, lower := range lowerArchives {
seen := make(map[int]bool)
propagateFurther := false
for _, point := range alignedPoints {
interval := point.interval - mod(point.interval, lower.secondsPerPoint)
if !seen[interval] {
if propagated, err := whisper.propagate(interval, higher, lower); err != nil {
panic("Failed to propagate")
} else if propagated {
propagateFurther = true
}
}
}
if !propagateFurther {
break
}
higher = lower
}
return nil
}
func extractPoints(points []*TimeSeriesPoint, now int, maxRetention int) (currentPoints []*TimeSeriesPoint, remainingPoints []*TimeSeriesPoint) {
maxAge := now - maxRetention
for i, point := range points {
if point.Time < maxAge {
if i > 0 {
return points[:i-1], points[i-1:]
} else {
return []*TimeSeriesPoint{}, points
}
}
}
return points, remainingPoints
}
func alignPoints(archive *archiveInfo, points []*TimeSeriesPoint) []dataPoint {
alignedPoints := make([]dataPoint, 0, len(points))
positions := make(map[int]int)
for _, point := range points {
dPoint := dataPoint{point.Time - mod(point.Time, archive.secondsPerPoint), point.Value}
if p, ok := positions[dPoint.interval]; ok {
alignedPoints[p] = dPoint
} else {
alignedPoints = append(alignedPoints, dPoint)
positions[dPoint.interval] = len(alignedPoints) - 1
}
}
return alignedPoints
}
func packSequences(archive *archiveInfo, points []dataPoint) (intervals []int, packedBlocks [][]byte) {
intervals = make([]int, 0)
packedBlocks = make([][]byte, 0)
for i, point := range points {
if i == 0 || point.interval != intervals[len(intervals)-1]+archive.secondsPerPoint {
intervals = append(intervals, point.interval)
packedBlocks = append(packedBlocks, point.Bytes())
} else {
packedBlocks[len(packedBlocks)-1] = append(packedBlocks[len(packedBlocks)-1], point.Bytes()...)
}
}
return
}
/*
Calculate the offset for a given interval in an archive
This method retrieves the baseInterval and the
*/
func (whisper *Whisper) getPointOffset(start int, archive *archiveInfo) int64 {
baseInterval := whisper.getBaseInterval(archive)
if baseInterval == 0 {
return archive.Offset()
}
return archive.PointOffset(baseInterval, start)
}
func (whisper *Whisper) getBaseInterval(archive *archiveInfo) int {
baseInterval, err := whisper.readInt(archive.Offset())
if err != nil {
panic("Failed to read baseInterval")
}
return baseInterval
}
func (whisper *Whisper) lowerArchives(archive *archiveInfo) (lowerArchives []*archiveInfo) {
for i, lower := range whisper.archives {
if lower.secondsPerPoint > archive.secondsPerPoint {
return whisper.archives[i:]
}
}
return
}
func (whisper *Whisper) propagate(timestamp int, higher, lower *archiveInfo) (bool, error) {
lowerIntervalStart := timestamp - mod(timestamp, lower.secondsPerPoint)
higherFirstOffset := whisper.getPointOffset(lowerIntervalStart, higher)
// TODO: extract all this series extraction stuff
higherPoints := lower.secondsPerPoint / higher.secondsPerPoint
higherSize := higherPoints * PointSize
relativeFirstOffset := higherFirstOffset - higher.Offset()
relativeLastOffset := int64(mod(int(relativeFirstOffset+int64(higherSize)), higher.Size()))
higherLastOffset := relativeLastOffset + higher.Offset()
series, err := whisper.readSeries(higherFirstOffset, higherLastOffset, higher)
if err != nil {
return false, err
}
// and finally we construct a list of values
knownValues := make([]float64, 0, len(series))
currentInterval := lowerIntervalStart
for _, dPoint := range series {
if dPoint.interval == currentInterval {
knownValues = append(knownValues, dPoint.value)
}
currentInterval += higher.secondsPerPoint
}
// propagate aggregateValue to propagate from neighborValues if we have enough known points
if len(knownValues) == 0 {
return false, nil
}
knownPercent := float32(len(knownValues)) / float32(len(series))
if knownPercent < whisper.xFilesFactor { // check we have enough data points to propagate a value
return false, nil
} else {
aggregateValue := aggregate(whisper.aggregationMethod, knownValues)
point := dataPoint{lowerIntervalStart, aggregateValue}
if _, err := whisper.file.WriteAt(point.Bytes(), whisper.getPointOffset(lowerIntervalStart, lower)); err != nil {
return false, err
}
}
return true, nil
}
func (whisper *Whisper) readSeries(start, end int64, archive *archiveInfo) ([]dataPoint, error) {
var b []byte
if start < end {
b = make([]byte, end-start)
err := whisper.fileReadAt(b, start)
if err != nil {
return nil, err
}
} else {
b = make([]byte, archive.End()-start)
err := whisper.fileReadAt(b, start)
if err != nil {
return nil, err
}
b2 := make([]byte, end-archive.Offset())
err = whisper.fileReadAt(b2, archive.Offset())
if err != nil {
return nil, err
}
b = append(b, b2...)
}
return unpackDataPoints(b), nil
}
func (whisper *Whisper) checkSeriesEmpty(start, end int64, archive *archiveInfo, fromTime, untilTime int) (bool, error) {
if start < end {
len := end - start
return whisper.checkSeriesEmptyAt(start, len, fromTime, untilTime)
}
len := archive.End() - start
empty, err := whisper.checkSeriesEmptyAt(start, len, fromTime, untilTime)
if err != nil || !empty {
return empty, err
}
return whisper.checkSeriesEmptyAt(archive.Offset(), end-archive.Offset(), fromTime, untilTime)
}
func (whisper *Whisper) checkSeriesEmptyAt(start, len int64, fromTime, untilTime int) (bool, error) {
b1 := make([]byte, 4)
// Read first point
err := whisper.fileReadAt(b1, start)
if err != nil {
return false, err
}
pointTime := unpackInt(b1)
if pointTime > fromTime && pointTime < untilTime {
return false, nil
}
b2 := make([]byte, 4)
// Read last point
err = whisper.fileReadAt(b2, len-12)
if err != nil {
return false, err
}
pointTime = unpackInt(b1)
if pointTime > fromTime && pointTime < untilTime {
return false, nil
}
return true, nil
}
/*
Calculate the starting time for a whisper db.
*/
func (whisper *Whisper) StartTime() int {
now := int(time.Now().Unix()) // TODO: danger of 2030 something overflow
return now - whisper.maxRetention
}
/*
Fetch a TimeSeries for a given time span from the file.
*/
func (whisper *Whisper) Fetch(fromTime, untilTime int) (timeSeries *TimeSeries, err error) {
now := int(time.Now().Unix()) // TODO: danger of 2030 something overflow
if fromTime > untilTime {
return nil, fmt.Errorf("Invalid time interval: from time '%d' is after until time '%d'", fromTime, untilTime)
}
oldestTime := whisper.StartTime()
// range is in the future
if fromTime > now {
return nil, nil
}
// range is beyond retention
if untilTime < oldestTime {
return nil, nil
}
if fromTime < oldestTime {
fromTime = oldestTime
}
if untilTime > now {
untilTime = now
}
// TODO: improve this algorithm it's ugly
diff := now - fromTime
var archive *archiveInfo
for _, archive = range whisper.archives {
if archive.MaxRetention() >= diff {
break
}
}
fromInterval := archive.Interval(fromTime)
untilInterval := archive.Interval(untilTime)
baseInterval := whisper.getBaseInterval(archive)
if baseInterval == 0 {
step := archive.secondsPerPoint
points := (untilInterval - fromInterval) / step
values := make([]float64, points)
for i := range values {
values[i] = math.NaN()
}
return &TimeSeries{fromInterval, untilInterval, step, values}, nil
}
// Zero-length time range: always include the next point
if fromInterval == untilInterval {
untilInterval += archive.SecondsPerPoint()
}
fromOffset := archive.PointOffset(baseInterval, fromInterval)
untilOffset := archive.PointOffset(baseInterval, untilInterval)
series, err := whisper.readSeries(fromOffset, untilOffset, archive)
if err != nil {
return nil, err
}
values := make([]float64, len(series))
for i := range values {
values[i] = math.NaN()
}
currentInterval := fromInterval
step := archive.secondsPerPoint
for i, dPoint := range series {
if dPoint.interval == currentInterval {
values[i] = dPoint.value
}
currentInterval += step
}
return &TimeSeries{fromInterval, untilInterval, step, values}, nil
}
/*
Check a TimeSeries has a points for a given time span from the file.
*/
func (whisper *Whisper) CheckEmpty(fromTime, untilTime int) (exist bool, err error) {
now := int(time.Now().Unix()) // TODO: danger of 2030 something overflow
if fromTime > untilTime {
return true, fmt.Errorf("Invalid time interval: from time '%d' is after until time '%d'", fromTime, untilTime)
}
oldestTime := whisper.StartTime()
// range is in the future
if fromTime > now {
return true, nil
}
// range is beyond retention
if untilTime < oldestTime {
return true, nil
}
if fromTime < oldestTime {
fromTime = oldestTime
}
if untilTime > now {
untilTime = now
}
// TODO: improve this algorithm it's ugly
diff := now - fromTime
var archive *archiveInfo
for _, archive = range whisper.archives {
fromInterval := archive.Interval(fromTime)
untilInterval := archive.Interval(untilTime)
baseInterval := whisper.getBaseInterval(archive)
if baseInterval == 0 {
return true, nil
}
// Zero-length time range: always include the next point
if fromInterval == untilInterval {
untilInterval += archive.SecondsPerPoint()
}
fromOffset := archive.PointOffset(baseInterval, fromInterval)
untilOffset := archive.PointOffset(baseInterval, untilInterval)
empty, err := whisper.checkSeriesEmpty(fromOffset, untilOffset, archive, fromTime, untilTime)
if err != nil || !empty {
return empty, err
}
if archive.MaxRetention() >= diff {
break
}
}
return true, nil
}
func (whisper *Whisper) readInt(offset int64) (int, error) {
// TODO: make errors better
b := make([]byte, IntSize)
_, err := whisper.file.ReadAt(b, offset)
if err != nil {
return 0, err
}
return unpackInt(b), nil
}
/*
A retention level.
Retention levels describe a given archive in the database. How detailed it is and how far back
it records.
*/
type Retention struct {
secondsPerPoint int
numberOfPoints int
}
func (retention *Retention) MaxRetention() int {
return retention.secondsPerPoint * retention.numberOfPoints
}
func (retention *Retention) Size() int {
return retention.numberOfPoints * PointSize
}
func (retention *Retention) SecondsPerPoint() int {
return retention.secondsPerPoint
}
func (retention *Retention) NumberOfPoints() int {
return retention.numberOfPoints
}
func NewRetention(secondsPerPoint, numberOfPoints int) Retention {
return Retention{
secondsPerPoint,
numberOfPoints,
}
}
type Retentions []*Retention
func (r Retentions) Len() int {
return len(r)
}
func (r Retentions) Swap(i, j int) {
r[i], r[j] = r[j], r[i]
}
type retentionsByPrecision struct{ Retentions }
func (r retentionsByPrecision) Less(i, j int) bool {
return r.Retentions[i].secondsPerPoint < r.Retentions[j].secondsPerPoint
}
/*
Describes a time series in a file.
The only addition this type has over a Retention is the offset at which it exists within the
whisper file.
*/
type archiveInfo struct {
Retention
offset int
}
func (archive *archiveInfo) Offset() int64 {
return int64(archive.offset)
}
func (archive *archiveInfo) PointOffset(baseInterval, interval int) int64 {
timeDistance := interval - baseInterval
pointDistance := timeDistance / archive.secondsPerPoint
byteDistance := pointDistance * PointSize
myOffset := archive.Offset() + int64(mod(byteDistance, archive.Size()))
return myOffset
}
func (archive *archiveInfo) End() int64 {
return archive.Offset() + int64(archive.Size())
}
func (archive *archiveInfo) Interval(time int) int {
return time - mod(time, archive.secondsPerPoint) + archive.secondsPerPoint
}
type TimeSeries struct {
fromTime int
untilTime int
step int
values []float64
}
func (ts *TimeSeries) FromTime() int {
return ts.fromTime
}
func (ts *TimeSeries) UntilTime() int {
return ts.untilTime
}
func (ts *TimeSeries) Step() int {
return ts.step
}
func (ts *TimeSeries) Values() []float64 {
return ts.values
}
func (ts *TimeSeries) Points() []TimeSeriesPoint {
points := make([]TimeSeriesPoint, len(ts.values))
for i, value := range ts.values {
points[i] = TimeSeriesPoint{Time: ts.fromTime + ts.step*i, Value: value}
}
return points
}
func (ts *TimeSeries) String() string {
return fmt.Sprintf("TimeSeries{'%v' '%-v' %v %v}", time.Unix(int64(ts.fromTime), 0), time.Unix(int64(ts.untilTime), 0), ts.step, ts.values)
}