/
storage_manager.go
2175 lines (1810 loc) · 61.6 KB
/
storage_manager.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
// Copyright 2014-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package indexer
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
"math"
"os"
"sort"
"sync"
"time"
"github.com/couchbase/indexing/secondary/common"
forestdb "github.com/couchbase/indexing/secondary/fdb"
"github.com/couchbase/indexing/secondary/logging"
)
var (
ErrIndexRollback = errors.New("Indexer rollback")
ErrIndexRollbackOrBootstrap = errors.New("Indexer rollback or warmup")
)
type KeyspaceIdInstList map[string][]common.IndexInstId
type StreamKeyspaceIdInstList map[common.StreamId]KeyspaceIdInstList
type KeyspaceIdInstsPerWorker map[string][][]common.IndexInstId
type StreamKeyspaceIdInstsPerWorker map[common.StreamId]KeyspaceIdInstsPerWorker
//StorageManager manages the snapshots for the indexes and responsible for storing
//indexer metadata in a config database
const INST_MAP_KEY_NAME = "IndexInstMap"
type StorageManager interface {
}
type storageMgr struct {
supvCmdch MsgChannel //supervisor sends commands on this channel
supvRespch MsgChannel //channel to send any async message to supervisor
snapshotReqCh []MsgChannel // Channel to listen for snapshot requests from scan coordinator
snapshotNotifych []chan IndexSnapshot
indexInstMap IndexInstMapHolder
indexPartnMap IndexPartnMapHolder
streamKeyspaceIdInstList StreamKeyspaceIdInstListHolder
streamKeyspaceIdInstsPerWorker StreamKeyspaceIdInstsPerWorkerHolder
// Latest readable index snapshot for each index instance
indexSnapMap IndexSnapMapHolder
// List of waiters waiting for a snapshot to be created with expected
// atleast-timestamp
waitersMap SnapshotWaitersMapHolder
dbfile *forestdb.File
meta *forestdb.KVStore // handle for index meta
config common.Config
stats IndexerStatsHolder
muSnap sync.Mutex //lock to protect updates to snapMap and waitersMap
statsLock sync.Mutex
lastFlushDone int64
}
type snapshotWaiter struct {
wch chan interface{}
ts *common.TsVbuuid
cons common.Consistency
idxInstId common.IndexInstId
expired time.Time
}
type PartnSnapMap map[common.PartitionId]PartitionSnapshot
func newSnapshotWaiter(idxId common.IndexInstId, ts *common.TsVbuuid,
cons common.Consistency,
ch chan interface{}, expired time.Time) *snapshotWaiter {
return &snapshotWaiter{
ts: ts,
cons: cons,
wch: ch,
idxInstId: idxId,
expired: expired,
}
}
func (w *snapshotWaiter) Notify(is IndexSnapshot) {
w.wch <- is
}
func (w *snapshotWaiter) Error(err error) {
w.wch <- err
}
//NewStorageManager returns an instance of storageMgr or err message
//It listens on supvCmdch for command and every command is followed
//by a synchronous response of the supvCmdch.
//Any async response to supervisor is sent to supvRespch.
//If supvCmdch get closed, storageMgr will shut itself down.
func NewStorageManager(supvCmdch MsgChannel, supvRespch MsgChannel,
indexPartnMap IndexPartnMap, config common.Config, snapshotNotifych []chan IndexSnapshot,
snapshotReqCh []MsgChannel) (StorageManager, Message) {
//Init the storageMgr struct
s := &storageMgr{
supvCmdch: supvCmdch,
supvRespch: supvRespch,
snapshotNotifych: snapshotNotifych,
snapshotReqCh: snapshotReqCh,
config: config,
}
s.indexInstMap.Init()
s.indexPartnMap.Init()
s.indexSnapMap.Init()
s.waitersMap.Init()
s.streamKeyspaceIdInstList.Init()
s.streamKeyspaceIdInstsPerWorker.Init()
//if manager is not enabled, create meta file
if config["enableManager"].Bool() == false {
fdbconfig := forestdb.DefaultConfig()
kvconfig := forestdb.DefaultKVStoreConfig()
var err error
if s.dbfile, err = forestdb.Open("meta", fdbconfig); err != nil {
return nil, &MsgError{err: Error{cause: err}}
}
// Make use of default kvstore provided by forestdb
if s.meta, err = s.dbfile.OpenKVStore("default", kvconfig); err != nil {
return nil, &MsgError{err: Error{cause: err}}
}
}
for i := 0; i < len(s.snapshotReqCh); i++ {
go s.listenSnapshotReqs(i)
}
//start Storage Manager loop which listens to commands from its supervisor
go s.run()
return s, &MsgSuccess{}
}
//run starts the storage manager loop which listens to messages
//from its supervisor(indexer)
func (s *storageMgr) run() {
//main Storage Manager loop
loop:
for {
select {
case cmd, ok := <-s.supvCmdch:
if ok {
if cmd.GetMsgType() == STORAGE_MGR_SHUTDOWN {
logging.Infof("StorageManager::run Shutting Down")
for i := 0; i < len(s.snapshotNotifych); i++ {
close(s.snapshotNotifych[i])
}
s.supvCmdch <- &MsgSuccess{}
break loop
}
s.handleSupvervisorCommands(cmd)
} else {
//supervisor channel closed. exit
break loop
}
}
}
}
func (s *storageMgr) handleSupvervisorCommands(cmd Message) {
switch cmd.GetMsgType() {
case MUT_MGR_FLUSH_DONE:
s.handleCreateSnapshot(cmd)
case INDEXER_ROLLBACK:
s.handleRollback(cmd)
case UPDATE_INDEX_INSTANCE_MAP:
s.handleUpdateIndexInstMap(cmd)
case UPDATE_INDEX_PARTITION_MAP:
s.handleUpdateIndexPartnMap(cmd)
case UPDATE_KEYSPACE_STATS_MAP:
s.handleUpdateKeyspaceStatsMap(cmd)
case STORAGE_INDEX_SNAP_REQUEST:
s.handleGetIndexSnapshot(cmd)
case STORAGE_INDEX_STORAGE_STATS:
s.handleGetIndexStorageStats(cmd)
case STORAGE_INDEX_COMPACT:
s.handleIndexCompaction(cmd)
case STORAGE_STATS:
s.handleStats(cmd)
case STORAGE_INDEX_MERGE_SNAPSHOT:
s.handleIndexMergeSnapshot(cmd)
case STORAGE_INDEX_PRUNE_SNAPSHOT:
s.handleIndexPruneSnapshot(cmd)
case STORAGE_UPDATE_SNAP_MAP:
s.handleUpdateIndexSnapMapForIndex(cmd)
case INDEXER_ACTIVE:
s.handleRecoveryDone()
case CONFIG_SETTINGS_UPDATE:
s.handleConfigUpdate(cmd)
}
}
//handleCreateSnapshot will create the necessary snapshots
//after flush has completed
func (s *storageMgr) handleCreateSnapshot(cmd Message) {
s.supvCmdch <- &MsgSuccess{}
logging.Tracef("StorageMgr::handleCreateSnapshot %v", cmd)
msgFlushDone := cmd.(*MsgMutMgrFlushDone)
keyspaceId := msgFlushDone.GetKeyspaceId()
tsVbuuid := msgFlushDone.GetTS()
streamId := msgFlushDone.GetStreamId()
flushWasAborted := msgFlushDone.GetAborted()
hasAllSB := msgFlushDone.HasAllSB()
numVbuckets := s.config["numVbuckets"].Int()
snapType := tsVbuuid.GetSnapType()
tsVbuuid.Crc64 = common.HashVbuuid(tsVbuuid.Vbuuids)
streamKeyspaceIdInstList := s.streamKeyspaceIdInstList.Get()
instIdList := streamKeyspaceIdInstList[streamId][keyspaceId]
streamKeyspaceIdInstsPerWorker := s.streamKeyspaceIdInstsPerWorker.Get()
instsPerWorker := streamKeyspaceIdInstsPerWorker[streamId][keyspaceId]
// The num_snapshot_workers config has changed. Re-adjust the
// streamKeyspaceIdInstsPerWorker map according to new snapshot workers
numSnapshotWorkers := s.getNumSnapshotWorkers()
if len(instsPerWorker) != numSnapshotWorkers {
func() {
s.muSnap.Lock()
defer s.muSnap.Unlock()
newStreamKeyspaceIdInstsPerWorker := getStreamKeyspaceIdInstsPerWorker(streamKeyspaceIdInstList, numSnapshotWorkers)
s.streamKeyspaceIdInstsPerWorker.Set(newStreamKeyspaceIdInstsPerWorker)
instsPerWorker = newStreamKeyspaceIdInstsPerWorker[streamId][keyspaceId]
logging.Infof("StorageMgr::handleCreateSnapshot Re-adjusting the streamKeyspaceIdInstsPerWorker map to %v workers. "+
"StreamId: %v, keyspaceId: %v", numSnapshotWorkers, streamId, keyspaceId)
}()
}
if snapType == common.NO_SNAP || snapType == common.NO_SNAP_OSO {
logging.Debugf("StorageMgr::handleCreateSnapshot Skip Snapshot For %v "+
"%v SnapType %v", streamId, keyspaceId, snapType)
indexInstMap := s.indexInstMap.Get()
indexPartnMap := s.indexPartnMap.Get()
go s.flushDone(streamId, keyspaceId, indexInstMap, indexPartnMap,
instIdList, tsVbuuid, flushWasAborted, hasAllSB)
return
}
s.muSnap.Lock()
defer s.muSnap.Unlock()
//pass copy of maps to worker
indexInstMap := s.indexInstMap.Get()
indexPartnMap := s.indexPartnMap.Get()
indexSnapMap := s.indexSnapMap.Get()
tsVbuuid_copy := tsVbuuid.Copy()
stats := s.stats.Get()
go s.createSnapshotWorker(streamId, keyspaceId, tsVbuuid_copy, indexSnapMap,
numVbuckets, indexInstMap, indexPartnMap, instIdList, instsPerWorker, stats, flushWasAborted, hasAllSB)
}
func (s *storageMgr) createSnapshotWorker(streamId common.StreamId, keyspaceId string,
tsVbuuid *common.TsVbuuid, indexSnapMap IndexSnapMap, numVbuckets int,
indexInstMap common.IndexInstMap, indexPartnMap IndexPartnMap,
instIdList []common.IndexInstId, instsPerWorker [][]common.IndexInstId,
stats *IndexerStats, flushWasAborted bool, hasAllSB bool) {
startTime := time.Now().UnixNano()
var needsCommit bool
var forceCommit bool
snapType := tsVbuuid.GetSnapType()
if snapType == common.DISK_SNAP ||
snapType == common.DISK_SNAP_OSO {
needsCommit = true
} else if snapType == common.FORCE_COMMIT {
forceCommit = true
}
var wg sync.WaitGroup
wg.Add(len(instIdList))
for _, instListPerWorker := range instsPerWorker {
go func(instList []common.IndexInstId) {
for _, idxInstId := range instList {
s.createSnapshotForIndex(streamId, keyspaceId, indexInstMap,
indexPartnMap, indexSnapMap, numVbuckets, idxInstId, tsVbuuid,
stats, hasAllSB, flushWasAborted, needsCommit, forceCommit,
&wg, startTime)
}
}(instListPerWorker)
}
wg.Wait()
keyspaceStats := s.stats.GetKeyspaceStats(streamId, keyspaceId)
end := time.Now().UnixNano()
if keyspaceStats != nil {
if keyspaceStats.lastSnapDone.Value() == 0 {
keyspaceStats.lastSnapDone.Set(end)
}
keyspaceStats.snapLatDist.Add(end - keyspaceStats.lastSnapDone.Value())
keyspaceStats.lastSnapDone.Set(end)
}
s.lastFlushDone = end
s.supvRespch <- &MsgMutMgrFlushDone{mType: STORAGE_SNAP_DONE,
streamId: streamId,
keyspaceId: keyspaceId,
ts: tsVbuuid,
aborted: flushWasAborted}
}
func (s *storageMgr) createSnapshotForIndex(streamId common.StreamId,
keyspaceId string, indexInstMap common.IndexInstMap,
indexPartnMap IndexPartnMap, indexSnapMap IndexSnapMap, numVbuckets int,
idxInstId common.IndexInstId, tsVbuuid *common.TsVbuuid, stats *IndexerStats,
hasAllSB bool, flushWasAborted bool, needsCommit bool,
forceCommit bool, wg *sync.WaitGroup, startTime int64) {
idxInst := indexInstMap[idxInstId]
//process only if index belongs to the flushed keyspaceId and stream
if idxInst.Defn.KeyspaceId(idxInst.Stream) != keyspaceId ||
idxInst.Stream != streamId ||
idxInst.State == common.INDEX_STATE_DELETED {
wg.Done()
return
}
idxStats := stats.indexes[idxInst.InstId]
snapC := indexSnapMap[idxInstId]
snapC.Lock()
lastIndexSnap := CloneIndexSnapshot(snapC.snap)
defer DestroyIndexSnapshot(lastIndexSnap)
snapC.Unlock()
// Signal the wait group first before destroying the snapshot
// inorder to avoid the cost of destroying the snapshot in the
// snapshot generation code path
defer wg.Done()
// List of snapshots for reading current timestamp
var isSnapCreated bool = true
partnSnaps := make(map[common.PartitionId]PartitionSnapshot)
hasNewSnapshot := false
partnMap := indexPartnMap[idxInstId]
//for all partitions managed by this indexer
for _, partnInst := range partnMap {
partnId := partnInst.Defn.GetPartitionId()
var lastPartnSnap PartitionSnapshot
if lastIndexSnap != nil && len(lastIndexSnap.Partitions()) != 0 {
lastPartnSnap = lastIndexSnap.Partitions()[partnId]
}
sc := partnInst.Sc
sliceSnaps := make(map[SliceId]SliceSnapshot)
//create snapshot for all the slices
for _, slice := range sc.GetAllSlices() {
if flushWasAborted {
slice.IsDirty()
return
}
//if TK has seen all Stream Begins after stream restart,
//the MTR after rollback can be considered successful.
//All snapshots become eligible to retry for next rollback.
if hasAllSB {
slice.SetLastRollbackTs(nil)
}
var latestSnapshot Snapshot
if lastPartnSnap != nil {
lastSliceSnap := lastPartnSnap.Slices()[slice.Id()]
latestSnapshot = lastSliceSnap.Snapshot()
}
//if flush timestamp is greater than last
//snapshot timestamp, create a new snapshot
var snapTs Timestamp
if latestSnapshot != nil {
snapTsVbuuid := latestSnapshot.Timestamp()
snapTs = Timestamp(snapTsVbuuid.Seqnos)
} else {
snapTs = NewTimestamp(numVbuckets)
}
// Get Seqnos from TsVbuuid
ts := Timestamp(tsVbuuid.Seqnos)
//if flush is active for an instance and the flush TS is
// greater than the last snapshot TS and slice has some changes.
// Skip only in-memory snapshot in case of unchanged data.
if latestSnapshot == nil ||
((slice.IsDirty() || needsCommit) && ts.GreaterThan(snapTs)) ||
forceCommit {
newTsVbuuid := tsVbuuid
var err error
var info SnapshotInfo
var newSnapshot Snapshot
logging.Tracef("StorageMgr::handleCreateSnapshot Creating New Snapshot "+
"Index: %v PartitionId: %v SliceId: %v Commit: %v Force: %v", idxInstId,
partnId, slice.Id(), needsCommit, forceCommit)
if forceCommit {
needsCommit = forceCommit
}
slice.FlushDone()
snapCreateStart := time.Now()
if info, err = slice.NewSnapshot(newTsVbuuid, needsCommit); err != nil {
logging.Errorf("handleCreateSnapshot::handleCreateSnapshot Error "+
"Creating new snapshot Slice Index: %v Slice: %v. Skipped. Error %v", idxInstId,
slice.Id(), err)
isSnapCreated = false
common.CrashOnError(err)
continue
}
snapCreateDur := time.Since(snapCreateStart)
hasNewSnapshot = true
snapOpenStart := time.Now()
if newSnapshot, err = slice.OpenSnapshot(info); err != nil {
logging.Errorf("StorageMgr::handleCreateSnapshot Error Creating Snapshot "+
"for Index: %v Slice: %v. Skipped. Error %v", idxInstId,
slice.Id(), err)
isSnapCreated = false
common.CrashOnError(err)
continue
}
snapOpenDur := time.Since(snapOpenStart)
if needsCommit {
logging.Infof("StorageMgr::handleCreateSnapshot Added New Snapshot Index: %v "+
"PartitionId: %v SliceId: %v Crc64: %v (%v) SnapType %v SnapAligned %v "+
"SnapCreateDur %v SnapOpenDur %v", idxInstId, partnId, slice.Id(),
tsVbuuid.Crc64, info, tsVbuuid.GetSnapType(), tsVbuuid.IsSnapAligned(),
snapCreateDur, snapOpenDur)
}
ss := &sliceSnapshot{
id: slice.Id(),
snap: newSnapshot,
}
sliceSnaps[slice.Id()] = ss
} else {
// Increment reference
latestSnapshot.Open()
ss := &sliceSnapshot{
id: slice.Id(),
snap: latestSnapshot,
}
sliceSnaps[slice.Id()] = ss
if logging.IsEnabled(logging.Debug) {
logging.Debugf("StorageMgr::handleCreateSnapshot Skipped Creating New Snapshot for Index %v "+
"PartitionId %v SliceId %v. No New Mutations. IsDirty %v", idxInstId, partnId, slice.Id(), slice.IsDirty())
logging.Debugf("StorageMgr::handleCreateSnapshot SnapTs %v FlushTs %v", snapTs, ts)
}
continue
}
}
ps := &partitionSnapshot{
id: partnId,
slices: sliceSnaps,
}
partnSnaps[partnId] = ps
}
if hasNewSnapshot {
idxStats.numSnapshots.Add(1)
if needsCommit {
idxStats.numCommits.Add(1)
}
}
is := &indexSnapshot{
instId: idxInstId,
ts: tsVbuuid,
partns: partnSnaps,
}
if isSnapCreated {
s.updateSnapMapAndNotify(is, idxStats)
} else {
DestroyIndexSnapshot(is)
}
s.updateSnapIntervalStat(idxStats, startTime)
}
func (s *storageMgr) flushDone(streamId common.StreamId, keyspaceId string,
indexInstMap common.IndexInstMap, indexPartnMap IndexPartnMap,
instIdList []common.IndexInstId, tsVbuuid *common.TsVbuuid,
flushWasAborted bool, hasAllSB bool) {
isInitial := func() bool {
if streamId == common.INIT_STREAM {
return true
}
// TODO (Collections): It is not optimal to iterate over
// entire instIdList when there are large number of indexes on
// a node in MAINT_STREAM. This logic needs to be optimised further
// when writer tuning is enabled
for _, instId := range instIdList {
inst, ok := indexInstMap[instId]
if ok && inst.Stream == streamId &&
inst.Defn.KeyspaceId(inst.Stream) == keyspaceId &&
(inst.State == common.INDEX_STATE_INITIAL || inst.State == common.INDEX_STATE_CATCHUP) {
return true
}
}
return false
}
checkInterval := func() int64 {
if isInitial() {
return int64(time.Minute)
}
return math.MaxInt64
}
if common.GetStorageMode() == common.PLASMA {
if s.config["plasma.writer.tuning.enable"].Bool() &&
time.Now().UnixNano()-s.lastFlushDone > checkInterval() {
var wg sync.WaitGroup
for _, idxInstId := range instIdList {
wg.Add(1)
go func(idxInstId common.IndexInstId) {
defer wg.Done()
idxInst := indexInstMap[idxInstId]
if idxInst.Defn.KeyspaceId(idxInst.Stream) == keyspaceId &&
idxInst.Stream == streamId &&
idxInst.State != common.INDEX_STATE_DELETED {
partnMap := indexPartnMap[idxInstId]
for _, partnInst := range partnMap {
for _, slice := range partnInst.Sc.GetAllSlices() {
slice.FlushDone()
}
}
}
}(idxInstId)
}
wg.Wait()
s.lastFlushDone = time.Now().UnixNano()
}
}
//if TK has seen all Stream Begins after stream restart,
//the MTR after rollback can be considered successful.
//All snapshots become eligible to retry for next rollback.
if hasAllSB {
for idxInstId, partnMap := range indexPartnMap {
idxInst := indexInstMap[idxInstId]
if idxInst.Defn.KeyspaceId(idxInst.Stream) == keyspaceId &&
idxInst.Stream == streamId &&
idxInst.State != common.INDEX_STATE_DELETED {
for _, partnInst := range partnMap {
for _, slice := range partnInst.Sc.GetAllSlices() {
slice.SetLastRollbackTs(nil)
}
}
}
}
}
s.supvRespch <- &MsgMutMgrFlushDone{
mType: STORAGE_SNAP_DONE,
streamId: streamId,
keyspaceId: keyspaceId,
ts: tsVbuuid,
aborted: flushWasAborted}
}
func (s *storageMgr) updateSnapIntervalStat(idxStats *IndexStats, startTime int64) {
// Compute avgTsInterval
last := idxStats.lastTsTime.Value()
curr := int64(time.Now().UnixNano())
avg := idxStats.avgTsInterval.Value()
avg = common.ComputeAvg(avg, last, curr)
if avg != 0 {
idxStats.avgTsInterval.Set(avg)
idxStats.sinceLastSnapshot.Set(curr - last)
}
idxStats.snapGenLatDist.Add(curr - startTime)
idxStats.lastTsTime.Set(curr)
idxStats.updateAllPartitionStats(
func(idxStats *IndexStats) {
// Compute avgTsItemsCount
last = idxStats.lastNumFlushQueued.Value()
curr = idxStats.numDocsFlushQueued.Value()
avg = idxStats.avgTsItemsCount.Value()
avg = common.ComputeAvg(avg, last, curr)
idxStats.avgTsItemsCount.Set(avg)
idxStats.lastNumFlushQueued.Set(curr)
})
}
// Update index-snapshot map whenever a snapshot is created for an index
func (s *storageMgr) updateSnapMapAndNotify(is IndexSnapshot, idxStats *IndexStats) {
var snapC *IndexSnapshotContainer
var ok, updated bool
indexSnapMap := s.indexSnapMap.Get()
if snapC, ok = indexSnapMap[is.IndexInstId()]; !ok {
func() {
s.muSnap.Lock()
defer s.muSnap.Unlock()
snapC, updated = s.initSnapshotContainerForInst(is.IndexInstId(), is)
}()
}
if snapC == nil {
return
}
if updated == false {
snapC.Lock()
DestroyIndexSnapshot(snapC.snap)
snapC.snap = is
snapC.Unlock()
}
// notify a new snapshot through channel
// the channel receiver needs to destroy snapshot when done
s.notifySnapshotCreation(is)
var waitersContainer *SnapshotWaitersContainer
waiterMap := s.waitersMap.Get()
if waitersContainer, ok = waiterMap[is.IndexInstId()]; !ok {
waitersContainer = s.initSnapshotWaitersForInst(is.IndexInstId())
}
if waitersContainer == nil {
return
}
waitersContainer.Lock()
defer waitersContainer.Unlock()
waiters := waitersContainer.waiters
var numReplies int64
t := time.Now()
// Also notify any waiters for snapshots creation
var newWaiters []*snapshotWaiter
for _, w := range waiters {
// Clean up expired requests from queue
if !w.expired.IsZero() && t.After(w.expired) {
w.Error(common.ErrScanTimedOut)
idxStats.numSnapshotWaiters.Add(-1)
continue
}
if isSnapshotConsistent(is, w.cons, w.ts) {
w.Notify(CloneIndexSnapshot(is))
numReplies++
idxStats.numSnapshotWaiters.Add(-1)
continue
}
newWaiters = append(newWaiters, w)
}
waitersContainer.waiters = newWaiters
idxStats.numLastSnapshotReply.Set(numReplies)
}
func (sm *storageMgr) getSortedPartnInst(partnMap PartitionInstMap) partitionInstList {
if len(partnMap) == 0 {
return partitionInstList(nil)
}
result := make(partitionInstList, 0, len(partnMap))
for _, partnInst := range partnMap {
result = append(result, partnInst)
}
sort.Sort(result)
return result
}
//handleRollback will rollback to given timestamp
func (sm *storageMgr) handleRollback(cmd Message) {
sm.supvCmdch <- &MsgSuccess{}
// During rollback, some of the snapshot stats get reset
// or updated by slice. Therefore, serialise rollback and
// retrieving stats from slice to avoid any inconsistency
// in stats
sm.statsLock.Lock()
defer sm.statsLock.Unlock()
streamId := cmd.(*MsgRollback).GetStreamId()
rollbackTs := cmd.(*MsgRollback).GetRollbackTs()
keyspaceId := cmd.(*MsgRollback).GetKeyspaceId()
sessionId := cmd.(*MsgRollback).GetSessionId()
logging.Infof("StorageMgr::handleRollback %v %v rollbackTs %v", streamId, keyspaceId, rollbackTs)
var err error
var restartTs *common.TsVbuuid
var rollbackToZero bool
indexInstMap := sm.indexInstMap.Get()
indexPartnMap := sm.indexPartnMap.Get()
//for every index managed by this indexer
for idxInstId, partnMap := range indexPartnMap {
idxInst := indexInstMap[idxInstId]
//if this keyspace in stream needs to be rolled back
if idxInst.Defn.KeyspaceId(idxInst.Stream) == keyspaceId &&
idxInst.Stream == streamId &&
idxInst.State != common.INDEX_STATE_DELETED {
restartTs, err = sm.rollbackIndex(streamId,
keyspaceId, rollbackTs, idxInstId, partnMap, restartTs)
if err != nil {
sm.supvRespch <- &MsgRollbackDone{streamId: streamId,
keyspaceId: keyspaceId,
err: err,
sessionId: sessionId}
return
}
if restartTs == nil {
err = sm.rollbackAllToZero(streamId, keyspaceId)
if err != nil {
sm.supvRespch <- &MsgRollbackDone{streamId: streamId,
keyspaceId: keyspaceId,
err: err,
sessionId: sessionId}
return
}
rollbackToZero = true
break
}
}
}
go func() {
// Notify all scan waiters for indexes in this keyspaceId
// and stream with error
stats := sm.stats.Get()
waitersMap := sm.waitersMap.Get()
for idxInstId, wc := range waitersMap {
idxInst := sm.indexInstMap.Get()[idxInstId]
idxStats := stats.indexes[idxInst.InstId]
if idxInst.Defn.KeyspaceId(idxInst.Stream) == keyspaceId &&
idxInst.Stream == streamId {
wc.Lock()
for _, w := range wc.waiters {
w.Error(ErrIndexRollback)
if idxStats != nil {
idxStats.numSnapshotWaiters.Add(-1)
}
}
wc.waiters = nil
wc.Unlock()
}
}
}()
sm.updateIndexSnapMap(sm.indexPartnMap.Get(), streamId, keyspaceId)
keyspaceStats := sm.stats.GetKeyspaceStats(streamId, keyspaceId)
if keyspaceStats != nil {
keyspaceStats.numRollbacks.Add(1)
if rollbackToZero {
keyspaceStats.numRollbacksToZero.Add(1)
}
}
if restartTs != nil {
//for pre 7.0 index snapshots, the manifestUID needs to be set to epoch
restartTs.SetEpochManifestUIDIfEmpty()
restartTs = sm.validateRestartTsVbuuid(keyspaceId, restartTs)
}
sm.supvRespch <- &MsgRollbackDone{streamId: streamId,
keyspaceId: keyspaceId,
restartTs: restartTs,
sessionId: sessionId,
}
}
func (sm *storageMgr) rollbackIndex(streamId common.StreamId, keyspaceId string,
rollbackTs *common.TsVbuuid, idxInstId common.IndexInstId,
partnMap PartitionInstMap, minRestartTs *common.TsVbuuid) (*common.TsVbuuid, error) {
var restartTs *common.TsVbuuid
var err error
var markAsUsed bool
if rollbackTs.HasZeroSeqNum() {
markAsUsed = true
}
//for all partitions managed by this indexer
partnInstList := sm.getSortedPartnInst(partnMap)
for _, partnInst := range partnInstList {
partnId := partnInst.Defn.GetPartitionId()
sc := partnInst.Sc
for _, slice := range sc.GetAllSlices() {
snapInfo := sm.findRollbackSnapshot(slice, rollbackTs)
restartTs, err = sm.rollbackToSnapshot(idxInstId, partnId,
slice, snapInfo, markAsUsed)
if err != nil {
return nil, err
}
if restartTs == nil {
return nil, nil
}
//if restartTs is lower than the minimum, use that
if !restartTs.AsRecentTs(minRestartTs) {
minRestartTs = restartTs
}
}
}
return minRestartTs, nil
}
func (sm *storageMgr) findRollbackSnapshot(slice Slice,
rollbackTs *common.TsVbuuid) SnapshotInfo {
infos, err := slice.GetSnapshots()
if err != nil {
panic("Unable read snapinfo -" + err.Error())
}
s := NewSnapshotInfoContainer(infos)
//DCP doesn't allow using incomplete OSO snapshots
//for stream restart
for _, si := range s.List() {
if si.IsOSOSnap() {
return nil
}
}
//if dcp has requested rollback to 0 for any vb, it is better to
//try with all available disk snapshots. The rollback could be
//due to vbuuid mismatch and using an older disk snapshot may work.
var snapInfo SnapshotInfo
if rollbackTs.HasZeroSeqNum() {
lastRollbackTs := slice.LastRollbackTs()
latestSnapInfo := s.GetLatest()
if latestSnapInfo == nil || lastRollbackTs == nil {
logging.Infof("StorageMgr::handleRollback %v latestSnapInfo %v "+
"lastRollbackTs %v. Use latest snapshot.", slice.IndexInstId(), latestSnapInfo,
lastRollbackTs)
snapInfo = latestSnapInfo
} else {
slist := s.List()
for i, si := range slist {
if lastRollbackTs.Equal(si.Timestamp()) {
//if there are more snapshots, use the next one
if len(slist) >= i+2 {
snapInfo = slist[i+1]
logging.Infof("StorageMgr::handleRollback %v Discarding Already Used "+
"Snapshot %v. Using Next snapshot %v", slice.IndexInstId(), si, snapInfo)
} else {
logging.Infof("StorageMgr::handleRollback %v Unable to find a snapshot "+
"older than last used Snapshot %v. Use nil snapshot.", slice.IndexInstId(),
latestSnapInfo)
snapInfo = nil
}
break
} else {
//if lastRollbackTs is set(i.e. MTR after rollback wasn't completely successful)
//use only snapshots lower than lastRollbackTs
logging.Infof("StorageMgr::handleRollback %v Discarding Snapshot %v. Need older "+
"than last used snapshot %v.", slice.IndexInstId(), si, lastRollbackTs)
}
}
}
} else {
snapInfo = s.GetOlderThanTS(rollbackTs)
}
return snapInfo
}
func (sm *storageMgr) rollbackToSnapshot(idxInstId common.IndexInstId,
partnId common.PartitionId, slice Slice, snapInfo SnapshotInfo,
markAsUsed bool) (*common.TsVbuuid, error) {
var restartTs *common.TsVbuuid
if snapInfo != nil {
err := slice.Rollback(snapInfo)
if err == nil {
logging.Infof("StorageMgr::handleRollback Rollback Index: %v "+
"PartitionId: %v SliceId: %v To Snapshot %v ", idxInstId, partnId,
slice.Id(), snapInfo)
restartTs = snapInfo.Timestamp()
if markAsUsed {
slice.SetLastRollbackTs(restartTs)
}
} else {
//send error response back
return nil, err
}
} else {
//if there is no snapshot available, rollback to zero
err := slice.RollbackToZero()
if err == nil {
logging.Infof("StorageMgr::handleRollback Rollback Index: %v "+
"PartitionId: %v SliceId: %v To Zero ", idxInstId, partnId,
slice.Id())
//once rollback to zero has happened, set response ts to nil
//to represent the initial state of storage
restartTs = nil
slice.SetLastRollbackTs(nil)
} else {
//send error response back
return nil, err
}
}
return restartTs, nil
}
func (sm *storageMgr) rollbackAllToZero(streamId common.StreamId,
keyspaceId string) error {
logging.Infof("StorageMgr::rollbackAllToZero %v %v", streamId, keyspaceId)