-
Notifications
You must be signed in to change notification settings - Fork 178
/
scaffold.go
778 lines (645 loc) · 24.2 KB
/
scaffold.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
package cmd
import (
"encoding/json"
"errors"
"fmt"
"math/rand"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/dgraph-io/badger/v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/rs/zerolog"
"github.com/spf13/pflag"
"github.com/onflow/flow-go/crypto"
"github.com/onflow/flow-go/model/bootstrap"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/model/flow/filter"
"github.com/onflow/flow-go/module"
"github.com/onflow/flow-go/module/local"
"github.com/onflow/flow-go/module/metrics"
"github.com/onflow/flow-go/module/trace"
jsoncodec "github.com/onflow/flow-go/network/codec/json"
"github.com/onflow/flow-go/network/gossip/libp2p"
"github.com/onflow/flow-go/network/gossip/libp2p/topology"
"github.com/onflow/flow-go/network/gossip/libp2p/validators"
protocol "github.com/onflow/flow-go/state/protocol/badger"
"github.com/onflow/flow-go/state/protocol/events"
"github.com/onflow/flow-go/storage"
storerr "github.com/onflow/flow-go/storage"
bstorage "github.com/onflow/flow-go/storage/badger"
"github.com/onflow/flow-go/storage/badger/operation"
sutil "github.com/onflow/flow-go/storage/util"
"github.com/onflow/flow-go/utils/debug"
"github.com/onflow/flow-go/utils/io"
"github.com/onflow/flow-go/utils/logging"
)
const notSet = "not set"
// BaseConfig is the general config for the FlowNodeBuilder
type BaseConfig struct {
nodeIDHex string
bindAddr string
nodeRole string
timeout time.Duration
datadir string
level string
metricsPort uint
BootstrapDir string
profilerEnabled bool
profilerDir string
profilerInterval time.Duration
profilerDuration time.Duration
}
type Metrics struct {
Network module.NetworkMetrics
Engine module.EngineMetrics
Compliance module.ComplianceMetrics
Cache module.CacheMetrics
Mempool module.MempoolMetrics
}
type Storage struct {
Headers storage.Headers
Index storage.Index
Identities storage.Identities
Guarantees storage.Guarantees
Seals storage.Seals
Payloads storage.Payloads
Blocks storage.Blocks
Transactions storage.Transactions
Collections storage.Collections
Setups storage.EpochSetups
Commits storage.EpochCommits
Statuses storage.EpochStatuses
}
type namedModuleFunc struct {
fn func(*FlowNodeBuilder) error
name string
}
type namedComponentFunc struct {
fn func(*FlowNodeBuilder) (module.ReadyDoneAware, error)
name string
}
type namedDoneObject struct {
ob module.ReadyDoneAware
name string
}
// FlowNodeBuilder is the builder struct used for all flow nodes
// It runs a node process with following structure, in sequential order
// Base inits (network, storage, state, logger)
// PostInit handlers, if any
// Components handlers, if any, wait sequentially
// Run() <- main loop
// Components destructors, if any
type FlowNodeBuilder struct {
BaseConfig BaseConfig
NodeID flow.Identifier
flags *pflag.FlagSet
Logger zerolog.Logger
Me *local.Local
Tracer *trace.OpenTracer
MetricsRegisterer prometheus.Registerer
Metrics Metrics
DB *badger.DB
Storage Storage
ProtocolEvents *events.Distributor
State *protocol.State
Middleware *libp2p.Middleware
Network *libp2p.Network
MsgValidators []validators.MessageValidator
modules []namedModuleFunc
components []namedComponentFunc
doneObject []namedDoneObject
sig chan os.Signal
postInitFns []func(*FlowNodeBuilder)
stakingKey crypto.PrivateKey
networkKey crypto.PrivateKey
// root state information
RootBlock *flow.Block
RootQC *flow.QuorumCertificate
RootResult *flow.ExecutionResult
RootSeal *flow.Seal
RootChainID flow.ChainID
}
func (fnb *FlowNodeBuilder) baseFlags() {
homedir, _ := os.UserHomeDir()
datadir := filepath.Join(homedir, ".flow", "database")
// bind configuration parameters
fnb.flags.StringVar(&fnb.BaseConfig.nodeIDHex, "nodeid", notSet, "identity of our node")
fnb.flags.StringVar(&fnb.BaseConfig.bindAddr, "bind", notSet, "address to bind on")
fnb.flags.StringVarP(&fnb.BaseConfig.BootstrapDir, "bootstrapdir", "b", "bootstrap", "path to the bootstrap directory")
fnb.flags.DurationVarP(&fnb.BaseConfig.timeout, "timeout", "t", 1*time.Minute, "how long to try connecting to the network")
fnb.flags.StringVarP(&fnb.BaseConfig.datadir, "datadir", "d", datadir, "directory to store the protocol state")
fnb.flags.StringVarP(&fnb.BaseConfig.level, "loglevel", "l", "info", "level for logging output")
fnb.flags.UintVarP(&fnb.BaseConfig.metricsPort, "metricport", "m", 8080, "port for /metrics endpoint")
fnb.flags.BoolVar(&fnb.BaseConfig.profilerEnabled, "profiler-enabled", false, "whether to enable the auto-profiler")
fnb.flags.StringVar(&fnb.BaseConfig.profilerDir, "profiler-dir", "profiler", "directory to create auto-profiler profiles")
fnb.flags.DurationVar(&fnb.BaseConfig.profilerInterval, "profiler-interval", 15*time.Minute,
"the interval between auto-profiler runs")
fnb.flags.DurationVar(&fnb.BaseConfig.profilerDuration, "profiler-duration", 10*time.Second,
"the duration to run the auto-profile for")
}
func (fnb *FlowNodeBuilder) enqueueNetworkInit() {
fnb.Component("network", func(builder *FlowNodeBuilder) (module.ReadyDoneAware, error) {
codec := jsoncodec.NewCodec()
myAddr := fnb.Me.Address()
if fnb.BaseConfig.bindAddr != notSet {
myAddr = fnb.BaseConfig.bindAddr
}
mw, err := libp2p.NewMiddleware(fnb.Logger.Level(zerolog.ErrorLevel), codec, myAddr, fnb.Me.NodeID(),
fnb.networkKey, fnb.Metrics.Network, libp2p.DefaultMaxUnicastMsgSize, libp2p.DefaultMaxPubSubMsgSize,
fnb.RootBlock.ID().String(),
fnb.MsgValidators...)
if err != nil {
return nil, fmt.Errorf("could not initialize middleware: %w", err)
}
fnb.Middleware = mw
participants, err := fnb.State.Final().Identities(filter.Any)
if err != nil {
return nil, fmt.Errorf("could not get network identities: %w", err)
}
nodeID, err := fnb.State.Final().Identity(fnb.Me.NodeID())
if err != nil {
return nil, fmt.Errorf("could not get node id: %w", err)
}
nodeRole := nodeID.Role
var nodeTopology topology.Topology
if nodeRole == flow.RoleCollection {
nodeTopology, err = topology.NewCollectionTopology(nodeID.NodeID, fnb.State)
} else {
nodeTopology, err = topology.NewRandPermTopology(nodeRole, nodeID.NodeID)
}
if err != nil {
return nil, fmt.Errorf("could not create topology: %w", err)
}
net, err := libp2p.NewNetwork(fnb.Logger, codec, participants, fnb.Me, fnb.Middleware, 10e6, nodeTopology, fnb.Metrics.Network)
if err != nil {
return nil, fmt.Errorf("could not initialize network: %w", err)
}
fnb.Network = net
return net, err
})
}
func (fnb *FlowNodeBuilder) enqueueMetricsServerInit() {
fnb.Component("metrics server", func(builder *FlowNodeBuilder) (module.ReadyDoneAware, error) {
server := metrics.NewServer(fnb.Logger, fnb.BaseConfig.metricsPort, fnb.BaseConfig.profilerEnabled)
return server, nil
})
}
func (fnb *FlowNodeBuilder) registerBadgerMetrics() {
metrics.RegisterBadgerMetrics()
}
func (fnb *FlowNodeBuilder) enqueueTracer() {
fnb.Component("tracer", func(builder *FlowNodeBuilder) (module.ReadyDoneAware, error) {
return fnb.Tracer, nil
})
}
func (fnb *FlowNodeBuilder) parseAndPrintFlags() {
// parse configuration parameters
pflag.Parse()
// print all flags
log := fnb.Logger.Info()
pflag.VisitAll(func(flag *pflag.Flag) {
log = log.Str(flag.Name, flag.Value.String())
})
log.Msg("flags loaded")
}
func (fnb *FlowNodeBuilder) initNodeInfo() {
if fnb.BaseConfig.nodeIDHex == notSet {
fnb.Logger.Fatal().Msg("cannot start without node ID")
}
nodeID, err := flow.HexStringToIdentifier(fnb.BaseConfig.nodeIDHex)
if err != nil {
fnb.Logger.Fatal().Err(err).Msgf("could not parse node ID from string: %v", fnb.BaseConfig.nodeIDHex)
}
info, err := loadPrivateNodeInfo(fnb.BaseConfig.BootstrapDir, nodeID)
if err != nil {
fnb.Logger.Fatal().Err(err).Msg("failed to load private node info")
}
fnb.NodeID = nodeID
fnb.stakingKey = info.StakingPrivKey.PrivateKey
fnb.networkKey = info.NetworkPrivKey.PrivateKey
}
func (fnb *FlowNodeBuilder) initLogger() {
// configure logger with standard level, node ID and UTC timestamp
zerolog.TimestampFunc = func() time.Time { return time.Now().UTC() }
log := fnb.Logger.With().
Timestamp().
Str("node_role", fnb.BaseConfig.nodeRole).
Str("node_id", fnb.BaseConfig.nodeIDHex).
Logger()
log.Info().Msgf("flow %s node starting up", fnb.BaseConfig.nodeRole)
// parse config log level and apply to logger
lvl, err := zerolog.ParseLevel(strings.ToLower(fnb.BaseConfig.level))
if err != nil {
log.Fatal().Err(err).Msg("invalid log level")
}
log = log.Level(lvl)
fnb.Logger = log
}
func (fnb *FlowNodeBuilder) initMetrics() {
tracer, err := trace.NewTracer(fnb.Logger, fnb.BaseConfig.nodeRole)
fnb.MustNot(err).Msg("could not initialize tracer")
fnb.MetricsRegisterer = prometheus.DefaultRegisterer
fnb.Tracer = tracer
mempools := metrics.NewMempoolCollector(5 * time.Second)
fnb.Metrics = Metrics{
Network: metrics.NewNetworkCollector(),
Engine: metrics.NewEngineCollector(),
Compliance: metrics.NewComplianceCollector(),
Cache: metrics.NewCacheCollector(fnb.RootChainID),
Mempool: mempools,
}
// registers mempools as a Component so that its Ready method is invoked upon startup
fnb.Component("mempools metrics", func(builder *FlowNodeBuilder) (module.ReadyDoneAware, error) {
return mempools, nil
})
}
func (fnb *FlowNodeBuilder) initProfiler() {
if !fnb.BaseConfig.profilerEnabled {
return
}
profiler, err := debug.NewAutoProfiler(
fnb.Logger,
fnb.BaseConfig.profilerDir,
fnb.BaseConfig.profilerInterval,
fnb.BaseConfig.profilerDuration,
)
fnb.MustNot(err).Msg("could not initialize profiler")
fnb.Component("profiler", func(node *FlowNodeBuilder) (module.ReadyDoneAware, error) {
return profiler, nil
})
}
func (fnb *FlowNodeBuilder) initDB() {
// Pre-create DB path (Badger creates only one-level dirs)
err := os.MkdirAll(fnb.BaseConfig.datadir, 0700)
fnb.MustNot(err).Str("dir", fnb.BaseConfig.datadir).Msg("could not create datadir")
log := sutil.NewLogger(fnb.Logger)
// we initialize the database with options that allow us to keep the maximum
// item size in the trie itself (up to 1MB) and where we keep all level zero
// tables in-memory as well; this slows down compaction and increases memory
// usage, but it improves overall performance and disk i/o
opts := badger.
DefaultOptions(fnb.BaseConfig.datadir).
WithKeepL0InMemory(true).
WithLogger(log).
// the ValueLogFileSize option specifies how big the value of a
// key-value pair is allowed to be saved into badger.
// exceeding this limit, will fail with an error like this:
// could not store data: Value with size <xxxx> exceeded 1073741824 limit
// Maximum value size is 10G, needed by execution node
// TODO: finding a better max value for each node type
WithValueLogFileSize(128 << 23).
WithValueLogMaxEntries(100000) // Default is 1000000
db, err := badger.Open(opts)
fnb.MustNot(err).Msg("could not open key-value store")
fnb.DB = db
}
func (fnb *FlowNodeBuilder) initStorage() {
// in order to void long iterations with big keys when initializing with an
// already populated database, we bootstrap the initial maximum key size
// upon starting
err := operation.RetryOnConflict(fnb.DB.Update, func(tx *badger.Txn) error {
return operation.InitMax(tx)
})
fnb.MustNot(err).Msg("could not initialize max tracker")
headers := bstorage.NewHeaders(fnb.Metrics.Cache, fnb.DB)
guarantees := bstorage.NewGuarantees(fnb.Metrics.Cache, fnb.DB)
seals := bstorage.NewSeals(fnb.Metrics.Cache, fnb.DB)
index := bstorage.NewIndex(fnb.Metrics.Cache, fnb.DB)
payloads := bstorage.NewPayloads(fnb.DB, index, guarantees, seals)
blocks := bstorage.NewBlocks(fnb.DB, headers, payloads)
transactions := bstorage.NewTransactions(fnb.Metrics.Cache, fnb.DB)
collections := bstorage.NewCollections(fnb.DB, transactions)
setups := bstorage.NewEpochSetups(fnb.Metrics.Cache, fnb.DB)
commits := bstorage.NewEpochCommits(fnb.Metrics.Cache, fnb.DB)
statuses := bstorage.NewEpochStatuses(fnb.Metrics.Cache, fnb.DB)
fnb.Storage = Storage{
Headers: headers,
Guarantees: guarantees,
Seals: seals,
Index: index,
Payloads: payloads,
Blocks: blocks,
Transactions: transactions,
Collections: collections,
Setups: setups,
Commits: commits,
Statuses: statuses,
}
}
func (fnb *FlowNodeBuilder) initState() {
distributor := events.NewDistributor()
state, err := protocol.NewState(
fnb.Metrics.Compliance,
fnb.DB,
fnb.Storage.Headers,
fnb.Storage.Seals,
fnb.Storage.Index,
fnb.Storage.Payloads,
fnb.Storage.Blocks,
fnb.Storage.Setups,
fnb.Storage.Commits,
fnb.Storage.Statuses,
distributor,
)
fnb.MustNot(err).Msg("could not initialize flow state")
// check if database is initialized
_, err = state.Final().Head()
if errors.Is(err, storerr.ErrNotFound) {
// Bootstrap!
fnb.Logger.Info().Msg("bootstrapping empty protocol state")
// load the root block from bootstrap files and set the chain ID based on it
fnb.RootBlock, err = loadRootBlock(fnb.BaseConfig.BootstrapDir)
fnb.MustNot(err).Msg("could not load root block")
// set the root chain ID based on the root block
fnb.RootChainID = fnb.RootBlock.Header.ChainID
// load the root QC data from bootstrap files
fnb.RootQC, err = loadRootQC(fnb.BaseConfig.BootstrapDir)
fnb.MustNot(err).Msg("could not load root QC")
// load the root execution result from bootstrap files
fnb.RootResult, err = loadRootResult(fnb.BaseConfig.BootstrapDir)
fnb.MustNot(err).Msg("could not load root execution result")
// load the root block seal from bootstrap files
fnb.RootSeal, err = loadRootSeal(fnb.BaseConfig.BootstrapDir)
fnb.MustNot(err).Msg("could not load root seal")
// bootstrap the protocol state with the loaded data
err = state.Mutate().Bootstrap(fnb.RootBlock, fnb.RootResult, fnb.RootSeal)
fnb.MustNot(err).Msg("could not bootstrap protocol state")
fnb.Logger.Info().
Hex("root_result_id", logging.Entity(fnb.RootResult)).
Hex("root_state_commitment", fnb.RootSeal.FinalState).
Hex("root_block_id", logging.Entity(fnb.RootBlock)).
Uint64("root_block_height", fnb.RootBlock.Header.Height).
Msg("genesis state bootstrapped")
} else if err != nil {
fnb.Logger.Fatal().Err(err).Msg("could not check existing database")
} else {
// TODO: we shouldn't have to load any files again after bootstrapping; in
// order to make it unnecessary, we need to changes:
// 1) persist the root QC along the root block so it can be loaded from DB
// => https://github.com/dapperlabs/flow-go/issues/4166
// 2) bootstrap and persist DKG state in a similar fashion to protocol state
// => https://github.com/dapperlabs/flow-go/issues/4165
// load the root block from bootstrap files and set the chain ID based on it
fnb.RootBlock, err = loadRootBlock(fnb.BaseConfig.BootstrapDir)
fnb.MustNot(err).Msg("could not load root block")
// set the chain ID based on the root header
// TODO: as the root header can now be loaded from protocol state, we should
// not use a global variable for chain ID anymore, but rely on the protocol
// state as final authority on what the chain ID is
// => https://github.com/dapperlabs/flow-go/issues/4167
fnb.RootChainID = fnb.RootBlock.Header.ChainID
// load the root QC data from bootstrap files
fnb.RootQC, err = loadRootQC(fnb.BaseConfig.BootstrapDir)
fnb.MustNot(err).Msg("could not load root QC")
// load the root execution result from bootstrap files
fnb.RootResult, err = loadRootResult(fnb.BaseConfig.BootstrapDir)
fnb.MustNot(err).Msg("could not load root execution result")
// load the root block seal from bootstrap files
fnb.RootSeal, err = loadRootSeal(fnb.BaseConfig.BootstrapDir)
fnb.MustNot(err).Msg("could not load root seal")
}
myID, err := flow.HexStringToIdentifier(fnb.BaseConfig.nodeIDHex)
fnb.MustNot(err).Msg("could not parse node identifier")
rootBlockHeader, err := state.Params().Root()
fnb.MustNot(err).Msg("could not get root block from protocol state")
// this happens when the bootstrap root block is updated (because of new spork),
// but the protocol state is not updated, so they don't match
// when this happens during a spork, we could try deleting the protocol state database.
// TODO: revisit this check when implementing Epoch
if rootBlockHeader.ID() != fnb.RootBlock.ID() {
fnb.Logger.Fatal().Msgf("mismatching root block ID, protocol state block ID: %v, bootstrap root block ID: %v",
rootBlockHeader.ID(),
fnb.RootBlock.ID())
}
self, err := state.Final().Identity(myID)
// there are two cases that will cause the following error:
// 1) used the wrong node id, which is not part of the identity list of the finalized state
// 2) the node id is a new one for a new spork, but the bootstrap data has not been updated.
fnb.MustNot(err).Msgf("node identity not found in the identity list of the finalized state: %v", myID)
if self.Role.String() != fnb.BaseConfig.nodeRole {
if rootBlockHeader.ChainID == flow.Mainnet {
fnb.Logger.Fatal().Msgf("running as incorrect role, expected: %v, actual: %v, exiting",
self.Role.String(),
fnb.BaseConfig.nodeRole)
} else {
// This allows ghost node to run as any role when not on mainnet
fnb.Logger.Warn().Msgf("running as incorrect role, expected: %v, actual: %v, continuing",
self.Role.String(),
fnb.BaseConfig.nodeRole)
}
}
// ensure that the configured staking/network keys are consistent with the protocol state
if !self.NetworkPubKey.Equals(fnb.networkKey.PublicKey()) {
fnb.Logger.Fatal().Msg("configured networking key does not match protocol state")
}
if !self.StakingPubKey.Equals(fnb.stakingKey.PublicKey()) {
fnb.Logger.Fatal().Msg("configured staking key does not match protocol state")
}
fnb.Me, err = local.New(self, fnb.stakingKey)
fnb.MustNot(err).Msg("could not initialize local")
lastFinalized, err := state.Final().Head()
fnb.MustNot(err).Msg("could not get last finalized state")
fnb.Logger.Info().
Hex("block_id", logging.Entity(lastFinalized)).
Uint64("height", lastFinalized.Height).
Msg("last finalized block")
fnb.State = state
fnb.ProtocolEvents = distributor
}
func (fnb *FlowNodeBuilder) handleModule(v namedModuleFunc) {
err := v.fn(fnb)
if err != nil {
fnb.Logger.Fatal().Err(err).Str("module", v.name).Msg("module initialization failed")
} else {
fnb.Logger.Info().Str("module", v.name).Msg("module initialization complete")
}
}
func (fnb *FlowNodeBuilder) handleComponent(v namedComponentFunc) {
log := fnb.Logger.With().Str("component", v.name).Logger()
readyAware, err := v.fn(fnb)
if err != nil {
log.Fatal().Err(err).Msg("component initialization failed")
} else {
log.Info().Msg("component initialization complete")
}
select {
case <-readyAware.Ready():
log.Info().Msg("component startup complete")
case <-time.After(fnb.BaseConfig.timeout):
log.Fatal().Msg("component startup timed out")
case <-fnb.sig:
log.Warn().Msg("component startup aborted")
os.Exit(1)
}
fnb.doneObject = append(fnb.doneObject, namedDoneObject{
readyAware, v.name,
})
}
func (fnb *FlowNodeBuilder) handleDoneObject(v namedDoneObject) {
log := fnb.Logger.With().Str("component", v.name).Logger()
select {
case <-v.ob.Done():
log.Info().Msg("component shutdown complete")
case <-time.After(fnb.BaseConfig.timeout):
log.Fatal().Msg("component shutdown timed out")
case <-fnb.sig:
log.Warn().Msg("component shutdown aborted")
os.Exit(1)
}
}
// ExtraFlags enables binding additional flags beyond those defined in BaseConfig.
func (fnb *FlowNodeBuilder) ExtraFlags(f func(*pflag.FlagSet)) *FlowNodeBuilder {
f(fnb.flags)
return fnb
}
// Module enables setting up dependencies of the engine with the builder context.
func (fnb *FlowNodeBuilder) Module(name string, f func(builder *FlowNodeBuilder) error) *FlowNodeBuilder {
fnb.modules = append(fnb.modules, namedModuleFunc{
fn: f,
name: name,
})
return fnb
}
// MustNot asserts that the given error must not occur.
//
// If the error is nil, returns a nil log event (which acts as a no-op).
// If the error is not nil, returns a fatal log event containing the error.
func (fnb *FlowNodeBuilder) MustNot(err error) *zerolog.Event {
if err != nil {
return fnb.Logger.Fatal().Err(err)
}
return nil
}
// Component adds a new component to the node that conforms to the ReadyDone
// interface.
//
// When the node is run, this component will be started with `Ready`. When the
// node is stopped, we will wait for the component to exit gracefully with
// `Done`.
func (fnb *FlowNodeBuilder) Component(name string, f func(*FlowNodeBuilder) (module.ReadyDoneAware, error)) *FlowNodeBuilder {
fnb.components = append(fnb.components, namedComponentFunc{
fn: f,
name: name,
})
return fnb
}
func (fnb *FlowNodeBuilder) PostInit(f func(node *FlowNodeBuilder)) *FlowNodeBuilder {
fnb.postInitFns = append(fnb.postInitFns, f)
return fnb
}
// FlowNode creates a new Flow node builder with the given name.
func FlowNode(role string) *FlowNodeBuilder {
builder := &FlowNodeBuilder{
BaseConfig: BaseConfig{
nodeRole: role,
},
Logger: zerolog.New(os.Stderr),
flags: pflag.CommandLine,
}
builder.baseFlags()
builder.enqueueNetworkInit()
builder.enqueueMetricsServerInit()
builder.registerBadgerMetrics()
builder.enqueueTracer()
return builder
}
// Run initiates all common components (logger, database, protocol state etc.)
// then starts each component. It also sets up a channel to gracefully shut
// down each component if a SIGINT is received.
func (fnb *FlowNodeBuilder) Run() {
// initialize signal catcher
fnb.sig = make(chan os.Signal, 1)
signal.Notify(fnb.sig, os.Interrupt, syscall.SIGTERM)
fnb.parseAndPrintFlags()
// seed random generator
rand.Seed(time.Now().UnixNano())
fnb.initNodeInfo()
fnb.initLogger()
fnb.initProfiler()
fnb.initDB()
fnb.initMetrics()
fnb.initStorage()
fnb.initState()
for _, f := range fnb.postInitFns {
fnb.handlePostInit(f)
}
// set up all modules
for _, f := range fnb.modules {
fnb.handleModule(f)
}
// initialize all components
for _, f := range fnb.components {
fnb.handleComponent(f)
}
fnb.Logger.Info().Msgf("%s node startup complete", fnb.BaseConfig.nodeRole)
<-fnb.sig
fnb.Logger.Info().Msgf("%s node shutting down", fnb.BaseConfig.nodeRole)
for i := len(fnb.doneObject) - 1; i >= 0; i-- {
doneObject := fnb.doneObject[i]
fnb.handleDoneObject(doneObject)
}
fnb.closeDatabase()
fnb.Logger.Info().Msgf("%s node shutdown complete", fnb.BaseConfig.nodeRole)
os.Exit(0)
}
func (fnb *FlowNodeBuilder) handlePostInit(f func(node *FlowNodeBuilder)) {
f(fnb)
}
func (fnb *FlowNodeBuilder) closeDatabase() {
err := fnb.DB.Close()
if err != nil {
fnb.Logger.Error().
Err(err).
Msg("could not close database")
}
}
func loadRootBlock(dir string) (*flow.Block, error) {
data, err := io.ReadFile(filepath.Join(dir, bootstrap.PathRootBlock))
if err != nil {
return nil, err
}
var block flow.Block
err = json.Unmarshal(data, &block)
return &block, err
}
func loadRootQC(dir string) (*flow.QuorumCertificate, error) {
data, err := io.ReadFile(filepath.Join(dir, bootstrap.PathRootQC))
if err != nil {
return nil, err
}
var qc flow.QuorumCertificate
err = json.Unmarshal(data, &qc)
return &qc, err
}
func loadRootResult(dir string) (*flow.ExecutionResult, error) {
data, err := io.ReadFile(filepath.Join(dir, bootstrap.PathRootResult))
if err != nil {
return nil, err
}
var result flow.ExecutionResult
err = json.Unmarshal(data, &result)
return &result, err
}
func loadRootSeal(dir string) (*flow.Seal, error) {
data, err := io.ReadFile(filepath.Join(dir, bootstrap.PathRootSeal))
if err != nil {
return nil, err
}
var seal flow.Seal
err = json.Unmarshal(data, &seal)
return &seal, err
}
// Loads the private info for this node from disk (eg. private staking/network keys).
func loadPrivateNodeInfo(dir string, myID flow.Identifier) (*bootstrap.NodeInfoPriv, error) {
data, err := io.ReadFile(filepath.Join(dir, fmt.Sprintf(bootstrap.PathNodeInfoPriv, myID)))
if err != nil {
return nil, err
}
var info bootstrap.NodeInfoPriv
err = json.Unmarshal(data, &info)
return &info, err
}