-
Notifications
You must be signed in to change notification settings - Fork 199
/
trieStorageManager.go
614 lines (508 loc) · 17.3 KB
/
trieStorageManager.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
package trie
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"path"
"sort"
"strconv"
"sync"
"github.com/ElrondNetwork/elrond-go-core/core"
"github.com/ElrondNetwork/elrond-go-core/core/check"
"github.com/ElrondNetwork/elrond-go-core/core/closing"
"github.com/ElrondNetwork/elrond-go-core/hashing"
"github.com/ElrondNetwork/elrond-go-core/marshal"
"github.com/ElrondNetwork/elrond-go/common"
"github.com/ElrondNetwork/elrond-go/config"
"github.com/ElrondNetwork/elrond-go/storage"
"github.com/ElrondNetwork/elrond-go/storage/storageUnit"
)
// trieStorageManager manages all the storage operations of the trie (commit, snapshot, checkpoint, pruning)
type trieStorageManager struct {
db common.DBWriteCacher
snapshots []common.SnapshotDbHandler
snapshotId int
snapshotDbCfg config.DBConfig
snapshotReq chan *snapshotsQueueEntry
checkpointReq chan *snapshotsQueueEntry
checkpointHashesHolder CheckpointHashesHolder
pruningBlockingOps uint32
maxSnapshots uint32
keepSnapshots bool
cancelFunc context.CancelFunc
closer core.SafeCloser
closed bool
storageOperationMutex sync.RWMutex
}
type snapshotsQueueEntry struct {
rootHash []byte
newDb bool
leavesChan chan core.KeyValueHolder
}
// NewTrieStorageManagerArgs holds the arguments needed for creating a new trieStorageManager
type NewTrieStorageManagerArgs struct {
DB common.DBWriteCacher
Marshalizer marshal.Marshalizer
Hasher hashing.Hasher
SnapshotDbConfig config.DBConfig
GeneralConfig config.TrieStorageManagerConfig
CheckpointHashesHolder CheckpointHashesHolder
}
// NewTrieStorageManager creates a new instance of trieStorageManager
func NewTrieStorageManager(args NewTrieStorageManagerArgs) (*trieStorageManager, error) {
if check.IfNil(args.DB) {
return nil, ErrNilDatabase
}
if check.IfNil(args.Marshalizer) {
return nil, ErrNilMarshalizer
}
if check.IfNil(args.Hasher) {
return nil, ErrNilHasher
}
if check.IfNil(args.CheckpointHashesHolder) {
return nil, ErrNilCheckpointHashesHolder
}
snapshots, snapshotId, err := getSnapshotsAndSnapshotId(args.SnapshotDbConfig)
if err != nil {
log.Debug("get snapshot", "error", err.Error())
}
ctx, cancelFunc := context.WithCancel(context.Background())
tsm := &trieStorageManager{
db: args.DB,
snapshots: snapshots,
snapshotId: snapshotId,
snapshotDbCfg: args.SnapshotDbConfig,
snapshotReq: make(chan *snapshotsQueueEntry, args.GeneralConfig.SnapshotsBufferLen),
checkpointReq: make(chan *snapshotsQueueEntry, args.GeneralConfig.SnapshotsBufferLen),
pruningBlockingOps: 0,
maxSnapshots: args.GeneralConfig.MaxSnapshots,
keepSnapshots: args.GeneralConfig.KeepSnapshots,
cancelFunc: cancelFunc,
checkpointHashesHolder: args.CheckpointHashesHolder,
closer: closing.NewSafeChanCloser(),
}
go tsm.doCheckpointsAndSnapshots(ctx, args.Marshalizer, args.Hasher)
return tsm, nil
}
func (tsm *trieStorageManager) doCheckpointsAndSnapshots(ctx context.Context, msh marshal.Marshalizer, hsh hashing.Hasher) {
tsm.doProcessLoop(ctx, msh, hsh)
tsm.cleanupChans()
}
func (tsm *trieStorageManager) doProcessLoop(ctx context.Context, msh marshal.Marshalizer, hsh hashing.Hasher) {
for {
select {
case snapshotRequest := <-tsm.snapshotReq:
tsm.takeSnapshot(snapshotRequest, msh, hsh, ctx)
case snapshotRequest := <-tsm.checkpointReq:
tsm.takeCheckpoint(snapshotRequest, msh, hsh, ctx)
case <-ctx.Done():
log.Debug("trieStorageManager.storageProcessLoop go routine is closing...")
return
}
}
}
func (tsm *trieStorageManager) cleanupChans() {
<-tsm.closer.ChanClose()
//at this point we can not add new entries in the snapshot/checkpoint chans
for {
select {
case entry := <-tsm.snapshotReq:
tsm.finishOperation(entry, "trie snapshot finished on cleanup")
case entry := <-tsm.checkpointReq:
tsm.finishOperation(entry, "trie checkpoint finished on cleanup")
default:
log.Debug("finished trieStorageManager.cleanupChans")
return
}
}
}
func getOrderedSnapshots(snapshotsMap map[int]common.SnapshotDbHandler) []common.SnapshotDbHandler {
snapshots := make([]common.SnapshotDbHandler, 0)
keys := make([]int, 0)
for key := range snapshotsMap {
keys = append(keys, key)
}
sort.Ints(keys)
for _, key := range keys {
snapshots = append(snapshots, snapshotsMap[key])
}
return snapshots
}
func getSnapshotsAndSnapshotId(snapshotDbCfg config.DBConfig) ([]common.SnapshotDbHandler, int, error) {
snapshotsMap := make(map[int]common.SnapshotDbHandler)
snapshotId := 0
if !directoryExists(snapshotDbCfg.FilePath) {
return getOrderedSnapshots(snapshotsMap), snapshotId, nil
}
files, err := ioutil.ReadDir(snapshotDbCfg.FilePath)
if err != nil {
log.Debug("there is no snapshot in path", "path", snapshotDbCfg.FilePath)
return getOrderedSnapshots(snapshotsMap), snapshotId, err
}
for _, f := range files {
if !f.IsDir() {
continue
}
var snapshotName int
snapshotName, err = strconv.Atoi(f.Name())
if err != nil {
return getOrderedSnapshots(snapshotsMap), snapshotId, err
}
var db storage.Persister
arg := storageUnit.ArgDB{
DBType: storageUnit.DBType(snapshotDbCfg.Type),
Path: path.Join(snapshotDbCfg.FilePath, f.Name()),
BatchDelaySeconds: snapshotDbCfg.BatchDelaySeconds,
MaxBatchSize: snapshotDbCfg.MaxBatchSize,
MaxOpenFiles: snapshotDbCfg.MaxOpenFiles,
}
db, err = storageUnit.NewDB(arg)
if err != nil {
return getOrderedSnapshots(snapshotsMap), snapshotId, err
}
if snapshotName > snapshotId {
snapshotId = snapshotName
}
newSnapshot := &snapshotDb{
DBWriteCacher: db,
}
log.Debug("restored snapshot", "snapshot ID", snapshotName)
snapshotsMap[snapshotName] = newSnapshot
}
if len(snapshotsMap) != 0 {
snapshotId++
}
return getOrderedSnapshots(snapshotsMap), snapshotId, nil
}
// Database returns the main database
func (tsm *trieStorageManager) Database() common.DBWriteCacher {
return tsm.db
}
// EnterPruningBufferingMode increases the counter that tracks how many operations
// that block the pruning process are in progress
func (tsm *trieStorageManager) EnterPruningBufferingMode() {
tsm.storageOperationMutex.Lock()
defer tsm.storageOperationMutex.Unlock()
tsm.pruningBlockingOps++
log.Trace("enter pruning buffering state", "operations in progress that block pruning", tsm.pruningBlockingOps)
}
// ExitPruningBufferingMode decreases the counter that tracks how many operations
// that block the pruning process are in progress
func (tsm *trieStorageManager) ExitPruningBufferingMode() {
tsm.storageOperationMutex.Lock()
defer tsm.storageOperationMutex.Unlock()
if tsm.pruningBlockingOps < 1 {
log.Error("ExitPruningBufferingMode called too many times")
return
}
tsm.pruningBlockingOps--
log.Trace("exit pruning buffering state", "operations in progress that block pruning", tsm.pruningBlockingOps)
}
// GetSnapshotThatContainsHash returns the snapshot that contains the given hash
func (tsm *trieStorageManager) GetSnapshotThatContainsHash(rootHash []byte) common.SnapshotDbHandler {
tsm.storageOperationMutex.Lock()
defer tsm.storageOperationMutex.Unlock()
for i := len(tsm.snapshots) - 1; i >= 0; i-- {
_, err := tsm.snapshots[i].Get(rootHash)
hashPresent := err == nil
if hashPresent {
log.Trace("hash present in snapshot trie db", "hash", rootHash)
tsm.snapshots[i].IncreaseNumReferences()
return tsm.snapshots[i]
}
}
return nil
}
// TakeSnapshot creates a new snapshot, or if there is another snapshot or checkpoint in progress,
// it adds this snapshot in the queue.
func (tsm *trieStorageManager) TakeSnapshot(rootHash []byte, newDb bool, leavesChan chan core.KeyValueHolder) {
if tsm.isClosed() {
tsm.safelyCloseChan(leavesChan)
return
}
if bytes.Equal(rootHash, EmptyTrieHash) {
log.Trace("should not snapshot an empty trie")
tsm.safelyCloseChan(leavesChan)
return
}
tsm.EnterPruningBufferingMode()
tsm.checkpointHashesHolder.RemoveCommitted(rootHash)
snapshotEntry := &snapshotsQueueEntry{
rootHash: rootHash,
newDb: newDb,
leavesChan: leavesChan,
}
select {
case tsm.snapshotReq <- snapshotEntry:
case <-tsm.closer.ChanClose():
tsm.ExitPruningBufferingMode()
tsm.safelyCloseChan(leavesChan)
}
}
// SetCheckpoint creates a new checkpoint, or if there is another snapshot or checkpoint in progress,
// it adds this checkpoint in the queue. The checkpoint operation creates a new snapshot file
// only if there was no snapshot done prior to this
func (tsm *trieStorageManager) SetCheckpoint(rootHash []byte, leavesChan chan core.KeyValueHolder) {
if tsm.isClosed() {
tsm.safelyCloseChan(leavesChan)
return
}
if bytes.Equal(rootHash, EmptyTrieHash) {
log.Trace("should not set checkpoint for empty trie")
tsm.safelyCloseChan(leavesChan)
return
}
tsm.EnterPruningBufferingMode()
checkpointEntry := &snapshotsQueueEntry{
rootHash: rootHash,
newDb: false,
leavesChan: leavesChan,
}
select {
case tsm.checkpointReq <- checkpointEntry:
case <-tsm.closer.ChanClose():
tsm.ExitPruningBufferingMode()
tsm.safelyCloseChan(leavesChan)
}
}
func (tsm *trieStorageManager) safelyCloseChan(ch chan core.KeyValueHolder) {
if ch != nil {
close(ch)
}
}
func (tsm *trieStorageManager) finishOperation(snapshotEntry *snapshotsQueueEntry, message string) {
tsm.ExitPruningBufferingMode()
log.Trace(message, "rootHash", snapshotEntry.rootHash)
tsm.safelyCloseChan(snapshotEntry.leavesChan)
}
func (tsm *trieStorageManager) takeSnapshot(snapshotEntry *snapshotsQueueEntry, msh marshal.Marshalizer, hsh hashing.Hasher, ctx context.Context) {
defer tsm.finishOperation(snapshotEntry, "trie snapshot finished")
// use the main DB as that DB will certainly have all the trie nodes
// using a checkpoint DB is not safe because the process might contain an incomplete DB because the
// checkpointing/snapshotting operations can be stopped at shuffle out.
db := tsm.db
log.Trace("trie checkpoint started", "rootHash", snapshotEntry.rootHash)
newRoot, err := newSnapshotNode(db, msh, hsh, snapshotEntry.rootHash)
if err != nil {
log.Error("takeSnapshot: trie storage manager: newSnapshotTrie", "hash", snapshotEntry.rootHash, "error", err.Error())
return
}
newDb := tsm.getSnapshotDb(snapshotEntry.newDb)
if check.IfNil(newDb) {
return
}
err = newRoot.commitSnapshot(db, newDb, snapshotEntry.leavesChan, ctx)
if err == ErrContextClosing {
log.Debug("context closing while in commitSnapshot operation")
return
}
if err != nil {
log.Error("trie storage manager: commit", "error", err.Error())
}
}
func (tsm *trieStorageManager) takeCheckpoint(checkpointEntry *snapshotsQueueEntry, msh marshal.Marshalizer, hsh hashing.Hasher, ctx context.Context) {
defer tsm.finishOperation(checkpointEntry, "trie checkpoint finished")
if tsm.isPresentInLastSnapshotDb(checkpointEntry.rootHash) {
log.Trace("checkpoint for rootHash already taken, skipping", "rootHash", checkpointEntry.rootHash)
return
}
log.Trace("trie checkpoint started", "rootHash", checkpointEntry.rootHash)
newRoot, err := newSnapshotNode(tsm.db, msh, hsh, checkpointEntry.rootHash)
if err != nil {
log.Error("takeCheckpoint: trie storage manager: newSnapshotTrie", "hash", checkpointEntry.rootHash, "error", err.Error())
return
}
db := tsm.getSnapshotDb(checkpointEntry.newDb)
if check.IfNil(db) {
return
}
err = newRoot.commitCheckpoint(tsm.db, db, tsm.checkpointHashesHolder, checkpointEntry.leavesChan, ctx)
if err == ErrContextClosing {
log.Debug("context closing while in commitCheckpoint operation")
return
}
if err != nil {
log.Error("trie storage manager: commit", "error", err.Error())
}
}
func (tsm *trieStorageManager) isPresentInLastSnapshotDb(rootHash []byte) bool {
tsm.storageOperationMutex.Lock()
defer tsm.storageOperationMutex.Unlock()
lastSnapshotIndex := len(tsm.snapshots) - 1
if lastSnapshotIndex < 0 {
return false
}
val, err := tsm.snapshots[lastSnapshotIndex].Get(rootHash)
if err != nil || val == nil {
return false
}
return true
}
func (tsm *trieStorageManager) getSnapshotDb(newDb bool) common.DBWriteCacher {
tsm.storageOperationMutex.Lock()
defer tsm.storageOperationMutex.Unlock()
createNewDb := newDb || len(tsm.snapshots) == 0
if !createNewDb {
return tsm.snapshots[len(tsm.snapshots)-1]
}
db, err := tsm.newSnapshotDb()
if err != nil {
log.Error("trie storage manager: getSnapshotDb", "error", err.Error())
return nil
}
if uint32(len(tsm.snapshots)) > tsm.maxSnapshots {
if tsm.keepSnapshots {
tsm.disconnectSnapshot()
} else {
tsm.removeSnapshot()
}
}
return db
}
func (tsm *trieStorageManager) disconnectSnapshot() {
if len(tsm.snapshots) <= 0 {
return
}
firstSnapshot := tsm.snapshots[0]
tsm.snapshots = tsm.snapshots[1:]
if firstSnapshot.IsInUse() {
firstSnapshot.MarkForDisconnection()
log.Debug("can't disconnect, snapshot is still in use")
return
}
err := disconnectSnapshot(firstSnapshot)
if err != nil {
log.Error("trie storage manager: disconnectSnapshot", "error", err.Error())
}
}
func (tsm *trieStorageManager) removeSnapshot() {
if len(tsm.snapshots) <= 0 {
return
}
dbUniqueId := strconv.Itoa(tsm.snapshotId - len(tsm.snapshots))
firstSnapshot := tsm.snapshots[0]
tsm.snapshots = tsm.snapshots[1:]
removePath := path.Join(tsm.snapshotDbCfg.FilePath, dbUniqueId)
if firstSnapshot.IsInUse() {
log.Debug("snapshot is still in use", "path", removePath)
firstSnapshot.MarkForRemoval()
firstSnapshot.SetPath(removePath)
return
}
removeSnapshot(firstSnapshot, removePath)
}
func disconnectSnapshot(db common.DBWriteCacher) error {
return db.Close()
}
func removeSnapshot(db common.DBWriteCacher, path string) {
err := disconnectSnapshot(db)
if err != nil {
log.Error("trie storage manager: disconnectSnapshot", "error", err.Error())
return
}
log.Debug("remove trie snapshot db", "snapshot path", path)
go removeDirectory(path)
}
func removeDirectory(path string) {
err := os.RemoveAll(path)
if err != nil {
log.Error(err.Error())
}
}
func newSnapshotNode(
db common.DBWriteCacher,
msh marshal.Marshalizer,
hsh hashing.Hasher,
rootHash []byte,
) (snapshotNode, error) {
newRoot, err := getNodeFromDBAndDecode(rootHash, db, msh, hsh)
if err != nil {
return nil, err
}
return newRoot, nil
}
func (tsm *trieStorageManager) newSnapshotDb() (storage.Persister, error) {
snapshotPath := path.Join(tsm.snapshotDbCfg.FilePath, strconv.Itoa(tsm.snapshotId))
for directoryExists(snapshotPath) {
tsm.snapshotId++
snapshotPath = path.Join(tsm.snapshotDbCfg.FilePath, strconv.Itoa(tsm.snapshotId))
}
log.Debug("create new trie snapshot db", "snapshot ID", tsm.snapshotId)
arg := storageUnit.ArgDB{
DBType: storageUnit.DBType(tsm.snapshotDbCfg.Type),
Path: snapshotPath,
BatchDelaySeconds: tsm.snapshotDbCfg.BatchDelaySeconds,
MaxBatchSize: tsm.snapshotDbCfg.MaxBatchSize,
MaxOpenFiles: tsm.snapshotDbCfg.MaxOpenFiles,
}
db, err := storageUnit.NewDB(arg)
if err != nil {
return nil, err
}
tsm.snapshotId++
newSnapshot := &snapshotDb{
DBWriteCacher: db,
}
tsm.snapshots = append(tsm.snapshots, newSnapshot)
return db, nil
}
func directoryExists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
// IsPruningEnabled returns true if the trie pruning is enabled
func (tsm *trieStorageManager) IsPruningEnabled() bool {
return true
}
// IsPruningBlocked returns true if there is any pruningBlockingOperation in progress
func (tsm *trieStorageManager) IsPruningBlocked() bool {
tsm.storageOperationMutex.RLock()
defer tsm.storageOperationMutex.RUnlock()
return tsm.pruningBlockingOps != 0
}
// GetSnapshotDbBatchDelay returns the batch write delay in seconds
func (tsm *trieStorageManager) GetSnapshotDbBatchDelay() int {
return tsm.snapshotDbCfg.BatchDelaySeconds
}
// AddDirtyCheckpointHashes adds the given hashes to the checkpoint hashes holder
func (tsm *trieStorageManager) AddDirtyCheckpointHashes(rootHash []byte, hashes common.ModifiedHashes) bool {
return tsm.checkpointHashesHolder.Put(rootHash, hashes)
}
// Remove removes the given hash form the storage and from the checkpoint hashes holder
func (tsm *trieStorageManager) Remove(hash []byte) error {
tsm.checkpointHashesHolder.Remove(hash)
return tsm.db.Remove(hash)
}
func (tsm *trieStorageManager) isClosed() bool {
tsm.storageOperationMutex.RLock()
defer tsm.storageOperationMutex.RUnlock()
return tsm.closed
}
// Close - closes all underlying components
func (tsm *trieStorageManager) Close() error {
tsm.storageOperationMutex.Lock()
defer tsm.storageOperationMutex.Unlock()
tsm.cancelFunc()
tsm.closed = true
//calling close on the SafeCloser instance should be the last instruction called
//(just to close some go routines started as edge cases that would otherwise hang)
defer tsm.closer.Close()
err := tsm.db.Close()
for _, sdb := range tsm.snapshots {
errSnapshotClose := sdb.Close()
if errSnapshotClose != nil {
log.Error("trieStorageManager.Close", "error", errSnapshotClose)
err = errSnapshotClose
}
}
if err != nil {
return fmt.Errorf("trieStorageManager close failed: %w", err)
}
return nil
}
// IsInterfaceNil returns true if there is no value under the interface
func (tsm *trieStorageManager) IsInterfaceNil() bool {
return tsm == nil
}