-
Notifications
You must be signed in to change notification settings - Fork 10
/
list.go
2290 lines (2104 loc) · 60.7 KB
/
list.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 rankdb
// Copyright 2019 Vivino. All rights reserved
//
// See LICENSE file for license details
//go:generate msgp $GOFILE
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/big"
"math/rand"
"os"
"runtime/debug"
"runtime/pprof"
"sort"
"sync"
"time"
"github.com/Vivino/rankdb/blobstore"
"github.com/Vivino/rankdb/log"
)
// List contains the segments representing a list
// as well as the index to look up segments by object ID.
//msgp:tuple List
type List struct {
sync.RWMutex `msg:"-" json:"-"`
ID ListID
Set string
Metadata map[string]string
SplitSize int
MergeSize int
LoadIndex bool
Scores SegmentsID
// segmentsLock is used to obtain access to scores/index segments.
// This lock should not be grabbed manually, but through loadSegments.
segmentsLock sync.RWMutex
scores *Segments
Index SegmentsID
index *Segments
// The update lock can be obtained when you need a consistent view of data in the list.
// This lock should not be grabbed manually, but through loadSegments.
updateLock sync.Mutex
manager *Manager
// Lock held while loading segments.
loadingLock sync.Mutex
cache Cache
}
// ListOption can be used to specify options when creating a list.
// Use either directly or use WithListOption.
//msgp:ignore ListOption
type ListOption func(*listOptions) error
type listOptions struct {
loadIndex bool
mergeSize, splitSize int
metadata map[string]string
populate []Element
clone *List
cache Cache
}
// defaultListOptions returns the default list options.
func defaultListOptions() listOptions {
return listOptions{
loadIndex: true,
mergeSize: 500, splitSize: 2000,
cache: nil,
}
}
// WithListOption provides an element to create list parameters.
var WithListOption = ListOption(nil)
// LoadIndex will signify that lists indexes should be loaded on startup.
// If not, they are loaded on demand, and reclaimed by the server based on global policy.
// By default indexes are loaded.
func (l ListOption) LoadIndex(b bool) ListOption {
return func(o *listOptions) error {
o.loadIndex = b
return nil
}
}
// Provide custom split/merge sizes for list.
// Merge must be < split.
func (l ListOption) MergeSplitSize(merge, split int) ListOption {
return func(o *listOptions) error {
o.mergeSize = merge
o.splitSize = split
if o.mergeSize >= o.splitSize {
return fmt.Errorf("MergeSplitSize: Merge size (%d) cannot be >= Split size (%d)", o.mergeSize, o.splitSize)
}
return nil
}
}
// Populate will populate the list with supplied elements.
func (l ListOption) Populate(e []Element) ListOption {
return func(o *listOptions) error {
o.populate = e
if o.clone != nil {
return errors.New("cannot both clone list and populate")
}
return nil
}
}
// Clone will populate the list with the content of another list.
func (l ListOption) Clone(lst *List) ListOption {
return func(o *listOptions) error {
o.clone = lst
if o.populate != nil {
return errors.New("cannot both clone list and populate")
}
return nil
}
}
// Metadata will set metadata.
func (l ListOption) Metadata(m map[string]string) ListOption {
return func(o *listOptions) error {
o.metadata = m
return nil
}
}
// Cache will set cache of the list.
func (l ListOption) Cache(cache Cache) ListOption {
return func(o *listOptions) error {
o.cache = cache
return nil
}
}
// NewList creates a new list.
// A list ID and storage set must be provided.
// Use WithListOption to access additional options.
func NewList(ctx context.Context, id ListID, set string, bs blobstore.Store, opts ...ListOption) (*List, error) {
ctx = log.WithFn(ctx, "list_id", id)
options := defaultListOptions()
for _, opt := range opts {
err := opt(&options)
if err != nil {
return nil, err
}
}
if set == "" {
return nil, fmt.Errorf("NewList: No list set provided")
}
if bs == nil {
return nil, fmt.Errorf("no storage provided")
}
l := List{
ID: id,
Set: set,
SplitSize: options.splitSize,
MergeSize: options.mergeSize,
LoadIndex: options.loadIndex,
Metadata: options.metadata,
cache: options.cache,
}
if len(options.populate) > 0 {
e := Elements(options.populate)
e.UpdateTime(time.Now())
err := l.Populate(ctx, bs, e)
if err != nil {
return nil, err
}
}
if options.clone != nil {
err := l.cloneElements(ctx, bs, options.clone)
if err != nil {
return nil, err
}
}
if l.Scores.Unset() {
segs, err := l.initEmptyList(ctx, bs, nil)
if segs != nil {
segs.unlock()
}
if err != nil {
return nil, err
}
}
l.scores.cache = l.cache
l.index.cache = l.cache
return &l, nil
}
// newList creates a new, empty list.
func newList(c Cache, m *Manager) *List {
return &List{cache: c, manager: m}
}
// initEmptyList will create an empty list.
// The segments are saved, but the list itself is not.
// It is possible to transfer update locks from a previous segment,
// if this is replacing existing segments and you hold the update lock.
// Segments will be returned locked.
func (l *List) initEmptyList(ctx context.Context, bs blobstore.Store, xfer *segments) (*segments, error) {
// Create empty element list.
store := blobstore.StoreWithSet(bs, l.Set)
ctx = log.WithFn(ctx)
segs := l.newSegments(ctx, 1, true, xfer)
ls := segs.scores.newLockedSegment(ctx, store, MaxSegment())
err := segs.scores.replaceSegment(ctx, store, ls)
if err != nil {
return segs, err
}
// Create empty index.
ls = segs.index.newLockedSegment(ctx, store, MaxSegment())
err = segs.index.replaceSegment(ctx, store, ls)
if err != nil {
return segs, err
}
// Save
err = l.saveSegments(ctx, bs, segs)
if err != nil {
return segs, err
}
// Verify what we've done.
return segs, l.verify(ctx, bs, segs)
}
// listVersion should be incremented if non-compatible changes are made.
const listVersion = 1
// updateSegments will update the segments on the list.
func (l *List) updateSegments(ctx context.Context, s *segments) {
ctx = log.WithFn(ctx)
if s.readOnly {
log.Error(ctx, "Was sent segment for update with readonly segment")
return
}
l.scores = s.scores
l.index = s.index
if s.scores != nil {
l.Scores = s.scores.ID
} else {
l.Scores = ""
}
if s.index != nil {
l.Index = s.index.ID
} else {
l.Index = ""
}
}
// loadFlags indicate the intentions of grabbing the segments.
// Only certain combinations of flags are allowed:
// * segsWritable + segsLockUpdates
// * segsReadOnly + segsLockUpdates
// * segsReadOnly + segsAllowUpdates
type loadFlags uint8
const (
// Make segments writeable.
// This is only needed when you intend to remove or add segments.
// It is not required if you only intend to update elements in the segments.
// If specified segsLockUpdates should also be used.
segsWritable loadFlags = 1 << iota
// Opposite of segsWritable. Specified for code clarity.
segsReadOnly
// Make segments update locked, meaning you want a consistent view of the elements.
segsLockUpdates
// Opposite of segsLockUpdates. Specified for code clarity.
segsAllowUpdates
)
// segments is a structure that controls access to "scores" and "index" *Segments.
// (*List).loadSegments() or (*List).newSegments()
type segments struct {
scores, index *Segments
// Unlock will release all locks.
unlock func()
readOnly bool
updateLocked bool
}
// removeUnlock will remove the unlock function and make it print an error
// if unlock is called again.
func (s *segments) removeUnlock(ctx context.Context) {
s.unlock = func() {
log.Error(ctx, "INTERNAL ERROR: double unlock of segments. Dumping stack.")
debug.PrintStack()
}
}
// loadSegments loads and locks the segments for either readonly or write operations.
// A write locked segment may be returned, even if a readonly was requested.
// Callers may *not* hold list lock while calling.
func (l *List) loadSegments(ctx context.Context, bs blobstore.Store, fl loadFlags) (*segments, error) {
ctx = log.WithFn(ctx)
readOnly := fl&segsReadOnly != 0
updateLock := fl&segsLockUpdates != 0
if readOnly && fl&segsWritable != 0 {
return nil, errors.New("internal error: both segsWritable and segsReadOnly specified")
}
if updateLock && fl&segsAllowUpdates != 0 {
return nil, errors.New("internal error: both segsLockUpdates and segsAllowUpdates specified")
}
if !readOnly && !updateLock {
return nil, errors.New("segsWritable without segsLockUpdates requested")
}
if updateLock {
l.updateLock.Lock()
}
l.loadingLock.Lock()
defer l.loadingLock.Unlock()
var err error
s := segments{}
if readOnly {
l.segmentsLock.RLock()
s.unlock = func() {
l.segmentsLock.RUnlock()
if updateLock {
l.updateLock.Unlock()
}
s.removeUnlock(ctx)
}
} else {
l.segmentsLock.Lock()
s.unlock = func() {
l.segmentsLock.Unlock()
if updateLock {
l.updateLock.Unlock()
}
s.removeUnlock(ctx)
}
}
s.scores = l.scores
s.index = l.index
s.readOnly = readOnly
s.updateLocked = updateLock
// If everything ok, return
if s.scores != nil && s.index != nil {
return &s, nil
}
if s.readOnly {
l.segmentsLock.RUnlock()
l.segmentsLock.Lock()
s.unlock = func() {
l.segmentsLock.Unlock()
if updateLock {
l.updateLock.Unlock()
}
}
s.readOnly = false
}
if s.scores == nil && !l.Scores.Unset() {
s.scores, err = l.Scores.Load(ctx, blobstore.StoreWithSet(bs, l.Set), l.cache)
if err != nil {
log.Error(ctx, "Error loading scores segments", "error", err, "scores_id", l.Scores, "list_id", l.ID)
s.unlock()
return nil, err
}
}
if s.index == nil && !l.Index.Unset() {
s.index, err = l.Index.Load(ctx, blobstore.StoreWithSet(bs, l.Set), l.cache)
if err != nil {
log.Error(ctx, "Error loading index segments", "error", err, "index_id", l.Index, "list_id", l.ID)
// Ditch index and reindex.
nindex := NewSegments(0, false)
nindex.IsIndex = true
s.index = nindex
err := l.reindex(ctx, bs, &s)
if err != nil {
s.unlock()
return nil, err
}
}
}
l.updateSegments(ctx, &s)
// Return read only if that was what was requested.
if readOnly {
l.segmentsLock.Unlock()
l.segmentsLock.RLock()
s.unlock = func() {
l.segmentsLock.RUnlock()
if updateLock {
l.updateLock.Unlock()
}
s.removeUnlock(ctx)
}
}
return &s, nil
}
// newSegments returns a new set up segments that can be written to.
// withIdx indicates whether an index segment should be allocated.
// The returned segments will be write and update locked.
// It is possible to transfer update locks from a previous segment,
// if this is replacing existing segments and you hold the update lock.
func (l *List) newSegments(ctx context.Context, preAlloc int, withIdx bool, xfer *segments) *segments {
ctx = log.WithFn(ctx)
if xfer != nil {
log.Info(ctx, "replacing segments", "updatelocked", xfer.updateLocked, "readonly", xfer.readOnly)
}
// If update locked, we retain the lock.
if xfer != nil && !xfer.updateLocked {
log.Error(ctx, "newSegments: previous segment not update locked. Cannot reuse.")
xfer.unlock()
xfer = nil
}
s := segments{
scores: NewSegments(preAlloc, true),
readOnly: false,
updateLocked: true,
}
s.unlock = func() {
l.updateLock.Unlock()
l.segmentsLock.Unlock()
s.removeUnlock(ctx)
}
if withIdx {
s.index = NewSegments(preAlloc, false)
s.index.IsIndex = true
}
if xfer != nil {
if xfer.readOnly {
// Upgrade to full lock.
// We know we have update lock.
l.segmentsLock.RUnlock()
l.segmentsLock.Lock()
}
return &s
}
l.updateLock.Lock()
l.segmentsLock.Lock()
return &s
}
// saveSegments will update segments on the list and save them.
// This must be used when element counts within one or more segments have changed.
func (l *List) saveSegments(ctx context.Context, bs blobstore.Store, s *segments) error {
ctx = log.WithFn(ctx)
if s == nil {
return errors.New("no segments provided")
}
if !s.readOnly {
l.updateSegments(ctx, s)
}
l.RLock()
set := l.Set
l.RUnlock()
store := blobstore.StoreWithSet(bs, set)
if s.scores != nil {
err := s.scores.Save(ctx, store)
if err != nil {
return err
}
} else {
log.Info(ctx, "scores not loaded, cannot save")
}
if s.index != nil {
err := s.index.Save(ctx, store)
if err != nil {
return err
}
} else {
log.Info(ctx, "index not loaded, cannot save")
}
return nil
}
// cloneElements will replace all elements of this list with the elements of the original.
func (l *List) cloneElements(ctx context.Context, bs blobstore.Store, org *List) error {
ctx = log.WithFn(ctx)
// Ensure segments are loaded.
oSegs, err := org.loadSegments(ctx, bs, segsReadOnly|segsAllowUpdates)
if err != nil {
return fmt.Errorf("loading segments: %v", err)
}
oScores := oSegs.scores
defer oSegs.unlock()
org.RLock()
oSet := org.Set
org.RUnlock()
l.RLock()
dSet := l.Set
dMergeSize := l.MergeSize
dSplitSize := l.SplitSize
l.RUnlock()
bsDst := blobstore.StoreWithSet(bs, dSet)
newSegments := l.newSegments(ctx, len(oScores.Segments), false, nil)
defer newSegments.unlock()
dstIdx := IndexElements{Elements: make(Elements, 0, oScores.Elements())}
for i := range oScores.Segments {
ls, err := oScores.elementFullIdx(ctx, blobstore.StoreWithSet(bs, oSet), i, true)
if err != nil {
return err
}
newSeg := Segment{
ID: 0, // populated by newLockedSegment
Min: ls.seg.Min,
Max: ls.seg.Max,
MinTie: ls.seg.MinTie,
MaxTie: ls.seg.MaxTie,
N: len(ls.elements),
Parent: newSegments.scores.ID,
loader: &elementLoader{},
}
dst := newSegments.scores.newLockedSegment(ctx, bsDst, &newSeg)
dst.elements = ls.elements.Clone(true)
ls.unlock()
dstIdx.Elements = append(dstIdx.Elements, dst.elements.ElementIDs(dst.seg.ID).Elements...)
if err != nil {
dst.unlock()
return err
}
err = newSegments.scores.replaceSegment(ctx, bsDst, dst)
if err != nil {
log.Error(ctx, err.Error())
}
}
dstIdx.Sort()
// Add index elements.
wantSize := (dMergeSize + dSplitSize) / 2
newIdx, err := NewSegmentsElements(ctx, bsDst, dstIdx.SplitSize(wantSize), nil)
if err != nil {
return err
}
newSegments.index = newIdx
// List may have other split/merge settings, check that.
l.checkSplit(ctx, bs, newSegments)
return l.saveSegments(ctx, bs, newSegments)
}
// ScoreError is returned when error is related to scores.
type ScoreError error
// IndexError is returned when error is related to index
// and can be fixed by a re-index.
type IndexError error
// Verify a list without loading elements.
func (l *List) Verify(ctx context.Context, bs blobstore.Store) error {
ctx = log.WithFn(ctx)
// Ensure segments are loaded.
segs, err := l.loadSegments(ctx, bs, segsReadOnly|segsAllowUpdates)
if err != nil {
return fmt.Errorf("Loading segments: %v", err)
}
defer segs.unlock()
return l.verify(ctx, bs, segs)
}
// Verify a list without loading elements.
func (l *List) verify(ctx context.Context, bs blobstore.Store, segs *segments) error {
l.RLock()
ctx = log.WithFn(ctx, "list_id", l.ID)
set := l.Set
lMergeSize := l.MergeSize
lSplitSize := l.SplitSize
lScores := l.Scores
lIndex := l.Index
l.RUnlock()
err := func() error {
l.RLock()
defer l.RUnlock()
if l.Scores.Unset() {
return fmt.Errorf("Score Segments ID not set on list.")
}
if l.Index.Unset() {
return fmt.Errorf("Index Segments ID not set on list.")
}
if segs.scores.ID != l.Scores {
return fmt.Errorf("Scores Segments ID mismatch. List: %v, Segments:%v", l.Scores, l.scores.ID)
}
if segs.index.ID != l.Index {
return IndexError(fmt.Errorf("Index Segments ID mismatch. List: %v, Segments:%v", l.Index, l.index.ID))
}
if segs.scores.IsIndex {
return fmt.Errorf("Score Segments was marked as index.")
}
if !segs.index.IsIndex {
return IndexError(fmt.Errorf("Index Segments was not marked as index."))
}
if l.SplitSize < l.MergeSize {
return fmt.Errorf("SplitSize (%d) < MergeSize (%d)", l.SplitSize, l.MergeSize)
}
return nil
}()
if err != nil {
return err
}
store := blobstore.StoreWithSet(bs, set)
err = segs.scores.Verify(ctx, store)
if err != nil {
log.Info(ctx, "Scores:", "segments", segs.scores)
return ScoreError(fmt.Errorf("Verifying Scores: %v", err))
}
shouldSplit := false
psegn := lMergeSize
for i := range segs.scores.Segments {
segs.scores.SegmentsLock.RLock()
seg := &segs.scores.Segments[i]
segs.scores.SegmentsLock.RUnlock()
if seg.Parent != lScores {
return ScoreError(fmt.Errorf("Scores Segment %d Parent ID mismatch. List: %v, Segment:%v", i, lScores, seg.Parent))
}
if seg.N > lSplitSize {
log.Info(ctx, "Score segment should be split", "seg_id", seg.ID, "n_elements", seg.N, "split_size", lSplitSize)
shouldSplit = true
}
if seg.N+psegn < lMergeSize {
log.Info(ctx, "Score segment should be merged with previous", "seg_id", seg.ID, "n_elements", seg.N+psegn, "merge_size", lMergeSize)
shouldSplit = true
}
psegn = seg.N
}
err = segs.index.Verify(ctx, store)
if err != nil {
log.Info(ctx, "Index:", "segments", segs.index)
return IndexError(fmt.Errorf("Verifying Index: %v", err))
}
psegn = lMergeSize
for i := range segs.index.Segments {
segs.index.SegmentsLock.RLock()
seg := &l.index.Segments[i]
segs.index.SegmentsLock.RUnlock()
if seg.Parent != lIndex {
return IndexError(fmt.Errorf("Index Segment %d Parent ID mismatch. List: %v, Segment:%v", i, lIndex, seg.Parent))
}
if seg.N > lSplitSize {
shouldSplit = true
log.Info(ctx, "Index segment should be split", "seg_id", seg.ID)
}
if i > 0 && seg.N+psegn < lMergeSize {
shouldSplit = true
log.Info(ctx, "Index segment should be merged with previous", "seg_id", seg.ID)
}
psegn = seg.N
}
if shouldSplit {
l.requestSplit(ctx)
}
return nil
}
// VerifyElements verifies elements in list.
func (l *List) VerifyElements(ctx context.Context, bs blobstore.Store) error {
l.RLock()
ctx = log.WithFn(ctx, "list_id", l.ID)
l.RUnlock()
// We want a consistent view of elements/indexes, so we need update.
segs, err := l.loadSegments(ctx, bs, segsReadOnly|segsLockUpdates)
if err != nil {
return err
}
defer segs.unlock()
return l.verifyElements(ctx, bs, segs)
}
// VerifyElements verifies elements in list.
// Caller should hold list updatelock for full consistency.
func (l *List) verifyElements(ctx context.Context, bs blobstore.Store, segs *segments) error {
ctx = log.WithFn(ctx)
l.RLock()
store := blobstore.StoreWithSet(bs, l.Set)
l.RUnlock()
var ids map[ElementID]SegmentID
// We do not get the update lock since caller may be holding it.
err := segs.scores.VerifyElements(ctx, store, &ids)
if err != nil {
return ScoreError(fmt.Errorf("Verifying Score Elements: %v", err))
}
var idxids map[ElementID]SegmentID
err = segs.index.VerifyElements(ctx, store, &idxids)
if err != nil {
return IndexError(fmt.Errorf("Verifying Index Elements: %v", err))
}
for id, segid := range ids {
if isegid, ok := idxids[id]; !ok {
return IndexError(fmt.Errorf("Object %v was not indexed", id))
} else {
if segid != isegid {
return IndexError(fmt.Errorf("Object %v is indexed to wrong segment (want:%v != got:%v)", id, segid, isegid))
}
}
delete(idxids, id)
}
for id := range idxids {
return IndexError(fmt.Errorf("Extra object ID %d found", id))
}
return nil
}
// Reindex will re-create the list element index.
func (l *List) Reindex(ctx context.Context, bs blobstore.Store) error {
ctx = log.WithFn(ctx)
segs, err := l.loadSegments(ctx, bs, segsWritable|segsLockUpdates)
if err != nil {
return err
}
defer segs.unlock()
return l.reindex(ctx, bs, segs)
}
// Reindex will re-create the list element index.
func (l *List) reindex(ctx context.Context, bs blobstore.Store, segs *segments) error {
ctx = log.WithFn(ctx)
if segs.readOnly {
return errors.New("reindex: readonly segments given")
}
if !segs.updateLocked {
return errors.New("reindex: segments without update lock given")
}
ctx = log.WithFn(ctx, "list_id", l.ID)
store := blobstore.StoreWithSet(bs, l.Set)
l.RLock()
mergeSize := l.MergeSize
splitSize := l.SplitSize
l.RUnlock()
idx, err := segs.scores.ElementIndexAll(ctx, store)
if err != nil {
return err
}
wantSize := (mergeSize + splitSize) / 2
newIdx, err := NewSegmentsElements(ctx, store, idx.SplitSize(wantSize), nil)
if err != nil {
return err
}
// Save index.
err = newIdx.Save(ctx, store)
if err != nil {
log.Error(ctx, "Saving new index:", "err", err)
return err
}
// Delete old
err = segs.index.Delete(ctx, store)
if err != nil {
// We will survive, but want to know
log.Error(ctx, "Deleting index:", "err", err)
}
// Replace
segs.index = newIdx
err = l.saveSegments(ctx, bs, segs)
if err != nil {
segs.unlock()
return err
}
return nil
}
// VerifyUnlocked validates that all elements of the list can be locked.
// This is only really usable for tests, where list context is controlled.
func (l *List) VerifyUnlocked(ctx context.Context, timeout time.Duration) error {
var fail = make(chan struct{})
var ok = make(chan struct{})
var wg = &sync.WaitGroup{}
go func() {
time.Sleep(timeout)
close(fail)
}()
// Check list can be locked.
testLock(log.Logger(ctx).New("lock", "list"), fail, l, wg)
go func() {
wg.Wait()
close(ok)
}()
select {
case <-fail:
_ = pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
time.Sleep(time.Millisecond * 100)
return errors.New("timeout acquiring locks")
case <-ok:
}
ok = make(chan struct{})
// We need read lock.
l.RLock()
defer l.RUnlock()
testLock(log.Logger(ctx).New("lock", "list.loadingLock"), fail, &l.loadingLock, wg)
testLock(log.Logger(ctx).New("lock", "list.segmentsLock"), fail, &l.segmentsLock, wg)
testLock(log.Logger(ctx).New("lock", "list.updateLock"), fail, &l.updateLock, wg)
if l.index != nil {
testLock(log.Logger(ctx).New("lock", "list.index.segmentstats"), fail, &l.index.SegmentsLock, wg)
for i := range l.index.Segments {
seg := &l.index.Segments[i]
testLock(log.Logger(ctx).New("lock", "list.index.loader.Mu", "segment", i, "segment_id", seg.cacheID()), fail, &seg.loader.Mu, wg)
testLock(log.Logger(ctx).New("lock", "list.index.loader.LoadingMu", "segment", i, "segment_id", seg.cacheID()), fail, &seg.loader.LoadingMu, wg)
}
}
if l.scores != nil {
testLock(log.Logger(ctx).New("lock", "list.scores.segmentstats"), fail, &l.scores.SegmentsLock, wg)
for i := range l.scores.Segments {
seg := &l.scores.Segments[i]
testLock(log.Logger(ctx).New("lock", "list.scores.loader.Mu", "segment", i, "segment_id", seg.cacheID()), fail, &seg.loader.Mu, wg)
testLock(log.Logger(ctx).New("lock", "list.scores.loader.LoadingMu", "segment", i, "segment_id", seg.cacheID()), fail, &seg.loader.LoadingMu, wg)
}
}
go func() {
wg.Wait()
close(ok)
}()
select {
case <-fail:
_ = pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
time.Sleep(time.Millisecond * 100)
return errors.New("timeout acquiring locks")
case <-ok:
log.Info(ctx, "All locks acquired")
return nil
}
}
func testLock(log log.Adapter, fail chan struct{}, locker sync.Locker, wg *sync.WaitGroup) {
wg.Add(1)
var ok = make(chan struct{})
go func() {
locker.Lock()
close(ok)
locker.Unlock()
}()
go func() {
select {
case <-ok:
wg.Done()
case <-fail:
log.Error("Timeout acquiring lock")
}
}()
}
// Populate will replace content of list with the supplied elements.
// Elements are assumed to be de-duplicated.
func (l *List) Populate(ctx context.Context, bs blobstore.Store, e Elements) error {
ctx = log.WithFn(ctx)
segs, err := l.loadSegments(ctx, bs, segsWritable|segsLockUpdates)
if err != nil {
// Log error, but proceed.
log.Error(ctx, "Populate: error loading existing segments", "error", err.Error())
}
segs, err = l.populate(ctx, bs, e, segs)
if segs != nil {
segs.unlock()
}
return err
}
// Populate will replace content of list with the supplied elements.
// Elements are assumed to be de-duplicated.
// Even if an error is returned, the returned segments must be unlocked of not nil.
func (l *List) populate(ctx context.Context, bs blobstore.Store, e Elements, segs *segments) (*segments, error) {
ctx = log.WithFn(ctx, "list_id", l.ID)
store := blobstore.StoreWithSet(bs, l.Set)
l.RLock()
hasValid := (!l.Scores.Unset() || !l.Index.Unset()) && segs != nil
l.RUnlock()
if hasValid {
err := l.deleteAll(ctx, bs, segs)
if err != nil {
return segs, err
}
}
if len(e) == 0 {
segs, err := l.initEmptyList(ctx, bs, segs)
return segs, err
}
// Retain full lock while populating.
l.Lock()
// Above ~200k we get significant slowdown, we defer these.
var deferred Elements
const insertLimit = 100000
if len(e) > insertLimit && !sort.SliceIsSorted(e, e.Sorter()) {
// We want the initial list to contain random ordered elements,
// so the initial segments are split across all of the range.
// Forcefully shuffle the slice.
rng := rand.New(rand.NewSource(0xc0cac01a))
for i := range e {
j := rng.Intn(i + 1)
e[i], e[j] = e[j], e[i]
}
deferred = e[insertLimit:]
e = e[:insertLimit]
}
e.Sort()
// Calculate size of each segment
wantSize := (l.MergeSize + l.SplitSize) / 2
if len(deferred) > 0 {
factor := float64(len(deferred)+len(e)) / float64(len(e))
wantSize = int(float64(wantSize) / factor)
// Avoid too many merges.
if wantSize < l.MergeSize/4 {
wantSize = l.MergeSize / 4
}
}
// Split input
split := e.SplitSize(wantSize)
segs = l.newSegments(ctx, 0, false, segs)
ids := IndexElements{make(Elements, 0, len(e))}
scores, err := NewSegmentsElements(ctx, store, split, &ids)
if err != nil {
l.Unlock()
return segs, err
}
scores.cache = l.cache
segs.scores = scores
// Generate Index segments.
ids.Sort()
split = ids.SplitSize(wantSize)
idx, err := NewSegmentsElements(ctx, store, split, nil)
if err != nil {
segs.unlock()
return segs, err
}
idx.cache = l.cache
segs.index = idx
l.Unlock()
if len(deferred) > 0 {
l.updateSegments(ctx, segs)
err = l.insert(ctx, bs, deferred, segs)
if err != nil {
return segs, err
}
}
l.updateSegments(ctx, segs)
err = l.saveSegments(ctx, bs, segs)
if err != nil {
return segs, err
}
// verify will queue merge/split if needed.
return segs, l.verify(ctx, bs, segs)
}
// Len returns the number of elements in the list.
func (l *List) Len(ctx context.Context, bs blobstore.Store) (int, error) {
ctx = log.WithFn(ctx)
// Ensure segments are loaded.
segs, err := l.loadSegments(ctx, bs, segsReadOnly|segsAllowUpdates)
if err != nil {
return 0, err
}
defer segs.unlock()
scores := segs.scores
index := segs.index
n := scores.Elements()
if sanityChecks {
n2 := index.Elements()
if n != n2 {
log.Error(ctx, "Element count mismatch", "scores", n, "index", n2)
return 0, errors.New("Element count mismatch")
}
}
return n, nil
}
// ListStats provides overall stats for a list
type ListStats struct {
Elements int