-
Notifications
You must be signed in to change notification settings - Fork 268
/
nodedb.go
1341 lines (1147 loc) · 35.1 KB
/
nodedb.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 iavl
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"sync"
"time"
corestore "cosmossdk.io/core/store"
"github.com/cosmos/iavl/cache"
"github.com/cosmos/iavl/fastnode"
ibytes "github.com/cosmos/iavl/internal/bytes"
"github.com/cosmos/iavl/keyformat"
)
const (
int32Size = 4
int64Size = 8
hashSize = sha256.Size
genesisVersion = 1
storageVersionKey = "storage_version"
// We store latest saved version together with storage version delimited by the constant below.
// This delimiter is valid only if fast storage is enabled (i.e. storageVersion >= fastStorageVersionValue).
// The latest saved version is needed for protection against downgrade and re-upgrade. In such a case, it would
// be possible to observe mismatch between the latest version state and the fast nodes on disk.
// Therefore, we would like to detect that and overwrite fast nodes on disk with the latest version state.
fastStorageVersionDelimiter = "-"
// Using semantic versioning: https://semver.org/
defaultStorageVersionValue = "1.0.0"
fastStorageVersionValue = "1.1.0"
fastNodeCacheSize = 100000
)
var (
// All new node keys are prefixed with the byte 's'. This ensures no collision is
// possible with the legacy nodes, and makes them easier to traverse. They are indexed by the version and the local nonce.
nodeKeyFormat = keyformat.NewFastPrefixFormatter('s', int64Size+int32Size) // s<version><nonce>
// This is only used for the iteration purpose.
nodeKeyPrefixFormat = keyformat.NewFastPrefixFormatter('s', int64Size) // s<version>
// Key Format for making reads and iterates go through a data-locality preserving db.
// The value at an entry will list what version it was written to.
// Then to query values, you first query state via this fast method.
// If its present, then check the tree version. If tree version >= result_version,
// return result_version. Else, go through old (slow) IAVL get method that walks through tree.
fastKeyFormat = keyformat.NewKeyFormat('f', 0) // f<keystring>
// Key Format for storing metadata about the chain such as the version number.
// The value at an entry will be in a variable format and up to the caller to
// decide how to parse.
metadataKeyFormat = keyformat.NewKeyFormat('m', 0) // m<keystring>
// All legacy node keys are prefixed with the byte 'n'.
legacyNodeKeyFormat = keyformat.NewFastPrefixFormatter('n', hashSize) // n<hash>
// All legacy orphan keys are prefixed with the byte 'o'.
legacyOrphanKeyFormat = keyformat.NewKeyFormat('o', int64Size, int64Size, hashSize) // o<last-version><first-version><hash>
// All legacy root keys are prefixed with the byte 'r'.
legacyRootKeyFormat = keyformat.NewKeyFormat('r', int64Size) // r<version>
)
var errInvalidFastStorageVersion = fmt.Errorf("fast storage version must be in the format <storage version>%s<latest fast cache version>", fastStorageVersionDelimiter)
type nodeDB struct {
ctx context.Context
cancel context.CancelFunc
logger Logger
mtx sync.Mutex // Read/write lock.
done chan struct{} // Channel to signal that the pruning process is done.
db corestore.KVStoreWithBatch // Persistent node storage.
batch corestore.Batch // Batched writing buffer.
opts Options // Options to customize for pruning/writing
versionReaders map[int64]uint32 // Number of active version readers
storageVersion string // Storage version
firstVersion int64 // First version of nodeDB.
latestVersion int64 // Latest version of nodeDB.
pruneVersion int64 // Version to prune up to.
legacyLatestVersion int64 // Latest version of nodeDB in legacy format.
nodeCache cache.Cache // Cache for nodes in the regular tree that consists of key-value pairs at any version.
fastNodeCache cache.Cache // Cache for nodes in the fast index that represents only key-value pairs at the latest version.
isCommitting bool // Flag to indicate that the nodeDB is committing.
chCommitting chan struct{} // Channel to signal that the committing is done.
}
func newNodeDB(db corestore.KVStoreWithBatch, cacheSize int, opts Options, lg Logger) *nodeDB {
storeVersion, err := db.Get(metadataKeyFormat.Key([]byte(storageVersionKey)))
if err != nil || storeVersion == nil {
storeVersion = []byte(defaultStorageVersionValue)
}
ctx, cancel := context.WithCancel(context.Background())
ndb := &nodeDB{
ctx: ctx,
cancel: cancel,
logger: lg,
db: db,
batch: NewBatchWithFlusher(db, opts.FlushThreshold),
opts: opts,
firstVersion: 0,
latestVersion: 0, // initially invalid
legacyLatestVersion: 0,
pruneVersion: 0,
nodeCache: cache.New(cacheSize),
fastNodeCache: cache.New(fastNodeCacheSize),
versionReaders: make(map[int64]uint32, 8),
storageVersion: string(storeVersion),
chCommitting: make(chan struct{}, 1),
}
if opts.AsyncPruning {
ndb.done = make(chan struct{})
go ndb.startPruning()
}
return ndb
}
// GetNode gets a node from memory or disk. If it is an inner node, it does not
// load its children.
// It is used for both formats of nodes: legacy and new.
// `legacy`: nk is the hash of the node. `new`: <version><nonce>.
func (ndb *nodeDB) GetNode(nk []byte) (*Node, error) {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
if nk == nil {
return nil, ErrNodeMissingNodeKey
}
// Check the cache.
if cachedNode := ndb.nodeCache.Get(nk); cachedNode != nil {
ndb.opts.Stat.IncCacheHitCnt()
return cachedNode.(*Node), nil
}
ndb.opts.Stat.IncCacheMissCnt()
// Doesn't exist, load.
isLegcyNode := len(nk) == hashSize
var nodeKey []byte
if isLegcyNode {
nodeKey = ndb.legacyNodeKey(nk)
} else {
nodeKey = ndb.nodeKey(nk)
}
buf, err := ndb.db.Get(nodeKey)
if err != nil {
return nil, fmt.Errorf("can't get node %v: %v", nk, err)
}
if buf == nil && !isLegcyNode {
// if the node is reformatted by pruning, check against (version, 0)
nKey := GetNodeKey(nk)
if nKey.nonce == 1 {
nodeKey = ndb.nodeKey((&NodeKey{
version: nKey.version,
nonce: 0,
}).GetKey())
buf, err = ndb.db.Get(nodeKey)
if err != nil {
return nil, fmt.Errorf("can't get the reformatted node %v: %v", nk, err)
}
}
}
if buf == nil {
return nil, fmt.Errorf("Value missing for key %v corresponding to nodeKey %x", nk, nodeKey)
}
var node *Node
if isLegcyNode {
node, err = MakeLegacyNode(nk, buf)
if err != nil {
return nil, fmt.Errorf("error reading Legacy Node. bytes: %x, error: %v", buf, err)
}
} else {
node, err = MakeNode(nk, buf)
if err != nil {
return nil, fmt.Errorf("error reading Node. bytes: %x, error: %v", buf, err)
}
}
ndb.nodeCache.Add(node)
return node, nil
}
func (ndb *nodeDB) GetFastNode(key []byte) (*fastnode.Node, error) {
if !ndb.hasUpgradedToFastStorage() {
return nil, errors.New("storage version is not fast")
}
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
if len(key) == 0 {
return nil, fmt.Errorf("nodeDB.GetFastNode() requires key, len(key) equals 0")
}
if cachedFastNode := ndb.fastNodeCache.Get(key); cachedFastNode != nil {
ndb.opts.Stat.IncFastCacheHitCnt()
return cachedFastNode.(*fastnode.Node), nil
}
ndb.opts.Stat.IncFastCacheMissCnt()
// Doesn't exist, load.
buf, err := ndb.db.Get(ndb.fastNodeKey(key))
if err != nil {
return nil, fmt.Errorf("can't get FastNode %X: %w", key, err)
}
if buf == nil {
return nil, nil
}
fastNode, err := fastnode.DeserializeNode(key, buf)
if err != nil {
return nil, fmt.Errorf("error reading FastNode. bytes: %x, error: %w", buf, err)
}
ndb.fastNodeCache.Add(fastNode)
return fastNode, nil
}
// SaveNode saves a node to disk.
func (ndb *nodeDB) SaveNode(node *Node) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
if node.nodeKey == nil {
return ErrNodeMissingNodeKey
}
// Save node bytes to db.
var buf bytes.Buffer
buf.Grow(node.encodedSize())
if err := node.writeBytes(&buf); err != nil {
return err
}
if err := ndb.batch.Set(ndb.nodeKey(node.GetKey()), buf.Bytes()); err != nil {
return err
}
ndb.logger.Debug("BATCH SAVE", "node", node)
ndb.nodeCache.Add(node)
return nil
}
// SaveFastNode saves a FastNode to disk and add to cache.
func (ndb *nodeDB) SaveFastNode(node *fastnode.Node) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
return ndb.saveFastNodeUnlocked(node, true)
}
// SaveFastNodeNoCache saves a FastNode to disk without adding to cache.
func (ndb *nodeDB) SaveFastNodeNoCache(node *fastnode.Node) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
return ndb.saveFastNodeUnlocked(node, false)
}
// SetCommitting sets the committing flag to true.
// This is used to let the pruning process know that the nodeDB is committing.
func (ndb *nodeDB) SetCommitting() {
for len(ndb.chCommitting) > 0 {
<-ndb.chCommitting
}
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
ndb.isCommitting = true
}
// UnsetCommitting sets the committing flag to false.
// This is used to let the pruning process know that the nodeDB is done committing.
func (ndb *nodeDB) UnsetCommitting() {
ndb.mtx.Lock()
ndb.isCommitting = false
ndb.mtx.Unlock()
ndb.chCommitting <- struct{}{}
}
// IsCommitting returns true if the nodeDB is committing, false otherwise.
func (ndb *nodeDB) IsCommitting() bool {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
return ndb.isCommitting
}
// SetFastStorageVersionToBatch sets storage version to fast where the version is
// 1.1.0-<version of the current live state>. Returns error if storage version is incorrect or on
// db error, nil otherwise. Requires changes to be committed after to be persisted.
func (ndb *nodeDB) SetFastStorageVersionToBatch(latestVersion int64) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
var newVersion string
if ndb.storageVersion >= fastStorageVersionValue {
// Storage version should be at index 0 and latest fast cache version at index 1
versions := strings.Split(ndb.storageVersion, fastStorageVersionDelimiter)
if len(versions) > 2 {
return errInvalidFastStorageVersion
}
newVersion = versions[0]
} else {
newVersion = fastStorageVersionValue
}
newVersion += fastStorageVersionDelimiter + strconv.Itoa(int(latestVersion))
if err := ndb.batch.Set(metadataKeyFormat.Key([]byte(storageVersionKey)), []byte(newVersion)); err != nil {
return err
}
ndb.storageVersion = newVersion
return nil
}
func (ndb *nodeDB) getStorageVersion() string {
return ndb.storageVersion
}
// Returns true if the upgrade to latest storage version has been performed, false otherwise.
func (ndb *nodeDB) hasUpgradedToFastStorage() bool {
return ndb.getStorageVersion() >= fastStorageVersionValue
}
// Returns true if the upgrade to fast storage has occurred but it does not match the live state, false otherwise.
// When the live state is not matched, we must force reupgrade.
// We determine this by checking the version of the live state and the version of the live state when
// latest storage was updated on disk the last time.
func (ndb *nodeDB) shouldForceFastStorageUpgrade() (bool, error) {
versions := strings.Split(ndb.storageVersion, fastStorageVersionDelimiter)
if len(versions) == 2 {
_, latestVersion, err := ndb.getLatestVersion()
if err != nil {
// TODO: should be true or false as default? (removed panic here)
return false, err
}
if versions[1] != strconv.Itoa(int(latestVersion)) {
return true, nil
}
}
return false, nil
}
// saveFastNodeUnlocked saves a FastNode to disk.
func (ndb *nodeDB) saveFastNodeUnlocked(node *fastnode.Node, shouldAddToCache bool) error {
if node.GetKey() == nil {
return errors.New("cannot have FastNode with a nil value for key")
}
// Save node bytes to db.
var buf bytes.Buffer
buf.Grow(node.EncodedSize())
if err := node.WriteBytes(&buf); err != nil {
return fmt.Errorf("error while writing fastnode bytes. Err: %w", err)
}
if err := ndb.batch.Set(ndb.fastNodeKey(node.GetKey()), buf.Bytes()); err != nil {
return fmt.Errorf("error while writing key/val to nodedb batch. Err: %w", err)
}
if shouldAddToCache {
ndb.fastNodeCache.Add(node)
}
return nil
}
// Has checks if a node key exists in the database.
func (ndb *nodeDB) Has(nk []byte) (bool, error) {
return ndb.db.Has(ndb.nodeKey(nk))
}
// deleteFromPruning deletes the orphan nodes from the pruning process.
func (ndb *nodeDB) deleteFromPruning(key []byte) error {
if ndb.IsCommitting() {
// if the nodeDB is committing, the pruning process will be done after the committing.
<-ndb.chCommitting
}
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
return ndb.batch.Delete(key)
}
// saveNodeFromPruning saves the orphan nodes to the pruning process.
func (ndb *nodeDB) saveNodeFromPruning(node *Node) error {
if ndb.IsCommitting() {
// if the nodeDB is committing, the pruning process will be done after the committing.
<-ndb.chCommitting
}
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
// Save node bytes to db.
var buf bytes.Buffer
buf.Grow(node.encodedSize())
if err := node.writeBytes(&buf); err != nil {
return err
}
return ndb.batch.Set(ndb.nodeKey(node.GetKey()), buf.Bytes())
}
// deleteVersion deletes a tree version from disk.
// deletes orphans
func (ndb *nodeDB) deleteVersion(version int64) error {
rootKey, err := ndb.GetRoot(version)
if err != nil {
return err
}
if err := ndb.traverseOrphans(version, version+1, func(orphan *Node) error {
if orphan.nodeKey.nonce == 0 && !orphan.isLegacy {
// if the orphan is a reformatted root, it can be a legacy root
// so it should be removed from the pruning process.
if err := ndb.deleteFromPruning(ndb.legacyNodeKey(orphan.hash)); err != nil {
return err
}
}
if orphan.nodeKey.nonce == 1 && orphan.nodeKey.version < version {
// if the orphan is referred to the previous root, it should be reformatted
// to (version, 0), because the root (version, 1) should be removed but not
// applied now due to the batch writing.
orphan.nodeKey.nonce = 0
}
nk := orphan.GetKey()
if orphan.isLegacy {
return ndb.deleteFromPruning(ndb.legacyNodeKey(nk))
}
return ndb.deleteFromPruning(ndb.nodeKey(nk))
}); err != nil {
return err
}
literalRootKey := GetRootKey(version)
if rootKey == nil || !bytes.Equal(rootKey, literalRootKey) {
// if the root key is not matched with the literal root key, it means the given root
// is a reference root to the previous version.
if err := ndb.deleteFromPruning(ndb.nodeKey(literalRootKey)); err != nil {
return err
}
}
// check if the version is referred by the next version
nextRootKey, err := ndb.GetRoot(version + 1)
if err != nil {
return err
}
if bytes.Equal(literalRootKey, nextRootKey) {
root, err := ndb.GetNode(nextRootKey)
if err != nil {
return err
}
// ensure that the given version is not included in the root search
if err := ndb.deleteFromPruning(ndb.nodeKey(literalRootKey)); err != nil {
return err
}
// instead, the root should be reformatted to (version, 0)
root.nodeKey.nonce = 0
if err := ndb.saveNodeFromPruning(root); err != nil {
return err
}
}
return nil
}
// deleteLegacyNodes deletes all legacy nodes with the given version from disk.
// NOTE: This is only used for DeleteVersionsFrom.
func (ndb *nodeDB) deleteLegacyNodes(version int64, nk []byte) error {
node, err := ndb.GetNode(nk)
if err != nil {
return err
}
if node.nodeKey.version < version {
// it will skip the whole subtree.
return nil
}
if node.leftNodeKey != nil {
if err := ndb.deleteLegacyNodes(version, node.leftNodeKey); err != nil {
return err
}
}
if node.rightNodeKey != nil {
if err := ndb.deleteLegacyNodes(version, node.rightNodeKey); err != nil {
return err
}
}
return ndb.batch.Delete(ndb.legacyNodeKey(nk))
}
// deleteLegacyVersions deletes all legacy versions from disk.
func (ndb *nodeDB) deleteLegacyVersions(legacyLatestVersion int64) error {
// Delete the last version for the legacyLastVersion
if err := ndb.traverseOrphans(legacyLatestVersion, legacyLatestVersion+1, func(orphan *Node) error {
return ndb.deleteFromPruning(ndb.legacyNodeKey(orphan.hash))
}); err != nil {
return err
}
// Delete orphans for all legacy versions
if err := ndb.traversePrefix(legacyOrphanKeyFormat.Key(), func(key, value []byte) error {
if err := ndb.deleteFromPruning(key); err != nil {
return err
}
var fromVersion, toVersion int64
legacyOrphanKeyFormat.Scan(key, &toVersion, &fromVersion)
if (fromVersion <= legacyLatestVersion && toVersion < legacyLatestVersion) || fromVersion > legacyLatestVersion {
return ndb.deleteFromPruning(ndb.legacyNodeKey(value))
}
return nil
}); err != nil {
return err
}
// Delete all legacy roots
if err := ndb.traversePrefix(legacyRootKeyFormat.Key(), func(key, _ []byte) error {
return ndb.deleteFromPruning(key)
}); err != nil {
return err
}
return nil
}
// DeleteVersionsFrom permanently deletes all tree versions from the given version upwards.
func (ndb *nodeDB) DeleteVersionsFrom(fromVersion int64) error {
_, latest, err := ndb.getLatestVersion()
if err != nil {
return err
}
if latest < fromVersion {
return nil
}
ndb.mtx.Lock()
for v, r := range ndb.versionReaders {
if v >= fromVersion && r != 0 {
ndb.mtx.Unlock() // Unlock before exiting
return fmt.Errorf("unable to delete version %v with %v active readers", v, r)
}
}
ndb.mtx.Unlock()
// Delete the legacy versions
legacyLatestVersion, err := ndb.getLegacyLatestVersion()
if err != nil {
return err
}
dumpFromVersion := fromVersion
if legacyLatestVersion >= fromVersion {
if err := ndb.traverseRange(legacyRootKeyFormat.Key(fromVersion), legacyRootKeyFormat.Key(legacyLatestVersion+1), func(k, v []byte) error {
var version int64
legacyRootKeyFormat.Scan(k, &version)
// delete the legacy nodes
if err := ndb.deleteLegacyNodes(version, v); err != nil {
return err
}
// it will skip the orphans because orphans will be removed at once in `deleteLegacyVersions`
// delete the legacy root
return ndb.batch.Delete(k)
}); err != nil {
return err
}
// Update the legacy latest version forcibly
ndb.legacyLatestVersion = 0
fromVersion = legacyLatestVersion + 1
}
// Delete the nodes for new format
if err = ndb.traverseRange(nodeKeyPrefixFormat.KeyInt64(fromVersion), nodeKeyPrefixFormat.KeyInt64(latest+1), func(k, _ []byte) error {
return ndb.batch.Delete(k)
}); err != nil {
return err
}
// NOTICE: we don't touch fast node indexes here, because it'll be rebuilt later because of version mismatch.
ndb.resetLatestVersion(dumpFromVersion - 1)
return nil
}
// startPruning starts the pruning process.
func (ndb *nodeDB) startPruning() {
for {
select {
case <-ndb.ctx.Done():
ndb.done <- struct{}{}
return
default:
ndb.mtx.Lock()
toVersion := ndb.pruneVersion
ndb.mtx.Unlock()
if toVersion == 0 {
time.Sleep(100 * time.Millisecond)
continue
}
if err := ndb.deleteVersionsTo(toVersion); err != nil {
ndb.logger.Error("Error while pruning", "err", err)
time.Sleep(1 * time.Second)
continue
}
ndb.mtx.Lock()
if ndb.pruneVersion <= toVersion {
ndb.pruneVersion = 0
}
ndb.mtx.Unlock()
}
}
}
// DeleteVersionsTo deletes the oldest versions up to the given version from disk.
func (ndb *nodeDB) DeleteVersionsTo(toVersion int64) error {
if !ndb.opts.AsyncPruning {
return ndb.deleteVersionsTo(toVersion)
}
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
ndb.pruneVersion = toVersion
return nil
}
func (ndb *nodeDB) deleteVersionsTo(toVersion int64) error {
legacyLatestVersion, err := ndb.getLegacyLatestVersion()
if err != nil {
return err
}
// If the legacy version is greater than the toVersion, we don't need to delete anything.
// It will delete the legacy versions at once.
if legacyLatestVersion > toVersion {
return nil
}
first, err := ndb.getFirstVersion()
if err != nil {
return err
}
_, latest, err := ndb.getLatestVersion()
if err != nil {
return err
}
if latest <= toVersion {
return fmt.Errorf("latest version %d is less than or equal to toVersion %d", latest, toVersion)
}
ndb.mtx.Lock()
for v, r := range ndb.versionReaders {
if v >= first && v <= toVersion && r != 0 {
ndb.mtx.Unlock()
return fmt.Errorf("unable to delete version %d with %d active readers", v, r)
}
}
ndb.mtx.Unlock()
// Delete the legacy versions
if legacyLatestVersion >= first {
if err := ndb.deleteLegacyVersions(legacyLatestVersion); err != nil {
ndb.logger.Error("Error deleting legacy versions", "err", err)
}
first = legacyLatestVersion + 1
// reset the legacy latest version forcibly to avoid multiple calls
ndb.resetLegacyLatestVersion(-1)
}
for version := first; version <= toVersion; version++ {
if err := ndb.deleteVersion(version); err != nil {
return err
}
ndb.resetFirstVersion(version + 1)
}
return nil
}
func (ndb *nodeDB) DeleteFastNode(key []byte) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
if err := ndb.batch.Delete(ndb.fastNodeKey(key)); err != nil {
return err
}
ndb.fastNodeCache.Remove(key)
return nil
}
func (ndb *nodeDB) nodeKey(nk []byte) []byte {
return nodeKeyFormat.Key(nk)
}
func (ndb *nodeDB) fastNodeKey(key []byte) []byte {
return fastKeyFormat.KeyBytes(key)
}
func (ndb *nodeDB) legacyNodeKey(nk []byte) []byte {
return legacyNodeKeyFormat.Key(nk)
}
func (ndb *nodeDB) legacyRootKey(version int64) []byte {
return legacyRootKeyFormat.Key(version)
}
func (ndb *nodeDB) getFirstVersion() (int64, error) {
ndb.mtx.Lock()
firstVersion := ndb.firstVersion
ndb.mtx.Unlock()
if firstVersion > 0 {
return firstVersion, nil
}
// Check if we have a legacy version
itr, err := ndb.getPrefixIterator(legacyRootKeyFormat.Key())
if err != nil {
return 0, err
}
defer itr.Close()
if itr.Valid() {
var version int64
legacyRootKeyFormat.Scan(itr.Key(), &version)
return version, nil
}
// Find the first version
_, latestVersion, err := ndb.getLatestVersion()
if err != nil {
return 0, err
}
for firstVersion < latestVersion {
version := (latestVersion + firstVersion) >> 1
has, err := ndb.hasVersion(version)
if err != nil {
return 0, err
}
if has {
latestVersion = version
} else {
firstVersion = version + 1
}
}
ndb.resetFirstVersion(latestVersion)
return latestVersion, nil
}
func (ndb *nodeDB) resetFirstVersion(version int64) {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
ndb.firstVersion = version
}
func (ndb *nodeDB) getLegacyLatestVersion() (int64, error) {
ndb.mtx.Lock()
latestVersion := ndb.legacyLatestVersion
ndb.mtx.Unlock()
if latestVersion != 0 {
return latestVersion, nil
}
itr, err := ndb.db.ReverseIterator(
legacyRootKeyFormat.Key(int64(1)),
legacyRootKeyFormat.Key(int64(math.MaxInt64)),
)
if err != nil {
return 0, err
}
defer itr.Close()
if itr.Valid() {
k := itr.Key()
var version int64
legacyRootKeyFormat.Scan(k, &version)
ndb.resetLegacyLatestVersion(version)
return version, nil
}
if err := itr.Error(); err != nil {
return 0, err
}
// If there are no legacy versions, set -1
ndb.resetLegacyLatestVersion(-1)
return -1, nil
}
func (ndb *nodeDB) resetLegacyLatestVersion(version int64) {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
ndb.legacyLatestVersion = version
}
func (ndb *nodeDB) getLatestVersion() (bool, int64, error) {
ndb.mtx.Lock()
latestVersion := ndb.latestVersion
ndb.mtx.Unlock()
if latestVersion > 0 {
return true, latestVersion, nil
}
itr, err := ndb.db.ReverseIterator(
nodeKeyPrefixFormat.KeyInt64(int64(1)),
nodeKeyPrefixFormat.KeyInt64(int64(math.MaxInt64)),
)
if err != nil {
return false, 0, err
}
defer itr.Close()
if itr.Valid() {
k := itr.Key()
var nk []byte
nodeKeyFormat.Scan(k, &nk)
latestVersion = GetNodeKey(nk).version
ndb.resetLatestVersion(latestVersion)
return true, latestVersion, nil
}
if err := itr.Error(); err != nil {
return false, 0, err
}
// If there are no versions, try to get the latest version from the legacy format.
latestVersion, err = ndb.getLegacyLatestVersion()
if err != nil {
return false, 0, err
}
if latestVersion > 0 {
ndb.resetLatestVersion(latestVersion)
return true, latestVersion, nil
}
return false, 0, nil
// return -1, nil
}
func (ndb *nodeDB) resetLatestVersion(version int64) {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
ndb.latestVersion = version
}
// hasVersion checks if the given version exists.
func (ndb *nodeDB) hasVersion(version int64) (bool, error) {
return ndb.db.Has(nodeKeyFormat.Key(GetRootKey(version)))
}
// hasLegacyVersion checks if the given version exists in the legacy format.
func (ndb *nodeDB) hasLegacyVersion(version int64) (bool, error) {
return ndb.db.Has(ndb.legacyRootKey(version))
}
// GetRoot gets the nodeKey of the root for the specific version.
func (ndb *nodeDB) GetRoot(version int64) ([]byte, error) {
rootKey := GetRootKey(version)
val, err := ndb.db.Get(nodeKeyFormat.Key(rootKey))
if err != nil {
return nil, err
}
if val == nil {
// try the legacy root key
val, err := ndb.db.Get(ndb.legacyRootKey(version))
if err != nil {
return nil, err
}
if val == nil {
return nil, ErrVersionDoesNotExist
}
if len(val) == 0 { // empty root
return nil, nil
}
return val, nil
}
if len(val) == 0 { // empty root
return nil, nil
}
isRef, n := isReferenceRoot(val)
if isRef { // point to the prev version
switch n {
case nodeKeyFormat.Length(): // (prefix, version, 1)
nk := GetNodeKey(val[1:])
val, err = ndb.db.Get(val)
if err != nil {
return nil, err
}
if val == nil { // the prev version does not exist
// check if the prev version root is reformatted due to the pruning
rnk := &NodeKey{version: nk.version, nonce: 0}
val, err = ndb.db.Get(nodeKeyFormat.Key(rnk.GetKey()))
if err != nil {
return nil, err
}
if val == nil {
return nil, ErrVersionDoesNotExist
}
return rnk.GetKey(), nil
}
return nk.GetKey(), nil
case nodeKeyPrefixFormat.Length(): // (prefix, version) before the lazy pruning
return append(val[1:], 0, 0, 0, 1), nil
default:
return nil, fmt.Errorf("invalid reference root: %x", val)
}
}
return rootKey, nil
}
// SaveEmptyRoot saves the empty root.
func (ndb *nodeDB) SaveEmptyRoot(version int64) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
return ndb.batch.Set(nodeKeyFormat.Key(GetRootKey(version)), []byte{})
}
// SaveRoot saves the root when no updates.
func (ndb *nodeDB) SaveRoot(version int64, nk *NodeKey) error {
ndb.mtx.Lock()
defer ndb.mtx.Unlock()
ndb.logger.Debug("SaveRoot", "version", version, "nodeKey", nk)
return ndb.batch.Set(nodeKeyFormat.Key(GetRootKey(version)), nodeKeyFormat.Key(nk.GetKey()))
}
// Traverse fast nodes and return error if any, nil otherwise
func (ndb *nodeDB) traverseFastNodes(fn func(k, v []byte) error) error {
return ndb.traversePrefix(fastKeyFormat.Key(), fn)
}
// Traverse all keys and return error if any, nil otherwise
func (ndb *nodeDB) traverse(fn func(key, value []byte) error) error {
return ndb.traverseRange(nil, nil, fn)
}
// Traverse all keys between a given range (excluding end) and return error if any, nil otherwise
func (ndb *nodeDB) traverseRange(start []byte, end []byte, fn func(k, v []byte) error) error {
itr, err := ndb.db.Iterator(start, end)
if err != nil {
return err
}
defer itr.Close()
for ; itr.Valid(); itr.Next() {
if err := fn(itr.Key(), itr.Value()); err != nil {
return err
}
}
return itr.Error()
}
// Traverse all keys with a certain prefix. Return error if any, nil otherwise
func (ndb *nodeDB) traversePrefix(prefix []byte, fn func(k, v []byte) error) error {
itr, err := ndb.getPrefixIterator(prefix)
if err != nil {
return err
}
defer itr.Close()
for ; itr.Valid(); itr.Next() {
if err := fn(itr.Key(), itr.Value()); err != nil {
return err
}
}
return nil
}
// Get the iterator for a given prefix.
func (ndb *nodeDB) getPrefixIterator(prefix []byte) (corestore.Iterator, error) {
var start, end []byte
if len(prefix) == 0 {
start = nil
end = nil
} else {
start = ibytes.Cp(prefix)
end = ibytes.CpIncr(prefix)
}