/
lineage_storage.go
1554 lines (1390 loc) · 47.2 KB
/
lineage_storage.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 storage
import (
"bytes"
"compress/gzip"
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
// "strings"
"sync"
"sync/atomic"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
csync "github.com/ds2-lab/infinistore/common/sync"
"github.com/ds2-lab/infinistore/common/sync/heap"
"github.com/kelindar/binary"
"github.com/zhangjyr/hashmap"
mys3 "github.com/ds2-lab/infinistore/common/aws/s3"
protocol "github.com/ds2-lab/infinistore/common/types"
"github.com/ds2-lab/infinistore/lambda/collector"
"github.com/ds2-lab/infinistore/lambda/types"
)
const (
LINEAGE_KEY = "%s%s/lineage-%d"
SNAPSHOT_KEY = "%s%s/snapshot-%d.gz"
RECOVERING_NONE uint32 = 0x00
RECOVERING_MAIN uint32 = 0x01
RECOVERING_BACKUP uint32 = 0x02
LineageStorageOverhead = StorageOverhead // Reuse StorageOverhead
BackupStoreageReservation = 0.1 // 1/N * 2, N = 20, backups per lambda.
MaximumCommitDelay = 1 * time.Second // 1 second
)
var (
Backups = 10
// Updated: 6/30/2010
// Try download as few as lineage file in batch: try one snapshot each term
SnapshotInterval = uint64(1)
// To minimize lineage recovery latency, try download the same file with multiple contenders.
LineageRecoveryContenders = 3
// Errors
ErrRecovering = errors.New("already recovering")
ErrRecovered = errors.New("already recovered")
ErrRecoveryInterrupted = errors.New("recovery interrupted")
ErrBackupSetForbidden = errors.New("forbidden to set backup objects")
)
// Storage with lineage
type LineageStorage struct {
*PersistentStorage
// Lineage
unconfirmed []*types.LineageTerm // The terms that are not confirmed yet.
unconfirmedStart int // The start index of unconfirmed.
unconfirmedEnd int // The end index of unconfirmed.
lineage *types.LineageTerm // The lineage of current/recent term. The lineage is updated to recent term while recovering.
recovered *types.LineageTerm // Stores recovered lineage if it is not fully recovered, and will replace lineage on returning.
snapshot *types.LineageTerm // The latest snapshot of the lineage.
diffrank LineageDifferenceRank
getSafe csync.WaitGroup
setSafe csync.WaitGroup
safenote uint32 // Flag what's going on
lineageMu sync.RWMutex // Mutex for lienage commit.
commited chan interface{}
delayed *time.Timer // Timer for delayed commit.
lsSignalTracker chan StorageSignal
// backup
backup *hashmap.HashMap // Just a index, all will be available to repo
backupLineage *types.LineageMeta // Only one backup is effective at a time.
backupLocator protocol.BackupLocator
backupRecoveryCanceller context.CancelFunc
// buffer delegates
bufferMeta StorageMeta
bufferQueue *ChunkQueue
}
func NewLineageStorage(id uint64, cap uint64) *LineageStorage {
storage := &LineageStorage{
PersistentStorage: NewPersistentStorage(id, cap),
unconfirmed: make([]*types.LineageTerm, 0, 10), // Just initialize unconfirmed with 10 elements.
lineage: &types.LineageTerm{
Term: 1, // Term start with 1 to avoid uninitialized term ambigulous.
Ops: make([]types.LineageOp, 0, 1), // We expect 1 "write" maximum for each term for sparse workload.
},
backup: hashmap.New(1000), // Initilize early to buy time for fast backup recovery.
diffrank: NewSimpleDifferenceRank(Backups),
}
storage.meta.Overhead = LineageStorageOverhead
storage.meta.Rsrved = uint64(float64(storage.meta.Cap) * BackupStoreageReservation)
storage.helper = storage
storage.persistHelper = storage
storage.meta.modifier = &storage.bufferMeta
return storage
}
// Storage Implementation
func (s *LineageStorage) getWithOption(key string, opt *types.OpWrapper) (*types.Chunk, *types.OpRet) {
// Before getting safely, try what is available so far.
chunk, ok := s.helper.get(key)
// !ok: Most likely, this is because an imcomplete lineage.
// not safe: Corresponding lineage is recovering, and the chunk is not just set
if !ok || !s.isSafeToGet(chunk) {
s.getSafe.Wait()
}
// Ask to not update chunk.Accessed.
if opt == nil {
opt = &types.OpWrapper{}
}
opt.Accessed = true
chunk, ret := s.PersistentStorage.getWithOption(key, opt)
if ret.Error() != nil {
return chunk, ret
} else if chunk.IsBuffered(false) {
// Increase the priority to be evicted, since the key will be migrated to hot node.
chunk.Accessed = time.Time{}
s.bufferFix(chunk)
} else {
// Make up for other objects.
chunk.Access()
}
return chunk, ret
}
func (s *LineageStorage) setWithOption(key string, chunk *types.Chunk, opt *types.OpWrapper) *types.OpRet {
if chunk.Backup {
return types.OpError(ErrBackupSetForbidden)
}
s.setSafe.Wait()
// Commented by Tianium: No lock required any more, chunk.Term is assigned initially, and decided after persisted.
// // Lock lineage, ensure operation get processed in the term.
// s.lineageMu.Lock()
// defer s.lineageMu.Unlock()
// s.log.Debug("in mutex of setting key %v", key)
// Oversize check.
if opt != nil && opt.Sized {
// pass
} else if updatedOpt, ok := s.helper.validate(chunk, opt); ok {
opt = updatedOpt
} else {
return types.OpError(ErrOOStorage)
}
return s.PersistentStorage.setWithOption(key, chunk, opt)
}
func (s *LineageStorage) newChunk(key string, chunkId string, size uint64, val []byte) *types.Chunk {
chunk := types.NewChunk(key, chunkId, val)
chunk.Size = size
chunk.Term = s.lineage.Term + 1 // Add one to reflect real term.
chunk.Bucket = s.getBucket(key)
return chunk
}
func (s *LineageStorage) validate(test *types.Chunk, opt *types.OpWrapper) (*types.OpWrapper, bool) {
if test.IsBuffered(true) {
s.bufferInit(100)
s.bufferAdd(test)
}
size := s.meta.IncreaseSize(test.Size) // Oversize test.
fit := true
for size >= s.meta.Effective() && s.bufferMeta.Size() > 0 { // No need to init buffer if test is not to be buffered, bufferMeta.Size() would be 0 in this case.
evicted := heap.Pop(s.bufferQueue).(*types.Chunk)
s.bufferMeta.DecreaseSize(evicted.Size)
// If validate is called iteratively, make sure iterate test chunks using reversed heap.
// RU of to be delegated is before LRU of delegated already. Stop.
if evicted == test {
fit = false
break
}
// evicted must be objects previously in buffer.
s.PersistentStorage.delWithOption(evicted, "eviction", nil)
s.log.Info("%s evicted", evicted.Key)
size = s.meta.Size()
}
// Modified by Tianium 20221120
// Don't load real time size. Use the local variable to be consistent.
if fit {
if opt == nil {
opt = &types.OpWrapper{}
}
opt.Sized = true // Size update has been dealed for both backups and nonbackups.
return opt, true
} else {
s.meta.DecreaseSize(test.Size) // Reset meta size.
return opt, false
}
}
func (s *LineageStorage) Del(key string, reason string) *types.OpRet {
s.getSafe.Wait()
chunk, ok := s.helper.get(key)
if !ok {
return types.OpError(types.ErrNotFound)
}
s.setSafe.Wait()
// Commented by Tianium: No lock required any more, chunk.Term is assigned initially, and decided after persisted.
// // Lock lineage
// s.lineageMu.Lock()
// defer s.lineageMu.Unlock()
chunk.Term = s.lineage.Term + 1 // Add one to reflect real term.
return s.helper.delWithOption(chunk, reason, nil)
}
func (s *LineageStorage) Len() int {
s.getSafe.Wait()
return s.repo.Len()
}
func (s *LineageStorage) Keys() <-chan string {
s.getSafe.Wait()
return s.PersistentStorage.Keys()
}
// Lineage Implementation
func (s *LineageStorage) ConfigS3(bucket string, prefix string) {
s.PersistentStorage.ConfigS3(bucket, prefix)
s.setSafe = csync.WaitGroup{}
s.getSafe = csync.WaitGroup{}
s.delaySet()
}
func (s *LineageStorage) Validate(meta *types.LineageMeta) (types.LineageValidationResult, error) {
consistent, err := s.IsConsistent(meta)
if meta.Type != types.LineageMetaTypeMain {
return types.LineageValidationResultFromConsistent(consistent), err
}
if consistent {
if s.unconfirmedEnd > s.unconfirmedStart {
// We will update unconfirmedStart to unconfirmedEnd now.
// Using a loop start s.unconfirmedEnd - 1 in case new term just committed.
s.lineageMu.Lock()
for i := s.unconfirmedEnd - 1; i >= s.unconfirmedStart; i-- {
// The validated term must be one of the unconfirmed terms.
if meta.Term == s.unconfirmed[i].Term {
s.unconfirmedStart = i + 1
break
}
}
s.lineageMu.Unlock()
}
return types.LineageValidationConsistent, nil
} else if err != nil {
// Check if the term is consistent with an unconfirmed history term.
s.lineageMu.Lock()
defer s.lineageMu.Unlock()
for i := s.unconfirmedEnd - 1; i >= s.unconfirmedStart; i-- {
if meta.Term < s.unconfirmed[i].Term {
continue
} else if s.isConsistent(meta, s.unconfirmed[i]) {
// Meta is a legacy meta, confirm it and pass.
s.unconfirmedStart = i + 1
return types.LineageValidationConsistentWithHistoryTerm, nil
} else {
// Hash not match or the validated term is not found in unconfirmed terms. stop.
break
}
}
}
return types.LineageValidationInconsistent, err
}
func (s *LineageStorage) IsConsistent(meta *types.LineageMeta) (bool, error) {
lineage := s.lineage
switch meta.Type {
case types.LineageMetaTypeBackup:
if s.backupLineage == nil || s.backupLineage.Id != meta.Id || s.backupLineage.BackupId != meta.BackupId || s.backupLineage.BackupTotal != meta.BackupTotal {
meta.Consistent = false
return meta.Consistent, nil
}
lineage = types.LineageTermFromMeta(s.backupLineage)
case types.LineageMetaTypeDelegate:
meta.Consistent = false
return meta.Consistent, nil
}
// Assertion: lineage exists.
if lineage.Term > meta.Term {
meta.Consistent = false
return meta.Consistent, fmt.Errorf("detected staled term of lambda %d, expected at least %d, have %d", meta.Id, lineage.Term, meta.Term)
}
// Don't check hash if term is the start term(1).
meta.Consistent = s.isConsistent(meta, lineage)
return meta.Consistent, nil
}
func (s *LineageStorage) isConsistent(meta *types.LineageMeta, term *types.LineageTerm) bool {
return meta.Term == term.Term && (meta.Term == 1 || meta.Hash == term.Hash)
}
func (s *LineageStorage) StartTracker() {
if s.chanOps == nil {
s.lineage.Ops = s.lineage.Ops[:0] // Reset metalogs
s.resetSet()
s.commited = make(chan interface{})
s.resetDelay(false)
s.lsSignalTracker = make(chan StorageSignal, 1)
s.PersistentStorage.StartTracker()
go s.generatePersistSignal(s.delayed, s.lsSignalTracker)
return
}
s.log.Error("You should not have seen this error for here is unreachable.")
}
func (s *LineageStorage) resetDelay(stopped bool) {
if s.delayed == nil {
s.delayed = time.NewTimer(MaximumCommitDelay)
return
}
if stopped || s.delayed.Stop() {
s.delayed.Reset(MaximumCommitDelay) // Extend timer if timer is stopped or being stopped here.
} // else avoid extending timer if timeout triggered outside, the routine that stops the timer will extend it.
}
func (s *LineageStorage) stopTimer(timer *time.Timer) {
if timer != nil && !timer.Stop() {
select {
case <-timer.C:
default:
}
}
}
func (s *LineageStorage) generatePersistSignal(timer *time.Timer, input <-chan StorageSignal) {
for {
select {
case <-timer.C:
if s.getSafe.IsWaiting() {
// Skip commit delay if data is being recovered.
s.resetDelay(true)
} else {
go s.commit(&types.CommitOption{StorageSignalFlags: StorageSignalFlagForceCommit})
}
case signal := <-input:
s.PersistentStorage.signal(signal)
}
}
}
func (s *LineageStorage) onPersisted(persisted *types.OpWrapper) {
// No lock required, onPersisted and doCommitTerm will not be called concurrently.
// Noted: the chunk.Term is initialized with a proper value that the fixing here will conflict with recovery process.
// The appended lineage may has newer term than the chunk term if StorageFlagForceCommit is enabled.
s.lineage.Ops = append(s.lineage.Ops, persisted.LineageOp)
// Fix term
if persisted.Chunk != nil {
persisted.Chunk.Term = s.lineage.Term + 1
}
// If lineage is not recovered (get unsafe), skip diffrank, it will be replay when lineage is recovered.
if !s.getSafe.IsWaiting() {
s.diffrank.AddOp(&persisted.LineageOp)
} // else: Skip
}
func (s *LineageStorage) signal(signal StorageSignal) bool {
if s.lsSignalTracker != nil {
s.lsSignalTracker <- signal
return true
} else {
return false
}
}
func (s *LineageStorage) onSignalTracker(signal StorageSignal) bool {
switch option := signal.(type) {
case *types.CommitOption:
// Stop timer (if not stopped) before commit.
s.stopTimer(s.delayed)
return s.doCommit(option)
default:
return s.PersistentStorage.onSignalTracker(signal)
}
}
func (s *LineageStorage) commit(option *types.CommitOption) (*types.CommitOption, error) {
// Signal and wait for committed.
s.log.Debug("Signal tracker to commit")
s.signal(option)
option = (<-s.commited).(*types.CommitOption)
// Reset timer after committed, the timer must have been stopped before.
s.resetDelay(true)
// Flag checked
return option, nil
}
func (s *LineageStorage) Commit() (*types.CommitOption, error) {
if s.signalTracker == nil {
return nil, ErrTrackerNotStarted
}
s.log.Debug("Commiting lineage...")
option := &types.CommitOption{}
// Are we goint to do the snapshot?
var snapshotTerm uint64
if s.snapshot != nil {
snapshotTerm = s.snapshot.Term
}
// For incompleted lineage recovery (s.recovered != nil), do not snapshot.
// On local laptop,
// it takes 1509 bytes and 3ms to snapshot 500 chunks and 125 bytes to persist one term, both gzipped,
// and it takes roughly same time to download a snapshot or up to 10 lineage terms.
// So snapshot every 5 - 10 terms will be appropriate.
option.Full = s.recovered == nil && s.lineage.Term-snapshotTerm >= SnapshotInterval-1
return s.commit(option)
}
func (s *LineageStorage) StopTracker() error {
err := s.PersistentStorage.StopTracker()
if err == nil {
s.stopTimer(s.delayed)
s.delayed = nil
s.lsSignalTracker = nil
s.commited = nil
if s.recovered != nil {
// The recovery is not complete, discard current term and replaced with whatever recovered.
// The node will try recovery in next invocation.
s.lineage = s.recovered
}
}
return err
}
// Status returns the status of the storage.
// If short is specified, returns nil if all terms confirmed, or returns the meta of main storage only.
func (s *LineageStorage) Status(short bool) (confirmedTerm uint64, status types.LineageStatus) {
confirmedTerm = s.lineage.Term
if s.unconfirmedStart < s.unconfirmedEnd {
confirmedTerm = s.unconfirmed[s.unconfirmedStart].Term
} else if short {
// If short and no unconfirmed, we are done.
return
}
meta := &protocol.Meta{
Id: s.id,
Term: s.lineage.Term,
Updates: s.lineage.Updates,
DiffRank: s.diffrank.Rank(),
Hash: s.lineage.Hash,
}
if s.snapshot != nil {
meta.SnapshotTerm = s.snapshot.Term
meta.SnapshotUpdates = s.snapshot.Updates
meta.SnapshotSize = s.snapshot.Size
}
if s.backupLineage != nil && !short {
return confirmedTerm, types.LineageStatus{meta, s.backupLineage.Meta}
} else {
return confirmedTerm, types.LineageStatus{meta}
}
}
// Recover based on the term of specified meta.
// We support partial recovery. Errors during recovery will be sent to returned channel.
// The recovery ends if returned channel is closed.
// If the first return value is false, no fast recovery is needed.
func (s *LineageStorage) Recover(meta *types.LineageMeta) (bool, <-chan error) {
if meta.Consistent {
return false, nil
}
// Accessing of delegated objects are optional and no safety guranteee.
s.log.Info("Start recovery of node %d(type:%v).", meta.Meta.Id, meta.Type)
chanErr := make(chan error, 1)
recoverFlag := s.getRecoverFlag(meta)
// Flag get as unsafe
if !s.delayGet(recoverFlag) {
chanErr <- ErrRecovering
return false, chanErr
}
// Double check consistency
consistent, err := s.IsConsistent(meta)
if err != nil {
s.resetGet(recoverFlag)
chanErr <- err
return false, chanErr
} else if consistent {
s.resetGet(recoverFlag)
chanErr <- ErrRecovered
return false, chanErr
}
// Copy lineage data for recovery, update term to the recent record, and we are ready for write operatoins.
var old *types.LineageTerm
if meta.Type == types.LineageMetaTypeMain {
old = &types.LineageTerm{
Term: s.lineage.Term,
Updates: s.lineage.Updates,
}
s.lineage.Term = meta.Term
s.lineage.Updates = meta.Updates
s.lineage.Hash = meta.Hash
s.log.Info("During recovery, write operations enabled at term %d", s.lineage.Term+1)
} else if meta.Type == types.LineageMetaTypeBackup {
if s.backupLineage != nil &&
s.backupLineage.Meta.Id == meta.Meta.Id &&
s.backupLineage.BackupId == meta.BackupId &&
s.backupLineage.BackupTotal == meta.BackupTotal {
// Compare metas of backups for the same lambda
old = types.LineageTermFromMeta(s.backupLineage)
} else {
// New backup lambda
old = types.LineageTermFromMeta(nil)
if s.backupLineage != nil && s.backupLineage.Meta.Id != meta.Meta.Id {
s.log.Info("Backup data of node %d cleared to serve %d.", s.backupLineage.Meta.Id, meta.Meta.Id)
// Clean obsolete backups
if s.backupRecoveryCanceller != nil {
s.backupRecoveryCanceller()
}
s.ClearBackup()
}
}
} // No old lineage for delegate objects. They will be merged into main and evictable.
ctx := context.Background()
if meta.Type == types.LineageMetaTypeBackup {
newCtx, cancel := context.WithCancel(ctx)
ctx = newCtx
s.backupRecoveryCanceller = func() {
// before canceller take affect, resetGet is called at the end of replaying lineage.
s.backupRecoveryCanceller = nil
cancel()
}
}
go s.doRecover(ctx, old, meta, chanErr)
// Fast recovery if the node is not backup and significant enough.
return meta.Type == types.LineageMetaTypeMain && s.diffrank.IsSignificant(meta.DiffRank), chanErr
}
func (s *LineageStorage) ClearBackup() {
// Batch cleanup, no size need to be updated.
for keyValue := range s.backup.Iter() {
chunk := keyValue.Value.(*types.Chunk)
chunk.Body = nil
s.repo.Del(keyValue.Key)
s.backup.Del(keyValue.Key)
}
s.backupLineage = nil
s.meta.bakSize = 0
}
func (s *LineageStorage) doCommit(opt *types.CommitOption) bool {
if len(s.lineage.Ops) > 0 {
var termBytes, ssBytes int
uploader := s3manager.NewUploader(types.AWSSession(), func(u *s3manager.Uploader) {
u.Concurrency = 1
})
start := time.Now()
lineage, term, err := s.doCommitTerm(s.lineage, uploader)
s.lineage = lineage
stop1 := time.Now()
if err != nil {
s.log.Warn("Failed to commit term %d: %v", term, err)
} else {
termBytes = int(s.lineage.Size)
if !opt.Full || opt.Snapshotted {
// pass
} else if snapshot, err := s.doSnapshot(s.lineage, uploader); err != nil {
s.log.Warn("Failed to snapshot up to term %d: %v", term, err)
} else {
ssBytes = int(snapshot.Size)
s.snapshot = snapshot
opt.Snapshotted = true
}
}
end := time.Now()
// Can be other operations during persisting, signal tracker again.
// This time, ignore argument "full" if snapshotted.
s.log.Info("Term %d commited, resignal to check possible new term during committing.", term)
s.log.Trace("action,lineage,snapshot,elapsed,bytes")
s.log.Trace("commit,%d,%d,%d,%d", stop1.Sub(start), end.Sub(stop1), end.Sub(start), termBytes+ssBytes)
collector.AddCommit(
start, types.OP_COMMIT, 0, s.id, int(term),
stop1.Sub(start), end.Sub(stop1), end.Sub(start), termBytes, ssBytes)
opt.BytesUploaded += uint64(termBytes + ssBytes)
opt.Checked = true
if opt.Flags()&StorageSignalFlagForceCommit > 0 {
// Done delayed commit.
s.commited <- opt
} else {
// Trigger double check for final commit.
s.persistHelper.signal(opt)
}
} else if opt.Flags()&StorageSignalFlagForceCommit > 0 {
// Done delayed commit.
s.commited <- opt
} else {
// No operation since last signal.This will be quick and we are ready to exit lambda.
// DO NOT close "committed", since there will be a double check on stoping the tracker.
if opt.Checked {
s.log.Info("Double checked: no more term to commit, signal committed.")
} else {
s.log.Info("Checked: no term to commit, signal committed.")
}
// Done final commit.
s.commited <- opt
}
return false
}
func (s *LineageStorage) doCommitTerm(lineage *types.LineageTerm, uploader *s3manager.Uploader) (*types.LineageTerm, uint64, error) {
// Lock local lineage
s.lineageMu.Lock()
// Marshal ops first, so it can be reused largely in calculating hash and to be uploaded.
raw, err := binary.Marshal(lineage.Ops)
if err != nil {
s.lineageMu.Unlock()
return lineage, lineage.Term + 1, err
}
// Construct the term.
term := &types.LineageTerm{
Term: lineage.Term + 1,
Updates: lineage.Updates, // Stores "Updates" of the last term, don't forget to fix this on recovery.
RawOps: raw,
}
hash := new(bytes.Buffer)
hashBinder := binary.NewEncoder(hash)
hashBinder.WriteUint64(term.Term)
hashBinder.WriteUint64(term.Updates)
hashBinder.Write(term.RawOps)
hashBinder.Write([]byte(lineage.Hash))
term.Hash = fmt.Sprintf("%x", sha256.Sum256(hash.Bytes()))
// Zip and marshal the term.
buf := new(bytes.Buffer)
zipWriter := gzip.NewWriter(buf)
if err := binary.MarshalTo(term, zipWriter); err != nil {
s.lineageMu.Unlock()
return lineage, term.Term, err
}
if err := zipWriter.Close(); err != nil {
s.lineageMu.Unlock()
return lineage, term.Term, err
}
// Compact unconfirmed terms
if s.unconfirmedEnd >= cap(s.unconfirmed) && s.unconfirmedStart > 0 {
copy(s.unconfirmed[:s.unconfirmedEnd-s.unconfirmedStart], s.unconfirmed[s.unconfirmedStart:s.unconfirmedEnd])
s.unconfirmedEnd -= s.unconfirmedStart
s.unconfirmedStart = 0
s.unconfirmed = s.unconfirmed[:s.unconfirmedEnd]
}
// Append unconfirmed term
s.unconfirmed = append(s.unconfirmed, term)
s.unconfirmedEnd++
// Update local lineage. Size must be updated before used for uploading.
lineage.Size = uint64(buf.Len())
lineage.Ops = lineage.Ops[:0]
lineage.Term = term.Term
lineage.Updates += lineage.Size // Fix local "Updates"
lineage.Hash = term.Hash
lineage.DiffRank = s.diffrank.Rank() // Store for snapshot use.
// Unlock lineage, the storage can server next term while uploading
s.lineageMu.Unlock()
// Upload
params := &s3manager.UploadInput{
Bucket: aws.String(s.s3bucketDefault),
Key: aws.String(fmt.Sprintf(LINEAGE_KEY, s.s3prefix, s.functionName(s.id), term.Term)),
Body: buf,
}
_, err = uploader.Upload(params)
// if err != nil {
// // TODO: Pending and retry at a later time.
// }
return lineage, term.Term, err
}
func (s *LineageStorage) doSnapshot(lineage *types.LineageTerm, uploader *s3manager.Uploader) (*types.LineageTerm, error) {
start := time.Now()
// Construct object list.
allOps := make([]types.LineageOp, 0, s.repo.Len())
lenBuffer := 0
for keyChunk := range s.repo.Iter() {
chunk := keyChunk.Value.(*types.Chunk)
buffered := chunk.IsBuffered(false) && !chunk.IsDeleted()
if buffered {
lenBuffer++
}
if !chunk.Backup && (!chunk.IsBuffered(true) || buffered) && chunk.Term <= lineage.Term {
allOps = append(allOps, types.LineageOp{
Op: chunk.Op(),
Key: chunk.Key,
Id: chunk.Id,
Size: chunk.Size,
Accessed: chunk.Accessed,
BIdx: chunk.BuffIdx,
})
}
}
// Construct the snapshot.
ss := &types.LineageTerm{
Term: lineage.Term,
Updates: lineage.Updates,
Ops: allOps,
Hash: lineage.Hash,
DiffRank: lineage.DiffRank,
Buffered: lenBuffer,
}
// Zip and marshal the snapshot.
buf := new(bytes.Buffer)
zipWriter := gzip.NewWriter(buf)
if err := binary.MarshalTo(ss, zipWriter); err != nil {
return nil, err
}
if err := zipWriter.Close(); err != nil {
return nil, err
}
// Release "Ops" and update size. Size must be updated before used for uploading.
ss.Ops = nil
ss.Size = uint64(buf.Len())
s.log.Trace("It took %v to snapshot %d chunks.", time.Since(start), len(allOps))
// Persists.
params := &s3manager.UploadInput{
Bucket: aws.String(s.s3bucketDefault),
Key: aws.String(fmt.Sprintf(SNAPSHOT_KEY, s.s3prefix, s.functionName(s.id), ss.Term)),
Body: buf,
}
if _, err := uploader.Upload(params); err != nil {
// Simply abandon.
return nil, err
}
return ss, nil
}
func (s *LineageStorage) getRecoverFlag(meta *types.LineageMeta) uint32 {
switch meta.Type {
case types.LineageMetaTypeMain:
return RECOVERING_MAIN
case types.LineageMetaTypeBackup:
return RECOVERING_BACKUP
default:
return RECOVERING_NONE
}
}
func (s *LineageStorage) doRecover(ctx context.Context, lineage *types.LineageTerm, meta *types.LineageMeta, chanErr chan error) {
// Initialize s3 api
downloader := s.getS3Downloader()
recoverFlag := s.getRecoverFlag(meta)
// Recover lineage
start := time.Now()
lineageBytes, terms, numOps, err := s.doRecoverLineage(lineage, meta.Meta, downloader)
stop1 := time.Since(start)
if err != nil {
chanErr <- err
}
s.log.Debug("Lineage recovered %d.", meta.Meta.Id)
if len(terms) == 0 {
// No term recovered
if meta.Type == types.LineageMetaTypeMain {
s.recovered = lineage // Flag for incomplete recovery
}
s.log.Error("No term is recovered for node %d.", meta.Meta.Id)
close(chanErr)
s.resetGet(recoverFlag)
return
}
// Replay lineage
var tbds []*types.Chunk
if meta.Type == types.LineageMetaTypeDelegate {
tbds = s.doDelegateLineage(meta, terms, numOps)
} else {
tbds = s.doReplayLineage(meta, terms, numOps)
}
// Now get is safe
s.resetGet(recoverFlag)
s.log.Debug("Lineage replayed %d.", meta.Meta.Id)
// s.log.Debug("tbds %d: %v", meta.Meta.Id, tbds)
// for i, t := range tbds {
// s.log.Debug("%d: %v", i, *t)
// }
start2 := time.Now()
objectBytes := 0
if len(tbds) > 0 {
objectBytes, err = s.doRecoverObjects(ctx, tbds, downloader)
}
stop2 := time.Since(start2)
if err != nil {
chanErr <- err
}
end := time.Since(start)
s.log.Info("End recovery of node %d.", meta.Meta.Id)
s.log.Trace("action,lineage,objects,elapsed,bytes")
s.log.Trace("recover,%d,%d,%d,%d", stop1, stop2, end, objectBytes)
collector.AddRecovery(
start, types.OP_RECOVERY, int(meta.Type), meta.Meta.Id, meta.BackupId,
stop1, stop2, end, lineageBytes, objectBytes, len(tbds))
close(chanErr)
}
func (s *LineageStorage) doRecoverLineage(lineage *types.LineageTerm, meta *protocol.Meta, downloader *mys3.Downloader) (int, []*types.LineageTerm, int, error) {
// If hash not match, invalidate lineage.
if lineage == nil {
lineage = &types.LineageTerm{Term: 1}
} else if meta.Term == lineage.Term && meta.Hash != lineage.Hash {
// Since snapshots are small, always load snapshot only if dismatch.
lineage.Term = 1
lineage.Updates = 0
lineage.Hash = ""
}
// meta.Updates - meta.SnapshotUpdates + meta.SnapshotSize < meta.Updates - lineage.Updates
baseTerm := lineage.Term
snapshot := false
if meta.SnapshotUpdates-meta.SnapshotSize > lineage.Updates {
// Recover lineage from snapshot
baseTerm = meta.SnapshotTerm - 1
snapshot = true
s.log.Info("Recovering node %d from snapshot of term %d to term %d", meta.Id, meta.SnapshotTerm, meta.Term)
} else {
s.log.Info("Recovering node %d from term %d to term %d", meta.Id, lineage.Term, meta.Term)
}
// Setup receivers
terms := meta.Term - baseTerm
inputs := make(chan *mys3.BatchDownloadObject, IntMin(int(terms)*LineageRecoveryContenders, downloader.Concurrency))
receivedFlags := make([]bool, terms)
receivedTerms := make([]*types.LineageTerm, 0, terms)
chanNotify := make(chan interface{}, len(inputs))
chanError := make(chan error)
from := 0
received := 0
receivedBytes := 0
receivedOps := 0
// Setup input for snapshot downloading.
if snapshot {
i := 0
input := &mys3.BatchDownloadObject{}
input.Object = &s3.GetObjectInput{
Bucket: aws.String(s.s3bucketDefault),
Key: aws.String(fmt.Sprintf(SNAPSHOT_KEY, s.s3prefix, s.functionName(meta.Id), baseTerm+1)), // meta.SnapshotTerm
}
input.Writer = aws.NewWriteAtBuffer(make([]byte, 0, meta.SnapshotSize))
input.After = s.getReadyNotifier(input, chanNotify)
input.Meta = &i
for j := 0; j < LineageRecoveryContenders; j++ {
inputs <- input
}
// skip 0
from++
}
// Setup inputs for terms downloading.
go func(from int) {
for from < int(terms) {
i := from
input := &mys3.BatchDownloadObject{}
input.Object = &s3.GetObjectInput{
Bucket: aws.String(s.s3bucketDefault),
Key: aws.String(fmt.Sprintf(LINEAGE_KEY, s.s3prefix, s.functionName(meta.Id), baseTerm+uint64(from)+1)),
}
input.Writer = new(aws.WriteAtBuffer)
input.After = s.getReadyNotifier(input, chanNotify)
input.Meta = &i
for j := 0; j < LineageRecoveryContenders; j++ {
inputs <- input
}
from++
}
close(inputs)
}(from)
// Start downloading.
go func() {
// iter := &s3manager.DownloadObjectsIterator{ Objects: inputs }
ctx := aws.BackgroundContext()
ctx = context.WithValue(ctx, &ContextKeyLog, s.log)
if err := downloader.DownloadWithIterator(ctx, inputs); err != nil {
chanError <- err
}
}()
// Wait for snapshot and lineage terms.
for received < int(terms) {
select {
case err := <-chanError:
return receivedBytes, receivedTerms, receivedOps, err
case input := <-chanNotify:
i := *(input.(*mys3.BatchDownloadObject).Meta.(*int))
// Because of contenders, only the first one is recorded.
if input.(*mys3.BatchDownloadObject).Error != nil || receivedFlags[i] {
break
}
receivedFlags[i] = true
for received < int(terms) && receivedFlags[received] {
raw := input.(*mys3.BatchDownloadObject).Bytes()
if len(raw) == 0 {
// Something wrong, reset receivedFlags and wait for error
receivedFlags[received] = false
break
}
receivedBytes += len(raw)
// Unzip
zipReader, err := gzip.NewReader(bytes.NewReader(raw))
if err != nil {
return receivedBytes, receivedTerms, receivedOps, err
}
rawTerm := new(bytes.Buffer)
if _, err := io.Copy(rawTerm, zipReader); err != nil {
return receivedBytes, receivedTerms, receivedOps, err
}
if err := zipReader.Close(); err != nil {
return receivedBytes, receivedTerms, receivedOps, err
}
// Unmarshal
var term types.LineageTerm
if err := binary.Unmarshal(rawTerm.Bytes(), &term); err != nil {
return receivedBytes, receivedTerms, receivedOps, err
}
// Fix values
term.Size = uint64(len(raw))
if term.RawOps != nil {
// Lineage terms have field "rawOps"
term.Ops = make([]types.LineageOp, 1)
if err := binary.Unmarshal(term.RawOps, &term.Ops); err != nil {
return receivedBytes, receivedTerms, receivedOps, err
}
// Fix "Updates"
term.RawOps = nil // Release
term.Updates += term.Size
}
// Collect terms
receivedTerms = append(receivedTerms, &term)
received++
receivedOps += len(term.Ops)
}
}
}
return receivedBytes, receivedTerms, receivedOps, nil
}
func (s *LineageStorage) doReplayLineage(meta *types.LineageMeta, terms []*types.LineageTerm, numOps int) []*types.Chunk {
var fromSnapshot uint64
if meta.Type == types.LineageMetaTypeMain && terms[0].DiffRank > 0 {