forked from lomik/go-whisper
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcompress.go
1888 lines (1610 loc) · 50.6 KB
/
compress.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
import (
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"math/bits"
"os"
"sort"
"strconv"
"sync"
"time"
"unsafe"
)
var (
CompressedMetadataSize = 28 + FreeCompressedMetadataSize
FreeCompressedMetadataSize = 16
VersionSize = 1
CompressedArchiveInfoSize = 92 + FreeCompressedArchiveInfoSize
FreeCompressedArchiveInfoSize = 36
compressedHeaderAggregationOffset = len(compressedMagicString) + VersionSize
compressedHeaderXFFOffset = compressedHeaderAggregationOffset + IntSize*2
BlockRangeSize = 16
endOfBlockSize = 5
// One can see that blocks that extend longer than two
// hours provide diminishing returns for compressed size. A
// two-hour block allows us to achieve a compression ratio of
// 1.37 bytes per data point.
// 4.1.2 Compressing values
// Gorilla: A Fast, Scalable, In-Memory Time Series Database
DefaultPointsPerBlock = 7200 // recommended by the gorilla paper algorithm
// using 2 buffer here to mitigate data points arriving at
// random orders causing early propagation
bufferCount = 2
compressedMagicString = []byte("whisper_compressed") // len = 18
debugCompress bool
debugBitsWrite bool
debugExtend bool
avgCompressedPointSize float32 = 2
)
// In worst case scenario all data points would required 2 bytes more space
// after compression, this buffer size make sure that it's always big enough
// to contain the compressed result
const MaxCompressedPointSize = PointSize + 2
const sizeEstimationBuffer = 0.618
func Debug(compress, bitsWrite bool) {
debugCompress = compress
debugBitsWrite = bitsWrite
}
func (whisper *Whisper) WriteHeaderCompressed() (err error) {
b := make([]byte, whisper.MetadataSize())
i := 0
// magic string
i += len(compressedMagicString)
copy(b, compressedMagicString)
// version
b[i] = whisper.compVersion
i += VersionSize
i += packInt(b, int(whisper.aggregationMethod), i)
i += packInt(b, whisper.maxRetention, i)
i += packFloat32(b, whisper.xFilesFactor, i)
i += packInt(b, whisper.pointsPerBlock, i)
i += packInt(b, len(whisper.archives), i)
i += packFloat32(b, whisper.avgCompressedPointSize, i)
i += packInt(b, 0, i) // crc32 always write at the end of whisper meta info header and before archive header
i += FreeCompressedMetadataSize
for _, archive := range whisper.archives {
i += packInt(b, archive.offset, i)
i += packInt(b, archive.secondsPerPoint, i)
i += packInt(b, archive.numberOfPoints, i)
i += packInt(b, archive.blockSize, i)
i += packInt(b, archive.blockCount, i)
i += packFloat32(b, archive.avgCompressedPointSize, i)
var mixSpecSize int
if archive.aggregationSpec != nil {
b[i] = byte(archive.aggregationSpec.Method)
i += ByteSize
i += packFloat32(b, archive.aggregationSpec.Percentile, i)
mixSpecSize = ByteSize + FloatSize
}
i += packInt(b, archive.cblock.index, i)
i += packInt(b, archive.cblock.p0.interval, i)
i += packFloat64(b, archive.cblock.p0.value, i)
i += packInt(b, archive.cblock.pn1.interval, i)
i += packFloat64(b, archive.cblock.pn1.value, i)
i += packInt(b, archive.cblock.pn2.interval, i)
i += packFloat64(b, archive.cblock.pn2.value, i)
i += packInt(b, int(archive.cblock.lastByte), i)
i += packInt(b, archive.cblock.lastByteOffset, i)
i += packInt(b, archive.cblock.lastByteBitPos, i)
i += packInt(b, archive.cblock.count, i)
i += packInt(b, int(archive.cblock.crc32), i)
i += packInt(b, int(archive.stats.discard.oldInterval), i)
i += packInt(b, int(archive.stats.extended), i)
i += FreeCompressedArchiveInfoSize - mixSpecSize
if FreeCompressedArchiveInfoSize < mixSpecSize {
panic("out of FreeCompressedArchiveInfoSize") // a panic that should never happens
}
}
// write block_range_info and buffer
for _, archive := range whisper.archives {
for _, bran := range archive.blockRanges {
i += packInt(b, bran.start, i)
i += packInt(b, bran.end, i)
i += packInt(b, bran.count, i)
i += packInt(b, int(bran.crc32), i)
}
if archive.hasBuffer() {
i += copy(b[i:], archive.buffer)
}
}
whisper.crc32 = crc32(b, 0)
packInt(b, int(whisper.crc32), whisper.crc32Offset())
if err := whisper.fileWriteAt(b, 0); err != nil {
return err
}
if _, err := whisper.file.Seek(int64(len(b)), 0); err != nil {
return err
}
return nil
}
func (whisper *Whisper) readHeaderCompressed() (err error) {
if _, err := whisper.file.Seek(int64(len(compressedMagicString)), 0); err != nil {
return err
}
offset := 0
hlen := whisper.MetadataSize() - len(compressedMagicString)
b := make([]byte, hlen)
readed, err := whisper.file.Read(b)
if err != nil {
err = fmt.Errorf("unable to read header: %s", err)
return
}
if readed != hlen {
err = fmt.Errorf("unable to read header: EOF")
return
}
whisper.compVersion = b[offset]
offset++
whisper.aggregationMethod = AggregationMethod(unpackInt(b[offset : offset+IntSize]))
offset += IntSize
whisper.maxRetention = unpackInt(b[offset : offset+IntSize])
offset += IntSize
whisper.xFilesFactor = unpackFloat32(b[offset : offset+FloatSize])
offset += FloatSize
whisper.pointsPerBlock = unpackInt(b[offset : offset+IntSize])
offset += IntSize
archiveCount := unpackInt(b[offset : offset+IntSize])
offset += IntSize
whisper.avgCompressedPointSize = unpackFloat32(b[offset : offset+FloatSize])
offset += FloatSize
whisper.crc32 = uint32(unpackInt(b[offset : offset+IntSize]))
offset += IntSize
offset += FreeCompressedMetadataSize
whisper.archives = make([]*archiveInfo, archiveCount)
for i := 0; i < archiveCount; i++ {
b := make([]byte, CompressedArchiveInfoSize)
readed, err = whisper.file.Read(b)
if err != nil || readed != CompressedArchiveInfoSize {
err = fmt.Errorf("unable to read compressed archive %d metadata: %s", i, err)
return
}
var offset int
var arc archiveInfo
arc.offset = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.secondsPerPoint = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.numberOfPoints = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.blockSize = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.blockCount = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.avgCompressedPointSize = unpackFloat32(b[offset : offset+FloatSize])
offset += FloatSize
if whisper.aggregationMethod == Mix && i > 0 {
arc.aggregationSpec = &MixAggregationSpec{}
arc.aggregationSpec.Method = AggregationMethod(b[offset])
offset += ByteSize
arc.aggregationSpec.Percentile = unpackFloat32(b[offset : offset+FloatSize])
offset += FloatSize
}
arc.cblock.index = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.cblock.p0.interval = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.cblock.p0.value = unpackFloat64(b[offset : offset+Float64Size])
offset += Float64Size
arc.cblock.pn1.interval = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.cblock.pn1.value = unpackFloat64(b[offset : offset+Float64Size])
offset += Float64Size
arc.cblock.pn2.interval = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.cblock.pn2.value = unpackFloat64(b[offset : offset+Float64Size])
offset += Float64Size
arc.cblock.lastByte = byte(unpackInt(b[offset : offset+IntSize]))
offset += IntSize
arc.cblock.lastByteOffset = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.cblock.lastByteBitPos = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.cblock.count = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.cblock.crc32 = uint32(unpackInt(b[offset : offset+IntSize]))
offset += IntSize
arc.stats.discard.oldInterval = uint32(unpackInt(b[offset : offset+IntSize]))
whisper.discardedPointsAtOpen += arc.stats.discard.oldInterval
offset += IntSize
arc.stats.extended = uint32(unpackInt(b[offset : offset+IntSize]))
offset += IntSize
whisper.archives[i] = &arc
}
whisper.initMetaInfo()
for i, arc := range whisper.archives {
b := make([]byte, BlockRangeSize*arc.blockCount)
readed, err = whisper.file.Read(b)
if err != nil || readed != BlockRangeSize*arc.blockCount {
err = fmt.Errorf("unable to read archive %d block ranges: %s", i, err)
return
}
offset := 0
arc.blockRanges = make([]blockRange, arc.blockCount)
for i := range arc.blockRanges {
arc.blockRanges[i].index = i
arc.blockRanges[i].start = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.blockRanges[i].end = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.blockRanges[i].count = unpackInt(b[offset : offset+IntSize])
offset += IntSize
arc.blockRanges[i].crc32 = uint32(unpackInt(b[offset : offset+IntSize]))
offset += IntSize
}
// arc.initBlockRanges()
if !arc.hasBuffer() {
continue
}
arc.buffer = make([]byte, arc.bufferSize)
readed, err = whisper.file.Read(arc.buffer)
if err != nil {
return fmt.Errorf("unable to read archive %d buffer: %s", i, err)
} else if readed != arc.bufferSize {
return fmt.Errorf("unable to read archive %d buffer: readed = %d want = %d", i, readed, arc.bufferSize)
}
}
return nil
}
func (a *archiveInfo) blockOffset(blockIndex int) int {
return a.offset + blockIndex*a.blockSize
}
const maxInt = 1<<uint(strconv.IntSize-1) - 1
func (archive *archiveInfo) getSortedBlockRanges() []blockRange {
brs := make([]blockRange, len(archive.blockRanges))
copy(brs, archive.blockRanges)
sort.SliceStable(brs, func(i, j int) bool {
istart := brs[i].start
if brs[i].start == 0 {
istart = maxInt
}
jstart := brs[j].start
if brs[j].start == 0 {
jstart = maxInt
}
return istart < jstart
})
return brs
}
func (archive *archiveInfo) getRange() (from, until int) {
for _, b := range archive.blockRanges {
if from == 0 || from > b.start {
from = b.start
}
if until == 0 || b.end > until {
until = b.end
}
}
return
}
func (archive *archiveInfo) hasBuffer() bool { return archive.bufferSize > 0 }
func (whisper *Whisper) fetchCompressed(start, end int64, archive *archiveInfo) ([]dataPoint, error) {
var dst []dataPoint // TODO: optimize this with pre-allocation
var buf = make([]byte, archive.blockSize)
for _, block := range archive.getSortedBlockRanges() {
if block.end >= int(start) && int(end) >= block.start {
if err := whisper.fileReadAt(buf, int64(archive.blockOffset(block.index))); err != nil {
return nil, fmt.Errorf("fetchCompressed.%d.%d: %s", archive.numberOfPoints, block.index, err)
}
var err error
dst, _, err = archive.ReadFromBlock(buf, dst, int(start), int(end))
if err != nil {
return dst, err
}
for i := 0; i < archive.blockSize; i++ {
buf[i] = 0
}
}
}
if archive.hasBuffer() {
dps := unpackDataPoints(archive.buffer)
for _, p := range dps {
if p.interval != 0 && int(start) <= p.interval && p.interval <= int(end) {
dst = append(dst, p)
}
}
}
base := whisper.archives[0]
if base == archive {
return dst, nil
}
// Start live aggregation. This probably has a read peformance hit.
if whisper.aggregationMethod == Mix {
// Mix aggregation is triggered when block in base archive is rotated and also
// depends on the sufficiency of data points. This could results to a over
// long gap when fetching data from higer archives, depending on different
// retention policy. Therefore cwhisper needs to do live aggregation.
var dps []dataPoint
var inBase bool
var baseLookupNeeded = len(dst) == 0 || dst[len(dst)-1].interval < int(end)
if baseLookupNeeded {
bstart, bend := base.getRange()
inBase = int64(bstart) <= end || end <= int64(bend)
}
if inBase {
nstart := start
if len(dst) > 0 {
// TODO: invest why shifting the last data point interval is wrong
nstart = int64(archive.Interval(dst[len(dst)-1].interval)) // + archive.secondsPerPoint
}
var err error
dps, err = whisper.fetchCompressed(nstart, end, base)
if err != nil {
return dst, err
}
}
if base.hasBuffer() {
for _, p := range unpackDataPoints(base.buffer) {
if p.interval != 0 && int(start) <= p.interval && p.interval <= int(end) {
dps = append(dps, p)
}
}
}
adps := whisper.aggregateByArchives(dps)
dst = append(dst, adps[archive]...)
} else {
// retrieve data points within range from the higher/previous archives
var dps []dataPoint
for i, arc := range whisper.archives {
if arc == archive || i == len(whisper.archives)-1 {
break
}
cvals := []float64{}
cinterval := 0
tdps := append(dps, unpackDataPoints(arc.buffer)...) // skipcq: CRT-D0001
dps = []dataPoint{}
for j, p := range tdps {
if p.interval == 0 && j < len(tdps)-1 {
continue
}
interval := arc.AggregateInterval(p.interval)
if cinterval == 0 || cinterval == interval {
cinterval = interval
cvals = append(cvals, p.value)
continue
}
dps = append(dps, dataPoint{cinterval, aggregate(whisper.aggregationMethod, cvals)})
cinterval = interval
cvals = []float64{p.value}
}
}
sort.SliceStable(dps, func(i, j int) bool { return dps[i].interval < dps[j].interval })
for i := 0; i < len(dps); i++ {
if int(start) <= dps[i].interval && dps[i].interval <= int(end) {
continue
}
dps = dps[:i]
break
}
dst = append(dst, dps...)
}
return dst, nil
}
// NOTE: this method assumes data saved in higer archives are fixed. If
// we mvoe to allowing data/intervals coming in non-monotonic order, we
// need to rethink the implementation here as well.
func (whisper *Whisper) archiveUpdateManyCompressed(archive *archiveInfo, points []*TimeSeriesPoint) error {
alignedPoints := alignPoints(archive, points)
// Note: in the current design, mix aggregation doesn't have any buffer in
// higer archives
if !archive.hasBuffer() {
rotated, err := archive.appendToBlockAndRotate(alignedPoints)
if err != nil {
return err
}
if !(whisper.aggregationMethod == Mix && rotated) {
return nil
}
return whisper.propagateToMixedArchivesCompressed()
}
baseIntervalsPerUnit, currentUnit, minInterval := archive.getBufferInfo()
bufferUnitPointsCount := archive.next.secondsPerPoint / archive.secondsPerPoint
for aindex := 0; aindex < len(alignedPoints); {
dp := alignedPoints[aindex]
dpBaseInterval := archive.AggregateInterval(dp.interval)
// NOTE: current implementation expects data points to be monotonically
// increasing in time
if minInterval != 0 && dpBaseInterval < minInterval { // TODO: check against cblock pn1.interval?
archive.stats.discard.oldInterval++
aindex++
continue
}
// Tolerate out of order data handling within the current buffer.
targetUnit := -1
for i, unitInterval := range baseIntervalsPerUnit {
if dpBaseInterval == unitInterval {
targetUnit = i
break
}
}
if targetUnit != -1 {
aindex++
// TODO: not efficient if many data points are being written in one call
offset := targetUnit*bufferUnitPointsCount + (dp.interval-dpBaseInterval)/archive.secondsPerPoint
copy(archive.buffer[offset*PointSize:], dp.Bytes())
continue
}
// check if buffer is full
if baseIntervalsPerUnit[currentUnit] == 0 || baseIntervalsPerUnit[currentUnit] == dpBaseInterval {
aindex++
baseIntervalsPerUnit[currentUnit] = dpBaseInterval
// TODO: not efficient if many data points are being written in one call
offset := currentUnit*bufferUnitPointsCount + (dp.interval-dpBaseInterval)/archive.secondsPerPoint
copy(archive.buffer[offset*PointSize:], dp.Bytes())
continue
}
currentUnit = (currentUnit + 1) % len(baseIntervalsPerUnit)
baseIntervalsPerUnit[currentUnit] = 0
// flush buffer
buffer := archive.getBufferByUnit(currentUnit)
dps := unpackDataPointsStrict(buffer)
// reset buffer
for i := range buffer {
buffer[i] = 0
}
if len(dps) <= 0 {
continue
}
if _, err := archive.appendToBlockAndRotate(dps); err != nil {
// TODO: record and continue?
return err
}
// propagate
lower := archive.next
lowerIntervalStart := archive.AggregateInterval(dps[0].interval)
var knownValues []float64
for _, dPoint := range dps {
knownValues = append(knownValues, dPoint.value)
}
knownPercent := float32(len(knownValues)) / float32(lower.secondsPerPoint/archive.secondsPerPoint)
// check we have enough data points to propagate a value
if knownPercent >= whisper.xFilesFactor {
aggregateValue := aggregate(whisper.aggregationMethod, knownValues)
point := &TimeSeriesPoint{lowerIntervalStart, aggregateValue}
// TODO: consider migrating to a non-recursive propagation implementation like mix policy
if err := whisper.archiveUpdateManyCompressed(lower, []*TimeSeriesPoint{point}); err != nil {
return err
}
}
}
return nil
}
func (archive *archiveInfo) getBufferInfo() (units []int, index, min int) {
var max int
for i := 0; i < archive.bufferUnitCount(); i++ {
v := getFirstDataPointStrict(archive.getBufferByUnit(i)).interval
if v > 0 {
v = archive.AggregateInterval(v)
}
units = append(units, v)
if max < v {
max = v
index = i
}
if min == 0 || min > v {
min = v
}
}
return
}
func (archive *archiveInfo) bufferUnitCount() int {
return len(archive.buffer) / PointSize / (archive.next.secondsPerPoint / archive.secondsPerPoint)
}
func (archive *archiveInfo) getBufferByUnit(unit int) []byte {
count := archive.next.secondsPerPoint / archive.secondsPerPoint
lb := unit * PointSize * count
ub := (unit + 1) * PointSize * count
return archive.buffer[lb:ub]
}
func (archive *archiveInfo) appendToBlockAndRotate(dps []dataPoint) (rotated bool, err error) {
whisper := archive.whisper // TODO: optimize away?
// Why MaxCompressedPointSize+1 and endOfBlockSize*2:
//
// MaxCompressedPointSize is set to 14, but in reality, a maximum compressed
// data point has a bit length of 14.125(113 bits). And there might be times
// when the current block is almost full, and more data needs to be set 0. So
// here go-whisper should prefer to have a large buffer just to be on the safe
// side.
//
// An edge case that can be fixed by this allocation strategy is that: the
// current block has less than 14 bytes plus endOfBlockSize (5) bytes
// available, and a data point that can't be well compressed comes in, then the
// buffer isn't large enough to fill the generated binary data.
//
// This allocation strategy makes sure that there is enough space in the block
// buffer for compression output.
blockBuffer := make([]byte, len(dps)*(MaxCompressedPointSize+1)+endOfBlockSize*2)
for {
offset := archive.cblock.lastByteOffset // lastByteOffset is updated in AppendPointsToBlock
size, left, rotate := archive.AppendPointsToBlock(blockBuffer, dps)
// flush block
if size >= len(blockBuffer) {
// TODO: panic?
size = len(blockBuffer)
}
if err := whisper.fileWriteAt(blockBuffer[:size], int64(offset)); err != nil {
return rotated, err
}
if len(left) == 0 {
break
}
// reset block
for i := 0; i < len(blockBuffer); i++ {
blockBuffer[i] = 0
}
dps = left
if !rotate {
continue
}
var nblock blockInfo
nblock.index = (archive.cblock.index + 1) % len(archive.blockRanges)
nblock.lastByteBitPos = 7
nblock.lastByteOffset = archive.blockOffset(nblock.index)
archive.cblock = nblock
archive.blockRanges[nblock.index].start = 0
archive.blockRanges[nblock.index].end = 0
rotated = true
}
return rotated, nil
}
func (whisper *Whisper) extendIfNeeded() error {
var rets []*Retention
var mixSpecs []MixAggregationSpec
var mixSizes = make(map[int][]float32)
var extend bool
var msg string
var nferrs []error
for _, arc := range whisper.archives {
ret := &Retention{
secondsPerPoint: arc.secondsPerPoint,
numberOfPoints: arc.numberOfPoints,
avgCompressedPointSize: arc.avgCompressedPointSize,
blockCount: arc.blockCount,
}
var totalPoints int
var totalBlocks int
for _, b := range arc.getSortedBlockRanges() {
if b.index == arc.cblock.index {
break
}
totalBlocks++
totalPoints += b.count
}
if totalPoints > 0 {
avgPointSize := float32(totalBlocks*arc.blockSize) / float32(totalPoints)
if avgPointSize > arc.avgCompressedPointSize {
extend = true
if avgPointSize-arc.avgCompressedPointSize < sizeEstimationBuffer {
avgPointSize += sizeEstimationBuffer
}
if debugExtend {
msg += fmt.Sprintf("%s:%v->%v ", ret, ret.avgCompressedPointSize, avgPointSize)
}
ret.avgCompressedPointSize = avgPointSize
arc.stats.extended++
}
}
rets = append(rets, ret)
}
if !extend {
return nil
}
if debugExtend {
fmt.Println("extend:", whisper.file.Name(), msg)
}
filename := whisper.file.Name()
if err := os.Remove(whisper.file.Name() + ".extend"); err != nil && !os.IsNotExist(err) {
nferrs = append(nferrs, err)
}
if whisper.aggregationMethod == Mix && len(rets) > 1 {
rets, mixSpecs, mixSizes = extractMixSpecs(rets, whisper.archives)
}
nwhisper, err := CreateWithOptions(
whisper.file.Name()+".extend", rets,
whisper.aggregationMethod, whisper.xFilesFactor,
&Options{
Compressed: true,
PointsPerBlock: DefaultPointsPerBlock,
InMemory: whisper.opts.InMemory,
MixAggregationSpecs: mixSpecs,
MixAvgCompressedPointSizes: mixSizes,
},
)
if err != nil {
return fmt.Errorf("extend: %s", err)
}
for i := len(whisper.archives) - 1; i >= 0; i-- {
archive := whisper.archives[i]
copy(nwhisper.archives[i].buffer, archive.buffer)
nwhisper.archives[i].stats = archive.stats
for _, block := range archive.getSortedBlockRanges() {
buf := make([]byte, archive.blockSize)
if err := whisper.fileReadAt(buf, int64(archive.blockOffset(block.index))); err != nil {
return fmt.Errorf("archives[%d].blocks[%d].file.read: %s", i, block.index, err)
}
dst, _, err := archive.ReadFromBlock(buf, []dataPoint{}, 0, maxInt)
if err != nil {
return fmt.Errorf("archives[%d].blocks[%d].read: %s", i, block.index, err)
}
if _, err := nwhisper.archives[i].appendToBlockAndRotate(dst); err != nil {
return fmt.Errorf("archives[%d].blocks[%d].write: %s", i, block.index, err)
}
}
nwhisper.archives[i].buffer = archive.buffer
}
if err := nwhisper.WriteHeaderCompressed(); err != nil {
return fmt.Errorf("extend: failed to writer header: %s", err)
}
if err := whisper.Close(); err != nil {
nferrs = append(nferrs, err)
}
if err := nwhisper.file.Close(); err != nil {
nferrs = append(nferrs, err)
}
if whisper.opts.InMemory {
whisper.file.(*memFile).data = nwhisper.file.(*memFile).data
releaseMemFile(filename + ".extend")
} else if err = os.Rename(filename+".extend", filename); err != nil {
return fmt.Errorf("extend/rename: %s", err)
}
nwhisper, err = OpenWithOptions(filename, whisper.opts)
*whisper = *nwhisper
whisper.Extended = true
whisper.NonFatalErrors = append(whisper.NonFatalErrors, nferrs...)
return err
}
func extractMixSpecs(orets Retentions, arcs []*archiveInfo) (Retentions, []MixAggregationSpec, map[int][]float32) {
var nrets Retentions
var specs []MixAggregationSpec
var sizes = make(map[int][]float32)
var specsCont bool
for i, ret := range orets {
sizes[ret.secondsPerPoint] = append(sizes[ret.secondsPerPoint], ret.avgCompressedPointSize)
if len(nrets) == 0 {
nrets = append(nrets, ret)
continue
}
if ret.secondsPerPoint != nrets[len(nrets)-1].secondsPerPoint {
nrets = append(nrets, ret)
if len(specs) == 0 {
specs = append(specs, *arcs[i].aggregationSpec)
specsCont = true
} else {
specsCont = false
}
} else if specsCont {
specs = append(specs, *arcs[i].aggregationSpec)
}
}
return nrets, specs, sizes
}
func (arc *archiveInfo) avgPointsPerBlockReal() float32 {
var totalPoints int
var totalBlocks int
for _, b := range arc.getSortedBlockRanges() {
if b.index == arc.cblock.index {
break
}
totalBlocks++
totalPoints += b.count
}
if totalPoints > 0 {
return float32(totalBlocks*arc.blockSize) / float32(totalPoints)
}
return 0
}
// Timestamp:
// 1. The block header stores the starting time stamp, t−1,
// which is aligned to a two hour window; the first time
// stamp, t0, in the block is stored as a delta from t−1 in
// 14 bits. 1
// 2. For subsequent time stamps, tn:
// (a) Calculate the delta of delta:
// D = (tn − tn−1) − (tn−1 − tn−2)
// (b) If D is zero, then store a single ‘0’ bit
// (c) If D is between [-63, 64], store ‘10’ followed by
// the value (7 bits)
// (d) If D is between [-255, 256], store ‘110’ followed by
// the value (9 bits)
// (e) if D is between [-2047, 2048], store ‘1110’ followed
// by the value (12 bits)
// (f) Otherwise store ‘1111’ followed by D using 32 bits
//
// Value:
// 1. The first value is stored with no compression
// 2. If XOR with the previous is zero (same value), store
// single ‘0’ bit
// 3. When XOR is non-zero, calculate the number of leading
// and trailing zeros in the XOR, store bit ‘1’ followed
// by either a) or b):
// (a) (Control bit ‘0’) If the block of meaningful bits
// falls within the block of previous meaningful bits,
// i.e., there are at least as many leading zeros and
// as many trailing zeros as with the previous value,
// use that information for the block position and
// just store the meaningful XORed value.
// (b) (Control bit ‘1’) Store the length of the number
// of leading zeros in the next 5 bits, then store the
// length of the meaningful XORed value in the next
// 6 bits. Finally store the meaningful bits of the
// XORed value.
func (a *archiveInfo) AppendPointsToBlock(buf []byte, ps []dataPoint) (written int, left []dataPoint, rotate bool) {
var bw bitsWriter
bw.buf = buf
bw.bitPos = a.cblock.lastByteBitPos
// set and clean possible end-of-block maker
bw.buf[0] = a.cblock.lastByte
bw.buf[0] &= 0xFF ^ (1<<uint(a.cblock.lastByteBitPos+1) - 1)
bw.buf[1] = 0
defer func() {
a.cblock.lastByte = bw.buf[bw.index]
a.cblock.lastByteBitPos = int(bw.bitPos)
a.cblock.lastByteOffset += bw.index
written = bw.index // size not including eob
// write end-of-block marker if there is enough space
bw.Write(4, 0x0f)
bw.Write(32, 0)
// exclude last byte from crc32 unless block is full
if rotate {
blockEnd := a.blockOffset(a.cblock.index) + a.blockSize - 1
if left := blockEnd - a.cblock.lastByteOffset - (bw.index - written); left > 0 {
bw.index += left
}
a.cblock.crc32 = crc32(buf[:bw.index+1], a.cblock.crc32)
a.cblock.lastByteOffset = blockEnd
} else if written > 0 {
// exclude eob for crc32 when block isn't full
a.cblock.crc32 = crc32(buf[:written], a.cblock.crc32)
}
written = bw.index + 1
a.blockRanges[a.cblock.index].start = a.cblock.p0.interval
a.blockRanges[a.cblock.index].end = a.cblock.pn1.interval
a.blockRanges[a.cblock.index].count = a.cblock.count
a.blockRanges[a.cblock.index].crc32 = a.cblock.crc32
}()
if debugCompress {
fmt.Printf("AppendPointsToBlock(%s): cblock.index=%d bw.index = %d lastByteOffset = %d blockSize = %d\n", a.Retention, a.cblock.index, bw.index, a.cblock.lastByteOffset, a.blockSize)
}
// TODO: return error if interval is not monotonically increasing?
for i, p := range ps {
if p.interval == 0 {
continue
} else if p.interval <= a.cblock.pn1.interval {
a.stats.discard.oldInterval++
continue
}
oldBwIndex := bw.index
oldBwBitPos := bw.bitPos
oldBwLastByte := bw.buf[bw.index]
var delta1, delta2 int
if a.cblock.p0.interval == 0 {
a.cblock.p0 = p
a.cblock.pn1 = p
a.cblock.pn2 = p
copy(buf, p.Bytes())
bw.index += PointSize
if debugCompress {
fmt.Printf("begin\n")
fmt.Printf("%d: %v\n", p.interval, p.value)
}
continue
}
delta1 = p.interval - a.cblock.pn1.interval
delta2 = a.cblock.pn1.interval - a.cblock.pn2.interval
delta := (delta1 - delta2) / a.secondsPerPoint
if debugCompress {
fmt.Printf("%d %d: %v\n", i, p.interval, p.value)
}
// TODO: use two's complement instead to extend delta range?
if delta == 0 {
if debugCompress {
fmt.Printf("\tbuf.index = %d/%d delta = %d: %0s\n", bw.bitPos, bw.index, delta, dumpBits(1, 0))
}
bw.Write(1, 0)
a.stats.interval.len1++
} else if -63 < delta && delta < 64 {
if delta < 0 {
delta *= -1
delta |= 64
}
if debugCompress {
fmt.Printf("\tbuf.index = %d/%d delta = %d: %0s\n", bw.bitPos, bw.index, delta, dumpBits(2, 2, 7, uint64(delta)))
}
bw.Write(2, 2)
bw.Write(7, uint64(delta))
a.stats.interval.len9++
} else if -255 < delta && delta < 256 {
if delta < 0 {
delta *= -1
delta |= 256
}
if debugCompress {
fmt.Printf("\tbuf.index = %d/%d delta = %d: %0s\n", bw.bitPos, bw.index, delta, dumpBits(3, 6, 9, uint64(delta)))
}
bw.Write(3, 6)
bw.Write(9, uint64(delta))
a.stats.interval.len12++
} else if -2047 < delta && delta < 2048 {
if delta < 0 {
delta *= -1
delta |= 2048
}
if debugCompress {
fmt.Printf("\tbuf.index = %d/%d delta = %d: %0s\n", bw.bitPos, bw.index, delta, dumpBits(4, 14, 12, uint64(delta)))
}
bw.Write(4, 14)
bw.Write(12, uint64(delta))
a.stats.interval.len16++
} else {
if debugCompress {
fmt.Printf("\tbuf.index = %d/%d delta = %d: %0s\n", bw.bitPos, bw.index, delta, dumpBits(4, 15, 32, uint64(delta)))
}
bw.Write(4, 15)