-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.go
4536 lines (3644 loc) · 117 KB
/
index.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"
"cmp"
"context"
"encoding/csv"
"encoding/gob"
"errors"
"fmt"
"io"
"math"
"math/rand"
"regexp/syntax"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/bleemeo/squirreldb/cassandra/connection"
"github.com/bleemeo/squirreldb/logger"
"github.com/bleemeo/squirreldb/types"
"github.com/cenkalti/backoff/v4"
"github.com/gocql/gocql"
"github.com/pilosa/pilosa/v2/roaring"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/prometheus/model/labels"
"github.com/rs/zerolog"
"golang.org/x/sync/errgroup"
)
const backgroundCheckInterval = time.Minute
const cacheExpirationDelay = 300 * time.Second
const (
concurrentInsert = 20
concurrentDelete = 20
concurrentPostingRead = 20
concurrentRead = 4
maxCQLInValue = 100 // limit of the number of value for the "IN" clause of a CQL query
verifyBulkSize = 1000
// Simple regex composed of less than maxOpAlertnateSubsForSimpleRegex OR
// clauses are simplified to multiple non regex matchers.
maxOpAlertnateSubsForSimpleRegex = 10
)
const (
metricCreationLockTimeToLive = 15 * time.Second
metricExpiratorLockTimeToLive = 10 * time.Minute
blockLockTimeToLive = 5 * time.Minute
)
// Update TTL of index entries in Cassandra every update delay.
// The actual TTL used in Cassandra is the metric data TTL + update delay.
// With long delay, there will be less updates on Cassandra, but entries will stay
// longer before being expired.
// This delay will have between 0 and cassandraTTLUpdateJitter added to avoid
// all update to happen at the same time.
const (
cassandraTTLUpdateDelay = 24 * time.Hour
cassandraTTLUpdateJitter = time.Hour
)
const (
clusterChannelPostingInvalidate = "index-invalidate-postings"
newMetricLockName = "index-new-metric"
expireMetricLockName = "index-ttl-metric"
expireMetricStateName = "index-expired-until"
expireBatchSize = 1000
)
const (
// The expiration of entries in Cassandra starts everyday at 00:00 UTC + expirationStartOffset.
expirationStartOffset = 6 * time.Hour
// The expiration is checked every expirationCheckInterval.
expirationCheckInterval = 15 * time.Minute
)
//nolint:gochecknoglobals
var (
// Shards <= 0 are invalid.
indexMinValidTime = time.Date(1971, 1, 1, 0, 0, 0, 0, time.UTC)
indexMaxValidTime = time.Date(100000, 1, 1, 0, 0, 0, 0, time.UTC)
)
var (
errTimeOutOfRange = errors.New("time out of range")
errBitmapEmpty = errors.New("the result bitmap is empty")
errNotASimpleRegex = errors.New("not a simple regex")
errNewMetricLockNotAcquired = errors.New("newMetricGlobalLock is not acquired")
errMetricDoesNotExist = errors.New("metric doesn't exist")
)
type idData struct {
cassandraEntryExpiration time.Time
cacheExpirationTime time.Time
mostRecentShard int32
unsortedLabels labels.Labels
id types.MetricID
}
type lockFactory interface {
CreateLock(name string, timeToLive time.Duration) types.TryLocker
}
type Options struct {
LockFactory lockFactory
States types.State
SchemaLock sync.Locker
Cluster types.Cluster
DefaultTimeToLive time.Duration
TenantLabelName string
PreCreateShardDuration time.Duration
PreCreateShardFraction int
ReadOnly bool
Logger zerolog.Logger
// InternalRunOnceCalled is true if this index is used by some testings/benchmarking tools
// that will call RunOnce directly.
InternalRunOnceCalled bool
// InternalNowFunction is the function used to get current time. It default to time.Now().
// This is useful when doing test that need to simulate long period of time.
InternalNowFunction func() time.Time
}
type CassandraIndex struct {
store storeImpl
options Options
wg sync.WaitGroup
cancel context.CancelFunc
// The three locks used in index are:
// * lookupIDMutex is a local lock and only protect local (in-memory) value.
// * newMetricGlobalLock is a global lock and protect values in Cassandra. It protect any
// value that could be written during metric creation. Since metric creation is done
// synchroniously when writing points, this lock should not be held for too long.
// * expirationGlobalLock is a global lock and protect values in Cassandra. Unlike newMetricGlobalLock
// it protect value that can't we written on metric creation.
lookupIDMutex sync.Mutex
postingCacheAccess sync.Mutex
newMetricGlobalLock types.TryLocker
expirationGlobalLock types.TryLocker
expirationUpdateRequests map[int64]expirationUpdateRequest
expirationBackoff backoff.BackOff
nextExpirationAt time.Time
labelsToID map[uint64][]idData
idInShard map[int32]*roaring.Bitmap
idInShardLastAccess map[int32]time.Time
existingShards *roaring.Bitmap
idsToLabels *labelsLookupCache
postingsCache *postingsCache
shardExpirationCache *shardExpirationCache
metrics *metrics
logger zerolog.Logger
}
func (c *CassandraIndex) getIDData(key uint64, unsortedLabels labels.Labels) (idData, bool) {
list := c.labelsToID[key]
for _, r := range list {
if labels.Equal(r.unsortedLabels, unsortedLabels) {
return r, true
}
}
return idData{}, false
}
func (c *CassandraIndex) setIDData(key uint64, value idData) {
list := c.labelsToID[key]
for i, r := range list {
if labels.Equal(r.unsortedLabels, value.unsortedLabels) {
list[i] = value
c.labelsToID[key] = list
return
}
}
list = append(list, value)
c.labelsToID[key] = list
c.metrics.CacheSize.WithLabelValues("lookup-id").Inc()
}
type storeImpl interface {
Init(ctx context.Context) error
SelectLabelsList2ID(ctx context.Context, sortedLabelsListString []string) (map[string]types.MetricID, error)
SelectIDS2LabelsAndExpiration(
ctx context.Context,
id []types.MetricID,
) (map[types.MetricID]labels.Labels, map[types.MetricID]time.Time, error)
SelectExpiration(ctx context.Context, day time.Time) ([]byte, error)
// SelectPostingByName return label value with the associated postings in sorted order
SelectPostingByName(ctx context.Context, shard int32, name string) postingIter
SelectPostingByNameValue(ctx context.Context, shard int32, name string, value string) ([]byte, error)
SelectValueForName(ctx context.Context, shard int32, name string) ([]string, [][]byte, error)
InsertPostings(ctx context.Context, shard int32, name string, value string, bitset []byte) error
InsertID2Labels(ctx context.Context, id types.MetricID, sortedLabels labels.Labels, expiration time.Time) error
InsertLabels2ID(ctx context.Context, sortedLabelsString string, id types.MetricID) error
InsertExpiration(ctx context.Context, day time.Time, bitset []byte) error
UpdateID2LabelsExpiration(ctx context.Context, id types.MetricID, expiration time.Time) error
DeleteLabels2ID(ctx context.Context, sortedLabelsString string) error
DeleteID2Labels(ctx context.Context, id types.MetricID) error
DeleteExpiration(ctx context.Context, day time.Time) error
DeletePostings(ctx context.Context, shard int32, name string, value string) error
DeletePostingsByNames(ctx context.Context, shard int32, names []string) error
}
const (
globalAllPostingLabel = "__global__all|metrics__" // we use the "|" since it's invalid for prometheus label name
allPostingLabel = "__all|metrics__"
postinglabelName = "__label|names__" // kept known labels name as label value
// ID are added in two-phase in postings. This one is updated first. See updatePostings.
maybePostingLabel = "__maybe|metrics__"
// existingShardsLabel is the label name used to store all known shards in postings.
existingShardsLabel = "__shard|exists__"
// expirationShardLabel is the label name used to store the expiration of a shard.
expirationShardLabel = "__shard|expiration"
postingShardSize = 7 * 24 * time.Hour
shardDateFormat = "2006-01-02"
// globalShardNumber value is an impossible value for a normal shard,
// because postingShardSize is a multiple of 2 hours making odd shard number
// impossible.
// Index is sharded by time for postings. The shard number (an int32) is the
// rounded to postingShardSize number of hours since epoc (1970).
globalShardNumber = -1
)
// New creates a new CassandraIndex object.
func New(
ctx context.Context,
reg prometheus.Registerer,
connection *connection.Connection,
options Options,
logger zerolog.Logger,
) (*CassandraIndex, error) {
metrics := newMetrics(reg)
return initialize(
ctx,
cassandraStore{
connection: connection,
schemaLock: options.SchemaLock,
metrics: metrics,
},
options,
metrics,
logger,
)
}
func initialize(
ctx context.Context,
store storeImpl,
options Options,
metrics *metrics,
logger zerolog.Logger,
) (*CassandraIndex, error) {
expBackoff := backoff.NewExponentialBackOff()
expBackoff.InitialInterval = time.Minute
expBackoff.MaxInterval = 15 * time.Minute
expBackoff.MaxElapsedTime = 0
expBackoff.Reset()
if options.InternalNowFunction == nil {
options.InternalNowFunction = time.Now
}
index := &CassandraIndex{
store: store,
options: options,
idInShard: make(map[int32]*roaring.Bitmap),
idInShardLastAccess: make(map[int32]time.Time),
labelsToID: make(map[uint64][]idData),
idsToLabels: &labelsLookupCache{cache: make(map[types.MetricID]labelsEntry)},
postingsCache: &postingsCache{
nowFunc: options.InternalNowFunction,
cache: make(map[postingsCacheKey]postingEntry),
},
shardExpirationCache: &shardExpirationCache{},
expirationUpdateRequests: make(map[int64]expirationUpdateRequest),
expirationBackoff: expBackoff,
newMetricGlobalLock: options.LockFactory.CreateLock(newMetricLockName, metricCreationLockTimeToLive),
expirationGlobalLock: options.LockFactory.CreateLock(expireMetricLockName, metricExpiratorLockTimeToLive),
metrics: metrics,
logger: logger,
}
if options.ReadOnly {
options.Logger.Debug().Msg("Read-only mode is activated. Not trying to initialize store and assuming it's done")
} else {
if err := index.store.Init(ctx); err != nil {
return nil, fmt.Errorf("failed to initialize store: %w", err)
}
}
options.Cluster.Subscribe(clusterChannelPostingInvalidate, index.invalidatePostingsListenner)
return index, nil
}
// Start starts all Cassandra Index services.
func (c *CassandraIndex) Start(_ context.Context) error { //nolint: contextcheck
if c.cancel != nil {
return nil
}
ctx, cancel := context.WithCancel(context.Background())
c.cancel = cancel
c.wg.Add(1)
go func() {
defer logger.ProcessPanic()
c.run(ctx)
}()
return nil
}
// Stop stop and wait all Cassandra Index services.
func (c *CassandraIndex) Stop() error {
if c.cancel == nil {
return errors.New("not started")
}
c.cancel()
c.cancel = nil
c.wg.Wait()
return nil
}
func (c *CassandraIndex) run(ctx context.Context) {
ticker := time.NewTicker(backgroundCheckInterval)
defer ticker.Stop()
for ctx.Err() == nil {
select {
case <-ticker.C:
if c.options.InternalRunOnceCalled {
continue
}
c.InternalRunOnce(ctx, c.options.InternalNowFunction())
case <-ctx.Done():
c.logger.Trace().Msg("Cassandra index service stopped")
return
}
}
}
// InternalRunOnce run the tasks scheduled by Run, return true if more work is pending.
// Prefer using Start() than calling InternalRunOnce multiple time. InternalRunOnce is mostly here
// for squirreldb-cassandra-index-bench program.
// When using InternalRunOnce you should set option InternalRunOnceCalled to true or you could cause
// some race condition.
func (c *CassandraIndex) InternalRunOnce(ctx context.Context, now time.Time) bool {
c.expire(now)
c.applyExpirationUpdateRequests(ctx, now)
c.periodicRefreshIDInShard(ctx, now)
c.shardPrecreate(ctx, now)
// Expire entries in cassandra every minute when there is more work, every 15mn when all work is done,
// or with an exponential backoff between 1mn and 15mn when errors occurs.
if now.Before(c.nextExpirationAt) {
return false
}
moreWork, err := c.cassandraExpire(ctx, now)
if err != nil {
nextBackoff := c.expirationBackoff.NextBackOff()
c.nextExpirationAt = now.Add(nextBackoff)
c.logger.Warn().Err(err).Msgf("Retrying in %v", nextBackoff.Round(time.Second))
} else {
c.expirationBackoff.Reset()
if !moreWork {
c.nextExpirationAt = now.Add(expirationCheckInterval)
}
}
return moreWork
}
func (c *CassandraIndex) shardPrecreate(ctx context.Context, now time.Time) {
nowShard := shardForTime(now.Unix())
futureShard := shardForTime(now.Add(c.options.PreCreateShardDuration).Unix())
if nowShard == futureShard {
return
}
updates := c.shardPrecreateGetBatch(futureShard)
c.logger.Debug().Msgf("shard pre-creation will do %d updates of posting", len(updates))
if len(updates) > 0 {
err := c.updatePostingShards(ctx, updates, true)
if err != nil {
c.logger.Warn().Err(err).Msg("shard pre-creation failed (this is an optimization, failing isn't fatal)")
return
}
// Update mostRecentShard for submitted updates
c.lookupIDMutex.Lock()
defer c.lookupIDMutex.Unlock()
for _, update := range updates {
entry, ok := c.labelsToID[update.idData.unsortedLabels.Hash()]
if !ok {
continue
}
for idx, row := range entry {
if labels.Compare(row.unsortedLabels, update.unsortedLabels) == 0 {
entry[idx].mostRecentShard = futureShard
}
}
}
}
}
func (c *CassandraIndex) shardPrecreateGetBatch(futureShard int32) []lookupEntry {
var updates []lookupEntry
c.lookupIDMutex.Lock()
defer c.lookupIDMutex.Unlock()
totalIDCount := 0
for _, idList := range c.labelsToID {
totalIDCount += len(idList)
}
numberOfUpdates := int(math.Ceil(float64(totalIDCount) / float64(c.options.PreCreateShardFraction)))
allLabelsKeys := make([]uint64, 0, len(c.labelsToID))
for key := range c.labelsToID {
allLabelsKeys = append(allLabelsKeys, key)
}
// sort the label to process to group the similar one together.
// The more similar metrics are grouped, the less update will be submitted, because an
// update of posting "__name__=disk_used" is one Cassandra update regardless of the number of metric IDs
// to add/remove for this posting.
// The tenant label is used to group similar metrics (because at least the tenant value is the same),
// and it feels a good candidate.
// The instance (server name) is the second label, to order with very large tenant.
slices.SortFunc(allLabelsKeys, func(x uint64, y uint64) int {
idList1 := c.labelsToID[x]
idList2 := c.labelsToID[y]
var (
tenantValue1, tenantValue2 string
instanceValue1, instanceValue2 string
)
// There is some approximation is sorting, especially only first idData is used, but:
// * normally only one idData exist in the list (or their is a conflict in labels Hash())
// * anyway this is for an optional optimization, if their is few wrong grouping it won't
// impact significantly the performance.
if len(idList1) > 0 {
tenantValue1 = idList1[0].unsortedLabels.Get(c.options.TenantLabelName)
instanceValue1 = idList1[0].unsortedLabels.Get("instance")
}
if len(idList2) > 0 {
tenantValue2 = idList2[0].unsortedLabels.Get(c.options.TenantLabelName)
instanceValue2 = idList2[0].unsortedLabels.Get("instance")
}
if tenantValue1 == tenantValue2 {
return cmp.Compare(instanceValue1, instanceValue2)
}
return cmp.Compare(tenantValue1, tenantValue2)
})
for _, labelsKey := range allLabelsKeys {
idList := c.labelsToID[labelsKey]
for _, data := range idList {
if data.mostRecentShard < futureShard {
if updates == nil {
updates = make([]lookupEntry, 0, numberOfUpdates)
}
updates = append(updates, lookupEntry{
idData: data,
labelsKey: labelsKey,
wantedShards: []int32{futureShard},
})
if len(updates) >= numberOfUpdates {
break
}
}
}
if len(updates) >= numberOfUpdates {
break
}
}
return updates
}
func (c *CassandraIndex) deleteIDsFromCache(deleteIDs []uint64) {
if len(deleteIDs) > 0 {
c.lookupIDMutex.Lock()
size := c.idsToLabels.Drop(deleteIDs)
c.metrics.CacheSize.WithLabelValues("lookup-labels").Set(float64(size))
// Since we don't force sorting labels on input, we don't known the key used
// for c.labelsToID (it's likely to be keyFromLabels(sortedLabels))
deleteIDsMap := make(map[types.MetricID]bool, len(deleteIDs))
for _, id := range deleteIDs {
deleteIDsMap[types.MetricID(id)] = true
}
for key, idsData := range c.labelsToID {
for _, v := range idsData {
if deleteIDsMap[v.id] {
// This may delete too many entry, but:
// 1) normally only 1 entry match the hash
// 2) it's a cache, we don't loss data
delete(c.labelsToID, key)
c.metrics.CacheSize.WithLabelValues("lookup-id").Sub(float64(len(idsData)))
break
}
}
}
for shard, bitmap := range c.idInShard {
_, _ = bitmap.RemoveN(deleteIDs...)
c.idInShard[shard] = bitmap
}
c.lookupIDMutex.Unlock()
}
}
func (c *CassandraIndex) getMaybePresent(ctx context.Context, shards []uint64) (map[int32]*roaring.Bitmap, error) {
results := make(map[int32]*roaring.Bitmap, len(shards))
l := &sync.Mutex{}
return results, c.concurrentTasks(
ctx,
concurrentPostingRead,
func(ctx context.Context, work chan<- func() error) error {
for _, shard := range shards {
shard := int32(shard)
task := func() error {
tmp, err := c.postings(ctx, []int32{shard}, maybePostingLabel, maybePostingLabel, false)
if err != nil {
return err
}
l.Lock()
results[shard] = tmp
l.Unlock()
return nil
}
select {
case work <- task:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
},
)
}
// Dump writes a CSV with all metrics known by this index.
// The format should not be considered stable and should only be used for debugging.
func (c *CassandraIndex) Dump(ctx context.Context, w io.Writer) error {
allPosting, err := c.postings(ctx, []int32{globalShardNumber}, globalAllPostingLabel, globalAllPostingLabel, false)
if err != nil {
return err
}
csvWriter := csv.NewWriter(w)
defer csvWriter.Flush()
if err := c.dumpPostings(ctx, csvWriter, allPosting); err != nil {
return err
}
return ctx.Err()
}
func (c *CassandraIndex) DumpByLabels(
ctx context.Context,
w io.Writer,
start, end time.Time,
matchers []*labels.Matcher,
) error {
metrics, err := c.Search(ctx, start, end, matchers)
if err != nil {
fmt.Fprintf(w, "fail to search labels: %v", err)
return nil
}
ids := make([]types.MetricID, 0, metrics.Count())
for metrics.Next() {
ids = append(ids, metrics.At().ID)
}
csvWriter := csv.NewWriter(w)
defer csvWriter.Flush()
return c.dumpBulk(ctx, csvWriter, ids)
}
func (c *CassandraIndex) DumpByExpirationDate(ctx context.Context, w io.Writer, expirationDate time.Time) error {
expirationBitmap, err := c.cassandraGetExpirationList(ctx, expirationDate.Truncate(24*time.Hour))
if err != nil {
return fmt.Errorf("unable to get metric expiration list: %w", err)
}
csvWriter := csv.NewWriter(w)
defer csvWriter.Flush()
if err := c.dumpPostings(ctx, csvWriter, expirationBitmap); err != nil {
return err
}
return ctx.Err()
}
func (c *CassandraIndex) DumpByShard(ctx context.Context, w io.Writer, shard time.Time) error {
allPosting, err := c.postings(ctx, []int32{shardForTime(shard.Unix())}, allPostingLabel, allPostingLabel, false)
if err != nil {
return fmt.Errorf("unable to get metric expiration list: %w", err)
}
csvWriter := csv.NewWriter(w)
defer csvWriter.Flush()
if err := c.dumpPostings(ctx, csvWriter, allPosting); err != nil {
return err
}
return ctx.Err()
}
func (c *CassandraIndex) DumpByPosting(
ctx context.Context,
w io.Writer,
shard time.Time,
name string,
value string,
) error {
shardID := shardForTime(shard.Unix())
if shard.IsZero() {
shardID = globalShardNumber
}
csvWriter := csv.NewWriter(w)
defer csvWriter.Flush()
if value == "" {
return c.dumpByPostingByName(ctx, csvWriter, shardID, name)
}
allPosting, err := c.postings(ctx, []int32{shardID}, name, value, false)
if err != nil {
return fmt.Errorf("unable to get metric expiration list: %w", err)
}
if err := c.dumpPostings(ctx, csvWriter, allPosting); err != nil {
return err
}
return ctx.Err()
}
func (c *CassandraIndex) dumpByPostingByName(
ctx context.Context,
csvWriter *csv.Writer,
shardID int32,
name string,
) error {
iter := c.store.SelectPostingByName(ctx, shardID, name)
defer iter.Close()
for iter.HasNext() {
tmp := roaring.NewBTreeBitmap()
labelValue, buffer := iter.Next()
err := tmp.UnmarshalBinary(buffer)
if err != nil {
return fmt.Errorf("unmarshal fail on %s=%s: %w", name, labelValue, err)
}
if tmp.Count() == 0 {
csvLine := []string{
"-1",
fmt.Sprintf("warning: posting %s=%s is empty", name, labelValue),
}
err := csvWriter.Write(csvLine)
if err != nil {
return err
}
} else {
if err := c.dumpPostings(ctx, csvWriter, tmp); err != nil {
return err
}
}
}
return ctx.Err()
}
func (c *CassandraIndex) dumpPostings(ctx context.Context, w *csv.Writer, posting *roaring.Bitmap) error {
iter := posting.Iterator()
pendingIDs := make([]types.MetricID, expireBatchSize)
for ctx.Err() == nil {
pendingIDs = pendingIDs[0:expireBatchSize]
n := 0
for id, eof := iter.Next(); !eof && n < expireBatchSize; id, eof = iter.Next() {
pendingIDs[n] = types.MetricID(id)
n++
}
pendingIDs = pendingIDs[:n]
if len(pendingIDs) == 0 {
break
}
err := c.dumpBulk(ctx, w, pendingIDs)
if err != nil {
return err
}
}
return ctx.Err()
}
func (c *CassandraIndex) dumpBulk(ctx context.Context, w *csv.Writer, ids []types.MetricID) error {
id2Labels, id2Expiration, err := c.selectIDS2LabelsAndExpiration(ctx, ids)
if err != nil {
return fmt.Errorf("get labels: %w", err)
}
for _, id := range ids {
expiration, expirationOk := id2Expiration[id]
lbls, labelsOk := id2Labels[id]
var csvLine []string
switch {
case !labelsOk:
csvLine = []string{
strconv.FormatInt(int64(id), 10),
"Missing labels! Partial write ?",
"",
}
case !expirationOk:
csvLine = []string{
strconv.FormatInt(int64(id), 10),
lbls.String(),
"Missing expiration which shouldn't be possible !",
}
default:
csvLine = []string{
strconv.FormatInt(int64(id), 10),
lbls.String(),
expiration.String(),
}
}
err := w.Write(csvLine)
if err != nil {
return err
}
}
return nil
}
func (c *CassandraIndex) InfoGlobal(ctx context.Context, w io.Writer) error {
allPosting, err := c.postings(ctx, []int32{globalShardNumber}, globalAllPostingLabel, globalAllPostingLabel, false)
if err != nil {
return err
}
shards, err := c.postings(ctx, []int32{globalShardNumber}, existingShardsLabel, existingShardsLabel, false)
if err != nil {
return fmt.Errorf("get postings for existing shards: %w", err)
}
fmt.Fprintf(w, "Number of metrics in global all Postings: %d\n", allPosting.Count())
fmt.Fprintf(w, "Number of shards (shard size %s): %d\n", postingShardSize, shards.Count())
it := shards.Iterator()
for ctx.Err() == nil {
shard, eof := it.Next()
if eof {
break
}
postingShard, err := c.postings(ctx, []int32{int32(shard)}, allPostingLabel, allPostingLabel, false)
if err != nil {
return err
}
maybepostingShard, err := c.postings(ctx, []int32{int32(shard)}, maybePostingLabel, maybePostingLabel, false)
if err != nil {
return err
}
labelNamesCount := 0
iter := c.store.SelectPostingByName(ctx, int32(shard), postinglabelName)
for iter.HasNext() {
labelNamesCount++
}
iter.Close()
shardExpiration, _, err := c.getShardExpirationFromStore(ctx, int32(shard))
// Some shard expiration metrics may not exist if the shard were created before the
// expiration was introduced. In this case the expiration will be shown at 0001-01-01 00:00:00.
if err != nil && !errors.Is(err, errMetricDoesNotExist) {
return err
}
fmt.Fprintf(
w,
"Shard %s (ID %d) has %d metrics (and %d in maybePosting), %d label names and expires at %s\n",
timeForShard(int32(shard)).Format(shardDateFormat),
shard,
postingShard.Count(),
maybepostingShard.Count(),
labelNamesCount,
shardExpiration,
)
}
block, ttl, err := c.newMetricGlobalLock.BlockStatus(ctx)
if err != nil {
return err
}
if block {
fmt.Fprintf(w, "Lock %s is blocked with remaining TTL of %v\n", newMetricLockName, ttl)
} else {
fmt.Fprintf(w, "Lock %s is unblocked\n", newMetricLockName)
}
block, ttl, err = c.expirationGlobalLock.BlockStatus(ctx)
if err != nil {
return err
}
if block {
fmt.Fprintf(w, "Lock %s is blocked with remaining TTL of %v\n", expireMetricLockName, ttl)
} else {
fmt.Fprintf(w, "Lock %s is unblocked\n", expireMetricLockName)
}
return nil
}
func (c *CassandraIndex) InfoByID(ctx context.Context, w io.Writer, id types.MetricID) error {
labelsMap, expiration, err := c.store.SelectIDS2LabelsAndExpiration(ctx, []types.MetricID{id})
if err != nil {
return err
}
allPosting, err := c.postings(ctx, []int32{globalShardNumber}, globalAllPostingLabel, globalAllPostingLabel, false)
if err != nil {
return err
}
shards, err := c.postings(ctx, []int32{globalShardNumber}, existingShardsLabel, existingShardsLabel, false)
if err != nil {
return fmt.Errorf("get postings for existing shards: %w", err)
}
var lbls labels.Labels
if len(labelsMap) == 0 {
fmt.Fprintf(w, "Metric ID %d not found in id2labels and isInGlobal=%v\n", id, allPosting.Contains(uint64(id)))
} else {
lbls = labelsMap[id]
fmt.Fprintf(
w,
"Metric ID %d has label %s with expiration %s and isInGlobal=%v\n",
id,
lbls,
expiration[id],
allPosting.Contains(uint64(id)),
)
sortedLabels := sortLabels(lbls)
sortedLabelsString := sortedLabels.String()
resp, err := c.store.SelectLabelsList2ID(ctx, []string{sortedLabelsString})
if err != nil {
return err
}
if len(resp) == 0 {
fmt.Fprintf(w, "Labels %s not found in labels2id\n", sortedLabelsString)
} else {
fmt.Fprintf(w, "Labels %s found in labels2id and ID is %d\n", sortedLabelsString, resp[sortedLabelsString])
}
}
it := shards.Iterator()
for ctx.Err() == nil {
shard, eof := it.Next()
if eof {
break
}
postingShard, err := c.postings(ctx, []int32{int32(shard)}, allPostingLabel, allPostingLabel, false)
if err != nil {
return err
}
maybepostingShard, err := c.postings(ctx, []int32{int32(shard)}, maybePostingLabel, maybePostingLabel, false)
if err != nil {
return err
}
inPosting := postingShard.Contains(uint64(id))
inMaybe := maybepostingShard.Contains(uint64(id))
fmt.Fprintf(
w,
"Shard %s (ID %d) has the metric in posting=%v, maybePosting=%v\n",
timeForShard(int32(shard)).Format(shardDateFormat),
shard,
inPosting,
inMaybe,
)
if len(labelsMap) > 0 && (inPosting || inMaybe) {
missingPostings := make([]string, 0)
for _, l := range lbls {
posting, err := c.postings(ctx, []int32{int32(shard)}, l.Name, l.Value, false)
if err != nil {
return err
}
if !posting.Contains(uint64(id)) {
missingPostings = append(missingPostings, fmt.Sprintf("%s=%s", l.Name, l.Value))
}
}
if len(missingPostings) > 0 {
fmt.Fprintf(
w,
"Shard %s: the following postings are missing: %s\n",
timeForShard(int32(shard)).Format(shardDateFormat),
strings.Join(missingPostings, ", "),
)
} else {
fmt.Fprintf(w, "Shard %s: all postings are present\n", timeForShard(int32(shard)).Format(shardDateFormat))
}
}
}
return nil
}
func (c *CassandraIndex) BlockCassandraWrite(ctx context.Context) error {
if err := c.expirationGlobalLock.BlockLock(ctx, blockLockTimeToLive); err != nil {
return fmt.Errorf("block expirationGlobalLock fail: %w", err)
}