forked from lomik/go-whisper
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathwhisper.go
1984 lines (1706 loc) · 51.7 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 (
"bytes"
"encoding/binary"
"errors"
"fmt"
"math"
"os"
"regexp"
"runtime/debug"
"sort"
"strconv"
"strings"
"syscall"
"time"
)
const (
// size constants
ByteSize = 1
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
)
const (
classicHeaderAggregationOffset = 0
classicHeaderXFFOffset = IntSize * 2
)
// Note: 4 bytes long in Whisper Header, 1 byte long in Archive Header
type AggregationMethod int
const Unknown AggregationMethod = -1
const (
Average AggregationMethod = iota + 1
Sum
Last
Max
Min
First
Mix // only used in whisper header
Percentile // only used in archive header
)
func (am AggregationMethod) String() string {
switch am {
case Average:
return "average"
case Sum:
return "sum"
case First:
return "first"
case Last:
return "last"
case Max:
return "max"
case Min:
return "min"
case Mix:
return "mix"
case Percentile:
return "percentile"
}
return fmt.Sprintf("%d", am)
}
func ParseAggregationMethod(am string) AggregationMethod {
switch strings.ToLower(am) {
case "average", "avg":
return Average
case "sum":
return Sum
case "first":
return First
case "last":
return Last
case "max":
return Max
case "min":
return Min
case "mix":
return Mix
case "percentile":
return Percentile
}
return Unknown
}
type Options struct {
Sparse bool
FLock bool
FlockType int
Compressed bool
// It's a hint, used if the retention is big enough, more in
// Retention.calculateSuitablePointsPerBlock
PointsPerBlock int
PointSize float32
InMemory bool
InMemoryContent []byte
OpenFileFlag *int
MixAggregationSpecs []MixAggregationSpec
MixAvgCompressedPointSizes map[int][]float32
SIMV bool // single interval multiple values
IgnoreNowOnWrite bool
}
type MixAggregationSpec struct {
Method AggregationMethod
Percentile float32
}
// a simple file interface, mainly used for testing and migration.
type file interface {
Seek(offset int64, whence int) (ret int64, err error)
Fd() uintptr
ReadAt(b []byte, off int64) (n int, err error)
WriteAt(b []byte, off int64) (n int, err error)
Read(b []byte) (n int, err error)
Name() string
Close() error
Write(b []byte) (n int, err error)
Truncate(size int64) error
}
/*
Represents a Whisper database file.
*/
type Whisper struct {
// file *os.File
file file
// Metadata
aggregationMethod AggregationMethod
maxRetention int
xFilesFactor float32
archives []*archiveInfo
compressed bool
compVersion uint8
pointsPerBlock int
avgCompressedPointSize float32
crc32 uint32
opts *Options
Extended bool
// TODO: improve
NonFatalErrors []error
discardedPointsAtOpen uint32
}
/*
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
// for compressed whisper (internal)
avgCompressedPointSize float32
blockCount int
}
/*
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
next *archiveInfo
whisper *Whisper
// NOTE: buffer design deprecated for v2 and mix
//
// why having buffer:
//
// original reasons:
// 1. less file writes per point
// 2. less file reads & no decompressions on propagation
//
// necessary reasons:
// cwhisper doesn't expect data points coming in randomly, having a buffer
// allows it to tolerate data points with different timestamp coming in
// non-increasing order for whatever reasons. But only the first/base archive
// is necessary to have it, so it's possible to optimize away buffers in lower
// archives.
buffer []byte
bufferSize int // dynamically calculated in Whisper.initMetaInfo
blockRanges []blockRange // TODO: remove: sorted by start
blockSize int
cblock blockInfo // mostly for quick block write
aggregationSpec *MixAggregationSpec
stats struct {
// interval and value stats are not saved on disk because they could be
// regenerated by scanning blocks
interval struct {
len1, len9, len12, len16, len36 uint32
}
value struct {
same, sameLen, variedLen uint32
}
extended uint32
discard struct {
oldInterval uint32
}
}
}
type blockInfo struct {
index int
crc32 uint32
p0, pn1, pn2 dataPoint // pn1/pn2: points at len(block_points) - 1/2
lastByte byte
lastByteOffset int
lastByteBitPos int
count int
}
type blockRange struct {
index int
start, end int // start and end timestamps
count int // should be named as index
crc32 uint32
}
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{secondsPerPoint: precision, numberOfPoints: 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
}
func MustParseRetentionDefs(retentionDefs string) Retentions {
rets, err := ParseRetentionDefs(retentionDefs)
if err != nil {
panic(err)
}
return rets
}
// 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,
FLock: false,
})
}
// CreateWithOptions is more customizable create function
//
// avgCompressedPointSize specification order:
//
// Options.PointSize < Retention.avgCompressedPointSize < Options.MixAggregationSpecs.AvgCompressedPointSize
func CreateWithOptions(path string, retentions Retentions, aggregationMethod AggregationMethod, xFilesFactor float32, options *Options) (whisper *Whisper, err error) {
if options == nil {
options = &Options{}
}
if aggregationMethod == Mix && !options.Compressed {
return nil, errors.New("mix aggregation method is currently supported only for compressed format")
}
sort.Sort(retentionsByPrecision{retentions})
if err = validateRetentions(retentions); err != nil {
return nil, err
}
_, err = os.Stat(path)
if err == nil {
return nil, os.ErrExist
}
var file file
if options.InMemory {
file = newMemFile(path)
err = nil
} else {
file, err = os.Create(path)
}
if err != nil {
return nil, err
}
if options.FLock && !options.InMemory {
if err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX); err != nil {
file.Close()
return nil, err
}
}
if options.PointSize == 0 {
options.PointSize = avgCompressedPointSize
}
if options.PointsPerBlock == 0 {
options.PointsPerBlock = DefaultPointsPerBlock
}
whisper = new(Whisper)
// Set the metadata
whisper.file = file
whisper.aggregationMethod = aggregationMethod
whisper.xFilesFactor = xFilesFactor
whisper.opts = options
whisper.compressed = options.Compressed
whisper.compVersion = 1
whisper.pointsPerBlock = options.PointsPerBlock
whisper.avgCompressedPointSize = options.PointSize
for _, retention := range retentions {
if retention.MaxRetention() > whisper.maxRetention {
whisper.maxRetention = retention.MaxRetention()
}
}
// Set the archive info
for i, retention := range retentions {
archive := &archiveInfo{Retention: *retention}
if archive.avgCompressedPointSize == 0 {
archive.avgCompressedPointSize = whisper.avgCompressedPointSize
}
if archive.blockCount == 0 {
archive.blockCount = whisper.blockCount(archive)
}
if whisper.aggregationMethod == Mix && i > 0 {
for i, spec := range options.MixAggregationSpecs {
narchive := *archive
narchive.aggregationSpec = &MixAggregationSpec{Method: spec.Method, Percentile: spec.Percentile}
ssp := narchive.secondsPerPoint
sindex := i % len(options.MixAggregationSpecs)
if msizes := options.MixAvgCompressedPointSizes; msizes != nil &&
msizes[ssp] != nil &&
isGoodFloat32(msizes[ssp][sindex]) {
narchive.avgCompressedPointSize = msizes[ssp][sindex]
}
whisper.archives = append(whisper.archives, &narchive)
}
} else {
whisper.archives = append(whisper.archives, archive)
}
}
offset := whisper.MetadataSize()
for i, retention := range retentions {
if !whisper.compressed {
archive := whisper.archives[i]
archive.offset = offset
offset += retention.Size()
continue
}
if whisper.aggregationMethod != Mix || i == 0 {
archive := whisper.archives[i]
if math.IsNaN(float64(archive.avgCompressedPointSize)) || archive.avgCompressedPointSize <= 0 {
archive.avgCompressedPointSize = avgCompressedPointSize
}
if archive.avgCompressedPointSize > MaxCompressedPointSize {
archive.avgCompressedPointSize = MaxCompressedPointSize
}
archive.cblock.lastByteBitPos = 7
ppb := archive.calculateSuitablePointsPerBlock(whisper.pointsPerBlock)
archive.blockSize = int(math.Ceil(float64(ppb)*float64(archive.avgCompressedPointSize))) + endOfBlockSize
archive.blockRanges = make([]blockRange, archive.blockCount)
archive.offset = offset
offset += archive.blockSize * archive.blockCount
if i > 0 {
size := archive.secondsPerPoint / whisper.archives[i-1].secondsPerPoint * PointSize * 2
whisper.archives[i-1].buffer = make([]byte, size)
}
continue
}
for j := range options.MixAggregationSpecs {
archive := whisper.archives[1+(i-1)*len(options.MixAggregationSpecs)+j]
archive.cblock.lastByteBitPos = 7
archive.blockSize = int(math.Ceil(float64(whisper.pointsPerBlock)*float64(archive.avgCompressedPointSize))) + endOfBlockSize
archive.blockRanges = make([]blockRange, archive.blockCount)
archive.offset = offset
offset += archive.blockSize * archive.blockCount
}
}
if whisper.compressed {
whisper.initMetaInfo()
err = whisper.WriteHeaderCompressed()
} else {
err = whisper.writeHeader()
}
if err != nil {
return nil, err
}
// pre-allocate file size, fallocate proved slower
//
// compressed format ignores sparse flag
if options.Sparse && !options.Compressed {
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 {
if err := allocateDiskSpace(whisper.file, whisper.Size()-whisper.MetadataSize()); err != nil {
return nil, err
}
}
return whisper, nil
}
func isGoodFloat32(n float32) bool {
return !math.IsNaN(float64(n)) && n > 0.0
}
func (whisper *Whisper) blockCount(archive *archiveInfo) int {
return int(math.Ceil(float64(archive.numberOfPoints)/float64(archive.calculateSuitablePointsPerBlock(whisper.pointsPerBlock)))) + 1
}
func allocateDiskSpace(file file, remaining int) error {
chunkSize := 16384
zeros := make([]byte, chunkSize)
for remaining > chunkSize {
if _, err := file.Write(zeros); err != nil {
return err
}
remaining -= chunkSize
}
if _, err := file.Write(zeros[:remaining]); err != nil {
return err
}
return 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)
}
}
// TODO: cwhisper has more strict retention limit, everything is aggregated from the first archive/retention
return nil
}
/*
Open an existing Whisper database and read it's header
*/
func Open(path string) (whisper *Whisper, err error) {
return OpenWithOptions(path, &Options{
FLock: false,
})
}
func OpenWithOptions(path string, options *Options) (whisper *Whisper, err error) {
var file file
if options.InMemory {
if mc := options.InMemoryContent; mc != nil {
file = &memFile{
name: path,
data: mc,
offset: 0,
}
} else {
file = newMemFile(path)
}
} else {
flag := os.O_RDWR
if options.OpenFileFlag != nil {
flag = *options.OpenFileFlag
}
file, err = os.OpenFile(path, flag, 0666) // skipcq: GSC-G302
}
if err != nil {
return
}
defer func() {
if err != nil {
whisper = nil
file.Close()
}
}()
if options.FLock {
if options.FlockType != syscall.LOCK_SH {
options.FlockType = syscall.LOCK_EX
}
if err = syscall.Flock(int(file.Fd()), options.FlockType); err != nil {
return
}
}
whisper = new(Whisper)
whisper.file = file
whisper.opts = options
b := make([]byte, len(compressedMagicString))
if _, err := whisper.file.Read(b); err != nil {
return nil, fmt.Errorf("unable to read magic string: %s", err)
} else if bytes.Equal(b, compressedMagicString) {
whisper.compressed = true
} else if _, err := whisper.file.Seek(0, 0); err != nil {
return nil, fmt.Errorf("unable to reset file offset: %s", err)
}
// read the metadata
if whisper.compressed {
return whisper, whisper.readHeaderCompressed()
}
b = make([]byte, MetadataSize)
readed, err := file.Read(b)
offset := 0
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: %s", i, err)
return
}
whisper.archives = append(whisper.archives, unpackArchiveInfo(b))
}
return whisper, nil
}
func (whisper *Whisper) initMetaInfo() {
for i, arc := range whisper.archives {
if arc.cblock.lastByteOffset == 0 {
arc.cblock.lastByteOffset = arc.blockOffset(arc.cblock.index)
}
arc.whisper = whisper
for i := range arc.blockRanges {
arc.blockRanges[i].index = i
}
if i == 0 {
continue
}
prevArc := whisper.archives[i-1]
prevArc.next = arc
if whisper.aggregationMethod != Mix && whisper.compVersion == 1 {
prevArc.bufferSize = arc.secondsPerPoint / prevArc.secondsPerPoint * PointSize * bufferCount
}
}
}
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
}
// skipcq: SCC-ST1006, RVV-B0013
func (whisper *Whisper) crc32Offset() int {
const crc32Size = IntSize
return len(compressedMagicString) + VersionSize + CompressedMetadataSize - crc32Size - FreeCompressedMetadataSize
}
/*
Close the whisper file
*/
func (whisper *Whisper) Close() error {
return 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 {
if whisper.compressed {
size += archive.blockSize * archive.blockCount
} else {
size += archive.Size()
}
}
return size
}
/*
Calculate the number of bytes the metadata section will be.
*/
func (whisper *Whisper) MetadataSize() int {
if whisper.compressed {
return len(compressedMagicString) + VersionSize + CompressedMetadataSize + (CompressedArchiveInfoSize * len(whisper.archives)) + whisper.blockRangesSize() + whisper.bufferSize()
}
return MetadataSize + (ArchiveInfoSize * len(whisper.archives))
}
func (whisper *Whisper) blockRangesSize() int {
var blockRangesSize int
for _, arc := range whisper.archives {
blockRangesSize += BlockRangeSize * arc.blockCount
}
return blockRangesSize
}
func (whisper *Whisper) bufferSize() int {
if whisper.aggregationMethod == Mix {
return 0
}
if len(whisper.archives) == 0 {
return 0
}
var bufSize int
for i, arc := range whisper.archives[1:] {
bufSize += arc.secondsPerPoint / whisper.archives[i].secondsPerPoint * PointSize * bufferCount
}
return bufSize
}
/* Return raw aggregation method */
func (whisper *Whisper) AggregationMethod() AggregationMethod { return whisper.aggregationMethod }
/* 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(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]
}
}
var Now = time.Now
func (whisper *Whisper) UpdateMany(points []*TimeSeriesPoint) (err error) {
return whisper.UpdateManyForArchive(points, -1)
}
/*
Returns updated amount of out-of-order discarded points since opening whisper file
*/
func (whisper *Whisper) GetDiscardedPointsSinceOpen() uint32 {
var discardedPointsNow uint32
if whisper.compressed {
for i := 0; i < len(whisper.archives); i++ {
archive := whisper.archives[i]
if archive.stats.discard.oldInterval > 0 {
discardedPointsNow += archive.stats.discard.oldInterval
}
}
}
if discardedPointsNow > whisper.discardedPointsAtOpen {
return discardedPointsNow - whisper.discardedPointsAtOpen
}
return 0
}
// Note: for compressed format, extensions is triggered after update is
// done, so updates of the same data set being done in one
// UpdateManyForArchive call would have different result in file than in
// many UpdateManyForArchive calls.
func (whisper *Whisper) UpdateManyForArchive(points []*TimeSeriesPoint, targetRetention int) (err error) {
// recover panics and return as error
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("update_many_for_archive panics: %s\n%s", e, debug.Stack())
}
}()
// sort the points, newest first
reversePoints(points)
sort.Stable(timeSeriesPointsNewestFirst{points})
now := int(Now().Unix()) // TODO: danger of 2030 something overflow
var currentPoints []*TimeSeriesPoint
for i := 0; i < len(whisper.archives); i++ {
archive := whisper.archives[i]
if targetRetention != -1 && targetRetention != archive.MaxRetention() {
continue
}
currentPoints, points = extractPoints(points, now, archive.MaxRetention())
if len(currentPoints) == 0 {
continue
}
// reverse currentPoints
reversePoints(currentPoints)
if whisper.compressed {
// Backfilling lower archives is not allowed/supported for mix
// aggreation policy with the current api, a new api/parameter is
// needed to specify which aggregaton target to backfill.
if whisper.aggregationMethod == Mix && i > 0 {
break
}
// TODO: add a new options to update data points in smaller chunks if
// it exceeeds certain size, so extension could be triggered
// properly: ChunkUpdateSize
err = whisper.archiveUpdateManyCompressed(archive, currentPoints)
} else {
err = whisper.archiveUpdateMany(archive, currentPoints)
}
if err != nil {
return
}
if len(points) == 0 || whisper.opts.IgnoreNowOnWrite { // nothing left to do or writing to lower archives is forbidden
break
}
}
if whisper.compressed {
if err := whisper.WriteHeaderCompressed(); err != nil {
return err
}
if err := whisper.extendIfNeeded(); err != nil {
return err
}
}
return
}
func (whisper *Whisper) archiveUpdateMany(archive *archiveInfo, points []*TimeSeriesPoint) error {
alignedPoints := alignPoints(archive, points)
return whisper.archiveUpdateManyDataPoints(archive, alignedPoints, true)
}
// skipcq: RVV-A0005
func (whisper *Whisper) archiveUpdateManyDataPoints(archive *archiveInfo, alignedPoints []dataPoint, propagate bool) error {
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())