-
Notifications
You must be signed in to change notification settings - Fork 0
/
verify.go
1270 lines (1021 loc) · 29.5 KB
/
verify.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 index
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/bleemeo/squirreldb/types"
"github.com/pilosa/pilosa/v2/roaring"
"github.com/prometheus/prometheus/model/labels"
)
type verifier struct {
index *CassandraIndex
doFix bool
acquireLock bool
strictMetricCreation bool
strictExpiration bool
pedanticExpiration bool
output io.Writer
now time.Time
}
type verifierExecution struct {
verifier
bulkDeleter *deleter
// allPosting is the content of the special posting globalAllPostingLabel
allPosting *roaring.Bitmap
// allGoodIDs will contains all MetricIDs which have correct id <-> labels entry in
// tables labels2id and id2labels.
allGoodIDs *roaring.Bitmap
// expectedExpiration contains the expected value for index_expiration table (based on id2labels table)
expectedExpiration map[int64]*roaring.Bitmap
// expectedUnknowDate contains the metric ID which should expire but we ignore when.
expectedUnknowDate *roaring.Bitmap
}
const maxIDBeforeTruncate = 50
func (c *CassandraIndex) Verifier(output io.Writer) types.IndexVerifier {
return verifier{
index: c,
now: c.options.InternalNowFunction(),
output: output,
}
}
// WithNow fixes the time the verify process think we are curretly. This is useful for test AND
// when running verify on a dump that is few day old.
func (v verifier) WithNow(now time.Time) types.IndexVerifier {
v.now = now
return v
}
// WithDoFix enable or disable fix for correctable error found. It imply taking the newMetricGlobalLock lock.
func (v verifier) WithDoFix(enable bool) types.IndexVerifier {
if enable {
v.acquireLock = true
}
v.doFix = enable
return v
}
// WithLock enable or disable taking lock during index verification.
// The lock is required as a metric creation / expiration during the verification process could
// return a false-positive, but holding the lock will block metric creation during the whole verification process.
// If disabled, it also disable DoFix.
func (v verifier) WithLock(enable bool) types.IndexVerifier {
v.acquireLock = enable
if !enable {
v.doFix = false
}
return v
}
// WithStrictExpiration enable or disable fail on warning condition for expiration.
// By default, it's only checked that expiration don't have fatal error (which would cause metric
// to don't expire at all for example). With this option, it also check that expiration information
// are up-to-date but still allow for duplicate. For this check to works, task like cassandraExpire()
// and applyExpirationUpdateRequests() must have run.
// To even disallow duplicate, with WithPedanticExpiration
// It modify the verifier and return it to allow chaining call.
func (v verifier) WithStrictExpiration(enable bool) types.IndexVerifier {
v.strictExpiration = enable
if !enable {
v.pedanticExpiration = false
}
return v
}
// WithStrictMetricCreation enable or disable fail on warning condition for metric creation.
// The way metric creation is done, could lead to partially creation metric, that will:
// * not be used
// * be cleaned on their expiration
// So such error don't have significant impact unless they happen way to often. They should
// only happen if during metric creation something goes wrong (like SquirrelDB crash or just
// the HTTP client that disconnect during the creation - i.e. timeout).
// It modify the verifier and return it to allow chaining call.
func (v verifier) WithStrictMetricCreation(enable bool) types.IndexVerifier {
v.strictMetricCreation = enable
return v
}
// WithPedanticExpiration enable or disable all check on expiration.
// It imply WithStrictExpiration and also enable checking the ID aren't duplicated in previous day.
// This check is advanced as it can't be easily avoided with a cluster:
// - Two SquirrelDB have knowledge of the same metric
// - SquirrelDB A created the metric, with expiration day D1
// - A write on SquirrelDB B cause the TTL to update from D1 to D2
// - Later, a write on SquirrelDB A cause another update. SquirrelDB A thing that update is from D1 to D3
// - SquirrelDB B restart (or refresh the expiration cache)
// - The metric is present in D2 and D3. No SquirrelDBs think that it's present in D2 and will not remove
// it from there (excepted when that day is processed by the expiration process).
//
// It modify the verifier and return it to allow chaining call.
func (v verifier) WithPedanticExpiration(enable bool) types.IndexVerifier {
v.pedanticExpiration = enable
if enable {
v.strictExpiration = true
}
return v
}
// Verify perform some checks on index consistency.
// It could apply fixes and could acquire the newMetricGlobalLock to ensure a consitent read of the index.
// When any issue is found, the hadIssue will be true (and description of the issue is written to w). Note
// that some issue might get fixed automatically (e.g. expired metrics that are not yet processed, partial write should
// be fixed when expiration is applied for them, ...).
func (v verifier) Verify(ctx context.Context) (hadIssue bool, err error) {
execution := &verifierExecution{
verifier: v,
bulkDeleter: newBulkDeleter(v.index),
expectedExpiration: make(map[int64]*roaring.Bitmap),
expectedUnknowDate: roaring.NewBTreeBitmap(),
}
return execution.verify(ctx)
}
func (ve *verifierExecution) verify(ctx context.Context) (hadIssue bool, err error) {
if ve.acquireLock {
ve.index.newMetricGlobalLock.Lock()
defer ve.index.newMetricGlobalLock.Unlock()
}
issueCount, shards, err := ve.verifyMissingShard(ctx)
if err != nil {
return hadIssue, err
}
hadIssue = hadIssue || issueCount > 0
ve.allGoodIDs = roaring.NewBTreeBitmap()
ve.allPosting, err = ve.index.postings(
ctx,
[]int32{globalShardNumber},
globalAllPostingLabel,
globalAllPostingLabel,
false,
)
if err != nil {
return hadIssue, err
}
fmt.Fprintf(ve.output, "Index had %d shards and should have %d metrics\n", shards.Count(), ve.allPosting.Count())
if respf, ok := ve.output.(http.Flusher); ok {
respf.Flush()
}
count := 0
it := ve.allPosting.Iterator()
pendingIDs := make([]types.MetricID, 0, 10000)
for ctx.Err() == nil {
pendingIDs = pendingIDs[:0]
for ctx.Err() == nil {
id, eof := it.Next()
if eof {
break
}
metricID := types.MetricID(id)
count++
pendingIDs = append(pendingIDs, metricID)
if len(pendingIDs) > verifyBulkSize {
break
}
}
if len(pendingIDs) == 0 {
break
}
if len(pendingIDs) > 0 {
bulkHadIssue, err := ve.verifyBulk(ctx, pendingIDs)
if err != nil {
return hadIssue, err
}
hadIssue = hadIssue || bulkHadIssue
}
}
fmt.Fprintf(ve.output, "Index contains %d metrics and %d ok\n", count, ve.allGoodIDs.Count())
if respf, ok := ve.output.(http.Flusher); ok {
respf.Flush()
}
if ve.doFix {
fmt.Fprintf(ve.output, "Applying fix...")
if err := ve.bulkDeleter.Delete(ctx); err != nil {
return hadIssue, err
}
}
for _, shard := range shards.Slice() {
shard := int32(shard)
fmt.Fprintf(ve.output, "Checking shard %s (ID %d)\n", timeForShard(shard).Format(shardDateFormat), shard)
shardHadIssue, err := ve.verifyShard(ctx, shard)
if err != nil {
return hadIssue, err
}
hadIssue = hadIssue || shardHadIssue
if respf, ok := ve.output.(http.Flusher); ok {
respf.Flush()
}
}
expirationIssue, err := ve.verifyExpiration(ctx)
if err != nil {
return hadIssue, err
}
hadIssue = hadIssue || expirationIssue
return hadIssue, ctx.Err()
}
// verifyMissingShard search from now+3 weeks to 100 weeks before now+3 weeks for shard not present in existingShards.
// It also verify that all shards in existingShards actually exists.
func (ve *verifierExecution) verifyMissingShard(
ctx context.Context) (errorCount int, shards *roaring.Bitmap, err error,
) {
shards, err = ve.index.postings(ctx, []int32{globalShardNumber}, existingShardsLabel, existingShardsLabel, false)
if err != nil {
return 0, shards, fmt.Errorf("get postings for existing shards: %w", err)
}
current := ve.verifier.index.options.InternalNowFunction().Add(3 * postingShardSize)
for range 100 {
if ctx.Err() != nil {
return 0, shards, ctx.Err()
}
queryShard := []int32{shardForTime(current.Unix())}
for _, name := range []string{maybePostingLabel, allPostingLabel} {
it, err := ve.index.postings(ctx, queryShard, name, name, false)
if err != nil {
return 0, shards, err
}
if it != nil && it.Any() && !shards.Contains(uint64(queryShard[0])) {
errorCount++
fmt.Fprintf(
ve.output,
"Shard %s for time %v isn't in all shards",
timeForShard(queryShard[0]).Format(shardDateFormat),
current.String(),
)
if ve.doFix {
_, err = shards.AddN(uint64(queryShard[0]))
if err != nil {
return 0, shards, fmt.Errorf("update bitmap: %w", err)
}
}
}
}
current = current.Add(-postingShardSize)
}
slice := shards.Slice()
for _, shard := range slice {
if ctx.Err() != nil {
return 0, shards, ctx.Err()
}
shard := int32(shard)
it, err := ve.index.postings(ctx, []int32{shard}, maybePostingLabel, maybePostingLabel, false)
if err != nil {
return 0, shards, fmt.Errorf("get postings for maybe metric IDs: %w", err)
}
if it == nil || !it.Any() {
errorCount++
fmt.Fprintf(
ve.output,
"Shard %s is listed in all shards but don't exists\n",
timeForShard(shard).Format(shardDateFormat),
)
if ve.doFix {
_, err = shards.RemoveN(uint64(shard))
if err != nil {
return 0, shards, fmt.Errorf("update bitmap: %w", err)
}
}
}
}
if errorCount > 0 && ve.doFix {
var buffer bytes.Buffer
_, err = shards.WriteTo(&buffer)
if err != nil {
return errorCount, shards, fmt.Errorf("serialize bitmap: %w", err)
}
err = ve.index.store.InsertPostings(ctx, globalShardNumber, existingShardsLabel, existingShardsLabel, buffer.Bytes())
if err != nil {
return errorCount, shards, fmt.Errorf("update existing shards: %w", err)
}
}
return errorCount, shards, nil
}
// check that given metric IDs existing in labels2id and id2labels.
func (ve *verifierExecution) verifyBulk( //nolint:maintidx
ctx context.Context,
ids []types.MetricID,
) (hadIssue bool, err error) {
id2Labels, id2expiration, err := ve.index.selectIDS2LabelsAndExpiration(ctx, ids)
if err != nil {
return hadIssue, fmt.Errorf("get labels: %w", err)
}
allLabelsString := make([]string, 0, len(ids))
for _, id := range ids {
lbls, ok := id2Labels[id]
if !ok && ve.strictMetricCreation {
fmt.Fprintf(ve.output, "ID %10d does not exists in ID2Labels, partial write ?\n", id)
hadIssue = true
if ve.doFix {
ve.bulkDeleter.PrepareDelete(id, nil, false)
}
}
if !ok {
if _, err := ve.expectedUnknowDate.AddN(uint64(id)); err != nil {
return false, err
}
continue
}
allLabelsString = append(allLabelsString, lbls.String())
_, ok = id2expiration[id]
if !ok {
fmt.Fprintf(
ve.output,
"ID %10d (%v) found in ID2labels but not for expiration! You may need to took the lock to verify\n",
id,
lbls.String(),
)
hadIssue = true
}
if !ok {
if _, err := ve.expectedUnknowDate.AddN(uint64(id)); err != nil {
return false, err
}
continue
}
}
if ctx.Err() != nil {
return hadIssue, ctx.Err()
}
labels2ID, err := ve.index.selectLabelsList2ID(ctx, allLabelsString)
if err != nil {
return hadIssue, fmt.Errorf("get labels2ID: %w", err)
}
for _, id := range ids {
if ctx.Err() != nil {
return hadIssue, ctx.Err()
}
lbls, ok := id2Labels[id]
if !ok {
continue
}
expiration, ok := id2expiration[id]
if !ok {
continue
}
expirationDay := expiration.Truncate(24 * time.Hour)
it := ve.expectedExpiration[expirationDay.Unix()]
if it == nil {
it = roaring.NewBTreeBitmap()
}
if _, err := it.AddN(uint64(id)); err != nil {
return false, err
}
ve.expectedExpiration[expirationDay.Unix()] = it
id2, ok := labels2ID[lbls.String()]
if !ok && ve.strictMetricCreation {
fmt.Fprintf(ve.output, "ID %10d (%v) not found in Labels2ID, partial write ?\n", id, lbls.String())
hadIssue = true
if ve.doFix {
ve.bulkDeleter.PrepareDelete(id, lbls, false)
}
}
if !ok {
continue
}
if id != id2 { //nolint:nestif
tmp, tmp2, err := ve.index.selectIDS2LabelsAndExpiration(ctx, []types.MetricID{id2})
if err != nil {
return hadIssue, fmt.Errorf("get labels from store: %w", err)
}
lbls2 := tmp[id2]
expiration2, ok := tmp2[id2]
if !ok && lbls2 != nil {
fmt.Fprintf(
ve.output,
"ID %10d (%v) found in ID2labels but not for expiration! You may need to took the lock to verify",
id2,
lbls2.String(),
)
hadIssue = true
continue
}
switch {
case lbls2 == nil:
fmt.Fprintf(
ve.output,
"ID %10d (%v) conflict with ID %d (which is a partial write! THIS SHOULD NOT HAPPEN.)\n",
id,
lbls.String(),
id2,
)
hadIssue = true
if ve.doFix {
// well, the only solution is to delete *both* ID.
ve.bulkDeleter.PrepareDelete(id2, lbls, false)
ve.bulkDeleter.PrepareDelete(id, lbls, false)
}
case !ve.allPosting.Contains(uint64(id2)):
fmt.Fprintf(
ve.output,
"ID %10d (%v) conflict with ID %d (which isn't listed in all posting! THIS SHOULD NOT HAPPEN.)\n",
id,
lbls.String(),
id2,
)
hadIssue = true
if ve.doFix {
// well, the only solution is to delete *both* ID.
ve.bulkDeleter.PrepareDelete(id2, lbls2, false)
ve.bulkDeleter.PrepareDelete(id, lbls, false)
}
case ve.strictMetricCreation:
fmt.Fprintf(
ve.output,
"ID %10d (%v) conflict with ID %d (%v). first expire at %v, second at %v\n",
id,
lbls.String(),
id2,
lbls2.String(),
expiration,
expiration2,
)
hadIssue = true
// Assume that metric2 is better. It has id2labels, labels2id and in all postings
if ve.doFix {
ve.bulkDeleter.PrepareDelete(id, lbls, true)
}
}
continue
}
if ve.now.After(expiration.Add(24 * time.Hour)) {
fmt.Fprintf(ve.output, "ID %10d (%v) should have expired on %v\n", id, lbls.String(), expiration)
hadIssue = true
if ve.doFix {
ve.bulkDeleter.PrepareDelete(id, lbls, false)
}
continue
}
_, err = ve.allGoodIDs.AddN(uint64(id))
if err != nil {
return hadIssue, fmt.Errorf("update bitmap: %w", err)
}
}
return hadIssue, nil
}
// check that postings for given shard is consistent.
func (ve *verifierExecution) verifyShard( //nolint:maintidx
ctx context.Context,
shard int32,
) (hadIssue bool, err error) {
updates := make([]postingUpdateRequest, 0)
labelToIndex := make(map[labels.Label]int)
localAll, err := ve.index.postings(ctx, []int32{shard}, allPostingLabel, allPostingLabel, false)
if err != nil {
return false, err
}
localMaybe, err := ve.index.postings(ctx, []int32{shard}, maybePostingLabel, maybePostingLabel, false)
if err != nil {
return false, err
}
if !localAll.Any() {
hadIssue = true
fmt.Fprintf(
ve.output,
"shard %s is empty (automatic cleanup may fix this)!\n",
timeForShard(shard).Format(shardDateFormat),
)
}
if !localMaybe.Any() {
hadIssue = true
fmt.Fprintf(
ve.output,
"shard %s is empty!\n",
timeForShard(shard).Format(shardDateFormat),
)
}
tmp := localAll.Difference(localMaybe)
it := tmp.Iterator()
for {
id, eof := it.Next()
if eof {
break
}
hadIssue = true
fmt.Fprintf(
ve.output,
"shard %s: ID %d is present in localAll but not in localMaybe!\n",
timeForShard(shard).Format(shardDateFormat),
id,
)
if ve.doFix {
lbl := labels.Label{
Name: maybePostingLabel,
Value: maybePostingLabel,
}
idx, ok := labelToIndex[lbl]
if !ok {
idx = len(updates)
updates = append(updates, postingUpdateRequest{
Label: lbl,
Shard: shard,
})
labelToIndex[lbl] = idx
}
updates[idx].AddIDs = append(updates[idx].AddIDs, id)
}
}
tmp = localMaybe.Difference(localAll)
it = tmp.Iterator()
for {
id, eof := it.Next()
if eof {
break
}
hadIssue = true
fmt.Fprintf(
ve.output,
"shard %s: ID %d is present in localMaybe but not in localAll (automatic cleanup may fix this)!\n",
timeForShard(shard).Format(shardDateFormat),
id,
)
if ve.doFix {
lbl := labels.Label{
Name: maybePostingLabel,
Value: maybePostingLabel,
}
idx, ok := labelToIndex[lbl]
if !ok {
idx = len(updates)
updates = append(updates, postingUpdateRequest{
Label: lbl,
Shard: shard,
})
labelToIndex[lbl] = idx
}
updates[idx].RemoveIDs = append(updates[idx].RemoveIDs, id)
}
}
wantedPostings := make(map[labels.Label]*roaring.Bitmap)
labelNames := make(map[string]interface{})
it = localAll.Iterator()
pendingIDs := make([]types.MetricID, 0, 10000)
for ctx.Err() == nil {
pendingIDs = pendingIDs[:0]
for ctx.Err() == nil {
id, eof := it.Next()
if eof {
break
}
pendingIDs = append(pendingIDs, types.MetricID(id))
if len(pendingIDs) > 1000 {
break
}
}
if len(pendingIDs) == 0 {
break
}
tmp, _, err := ve.index.selectIDS2LabelsAndExpiration(ctx, pendingIDs)
if err != nil {
return true, fmt.Errorf("get labels: %w", err)
}
for id, lbls := range tmp {
for _, lbl := range lbls {
labelNames[lbl.Name] = nil
bitset := wantedPostings[lbl]
if bitset == nil {
bitset = roaring.NewBTreeBitmap()
}
_, err = bitset.AddN(uint64(id))
if err != nil {
return true, fmt.Errorf("update bitmap: %w", err)
}
wantedPostings[lbl] = bitset
lbl2 := labels.Label{
Name: postinglabelName,
Value: lbl.Name,
}
bitset = wantedPostings[lbl2]
if bitset == nil {
bitset = roaring.NewBTreeBitmap()
}
_, err = bitset.AddN(uint64(id))
if err != nil {
return true, fmt.Errorf("update bitmap: %w", err)
}
wantedPostings[lbl2] = bitset
}
}
}
references := []struct {
it *roaring.Bitmap
name string
}{
{name: "global all IDs", it: ve.allPosting},
{name: "shard all IDs", it: localAll},
{name: "shard maybe present IDs", it: localMaybe},
}
labelNames[postinglabelName] = true
iter := ve.index.store.SelectPostingByName(ctx, shard, postinglabelName)
defer iter.Close()
for iter.HasNext() {
labelValue, buffer := iter.Next()
if _, ok := labelNames[labelValue]; !ok { //nolint:nestif
hadIssue = true
fmt.Fprintf(
ve.output,
"shard %s: postinglabelName has extra name=%s\n",
timeForShard(shard).Format(shardDateFormat),
labelValue,
)
if ve.doFix {
lbl := labels.Label{
Name: postinglabelName,
Value: labelValue,
}
tmp := roaring.NewBTreeBitmap()
err := tmp.UnmarshalBinary(buffer)
if err != nil {
return hadIssue, fmt.Errorf("unmarshal fail: %w", err)
}
idx, ok := labelToIndex[lbl]
if !ok {
idx = len(updates)
updates = append(updates, postingUpdateRequest{
Label: lbl,
Shard: shard,
})
labelToIndex[lbl] = idx
}
updates[idx].RemoveIDs = append(updates[idx].RemoveIDs, tmp.Slice()...)
}
}
}
for name := range labelNames {
if ctx.Err() != nil {
break
}
iter := ve.index.store.SelectPostingByName(ctx, shard, name)
defer iter.Close()
for iter.HasNext() {
tmp := roaring.NewBTreeBitmap()
labelValue, buffer := iter.Next()
err := tmp.UnmarshalBinary(buffer)
if err != nil {
return hadIssue, fmt.Errorf("unmarshal fail: %w", err)
}
lbl := labels.Label{
Name: name,
Value: labelValue,
}
wanted := wantedPostings[lbl]
if wanted == nil { //nolint:nestif
hadIssue = true
fmt.Fprintf(
ve.output,
"shard %s: extra posting for %s=%s exists (with %d IDs)\n",
timeForShard(shard).Format(shardDateFormat),
name,
labelValue,
tmp.Count(),
)
if ve.doFix {
idx, ok := labelToIndex[lbl]
if !ok {
idx = len(updates)
updates = append(updates, postingUpdateRequest{
Label: lbl,
Shard: shard,
})
labelToIndex[lbl] = idx
}
updates[idx].RemoveIDs = append(updates[idx].RemoveIDs, tmp.Slice()...)
}
} else {
delete(wantedPostings, lbl)
tmp2 := wanted.Difference(tmp)
it := tmp2.Iterator()
for {
id, eof := it.Next()
if eof {
break
}
hadIssue = true
fmt.Fprintf(
ve.output,
"shard %s: missing ID %d in posting for %s=%s\n",
timeForShard(shard).Format(shardDateFormat),
id,
name,
labelValue,
)
if ve.doFix {
idx, ok := labelToIndex[lbl]
if !ok {
idx = len(updates)
updates = append(updates, postingUpdateRequest{
Label: lbl,
Shard: shard,
})
labelToIndex[lbl] = idx
}
updates[idx].AddIDs = append(updates[idx].AddIDs, id)
}
}
tmp2 = tmp.Difference(wanted)
it = tmp2.Iterator()
for {
id, eof := it.Next()
if eof {
break
}
hadIssue = true
fmt.Fprintf(
ve.output,
"shard %s: extra ID %d in posting for %s=%s (present in maybe=%v allId=%v globalAll=%v)\n",
timeForShard(shard).Format(shardDateFormat),
id,
name,
labelValue,
localMaybe.Contains(id),
localAll.Contains(id),
ve.allPosting.Contains(id),
)
if ve.doFix {
idx, ok := labelToIndex[lbl]
if !ok {
idx = len(updates)
updates = append(updates, postingUpdateRequest{
Label: lbl,
Shard: shard,
})
labelToIndex[lbl] = idx
}
updates[idx].RemoveIDs = append(updates[idx].RemoveIDs, id)
}
}
}
for _, reference := range references {
tmp = tmp.Difference(reference.it)
it := tmp.Iterator()
for ctx.Err() == nil {
id, eof := it.Next()
if eof {
break
}
hadIssue = true
fmt.Fprintf(
ve.output,
"shard %s: posting for %s=%s has ID %d which is not in %s!\n",
timeForShard(shard).Format(shardDateFormat),
name,
labelValue,
id,
reference.name,
)
}
}
}
}
for lbl, wantValue := range wantedPostings {
hadIssue = true
fmt.Fprintf(
ve.output,
"shard %s: posting %s=%s was expected to exists\n",
timeForShard(shard).Format(shardDateFormat),
lbl.Name,
lbl.Value,
)
if ve.doFix {
idx, ok := labelToIndex[lbl]
if !ok {
idx = len(updates)
updates = append(updates, postingUpdateRequest{
Label: lbl,
Shard: shard,
})
labelToIndex[lbl] = idx
}
updates[idx].AddIDs = append(updates[idx].AddIDs, wantValue.Slice()...)
}
}
if ve.doFix && len(updates) > 0 {
err = ve.index.concurrentTasks(
ctx,
concurrentInsert,
func(ctx context.Context, work chan<- func() error) error {
for _, req := range updates {
task := func() error {
_, err := ve.index.postingUpdate(ctx, req)
if errors.Is(err, errBitmapEmpty) {
err = nil
}
return err
}
select {
case work <- task:
case <-ctx.Done():
return ctx.Err()
}
}