/
migrate.go
1457 lines (1255 loc) · 39.6 KB
/
migrate.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 badger
import (
"bytes"
"encoding/binary"
"fmt"
"math"
"github.com/dgraph-io/badger/v3"
"github.com/oasisprotocol/oasis-core/go/common/cbor"
"github.com/oasisprotocol/oasis-core/go/common/crypto/hash"
"github.com/oasisprotocol/oasis-core/go/common/keyformat"
"github.com/oasisprotocol/oasis-core/go/common/logging"
"github.com/oasisprotocol/oasis-core/go/storage/mkvs/db/api"
"github.com/oasisprotocol/oasis-core/go/storage/mkvs/node"
)
const (
flushInterval = 5000
maxTimestamp = math.MaxUint64
)
type migratorFactory func(db *badgerNodeDB, helper MigrationHelper) migration
var (
// ErrVersionNotFound can be returned by the migration helper when the
// relevant version can't be found in the history database.
ErrVersionNotFound = fmt.Errorf("version not found")
originVersions = map[uint64]migratorFactory{
3: func(db *badgerNodeDB, helper MigrationHelper) migration {
return &v4Migrator{
meta: v4MigratorMetadata{},
db: db,
helper: helper,
flushRemain: flushInterval,
}
},
4: func(db *badgerNodeDB, helper MigrationHelper) migration {
return &v5Migrator{
db: db,
helper: helper,
flushRemain: flushInterval,
}
},
}
migrationMetaKeyFmt = keyformat.New(0xff)
v3NodeKeyFmt = keyformat.New(0x00, &hash.Hash{})
v3WriteLogKeyFmt = keyformat.New(0x01, uint64(0), &hash.Hash{}, &hash.Hash{})
v3RootsMetadataKeyFmt = keyformat.New(0x02, uint64(0))
v3RootUpdatedNodesKeyFmt = keyformat.New(0x03, uint64(0), &hash.Hash{})
v3MetadataKeyFmt = keyformat.New(0x04)
v3MultipartRestoreNodeLogKeyFmt = keyformat.New(0x05, &hash.Hash{})
v4NodeKeyFmt = nodeKeyFmt
v4WriteLogKeyFmt = writeLogKeyFmt
v4RootsMetadataKeyFmt = rootsMetadataKeyFmt
v4RootUpdatedNodesKeyFmt = rootUpdatedNodesKeyFmt
v4MetadataKeyFmt = metadataKeyFmt
v4MultipartRestoreNodeLogKeyFmt = multipartRestoreNodeLogKeyFmt
v4RootNodeKeyFmt = rootNodeKeyFmt
v4NodeVersionSize = 8
v5NodeKeyFmt = nodeKeyFmt
v5WriteLogKeyFmt = writeLogKeyFmt
v5MetadataKeyFmt = metadataKeyFmt
v5RootsMetadataKeyFmt = rootsMetadataKeyFmt
v5RootUpdatedNodesKeyFmt = rootUpdatedNodesKeyFmt
v5RootNodeKeyFmt = rootNodeKeyFmt
)
type v3RootsMetadata struct {
_ struct{} `cbor:",toarray"`
Roots map[hash.Hash][]hash.Hash
}
type v4RootsMetadata = rootsMetadata
type v3UpdatedNode struct {
_ struct{} `cbor:",toarray"` // nolint
Removed bool
Hash hash.Hash
}
type v4UpdatedNode = updatedNode
// No change in metadata format between versions 3 and 4.
type v3SerializedMetadata = serializedMetadata
type v4SerializedMetadata = serializedMetadata
type DisplayHelper interface {
Display(msg string)
DisplayStepBegin(msg string)
DisplayStepEnd(msg string)
DisplayStep(msg string)
DisplayProgress(msg string, current, total uint64)
}
type MigrationHelper interface {
DisplayHelper
GetRootForHash(root hash.Hash, version uint64) ([]node.Root, error)
}
type migration interface {
// TargetVersion returns the version this migration will migrate to.
TargetVersion() uint64
// Migrate performs the migration, returning the target version.
Migrate() (uint64, error)
}
type migrationCommonMeta struct {
// An item with this key should always exist in the metadata blob.
// It is the original version of the database, before the migration started,
// so the migration driver can choose the correct migration to resume with
// even in cases where the database metadata key was already migrated.
BaseDBVersion uint64 `json:"base_version"`
}
type v4MigratorMetadata struct {
migrationCommonMeta
InitComplete bool `json:"init_complete"`
MetaComplete bool `json:"meta_complete"`
MultipartActive bool `json:"multipart_active"`
LastKey []byte `json:"last_key"`
LastKeyVersion uint64 `json:"last_key_version"`
MetaCount uint64 `json:"meta_count"`
CurrentMetaCount uint64 `json:"current_meta_count"`
}
func (m *v4MigratorMetadata) load(db *badger.DB) error {
txn := db.NewTransactionAt(tsMetadata, false)
defer txn.Discard()
item, err := txn.Get(migrationMetaKeyFmt.Encode())
if err != nil {
return err
}
return item.Value(func(data []byte) error {
return cbor.Unmarshal(data, m)
})
}
func (m *v4MigratorMetadata) save(batch *badger.WriteBatch) error {
return batch.SetEntryAt(badger.NewEntry(
migrationMetaKeyFmt.Encode(),
cbor.Marshal(m),
), tsMetadata)
}
func (m *v4MigratorMetadata) remove(batch *badger.WriteBatch) error {
return batch.DeleteAt(migrationMetaKeyFmt.Encode(), tsMetadata)
}
type v4Migrator struct {
db *badgerNodeDB
helper MigrationHelper
readTxn *badger.Txn
changeBatch *badger.WriteBatch
flushRemain int
meta v4MigratorMetadata
done bool
}
func (v4 *v4Migrator) flush(force bool) error {
v4.flushRemain--
if v4.flushRemain < 0 || force {
v4.flushRemain = flushInterval
if v4.done {
if err := v4.meta.remove(v4.changeBatch); err != nil {
return fmt.Errorf("error clearing progress: %w", err)
}
} else {
if err := v4.meta.save(v4.changeBatch); err != nil {
return fmt.Errorf("error saving progress: %w", err)
}
}
if err := v4.changeBatch.Flush(); err != nil {
return fmt.Errorf("error committing database state: %w", err)
}
v4.changeBatch = v4.db.db.NewWriteBatchAt(maxTimestamp)
}
return nil
}
// This is only usable once rootsMetadataKeyFmt keys have been migrated!
func (v4 *v4Migrator) getRootType(rh hash.Hash, version uint64) ([]node.RootType, error) {
roots, err := v4.helper.GetRootForHash(rh, version)
if err == nil && len(roots) > 0 {
rootTypes := make([]node.RootType, len(roots))
for i, root := range roots {
rootTypes[i] = root.Type
}
return rootTypes, nil
}
// If not directly discoverable, try traversing finalized roots metadata.
meta, err := loadRootsMetadata(v4.readTxn, version)
if err != nil {
return nil, err
}
found := map[node.RootType]struct{}{}
for root, chain := range meta.Roots {
h := root.Hash()
if h.Equal(&rh) {
found[root.Type()] = struct{}{}
}
for _, droot := range chain {
h := droot.Hash()
if h.Equal(&rh) {
found[droot.Type()] = struct{}{}
}
}
}
ret := make([]node.RootType, 0, len(found))
for typ := range found {
ret = append(ret, typ)
}
return ret, nil
}
func (v4 *v4Migrator) keyMetadata(item *badger.Item) error {
var meta3 v3SerializedMetadata
err := item.Value(func(data []byte) error {
return cbor.UnmarshalTrusted(data, &meta3)
})
if err != nil {
return fmt.Errorf("error decoding database metadata: %w", err)
}
meta4 := meta3
meta4.Version = 4
entry := badger.NewEntry(
v4MetadataKeyFmt.Encode(),
cbor.Marshal(meta4),
)
err = v4.changeBatch.SetEntryAt(entry, item.Version())
if err != nil {
return fmt.Errorf("error storing updated database metadata: %w", err)
}
return nil
}
func (v4 *v4Migrator) keyRootsMetadata(item *badger.Item) error { // nolint: gocyclo
if item.IsDeletedOrExpired() {
// Roots metadata keys are always at tsMetadata.
return nil
}
var version uint64
if !v3RootsMetadataKeyFmt.Decode(item.Key(), &version) {
return fmt.Errorf("error decoding roots metadata key")
}
var rootsMeta v3RootsMetadata
err := item.Value(func(data []byte) error {
return cbor.UnmarshalTrusted(data, &rootsMeta)
})
if err != nil {
return fmt.Errorf("error deserializing roots metadata: %w", err)
}
// Propagate type information throughout the derived root chains.
plainRoots := map[hash.Hash]map[node.RootType]struct{}{}
for root, chain := range rootsMeta.Roots {
plainRoots[root] = map[node.RootType]struct{}{}
for _, droot := range chain {
plainRoots[droot] = map[node.RootType]struct{}{}
}
}
remaining := len(plainRoots)
for root := range plainRoots {
var full []node.Root
full, err = v4.helper.GetRootForHash(root, version)
if err == nil && len(full) > 0 {
for _, r := range full {
plainRoots[root][r.Type] = struct{}{}
}
remaining--
}
if err != nil && err != ErrVersionNotFound {
return fmt.Errorf("error checking root %v for version %v: %w", root, version, err)
}
// If the root isn't found, we'll probably get stuck in the loop below and delete this key.
}
for remaining > 0 {
preLoop := remaining
for root, chain := range rootsMeta.Roots {
types := map[node.RootType]struct{}{}
all := append([]hash.Hash{root}, chain...)
for _, droot := range all {
if dtypes, ok := plainRoots[droot]; ok && len(dtypes) > 0 {
for typ := range dtypes {
types[typ] = struct{}{}
}
}
}
if len(types) > 0 {
for _, root := range all {
if len(plainRoots[root]) == 0 {
plainRoots[root] = types
remaining--
}
}
}
}
if remaining == preLoop {
// Can't find all versions, so probably for some roots the GetRootForHash call above
// failed with an ErrNotFound; this key must be stale.
err = v4.changeBatch.DeleteAt(item.KeyCopy(nil), item.Version())
if err != nil {
return fmt.Errorf("can't delete stale roots metadata key for version %v: %w", version, err)
}
return nil
}
}
// Create root typing keys.
for h, types := range plainRoots {
for t := range types {
th := typedHashFromParts(t, h)
entry := badger.NewEntry(
v4RootNodeKeyFmt.Encode(&th),
[]byte{},
)
if err = v4.changeBatch.SetEntryAt(entry, versionToTs(version)); err != nil {
return fmt.Errorf("error creating root typing key: %w", err)
}
}
}
// Build new roots structure.
var newRoots v4RootsMetadata
newRoots.Roots = map[typedHash][]typedHash{}
for root, chain := range rootsMeta.Roots {
for typ := range plainRoots[root] {
arr := make([]typedHash, 0, len(chain))
for _, droot := range chain {
th := typedHashFromParts(typ, droot)
arr = append(arr, th)
}
th := typedHashFromParts(typ, root)
newRoots.Roots[th] = arr
}
}
err = v4.changeBatch.DeleteAt(item.KeyCopy(nil), item.Version())
if err != nil {
return fmt.Errorf("error removing old root metadata: %w", err)
}
entry := badger.NewEntry(v4RootsMetadataKeyFmt.Encode(&version), cbor.Marshal(newRoots))
if err = v4.changeBatch.SetEntryAt(entry, item.Version()); err != nil {
return fmt.Errorf("error storing updated root metadata: %w", err)
}
return nil
}
func (v4 *v4Migrator) keyWriteLog(item *badger.Item) error {
var version uint64
var h1, h2 hash.Hash
var th1, th2 typedHash
if !v3WriteLogKeyFmt.Decode(item.Key(), &version, &h1, &h2) {
return fmt.Errorf("error decoding writelog key")
}
types, err := v4.getRootType(h1, version)
if err != nil {
return fmt.Errorf("error getting type for writelog root %v:%v: %w", h1, version, err)
}
if len(types) == 0 {
// Root doesn't exist anymore, so this writelog is probably stale
// and shouldn't exist anymore.
err = v4.changeBatch.DeleteAt(item.KeyCopy(nil), item.Version())
if err != nil {
return fmt.Errorf("can't delete stale writelog for root %v:%v: %w", h1, version, err)
}
return nil
}
err = v4.changeBatch.DeleteAt(item.KeyCopy(nil), item.Version())
if err != nil {
return fmt.Errorf("error removing old writelog key: %w", err)
}
var val []byte
_ = item.Value(func(data []byte) error {
val = data
return nil
})
for _, t1 := range types {
th1.FromParts(t1, h1)
th2.FromParts(t1, h2)
key := v4WriteLogKeyFmt.Encode(&version, &th1, &th2)
if item.IsDeletedOrExpired() {
err = v4.changeBatch.DeleteAt(key, item.Version())
if err != nil {
return fmt.Errorf("error setting removed flag for writelog key: %w", err)
}
} else {
entry := badger.NewEntry(key, val)
err = v4.changeBatch.SetEntryAt(entry, item.Version())
if err != nil {
return fmt.Errorf("error setting updated writelog key: %w", err)
}
}
}
return nil
}
func (v4 *v4Migrator) keyRootUpdatedNodes(item *badger.Item) error {
var version uint64
var h1 hash.Hash
if !v3RootUpdatedNodesKeyFmt.Decode(item.Key(), &version, &h1) {
return fmt.Errorf("error decoding root updated nodes key")
}
types, err := v4.getRootType(h1, version)
if err != nil || len(types) == 0 {
return fmt.Errorf("error getting root %v:%v for updated nodes list: %w", h1, version, err)
}
err = v4.changeBatch.DeleteAt(item.KeyCopy(nil), item.Version())
if err != nil {
return fmt.Errorf("error deleting old nodes nodes list for root %v: %w", h1, err)
}
if item.IsDeletedOrExpired() {
for _, typ := range types {
th := typedHashFromParts(typ, h1)
key := v4RootUpdatedNodesKeyFmt.Encode(version, &th)
if err = v4.changeBatch.DeleteAt(key, item.Version()); err != nil {
return fmt.Errorf("error transforming removed updated nodes list for root %v: %w", th, err)
}
}
return nil
}
var oldUpdatedNodes []v3UpdatedNode
err = item.Value(func(data []byte) error {
return cbor.UnmarshalTrusted(data, &oldUpdatedNodes)
})
if err != nil {
return fmt.Errorf("error decoding updated nodes list for root %v:%v: %w", h1, version, err)
}
newUpdatedNodes := make([]v4UpdatedNode, 0, len(oldUpdatedNodes))
for _, up := range oldUpdatedNodes {
newUpdatedNodes = append(newUpdatedNodes, v4UpdatedNode{
Removed: up.Removed,
Hash: up.Hash,
})
}
for _, typ := range types {
th := typedHashFromParts(typ, h1)
if v4.meta.MultipartActive {
entry := badger.NewEntry(
v4MultipartRestoreNodeLogKeyFmt.Encode(&th),
[]byte{},
)
if err = v4.changeBatch.SetEntryAt(entry, versionToTs(version)); err != nil {
return fmt.Errorf("error setting multipart marker for root %v: %w", th, err)
}
}
rootEntry := badger.NewEntry(
rootNodeKeyFmt.Encode(&th),
[]byte{},
)
if err = v4.changeBatch.SetEntryAt(rootEntry, versionToTs(version)); err != nil {
return fmt.Errorf("error setting root marker for root %v: %w", th, err)
}
entry := badger.NewEntry(
v4RootUpdatedNodesKeyFmt.Encode(version, &th),
cbor.Marshal(newUpdatedNodes),
)
err = v4.changeBatch.SetEntryAt(entry, item.Version())
if err != nil {
return fmt.Errorf("error storing updated nodes list for root %v: %w", th, err)
}
}
return nil
}
func (v4 *v4Migrator) keyMultipartRestoreNodeLog(item *badger.Item) error {
if item.IsDeletedOrExpired() {
// These keys are all at tsMetadata.
return nil
}
var h hash.Hash
if !v3MultipartRestoreNodeLogKeyFmt.Decode(item.Key(), &h) {
return fmt.Errorf("error decoding multipart restore key")
}
if err := v4.changeBatch.DeleteAt(item.KeyCopy(nil), item.Version()); err != nil {
return fmt.Errorf("can't delete old multipart restore log key for %v: %w", h, err)
}
th := typedHashFromParts(node.RootTypeInvalid, h)
entry := badger.NewEntry(
v4MultipartRestoreNodeLogKeyFmt.Encode(&th),
[]byte{},
)
if err := v4.changeBatch.SetEntryAt(entry, item.Version()); err != nil {
return fmt.Errorf("can't create new multipart restore log key for %v: %w", h, err)
}
return nil
}
func (v4 *v4Migrator) migrateMeta() error {
v4.helper.DisplayStepBegin("migrating storage roots and metadata")
keyOrder := []byte{
v3MetadataKeyFmt.Prefix(),
v3RootsMetadataKeyFmt.Prefix(),
v3WriteLogKeyFmt.Prefix(),
v3RootUpdatedNodesKeyFmt.Prefix(),
v3MultipartRestoreNodeLogKeyFmt.Prefix(),
// Other keys don't need to be migrated.
}
if len(v4.meta.LastKey) == 0 {
v4.meta.LastKey = []byte{keyOrder[0]}
v4.meta.LastKeyVersion = maxTimestamp
// LastKey records the last _already processed_ key, so
// if we're only just starting up, the first key we see
// won't have been processed yet.
}
keyNexts := map[byte]byte{}
for i := 0; i < len(keyOrder)-1; i++ {
keyNexts[keyOrder[i]] = keyOrder[i+1]
}
keyFuncs := map[byte]func(item *badger.Item) error{
v3MetadataKeyFmt.Prefix(): v4.keyMetadata,
v3RootsMetadataKeyFmt.Prefix(): v4.keyRootsMetadata,
v3WriteLogKeyFmt.Prefix(): v4.keyWriteLog,
v3RootUpdatedNodesKeyFmt.Prefix(): v4.keyRootUpdatedNodes,
v3MultipartRestoreNodeLogKeyFmt.Prefix(): v4.keyMultipartRestoreNodeLog,
}
opts := badger.DefaultIteratorOptions
opts.AllVersions = true
it := v4.readTxn.NewIterator(opts)
defer func() {
v4.readTxn.Discard()
v4.readTxn = v4.db.db.NewTransactionAt(maxTimestamp, false)
}()
defer func() {
it.Close()
}()
currentKey := v4.meta.LastKey[0]
var keyOk bool
for {
it.Rewind()
it.Seek(v4.meta.LastKey)
for ; it.Valid(); it.Next() {
if bytes.Equal(v4.meta.LastKey, it.Item().Key()) && it.Item().Version() >= v4.meta.LastKeyVersion {
continue
}
if it.Item().Key()[0] != currentKey {
break
}
if err := keyFuncs[currentKey](it.Item()); err != nil {
return err
}
v4.meta.CurrentMetaCount++
v4.helper.DisplayProgress("updated keys", v4.meta.CurrentMetaCount, v4.meta.MetaCount)
v4.meta.LastKey = it.Item().KeyCopy(v4.meta.LastKey)
v4.meta.LastKeyVersion = it.Item().Version()
// Save progress.
if err := v4.flush(false); err != nil {
return err
}
}
// Force flush everything.
if err := v4.flush(true); err != nil {
return err
}
it.Close()
v4.readTxn.Discard()
v4.readTxn = v4.db.db.NewTransactionAt(maxTimestamp, false)
it = v4.readTxn.NewIterator(badger.DefaultIteratorOptions)
currentKey, keyOk = keyNexts[currentKey]
if !keyOk {
break
}
v4.meta.LastKey = []byte{currentKey}
v4.meta.LastKeyVersion = maxTimestamp
}
v4.helper.DisplayStepEnd("done")
return nil
}
func (v4 *v4Migrator) TargetVersion() uint64 {
return 4
}
func (v4 *v4Migrator) Migrate() (rversion uint64, rerr error) {
v4.readTxn = v4.db.db.NewTransactionAt(maxTimestamp, false)
defer func() {
// readTxn will change throughout the process, don't
// bind the defer to a particular instance.
v4.readTxn.Discard()
}()
v4.changeBatch = v4.db.db.NewWriteBatchAt(maxTimestamp)
defer func() {
// changeBatch will change throughout the process, don't
// bind the defer to a particular instance.
v4.changeBatch.Cancel()
}()
// Load migration metadata.
err := v4.meta.load(v4.db.db)
if err != nil && err != badger.ErrKeyNotFound {
return 0, err
}
v4.meta.BaseDBVersion = 3
// Count keys first, so we can report some sensible progress to the user.
// Badger says this should be fast.
if !v4.meta.InitComplete {
v4.helper.DisplayStepBegin("scanning database")
v4.meta.MetaCount = 0
func() {
opts := badger.DefaultIteratorOptions
opts.PrefetchValues = false
opts.AllVersions = true
it := v4.readTxn.NewIterator(opts)
defer it.Close()
it.Rewind()
it.Seek([]byte{v3WriteLogKeyFmt.Prefix()})
for ; it.Valid(); it.Next() {
prefix := it.Item().Key()[0]
if prefix == v3MultipartRestoreNodeLogKeyFmt.Prefix() {
v4.meta.MultipartActive = true
}
if prefix != v3NodeKeyFmt.Prefix() && prefix != v3MultipartRestoreNodeLogKeyFmt.Prefix() {
v4.meta.MetaCount++
}
}
}()
v4.meta.InitComplete = true
v4.helper.DisplayStepEnd(fmt.Sprintf("%v keys to migrate", v4.meta.MetaCount))
}
// Migrate!
if !v4.meta.MetaComplete {
if err := v4.migrateMeta(); err != nil {
return 0, err
}
v4.meta.MetaComplete = true
v4.meta.LastKey = []byte{}
v4.meta.LastKeyVersion = maxTimestamp
if err := v4.flush(true); err != nil {
return 0, fmt.Errorf("error migrating metadata: %w", err)
}
}
// All done, flush and clean up.
v4.done = true
if err := v4.flush(true); err != nil {
return 0, err
}
return 4, nil
}
type v5MigratedRoot struct {
Hash typedHash `json:"hash"`
Version uint64 `json:"version"`
}
type v5MigratorMetadata struct {
migrationCommonMeta
LastMigratedVersion *uint64 `json:"last_migrated_version"`
LastMigratedRoots map[typedHash]v5MigratedRoot `json:"last_migrated_roots"`
LastPrunedVersion *uint64 `json:"last_pruned_version"`
}
func (m *v5MigratorMetadata) load(db *badger.DB) error {
txn := db.NewTransactionAt(tsMetadata, false)
defer txn.Discard()
item, err := txn.Get(migrationMetaKeyFmt.Encode())
if err != nil {
return err
}
return item.Value(func(data []byte) error {
return cbor.Unmarshal(data, m)
})
}
func (m *v5MigratorMetadata) save(batch *badger.WriteBatch) error {
return batch.SetEntryAt(badger.NewEntry(
migrationMetaKeyFmt.Encode(),
cbor.Marshal(m),
), tsMetadata)
}
func (m *v5MigratorMetadata) remove(batch *badger.WriteBatch) error {
return batch.DeleteAt(migrationMetaKeyFmt.Encode(), tsMetadata)
}
type v5Key struct {
key []byte
ts uint64
}
type v5Migrator struct {
db *badgerNodeDB
helper MigrationHelper
readTxn *badger.Txn
changeBatch *badger.WriteBatch
flushRemain int
deleteKeys []v5Key
meta v5MigratorMetadata
done bool
}
func (v5 *v5Migrator) flush(force bool) error {
v5.flushRemain--
if v5.flushRemain < 0 || force {
v5.flushRemain = flushInterval
if v5.done {
if err := v5.meta.remove(v5.changeBatch); err != nil {
return fmt.Errorf("error clearing progress: %w", err)
}
} else {
if err := v5.meta.save(v5.changeBatch); err != nil {
return fmt.Errorf("error saving progress: %w", err)
}
}
if err := v5.changeBatch.Flush(); err != nil {
return fmt.Errorf("error committing database state: %w", err)
}
v5.changeBatch = v5.db.db.NewWriteBatchAt(maxTimestamp)
}
return nil
}
func (v5 *v5Migrator) unmarshalV4InternalNode(n *node.InternalNode, data []byte) (int, error) {
if len(data) < 1+v4NodeVersionSize+node.DepthSize+1 {
return 0, node.ErrMalformedNode
}
pos := 0
if data[pos] != node.PrefixInternalNode {
return 0, node.ErrMalformedNode
}
pos++
// Skip version field.
pos += v4NodeVersionSize
if _, err := n.LabelBitLength.UnmarshalBinary(data[pos:]); err != nil {
return 0, fmt.Errorf("mkvs: failed to unmarshal LabelBitLength: %w", err)
}
labelLen := n.LabelBitLength.ToBytes()
pos += node.DepthSize
if pos+labelLen > len(data) {
return 0, node.ErrMalformedNode
}
n.Label = make(node.Key, labelLen)
copy(n.Label, data[pos:pos+labelLen])
pos += labelLen
if pos >= len(data) {
return 0, node.ErrMalformedNode
}
if data[pos] == node.PrefixNilNode {
n.LeafNode = nil
pos++
} else {
leafNode := node.LeafNode{}
var leafNodeBinarySize int
var err error
if leafNodeBinarySize, err = v5.unmarshalV4LeafNode(&leafNode, data[pos:]); err != nil {
return 0, fmt.Errorf("mkvs: failed to unmarshal leaf node: %w", err)
}
n.LeafNode = &node.Pointer{Clean: true, Hash: leafNode.Hash, Node: &leafNode}
pos += leafNodeBinarySize
}
var leftHash hash.Hash
if err := leftHash.UnmarshalBinary(data[pos : pos+hash.Size]); err != nil {
return 0, fmt.Errorf("mkvs: failed to unmarshal left hash: %w", err)
}
pos += hash.Size
var rightHash hash.Hash
if err := rightHash.UnmarshalBinary(data[pos : pos+hash.Size]); err != nil {
return 0, fmt.Errorf("mkvs: failed to unmarshal right hash: %w", err)
}
pos += hash.Size
if leftHash.IsEmpty() {
n.Left = nil
} else {
n.Left = &node.Pointer{Clean: true, Hash: leftHash}
}
if rightHash.IsEmpty() {
n.Right = nil
} else {
n.Right = &node.Pointer{Clean: true, Hash: rightHash}
}
n.UpdateHash()
n.Clean = true
return pos, nil
}
func (v5 *v5Migrator) unmarshalV4LeafNode(n *node.LeafNode, data []byte) (int, error) {
if len(data) < 1+v4NodeVersionSize+node.DepthSize+node.ValueLengthSize || data[0] != node.PrefixLeafNode {
return 0, node.ErrMalformedNode
}
pos := 1
// Skip version field.
pos += v4NodeVersionSize
var key node.Key
keySize, err := key.SizedUnmarshalBinary(data[pos:])
if err != nil {
return 0, err
}
pos += keySize
if pos+node.ValueLengthSize > len(data) {
return 0, node.ErrMalformedNode
}
valueSize := int(binary.LittleEndian.Uint32(data[pos : pos+node.ValueLengthSize]))
pos += node.ValueLengthSize
if pos+valueSize > len(data) {
return 0, node.ErrMalformedNode
}
value := make([]byte, valueSize)
copy(value, data[pos:pos+valueSize])
pos += valueSize
n.Clean = true
n.Key = key
n.Value = value
n.UpdateHash()
return pos, nil
}
func (v5 *v5Migrator) migrateNode(h hash.Hash, version uint64) (*hash.Hash, error) {
item, err := v5.readTxn.Get(v4NodeKeyFmt.Encode(&h))
if err != nil {
return nil, fmt.Errorf("error loading node %s: %w", h, err)
}
raw, err := item.ValueCopy(nil)
if err != nil {
return nil, fmt.Errorf("error loading node %s: %w", h, err)
}
// Decode node type.
var (
newHash hash.Hash
newNode []byte
)
switch raw[0] {
case node.PrefixInternalNode:
var n node.InternalNode
_, err = v5.unmarshalV4InternalNode(&n, raw)
if err != nil {
return nil, fmt.Errorf("error decoding internal node %s: %w", h, err)
}
// Migrate children.
for _, child := range []*node.Pointer{n.Left, n.Right} {
if child == nil {
continue
}
var nh *hash.Hash
nh, err = v5.migrateNode(child.Hash, version)
if err != nil {
return nil, err
}
child.Hash = *nh
}
n.UpdateHash()
newHash = n.GetHash()
newNode, _ = n.MarshalBinary()
case node.PrefixLeafNode:
var n node.LeafNode
_, err = v5.unmarshalV4LeafNode(&n, raw)
if err != nil {
return nil, fmt.Errorf("error decoding leaf node %s: %w", h, err)
}
newHash = n.GetHash()
newNode, _ = n.MarshalBinary()
default:
return nil, fmt.Errorf("unknown node type for node %s: 0x%02x", h, raw[0])
}
// Store node under the new hash.
entry := badger.NewEntry(v5NodeKeyFmt.Encode(&newHash), newNode)
err = v5.changeBatch.SetEntryAt(entry, item.Version())
if err != nil {
return nil, fmt.Errorf("error setting updated node key: %w", err)
}
// Queue removal of any old nodes.
v5.deleteKeys = append(v5.deleteKeys, v5Key{key: item.KeyCopy(nil), ts: item.Version()})
return &newHash, nil
}
func (v5 *v5Migrator) migrateWriteLog(oldSrcRoot, oldDstRoot, newSrcRoot typedHash, newDstRoot v5MigratedRoot) error {
item, err := v5.readTxn.Get(v4WriteLogKeyFmt.Encode(newDstRoot.Version, &oldDstRoot, &oldSrcRoot))
switch err {
case nil:
case badger.ErrKeyNotFound:
// Write log does not exist.
return nil
default:
return fmt.Errorf("error reading write log for %d: %s -> %s: %w", newDstRoot.Version, oldSrcRoot, oldDstRoot, err)
}
var value []byte
_ = item.Value(func(data []byte) error {
value = data
return nil
})
entry := badger.NewEntry(
v5WriteLogKeyFmt.Encode(newDstRoot.Version, &newDstRoot.Hash, &newSrcRoot),
value,
)
err = v5.changeBatch.SetEntryAt(entry, item.Version())
if err != nil {
return fmt.Errorf("error setting updated write log key: %w", err)
}
// Make sure old write log is removed.
v5.deleteKeys = append(v5.deleteKeys, v5Key{key: item.KeyCopy(nil), ts: item.Version()})
return nil
}
func (v5 *v5Migrator) migrateVersion(version uint64, migratedRoots map[typedHash]v5MigratedRoot) (bool, error) {
defer func() {
v5.readTxn.Discard()
v5.readTxn = v5.db.db.NewTransactionAt(maxTimestamp, false)
}()
v5.helper.DisplayStep(fmt.Sprintf("migrating version %d", version))
var roots v4RootsMetadata
item, err := v5.readTxn.Get(v4RootsMetadataKeyFmt.Encode(version))
switch err {
case nil:
case badger.ErrKeyNotFound:
// Version does not exist.
return false, nil