-
Notifications
You must be signed in to change notification settings - Fork 492
/
Copy pathcatchpointtracker.go
1706 lines (1490 loc) · 62.2 KB
/
catchpointtracker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2019-2025 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package ledger
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"database/sql"
"encoding/base32"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"sync/atomic"
"time"
"github.com/algorand/go-deadlock"
"github.com/golang/snappy"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/crypto/merkletrie"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/bookkeeping"
"github.com/algorand/go-algorand/ledger/ledgercore"
"github.com/algorand/go-algorand/ledger/store/trackerdb"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/logging/telemetryspec"
"github.com/algorand/go-algorand/protocol"
)
const (
// trieRebuildAccountChunkSize defines the number of accounts that would get read at a single chunk
// before added to the trie during trie construction
trieRebuildAccountChunkSize = 16384
// trieRebuildCommitFrequency defines the number of accounts that would get added before we call evict to commit the changes and adjust the memory cache.
trieRebuildCommitFrequency = 65536
// CatchpointFileVersionV5 is the catchpoint file version that was used when the database schema was V0-V5.
CatchpointFileVersionV5 = uint64(0200)
// CatchpointFileVersionV6 is the catchpoint file version that is matching database schema since V6.
// This version introduced accounts and resources separation. The first catchpoint
// round of this version is >= `reenableCatchpointsRound`.
CatchpointFileVersionV6 = uint64(0201)
// CatchpointFileVersionV7 is the catchpoint file version that is matching database schema V10.
// This version introduced state proof verification data and versioning for CatchpointLabel.
CatchpointFileVersionV7 = uint64(0202)
// CatchpointFileVersionV8 is the catchpoint file version that includes V6 and V7 data, as well
// as historical onlineaccounts and onlineroundparamstail table data (added in DB version V7,
// but until this version initialized with current round data, not 320 rounds of historical info).
CatchpointFileVersionV8 = uint64(0203)
// CatchpointContentFileName is a name of a file with catchpoint header info inside tar archive
CatchpointContentFileName = "content.msgpack"
// catchpointSPVerificationFileName is a name of a file with stateproof verification data
catchpointSPVerificationFileName = "stateProofVerificationContext.msgpack"
// catchpointBalancesFileNameTemplate is a template name of files with balances data
catchpointBalancesFileNameTemplate = "balances.%d.msgpack"
catchpointBalancesFileNamePrefix = "balances."
catchpointBalancesFileNameSuffix = ".msgpack"
)
func catchpointStage1Encoder(w io.Writer) (io.WriteCloser, error) {
return snappy.NewBufferedWriter(w), nil
}
type snappyReadCloser struct {
*snappy.Reader
}
func (snappyReadCloser) Close() error { return nil }
func catchpointStage1Decoder(r io.Reader) (io.ReadCloser, error) {
return snappyReadCloser{snappy.NewReader(r)}, nil
}
type catchpointTracker struct {
// tmpDir is the path to the currently building catchpoint file
tmpDir string
// dbDirectory is the path to the finished/cold data of catchpoint
dbDirectory string
// catchpointInterval is the configured interval at which the catchpointTracker would generate catchpoint labels and catchpoint files.
catchpointInterval uint64
// catchpointFileHistoryLength defines how many catchpoint files we want to store back.
// 0 means don't store any, -1 mean unlimited and positive number suggest the number of most recent catchpoint files.
catchpointFileHistoryLength int
// enableGeneratingCatchpointFiles determines whether catchpoints files should be generated by the trackers.
enableGeneratingCatchpointFiles bool
// log copied from ledger
log logging.Logger
// Connection to the database.
dbs trackerdb.Store
catchpointStore trackerdb.CatchpointReaderWriter
// The last catchpoint label that was written to the database. Should always align with what's in the database.
// note that this is the last catchpoint *label* and not the catchpoint file.
lastCatchpointLabel string
// catchpointDataSlowWriting suggests to the accounts writer that it should finish
// writing up the (first stage) catchpoint data file ASAP. When this channel is
// closed, the accounts writer would try and complete the writing as soon as possible.
// Otherwise, it would take its time and perform periodic sleeps between chunks
// processing.
catchpointDataSlowWriting chan struct{}
// catchpointDataWriting helps to synchronize the (first stage) catchpoint data file
// writing. When this atomic variable is 0, no writing is going on.
// Any non-zero value indicates a catchpoint being written, or scheduled to be written.
catchpointDataWriting atomic.Int32
// The Trie tracking the current account balances. Always matches the balances that were
// written to the database.
balancesTrie *merkletrie.Trie
// roundDigest stores the digest of the block for every round starting with dbRound+1 and every round after it.
roundDigest []crypto.Digest
// consensusVersion stores the consensus versions for every round starting with dbRound+1 and every round after it.
consensusVersion []protocol.ConsensusVersion
// reenableCatchpointsRound is a round where the EnableCatchpointsWithSPContexts feature was enabled via the consensus.
// we avoid generating catchpoints before that round in order to ensure the network remain consistent in the catchpoint
// label being produced. This variable could be "wrong" in two cases -
// 1. It's zero, meaning that the EnableCatchpointsWithSPContexts has yet to be seen.
// 2. It's non-zero meaning that it the given round is after the EnableCatchpointsWithSPContexts was enabled ( it might be exact round
// but that's only if newBlock was called with that round ), plus the lookback.
reenableCatchpointsRound basics.Round
// forceCatchpointFileWriting used for debugging purpose by bypassing the test against
// reenableCatchpointsRound in isCatchpointRound(), so that we could generate
// catchpoint files even before the protocol upgrade took place.
forceCatchpointFileWriting bool
// catchpointsMu protects roundDigest, reenableCatchpointsRound, cachedDBRound,
// lastCatchpointLabel and balancesTrie.
catchpointsMu deadlock.RWMutex
// cachedDBRound is always exactly tracker DB round (and therefore, accountsRound()),
// cached to use in lookup functions
cachedDBRound basics.Round
}
// initialize initializes the catchpointTracker structure
func (ct *catchpointTracker) initialize(cfg config.Local, paths DirsAndPrefix) {
// catchpoint uses the cold data directories, except for the temp file
ct.dbDirectory = paths.CatchpointGenesisDir
// the temp file uses the hot data directories
ct.tmpDir = paths.HotGenesisDir
if cfg.TracksCatchpoints() {
ct.catchpointInterval = cfg.CatchpointInterval
}
ct.enableGeneratingCatchpointFiles = cfg.StoresCatchpoints()
// Overwrite previous options if forceCatchpointFileGenerationTrackingMode
if cfg.CatchpointTracking == forceCatchpointFileGenerationTrackingMode && cfg.CatchpointInterval > 0 {
ct.catchpointInterval = cfg.CatchpointInterval
ct.forceCatchpointFileWriting = true
ct.enableGeneratingCatchpointFiles = true
}
ct.catchpointFileHistoryLength = cfg.CatchpointFileHistoryLength
if cfg.CatchpointFileHistoryLength < -1 {
ct.catchpointFileHistoryLength = -1
}
}
// GetLastCatchpointLabel retrieves the last catchpoint label that was stored to the database.
func (ct *catchpointTracker) GetLastCatchpointLabel() string {
ct.catchpointsMu.RLock()
defer ct.catchpointsMu.RUnlock()
return ct.lastCatchpointLabel
}
func (ct *catchpointTracker) getSPVerificationData() (encodedData []byte, spVerificationHash crypto.Digest, err error) {
err = ct.dbs.Snapshot(func(ctx context.Context, tx trackerdb.SnapshotScope) error {
rawData, dbErr := tx.MakeSpVerificationCtxReader().GetAllSPContexts(ctx)
if dbErr != nil {
return dbErr
}
wrappedData := catchpointStateProofVerificationContext{Data: rawData}
spVerificationHash, encodedData = crypto.EncodeAndHash(wrappedData)
return nil
})
if err != nil {
return nil, crypto.Digest{}, err
}
return encodedData, spVerificationHash, nil
}
func (ct *catchpointTracker) finishFirstStage(ctx context.Context, dbRound basics.Round, onlineAccountsForgetBefore basics.Round, blockProto protocol.ConsensusVersion, updatingBalancesDuration time.Duration) error {
ct.log.Infof("finishing catchpoint's first stage dbRound: %d", dbRound)
var totalAccounts, totalKVs, totalOnlineAccounts, totalOnlineRoundParams uint64
var totalChunks uint64
var biggestChunkLen uint64
var spVerificationHash crypto.Digest
var spVerificationEncodedData []byte
var catchpointGenerationStats telemetryspec.CatchpointGenerationEventDetails
var onlineAccountsHash, onlineRoundParamsHash crypto.Digest
params := config.Consensus[blockProto]
// Usually onlineAccountsForgetBefore is dbRound - params.MaxBalLookback (320 rounds of history),
// but if votersTracker needs more state, it can set lowestRound to be earlier than that.
// We want to only write MaxBalLookback rounds of history to the catchpoint file.
var onlineExcludeBefore basics.Round
if normalOnlineHorizon := catchpointLookbackHorizonForNextRound(dbRound, params); normalOnlineHorizon == onlineAccountsForgetBefore {
// this is the common case, so we pass 0 so the DB dumps the full table, as is
onlineExcludeBefore = 0
} else if normalOnlineHorizon > onlineAccountsForgetBefore {
// the previous flush left more online-related rows than we want in the DB. we need to tell
// the catchpoint writer to exclude the rows that are older than the ones we want to keep.
onlineExcludeBefore = normalOnlineHorizon
} else {
// The previous flush left less online-related rows than we want in the DB. This should not happen; return error
ct.log.Errorf("catchpointTracker.finishFirstStage: dbRound %d and onlineAccountsForgetBefore %d has less history than MaxBalLookback %d",
dbRound, onlineAccountsForgetBefore, params.MaxBalLookback)
return errors.New("catchpointTracker.finishFirstStage: onlineAccountsForgetBefore doesn't provide enough history")
}
if params.EnableCatchpointsWithSPContexts {
// Generate the SP Verification hash and encoded data. The hash is used in the label when tracking catchpoints,
// and the encoded data for that hash will be added to the catchpoint file if catchpoint generation is enabled.
var err error
spVerificationEncodedData, spVerificationHash, err = ct.getSPVerificationData()
if err != nil {
return err
}
}
if params.EnableCatchpointsWithOnlineAccounts {
// Generate hashes of the onlineaccounts and onlineroundparams tables.
err := ct.dbs.Snapshot(func(ctx context.Context, tx trackerdb.SnapshotScope) error {
var dbErr error
onlineAccountsHash, _, dbErr = calculateVerificationHash(ctx, makeCatchpointOrderedOnlineAccountsIterFactory(tx.MakeOrderedOnlineAccountsIter, dbRound, params), onlineExcludeBefore, false)
if dbErr != nil {
return dbErr
}
onlineRoundParamsHash, _, dbErr = calculateVerificationHash(ctx, tx.MakeOnlineRoundParamsIter, onlineExcludeBefore, false)
if dbErr != nil {
return dbErr
}
return nil
})
if err != nil {
return err
}
}
if ct.enableGeneratingCatchpointFiles {
// Generate the catchpoint file. This is done inline so that it will
// block any new accounts from being written. generateCatchpointData()
// expects that the accounts data would not be modified in the
// background during its execution.
var err error
catchpointGenerationStats.BalancesWriteTime = uint64(updatingBalancesDuration.Nanoseconds())
totalAccounts, totalKVs, totalOnlineAccounts, totalOnlineRoundParams, totalChunks, biggestChunkLen, err = ct.generateCatchpointData(
ctx, params, dbRound, onlineExcludeBefore, &catchpointGenerationStats, spVerificationEncodedData)
ct.catchpointDataWriting.Store(0)
if err != nil {
return err
}
}
return ct.dbs.Transaction(func(ctx context.Context, tx trackerdb.TransactionScope) error {
cw, err := tx.MakeCatchpointWriter()
if err != nil {
return err
}
err = ct.recordFirstStageInfo(ctx, tx, &catchpointGenerationStats, dbRound,
totalAccounts, totalKVs, totalOnlineAccounts, totalOnlineRoundParams, totalChunks, biggestChunkLen,
spVerificationHash, onlineAccountsHash, onlineRoundParamsHash)
if err != nil {
return err
}
// Clear the db record.
return cw.WriteCatchpointStateUint64(ctx, trackerdb.CatchpointStateWritingFirstStageInfo, 0)
})
}
// Possibly finish generating first stage catchpoint db record and data file after
// a crash.
func (ct *catchpointTracker) finishFirstStageAfterCrash(dbRound basics.Round, blockProto protocol.ConsensusVersion) error {
v, err := ct.catchpointStore.ReadCatchpointStateUint64(
context.Background(), trackerdb.CatchpointStateWritingFirstStageInfo)
if err != nil {
return err
}
if v == 0 {
return nil
}
// First, delete the unfinished data file.
relCatchpointDataFilePath := filepath.Join(trackerdb.CatchpointDirName, makeCatchpointDataFilePath(dbRound))
err = trackerdb.RemoveSingleCatchpointFileFromDisk(ct.tmpDir, relCatchpointDataFilePath)
if err != nil {
return err
}
// pass dbRound+1-maxBalLookback as the onlineAccountsForgetBefore parameter: since we can't be sure whether
// there are more than 320 rounds of history in the online accounts tables, this ensures the catchpoint
// will only contain the most recent 320 rounds.
onlineAccountsForgetBefore := catchpointLookbackHorizonForNextRound(dbRound, config.Consensus[blockProto])
return ct.finishFirstStage(context.Background(), dbRound, onlineAccountsForgetBefore, blockProto, 0)
}
func (ct *catchpointTracker) finishCatchpointsAfterCrash(blockProto protocol.ConsensusVersion, catchpointLookback uint64) error {
records, err := ct.catchpointStore.SelectUnfinishedCatchpoints(context.Background())
if err != nil {
return err
}
for _, record := range records {
// First, delete the unfinished catchpoint file.
relCatchpointFilePath := filepath.Join(trackerdb.CatchpointDirName, trackerdb.MakeCatchpointFilePath(basics.Round(record.Round)))
err = trackerdb.RemoveSingleCatchpointFileFromDisk(ct.dbDirectory, relCatchpointFilePath)
if err != nil {
return err
}
err = ct.finishCatchpoint(
context.Background(), record.Round, record.BlockHash, blockProto, catchpointLookback)
if err != nil {
return err
}
}
return nil
}
func (ct *catchpointTracker) recoverFromCrash(dbRound basics.Round, blockProto protocol.ConsensusVersion) error {
err := ct.finishFirstStageAfterCrash(dbRound, blockProto)
if err != nil {
return err
}
ctx := context.Background()
catchpointLookback, err := ct.catchpointStore.ReadCatchpointStateUint64(
ctx, trackerdb.CatchpointStateCatchpointLookback)
if err != nil {
return err
}
if catchpointLookback != 0 {
err = ct.finishCatchpointsAfterCrash(blockProto, catchpointLookback)
if err != nil {
return err
}
if uint64(dbRound) >= catchpointLookback {
err := ct.pruneFirstStageRecordsData(ctx, dbRound-basics.Round(catchpointLookback))
if err != nil {
return err
}
}
}
return nil
}
// loadFromDisk loads the state of a tracker from persistent
// storage. The ledger argument allows loadFromDisk to load
// blocks from the database, or access its own state. The
// ledgerForTracker interface abstracts away the details of
// ledger internals so that individual trackers can be tested
// in isolation.
func (ct *catchpointTracker) loadFromDisk(l ledgerForTracker, dbRound basics.Round) (err error) {
ct.log = l.trackerLog()
ct.dbs = l.trackerDB()
ct.catchpointStore, err = l.trackerDB().MakeCatchpointReaderWriter()
if err != nil {
return err
}
ct.catchpointsMu.Lock()
ct.cachedDBRound = dbRound
ct.roundDigest = nil
ct.consensusVersion = nil
ct.catchpointDataWriting.Store(0)
// keep these channel closed if we're not generating catchpoint
ct.catchpointDataSlowWriting = make(chan struct{}, 1)
close(ct.catchpointDataSlowWriting)
ct.catchpointsMu.Unlock()
err = ct.dbs.Transaction(func(ctx context.Context, tx trackerdb.TransactionScope) error {
return ct.initializeHashes(ctx, tx, dbRound)
})
if err != nil {
return err
}
ct.lastCatchpointLabel, err = ct.catchpointStore.ReadCatchpointStateString(
context.Background(), trackerdb.CatchpointStateLastCatchpoint)
if err != nil {
return
}
hdr, err := l.BlockHdr(dbRound)
if err != nil {
return
}
return ct.recoverFromCrash(dbRound, hdr.CurrentProtocol)
}
// newBlock informs the tracker of a new block from round
// rnd and a given ledgercore.StateDelta as produced by BlockEvaluator.
func (ct *catchpointTracker) newBlock(blk bookkeeping.Block, delta ledgercore.StateDelta) {
ct.catchpointsMu.Lock()
defer ct.catchpointsMu.Unlock()
ct.roundDigest = append(ct.roundDigest, blk.Digest())
ct.consensusVersion = append(ct.consensusVersion, blk.CurrentProtocol)
if (config.Consensus[blk.CurrentProtocol].EnableCatchpointsWithSPContexts || ct.forceCatchpointFileWriting) && ct.reenableCatchpointsRound == 0 {
catchpointLookback := config.Consensus[blk.CurrentProtocol].CatchpointLookback
if catchpointLookback == 0 {
catchpointLookback = config.Consensus[blk.CurrentProtocol].MaxBalLookback
}
ct.reenableCatchpointsRound = blk.BlockHeader.Round + basics.Round(catchpointLookback)
}
}
// committedUpTo implements the ledgerTracker interface for catchpointTracker.
// The method informs the tracker that committedRound and all it's previous rounds have
// been committed to the block database. The method returns what is the oldest round
// number that can be removed from the blocks database as well as the lookback that this
// tracker maintains.
func (ct *catchpointTracker) committedUpTo(rnd basics.Round) (retRound, lookback basics.Round) {
ct.catchpointsMu.RLock()
defer ct.catchpointsMu.RUnlock()
retRound = ct.cachedDBRound
return retRound, basics.Round(0)
}
// Calculate whether we have intermediate first stage catchpoint rounds and the
// new offset.
func calculateFirstStageRounds(oldBase basics.Round, offset uint64, reenableCatchpointsRound basics.Round, catchpointInterval uint64, catchpointLookback uint64) (hasIntermediateFirstStageRound bool, hasMultipleIntermediateFirstStageRounds bool, newOffset uint64) {
newOffset = offset
if reenableCatchpointsRound == 0 {
return
}
minFirstStageRound := oldBase + 1
if (reenableCatchpointsRound > basics.Round(catchpointLookback)) &&
(reenableCatchpointsRound-basics.Round(catchpointLookback) >
minFirstStageRound) {
minFirstStageRound =
reenableCatchpointsRound - basics.Round(catchpointLookback)
}
// The smallest integer r >= minFirstStageRound such that
// (r + catchpointLookback) % ct.catchpointInterval == 0.
first := (int64(minFirstStageRound)+int64(catchpointLookback)+
int64(catchpointInterval)-1)/
int64(catchpointInterval)*int64(catchpointInterval) -
int64(catchpointLookback)
// The largest integer r <= dcr.oldBase + dcr.offset such that
// (r + catchpointLookback) % ct.catchpointInterval == 0.
last := (int64(oldBase)+int64(offset)+int64(catchpointLookback))/
int64(catchpointInterval)*int64(catchpointInterval) - int64(catchpointLookback)
if first <= last {
hasIntermediateFirstStageRound = true
// We skip earlier catchpoints if there is more than one to generate.
newOffset = uint64(last) - uint64(oldBase)
if first < last {
hasMultipleIntermediateFirstStageRounds = true
}
}
return
}
func (ct *catchpointTracker) produceCommittingTask(committedRound basics.Round, dbRound basics.Round, dcr *deferredCommitRange) *deferredCommitRange {
if ct.catchpointInterval == 0 {
return dcr
}
ct.catchpointsMu.Lock()
reenableCatchpointsRound := ct.reenableCatchpointsRound
ct.catchpointsMu.Unlock()
// Check if we need to do the first stage of catchpoint generation.
var hasIntermediateFirstStageRound bool
var hasMultipleIntermediateFirstStageRounds bool
hasIntermediateFirstStageRound, hasMultipleIntermediateFirstStageRounds, dcr.offset =
calculateFirstStageRounds(
dcr.oldBase, dcr.offset, reenableCatchpointsRound,
ct.catchpointInterval, dcr.catchpointLookback)
// if we're still writing the previous balances, we can't move forward yet.
if ct.isWritingCatchpointDataFile() {
// if we hit this path, it means that we're still writing a catchpoint.
// see if the new delta range contains another catchpoint.
if hasIntermediateFirstStageRound {
// check if we're already attempting to perform fast-writing.
select {
case <-ct.catchpointDataSlowWriting:
// yes, we're already doing fast-writing.
default:
// no, we're not yet doing fast writing, make it so.
close(ct.catchpointDataSlowWriting)
}
}
return nil
}
if hasIntermediateFirstStageRound {
dcr.catchpointFirstStage = true
if ct.enableGeneratingCatchpointFiles {
ct.catchpointDataSlowWriting = make(chan struct{}, 1)
if hasMultipleIntermediateFirstStageRounds {
close(ct.catchpointDataSlowWriting)
}
}
}
dcr.enableGeneratingCatchpointFiles = ct.enableGeneratingCatchpointFiles
rounds := ct.calculateCatchpointRounds(dcr)
dcr.catchpointSecondStage = (len(rounds) > 0)
return dcr
}
// prepareCommit, commitRound and postCommit are called when it is time to commit tracker's data.
// If an error returned the process is aborted.
func (ct *catchpointTracker) prepareCommit(dcc *deferredCommitContext) error {
ct.catchpointsMu.RLock()
defer ct.catchpointsMu.RUnlock()
if ct.enableGeneratingCatchpointFiles && dcc.catchpointFirstStage {
// store non-zero ( all ones ) into the catchpointWriting atomic variable to indicate that a catchpoint is being written
ct.catchpointDataWriting.Store(int32(-1))
}
dcc.committedRoundDigests = make([]crypto.Digest, dcc.offset)
copy(dcc.committedRoundDigests, ct.roundDigest[:dcc.offset])
dcc.committedProtocolVersion = make([]protocol.ConsensusVersion, dcc.offset)
copy(dcc.committedProtocolVersion, ct.consensusVersion[:dcc.offset])
return nil
}
func (ct *catchpointTracker) commitRound(ctx context.Context, tx trackerdb.TransactionScope, dcc *deferredCommitContext) (err error) {
treeTargetRound := basics.Round(0)
offset := dcc.offset
dbRound := dcc.oldBase
defer func() {
if err != nil && dcc.catchpointFirstStage && ct.enableGeneratingCatchpointFiles {
ct.catchpointDataWriting.Store(0)
}
}()
cw, err := tx.MakeCatchpointWriter()
if err != nil {
return err
}
aw, err := tx.MakeAccountsWriter()
if err != nil {
return err
}
if ct.catchpointEnabled() {
var mc trackerdb.MerkleCommitter
mc, err = tx.MakeMerkleCommitter(false)
if err != nil {
return
}
var trie *merkletrie.Trie
ct.catchpointsMu.Lock()
if ct.balancesTrie == nil {
trie, err = merkletrie.MakeTrie(mc, trackerdb.TrieMemoryConfig)
if err != nil {
ct.log.Warnf("unable to create merkle trie during committedUpTo: %v", err)
ct.catchpointsMu.Unlock()
return err
}
ct.balancesTrie = trie
} else {
ct.balancesTrie.SetCommitter(mc)
}
ct.catchpointsMu.Unlock()
treeTargetRound = dbRound + basics.Round(offset)
}
if dcc.updateStats {
dcc.stats.MerkleTrieUpdateDuration = time.Duration(time.Now().UnixNano())
}
err = ct.accountsUpdateBalances(dcc.compactAccountDeltas, dcc.compactResourcesDeltas, dcc.compactKvDeltas, dcc.oldBase, dcc.newBase())
if err != nil {
return err
}
if dcc.updateStats {
now := time.Duration(time.Now().UnixNano())
dcc.stats.MerkleTrieUpdateDuration = now - dcc.stats.MerkleTrieUpdateDuration
}
err = aw.UpdateAccountsHashRound(ctx, treeTargetRound)
if err != nil {
return err
}
if dcc.catchpointFirstStage {
err = cw.WriteCatchpointStateUint64(ctx, trackerdb.CatchpointStateWritingFirstStageInfo, 1)
if err != nil {
return err
}
}
err = cw.WriteCatchpointStateUint64(ctx, trackerdb.CatchpointStateCatchpointLookback, dcc.catchpointLookback)
if err != nil {
return err
}
for _, round := range ct.calculateCatchpointRounds(&dcc.deferredCommitRange) {
err = cw.InsertUnfinishedCatchpoint(ctx, round, dcc.committedRoundDigests[round-dcc.oldBase-1])
if err != nil {
return err
}
}
return nil
}
func (ct *catchpointTracker) postCommit(ctx context.Context, dcc *deferredCommitContext) {
ct.catchpointsMu.Lock()
if ct.balancesTrie != nil {
_, err := ct.balancesTrie.Evict(false)
if err != nil {
ct.log.Warnf("merkle trie failed to evict: %v", err)
}
}
ct.roundDigest = ct.roundDigest[dcc.offset:]
ct.consensusVersion = ct.consensusVersion[dcc.offset:]
ct.cachedDBRound = dcc.newBase()
ct.catchpointsMu.Unlock()
dcc.updatingBalancesDuration = time.Since(dcc.flushTime)
if dcc.updateStats {
dcc.stats.MemoryUpdatesDuration = time.Duration(time.Now().UnixNano())
}
}
func doRepackCatchpoint(ctx context.Context, header CatchpointFileHeader, biggestChunkLen uint64, in *tar.Reader, out *tar.Writer) error {
bytes := protocol.Encode(&header)
err := out.WriteHeader(&tar.Header{
Name: CatchpointContentFileName,
Mode: 0600,
Size: int64(len(bytes)),
})
if err != nil {
return err
}
_, err = out.Write(bytes)
if err != nil {
return err
}
// make buffer for re-use that can fit biggest chunk
buf := make([]byte, biggestChunkLen)
for {
err := ctx.Err()
if err != nil {
return err
}
header, err := in.Next()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
n, err := io.ReadAtLeast(in, buf, int(header.Size))
if (err != nil) && (err != io.EOF) {
return err
}
if int64(n) != header.Size { // should not happen
return fmt.Errorf("read too many bytes from chunk %+v", header)
}
err = out.WriteHeader(header)
if err != nil {
return err
}
_, err = out.Write(buf[:header.Size])
if err != nil {
return err
}
}
}
// repackCatchpoint takes the header (that must be made "late" in order to have
// the latest blockhash) and the (snappy compressed) catchpoint data from
// dataPath and regurgitates it to look like catchpoints have always looked - a
// tar file with the header in the first "file" and the catchpoint data in file
// chunks, all compressed with gzip instead of snappy.
func repackCatchpoint(ctx context.Context, header CatchpointFileHeader, biggestChunkLen uint64, dataPath string, outPath string) error {
// Initialize streams.
fin, err := os.OpenFile(dataPath, os.O_RDONLY, 0666)
if err != nil {
return err
}
defer fin.Close()
compressorIn, err := catchpointStage1Decoder(fin)
if err != nil {
return err
}
defer compressorIn.Close()
tarIn := tar.NewReader(compressorIn)
fout, err := os.OpenFile(outPath, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return err
}
defer fout.Close()
gzipOut, err := gzip.NewWriterLevel(fout, gzip.BestSpeed)
if err != nil {
return err
}
defer gzipOut.Close()
tarOut := tar.NewWriter(gzipOut)
defer tarOut.Close()
// Repack.
err = doRepackCatchpoint(ctx, header, biggestChunkLen, tarIn, tarOut)
if err != nil {
return err
}
// Close streams.
err = tarOut.Close()
if err != nil {
return err
}
err = gzipOut.Close()
if err != nil {
return err
}
err = fout.Close()
if err != nil {
return err
}
err = compressorIn.Close()
if err != nil {
return err
}
err = fin.Close()
if err != nil {
return err
}
return nil
}
// Create a catchpoint (a label and possibly a file with db record) and remove
// the unfinished catchpoint record.
func (ct *catchpointTracker) createCatchpoint(ctx context.Context, accountsRound basics.Round, round basics.Round, dataInfo trackerdb.CatchpointFirstStageInfo, blockHash crypto.Digest, blockProto protocol.ConsensusVersion) error {
startTime := time.Now()
var labelMaker ledgercore.CatchpointLabelMaker
var version uint64
params := config.Consensus[blockProto]
if params.EnableCatchpointsWithOnlineAccounts {
if !params.EnableCatchpointsWithSPContexts {
return fmt.Errorf("invalid params for catchpoint file version v8: SP contexts not enabled")
}
labelMaker = ledgercore.MakeCatchpointLabelMakerCurrent(round, &blockHash, &dataInfo.TrieBalancesHash, dataInfo.Totals, &dataInfo.StateProofVerificationHash, &dataInfo.OnlineAccountsHash, &dataInfo.OnlineRoundParamsHash)
version = CatchpointFileVersionV8
} else if params.EnableCatchpointsWithSPContexts {
labelMaker = ledgercore.MakeCatchpointLabelMakerV7(round, &blockHash, &dataInfo.TrieBalancesHash, dataInfo.Totals, &dataInfo.StateProofVerificationHash)
version = CatchpointFileVersionV7
} else {
labelMaker = ledgercore.MakeCatchpointLabelMakerV6(round, &blockHash, &dataInfo.TrieBalancesHash, dataInfo.Totals)
version = CatchpointFileVersionV6
}
label := ledgercore.MakeLabel(labelMaker)
ct.log.Infof(
"creating catchpoint round: %d accountsRound: %d label: %s",
round, accountsRound, label)
err := ct.catchpointStore.WriteCatchpointStateString(
ctx, trackerdb.CatchpointStateLastCatchpoint, label)
if err != nil {
return err
}
ct.catchpointsMu.Lock()
ct.lastCatchpointLabel = label
ct.catchpointsMu.Unlock()
if !ct.enableGeneratingCatchpointFiles {
return nil
}
catchpointDataFilePath := filepath.Join(ct.tmpDir, trackerdb.CatchpointDirName)
catchpointDataFilePath =
filepath.Join(catchpointDataFilePath, makeCatchpointDataFilePath(accountsRound))
// Check if the data file exists.
_, err = os.Stat(catchpointDataFilePath)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
// Make a catchpoint file.
header := CatchpointFileHeader{
Version: version,
BalancesRound: accountsRound,
BlocksRound: round,
Totals: dataInfo.Totals,
TotalAccounts: dataInfo.TotalAccounts,
TotalKVs: dataInfo.TotalKVs,
TotalOnlineAccounts: dataInfo.TotalOnlineAccounts,
TotalOnlineRoundParams: dataInfo.TotalOnlineRoundParams,
TotalChunks: dataInfo.TotalChunks,
Catchpoint: label,
BlockHeaderDigest: blockHash,
}
relCatchpointFilePath := filepath.Join(trackerdb.CatchpointDirName, trackerdb.MakeCatchpointFilePath(round))
absCatchpointFilePath := filepath.Join(ct.dbDirectory, relCatchpointFilePath)
err = os.MkdirAll(filepath.Dir(absCatchpointFilePath), 0700)
if err != nil {
return err
}
err = repackCatchpoint(ctx, header, dataInfo.BiggestChunkLen, catchpointDataFilePath, absCatchpointFilePath)
if err != nil {
return err
}
fileInfo, err := os.Stat(absCatchpointFilePath)
if err != nil {
return err
}
err = ct.dbs.Transaction(func(ctx context.Context, tx trackerdb.TransactionScope) (err error) {
crw, err := tx.MakeCatchpointReaderWriter()
if err != nil {
return err
}
err = ct.recordCatchpointFile(ctx, crw, round, relCatchpointFilePath, fileInfo.Size())
if err != nil {
return err
}
return crw.DeleteUnfinishedCatchpoint(ctx, round)
})
if err != nil {
return err
}
ct.log.With("accountsRound", accountsRound).
With("writingDuration", uint64(time.Since(startTime).Nanoseconds())).
With("accountsCount", dataInfo.TotalAccounts).
With("kvsCount", dataInfo.TotalKVs).
With("onlineAccountsCount", dataInfo.TotalOnlineAccounts).
With("onlineRoundParamsCount", dataInfo.TotalOnlineRoundParams).
With("fileSize", fileInfo.Size()).
With("filepath", relCatchpointFilePath).
With("catchpointLabel", label).
Infof("Catchpoint file was created")
return nil
}
// Try create a catchpoint (a label and possibly a file with db record) and remove
// the unfinished catchpoint record.
func (ct *catchpointTracker) finishCatchpoint(ctx context.Context, round basics.Round, blockHash crypto.Digest, blockProto protocol.ConsensusVersion, catchpointLookback uint64) error {
accountsRound := round - basics.Round(catchpointLookback)
ct.log.Infof("finishing catchpoint round: %d accountsRound: %d", round, accountsRound)
dataInfo, exists, err := ct.catchpointStore.SelectCatchpointFirstStageInfo(ctx, accountsRound)
if err != nil {
return err
}
if !exists {
return ct.catchpointStore.DeleteUnfinishedCatchpoint(ctx, round)
}
return ct.createCatchpoint(ctx, accountsRound, round, dataInfo, blockHash, blockProto)
}
// Calculate catchpoint round numbers in [min, max]. `catchpointInterval` must be
// non-zero.
func calculateCatchpointRounds(min basics.Round, max basics.Round, catchpointInterval uint64) []basics.Round {
// The smallest integer i such that i * ct.catchpointInterval >= min.
l := (uint64(min) + catchpointInterval - 1) / catchpointInterval
// The largest integer i such that i * ct.catchpointInterval <= max.
r := uint64(max) / catchpointInterval
// handle situations when max - min < catchpointInterval,
// for example min=11, max=19, catchpointInterval = 10
if l > r {
return nil
}
res := make([]basics.Round, 0, r-l+1)
for i := l; i <= r; i++ {
round := basics.Round(i * catchpointInterval)
res = append(res, round)
}
return res
}
func (ct *catchpointTracker) calculateCatchpointRounds(dcc *deferredCommitRange) []basics.Round {
if ct.catchpointInterval == 0 {
return nil
}
min := dcc.oldBase + 1
if dcc.catchpointLookback+1 > uint64(min) {
min = basics.Round(dcc.catchpointLookback) + 1
}
max := dcc.oldBase + basics.Round(dcc.offset)
return calculateCatchpointRounds(min, max, ct.catchpointInterval)
}
// Delete old first stage catchpoint records and data files.
func (ct *catchpointTracker) pruneFirstStageRecordsData(ctx context.Context, maxRoundToDelete basics.Round) error {
rounds, err := ct.catchpointStore.SelectOldCatchpointFirstStageInfoRounds(ctx, maxRoundToDelete)
if err != nil {
return err
}
for _, round := range rounds {
relCatchpointDataFilePath :=
filepath.Join(trackerdb.CatchpointDirName, makeCatchpointDataFilePath(round))
err = trackerdb.RemoveSingleCatchpointFileFromDisk(ct.tmpDir, relCatchpointDataFilePath)
if err != nil {
return err
}
}
return ct.catchpointStore.DeleteOldCatchpointFirstStageInfo(ctx, maxRoundToDelete)
}
func (ct *catchpointTracker) postCommitUnlocked(ctx context.Context, dcc *deferredCommitContext) {
if dcc.catchpointFirstStage {
round := dcc.newBase()