-
Notifications
You must be signed in to change notification settings - Fork 107
/
node.go
1289 lines (1115 loc) · 38.1 KB
/
node.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 committee
import (
"container/heap"
"context"
"errors"
"fmt"
"math"
"sync"
"time"
"github.com/eapache/channels"
"github.com/prometheus/client_golang/prometheus"
"github.com/oasisprotocol/oasis-core/go/common/accessctl"
"github.com/oasisprotocol/oasis-core/go/common/crypto/hash"
"github.com/oasisprotocol/oasis-core/go/common/grpc/policy"
"github.com/oasisprotocol/oasis-core/go/common/logging"
"github.com/oasisprotocol/oasis-core/go/common/node"
"github.com/oasisprotocol/oasis-core/go/common/persistent"
"github.com/oasisprotocol/oasis-core/go/common/workerpool"
consensus "github.com/oasisprotocol/oasis-core/go/consensus/api"
commonFlags "github.com/oasisprotocol/oasis-core/go/oasis-node/cmd/common/flags"
registryApi "github.com/oasisprotocol/oasis-core/go/registry/api"
roothashApi "github.com/oasisprotocol/oasis-core/go/roothash/api"
"github.com/oasisprotocol/oasis-core/go/roothash/api/block"
"github.com/oasisprotocol/oasis-core/go/runtime/nodes"
"github.com/oasisprotocol/oasis-core/go/runtime/nodes/grpc"
scheduler "github.com/oasisprotocol/oasis-core/go/scheduler/api"
storageApi "github.com/oasisprotocol/oasis-core/go/storage/api"
"github.com/oasisprotocol/oasis-core/go/storage/client"
"github.com/oasisprotocol/oasis-core/go/storage/mkvs/checkpoint"
mkvsDB "github.com/oasisprotocol/oasis-core/go/storage/mkvs/db/api"
workerCommon "github.com/oasisprotocol/oasis-core/go/worker/common"
"github.com/oasisprotocol/oasis-core/go/worker/common/committee"
"github.com/oasisprotocol/oasis-core/go/worker/common/p2p"
"github.com/oasisprotocol/oasis-core/go/worker/registration"
"github.com/oasisprotocol/oasis-core/go/worker/storage/api"
)
var (
_ committee.NodeHooks = (*Node)(nil)
// ErrNonLocalBackend is the error returned when the storage backend doesn't implement the LocalBackend interface.
ErrNonLocalBackend = errors.New("storage: storage backend doesn't support local storage")
storageWorkerLastFullRound = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "oasis_worker_storage_full_round",
Help: "The last round that was fully synced and finalized.",
},
[]string{"runtime"},
)
storageWorkerLastSyncedRound = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "oasis_worker_storage_synced_round",
Help: "The last round that was synced but not yet finalized.",
},
[]string{"runtime"},
)
storageWorkerLastPendingRound = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "oasis_worker_storage_pending_round",
Help: "The last round that is in-flight for syncing.",
},
[]string{"runtime"},
)
storageWorkerCollectors = []prometheus.Collector{
storageWorkerLastFullRound,
storageWorkerLastSyncedRound,
storageWorkerLastPendingRound,
}
prometheusOnce sync.Once
)
const (
// RoundLatest is a magic value for the latest round.
RoundLatest = math.MaxUint64
defaultUndefinedRound = ^uint64(0)
checkpointSyncRetryDelay = 10 * time.Second
// The maximum number of rounds the worker can be behind the chain before it's sensible for
// it to register as available.
maximumRoundDelayForAvailability = uint64(10)
// The minimum number of rounds the worker can be behind the chain before it's sensible for
// it to stop advertising availability.
minimumRoundDelayForUnavailability = uint64(15)
// The number of rounds ahead of consensus that the worker will allow round waiters to wait.
// Trying to wait for rounds further in the future will return an error immediately.
roundWaitConsensusOffset = uint64(1)
)
type roundItem interface {
GetRound() uint64
}
// outOfOrderRoundQueue is a Round()-based min priority queue.
type outOfOrderRoundQueue []roundItem
// Sorting interface.
func (q outOfOrderRoundQueue) Len() int { return len(q) }
func (q outOfOrderRoundQueue) Less(i, j int) bool { return q[i].GetRound() < q[j].GetRound() }
func (q outOfOrderRoundQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
// Push appends x as the last element in the heap's array.
func (q *outOfOrderRoundQueue) Push(x interface{}) {
*q = append(*q, x.(roundItem))
}
// Pop removes and returns the last element in the heap's array.
func (q *outOfOrderRoundQueue) Pop() interface{} {
old := *q
n := len(old)
x := old[n-1]
*q = old[0 : n-1]
return x
}
// fetchedDiff has all the context needed for a single GetDiff operation.
type fetchedDiff struct {
fetched bool
srcNode *node.Node
err error
round uint64
prevRoot storageApi.Root
thisRoot storageApi.Root
writeLog storageApi.WriteLog
}
func (d *fetchedDiff) GetRound() uint64 {
return d.round
}
type finalizeResult struct {
summary *blockSummary
err error
}
// watcherState is the (persistent) watcher state.
type watcherState struct {
LastBlock blockSummary `json:"last_block"`
}
type roundWaiter struct {
round uint64
ch chan uint64
}
// Node watches blocks for storage changes.
type Node struct { // nolint: maligned
commonNode *committee.Node
roleProvider registration.RoleProvider
rpcRoleProvider registration.RoleProvider
roleAvailable bool
logger *logging.Logger
localStorage storageApi.LocalBackend
storageNodes nodes.NodeDescriptorLookup
storageNodesGrpc grpc.NodesClient
storageClient storageApi.ClientBackend
grpcPolicy *policy.DynamicRuntimePolicyChecker
undefinedRound uint64
fetchPool *workerpool.Pool
stateStore *persistent.ServiceStore
workerCommonCfg workerCommon.Config
checkpointer checkpoint.Checkpointer
checkpointSyncDisabled bool
checkpointSyncForced bool
syncedLock sync.RWMutex
syncedState watcherState
roundWaiters []roundWaiter
blockCh *channels.InfiniteChannel
diffCh chan *fetchedDiff
finalizeCh chan finalizeResult
ctx context.Context
ctxCancel context.CancelFunc
quitCh chan struct{}
rtWatcherQuitCh chan struct{}
workerQuitCh chan struct{}
initCh chan struct{}
}
func NewNode(
commonNode *committee.Node,
grpcPolicy *policy.DynamicRuntimePolicyChecker,
fetchPool *workerpool.Pool,
store *persistent.ServiceStore,
roleProvider registration.RoleProvider,
rpcRoleProvider registration.RoleProvider,
workerCommonCfg workerCommon.Config,
localStorage storageApi.LocalBackend,
checkpointerCfg *checkpoint.CheckpointerConfig,
checkpointSyncDisabled bool,
) (*Node, error) {
n := &Node{
commonNode: commonNode,
roleProvider: roleProvider,
rpcRoleProvider: rpcRoleProvider,
logger: logging.GetLogger("worker/storage/committee").With("runtime_id", commonNode.Runtime.ID()),
workerCommonCfg: workerCommonCfg,
localStorage: localStorage,
grpcPolicy: grpcPolicy,
fetchPool: fetchPool,
stateStore: store,
checkpointSyncDisabled: checkpointSyncDisabled,
blockCh: channels.NewInfiniteChannel(),
diffCh: make(chan *fetchedDiff),
finalizeCh: make(chan finalizeResult),
quitCh: make(chan struct{}),
rtWatcherQuitCh: make(chan struct{}),
workerQuitCh: make(chan struct{}),
initCh: make(chan struct{}),
}
n.syncedState.LastBlock.Round = defaultUndefinedRound
rtID := commonNode.Runtime.ID()
err := store.GetCBOR(rtID[:], &n.syncedState)
if err != nil && err != persistent.ErrNotFound {
return nil, fmt.Errorf("storage worker: failed to restore sync state: %w", err)
}
n.ctx, n.ctxCancel = context.WithCancel(context.Background())
n.ctx = storageApi.WithNodeBlacklist(n.ctx)
// Create a new storage client that will be used for remote sync.
// This storage client connects to all registered storage nodes for the runtime.
nl, err := nodes.NewRuntimeNodeLookup(
n.ctx,
n.commonNode.Consensus.Registry(),
rtID,
)
if err != nil {
return nil, fmt.Errorf("group: failed to create runtime node watcher: %w", err)
}
n.storageNodes = nodes.NewFilteredNodeLookup(nl,
nodes.WithAllFilters(
// Ignore self.
nodes.IgnoreNodeFilter(n.commonNode.Identity.NodeSigner.Public()),
// Only storage nodes.
nodes.TagFilter(nodes.TagsForRoleMask(node.RoleStorageWorker)[0]),
),
)
storageNodesGrpc, err := grpc.NewNodesClient(
n.ctx,
n.storageNodes,
grpc.WithClientAuthentication(n.commonNode.Identity),
)
if err != nil {
return nil, fmt.Errorf("storage/client: failed to create nodes gRPC client: %w", err)
}
n.storageNodesGrpc = storageNodesGrpc
scl, err := client.NewForNodesClient(
n.ctx,
n.storageNodesGrpc,
n.commonNode.Runtime,
)
if err != nil {
return nil, fmt.Errorf("storage worker: failed to create client: %w", err)
}
n.storageClient = scl.(storageApi.ClientBackend)
// Create a new checkpointer if enabled.
if checkpointerCfg != nil {
checkpointerCfg = &checkpoint.CheckpointerConfig{
Name: "runtime",
Namespace: commonNode.Runtime.ID(),
CheckInterval: checkpointerCfg.CheckInterval,
RootsPerVersion: 2, // State root and I/O root.
GetParameters: func(ctx context.Context) (*checkpoint.CreationParameters, error) {
rt, rerr := commonNode.Runtime.ActiveDescriptor(ctx)
if rerr != nil {
return nil, fmt.Errorf("failed to retrieve runtime descriptor: %w", rerr)
}
blk, rerr := commonNode.Consensus.RootHash().GetGenesisBlock(ctx, &roothashApi.RuntimeRequest{
RuntimeID: rt.ID,
Height: consensus.HeightLatest,
})
if rerr != nil {
return nil, fmt.Errorf("failed to retrieve genesis block: %w", rerr)
}
return &checkpoint.CreationParameters{
Interval: rt.Storage.CheckpointInterval,
NumKept: rt.Storage.CheckpointNumKept,
ChunkSize: rt.Storage.CheckpointChunkSize,
InitialVersion: blk.Header.Round,
}, nil
},
GetRoots: func(ctx context.Context, version uint64) ([]storageApi.Root, error) {
blk, berr := commonNode.Runtime.History().GetBlock(ctx, version)
if berr != nil {
return nil, berr
}
return blk.Header.StorageRoots(), nil
},
}
n.checkpointer, err = checkpoint.NewCheckpointer(
n.ctx,
localStorage.NodeDB(),
localStorage.Checkpointer(),
*checkpointerCfg,
)
if err != nil {
return nil, fmt.Errorf("storage worker: failed to create checkpointer: %w", err)
}
}
// Register prune handler.
commonNode.Runtime.History().Pruner().RegisterHandler(&pruneHandler{
logger: n.logger,
node: n,
})
prometheusOnce.Do(func() {
prometheus.MustRegister(storageWorkerCollectors...)
})
return n, nil
}
// Service interface.
// Name returns the service name.
func (n *Node) Name() string {
return "committee node"
}
// Start causes the worker to start responding to tendermint new block events.
func (n *Node) Start() error {
go n.watchQuit()
go n.worker()
return nil
}
// Stop causes the worker to stop watching and shut down.
func (n *Node) Stop() {
n.ctxCancel()
}
// Quit returns a channel that will be closed when the worker stops.
func (n *Node) Quit() <-chan struct{} {
return n.quitCh
}
// Cleanup cleans up any leftover state after the worker is stopped.
func (n *Node) Cleanup() {
// Nothing to do here?
}
// Initialized returns a channel that will be closed once the worker finished starting up.
func (n *Node) Initialized() <-chan struct{} {
return n.initCh
}
// GetStatus returns the storage committee node status.
func (n *Node) GetStatus(ctx context.Context) (*api.Status, error) {
n.syncedLock.RLock()
defer n.syncedLock.RUnlock()
return &api.Status{
LastFinalizedRound: n.syncedState.LastBlock.Round,
}, nil
}
func (n *Node) getMetricLabels() prometheus.Labels {
return prometheus.Labels{
"runtime": n.commonNode.Runtime.ID().String(),
}
}
func (n *Node) WaitForRound(round uint64, root *storageApi.Root) (<-chan uint64, error) {
retCh := make(chan uint64, 1)
if root != nil {
round = root.Version
}
n.commonNode.CrossNode.Lock()
consensusRound := n.commonNode.CurrentBlock.Header.Round
n.commonNode.CrossNode.Unlock()
if round > consensusRound+roundWaitConsensusOffset && !commonFlags.DebugDontBlameOasis() {
close(retCh)
return nil, storageApi.ErrVersionNotFound
}
n.syncedLock.Lock()
defer n.syncedLock.Unlock()
if round <= n.syncedState.LastBlock.Round || (root != nil && n.localStorage.NodeDB().HasRoot(*root)) {
retCh <- n.syncedState.LastBlock.Round
close(retCh)
return retCh, nil
}
n.roundWaiters = append(n.roundWaiters, roundWaiter{
round: round,
ch: retCh,
})
return retCh, nil
}
func (n *Node) PauseCheckpointer(pause bool) error {
if !commonFlags.DebugDontBlameOasis() {
return api.ErrCantPauseCheckpointer
}
n.checkpointer.Pause(pause)
return nil
}
// GetLocalStorage returns the local storage backend used by this storage node.
func (n *Node) GetLocalStorage() storageApi.LocalBackend {
return n.localStorage
}
// NodeHooks implementation.
func (n *Node) HandlePeerMessage(context.Context, *p2p.Message, bool) (bool, error) {
// Nothing to do here.
return false, nil
}
// Guarded by CrossNode.
func (n *Node) HandleEpochTransitionLocked(snapshot *committee.EpochSnapshot) {
// Nothing to do here.
}
// Guarded by CrossNode.
func (n *Node) HandleNewBlockEarlyLocked(*block.Block) {
// Nothing to do here.
}
// Guarded by CrossNode.
func (n *Node) HandleNewBlockLocked(blk *block.Block) {
// Notify the state syncer that there is a new block.
n.blockCh.In() <- blk
}
// Guarded by CrossNode.
func (n *Node) HandleNewEventLocked(*roothashApi.Event) {
// Nothing to do here.
}
// Guarded by CrossNode.
func (n *Node) HandleNodeUpdateLocked(update *nodes.NodeUpdate, snapshot *committee.EpochSnapshot) {
// Nothing to do here.
// Storage worker uses a separate watcher.
}
// Watcher implementation.
// GetLastSynced returns the height, IORoot hash and StateRoot hash of the last block that was fully synced to.
func (n *Node) GetLastSynced() (uint64, storageApi.Root, storageApi.Root) {
n.syncedLock.RLock()
defer n.syncedLock.RUnlock()
var io, state storageApi.Root
for _, root := range n.syncedState.LastBlock.Roots {
switch root.Type {
case storageApi.RootTypeIO:
io = root
case storageApi.RootTypeState:
state = root
}
}
return n.syncedState.LastBlock.Round, io, state
}
func (n *Node) fetchDiff(round uint64, prevRoot, thisRoot storageApi.Root) {
result := &fetchedDiff{
fetched: false,
round: round,
prevRoot: prevRoot,
thisRoot: thisRoot,
}
defer func() {
n.diffCh <- result
}()
// Check if the new root doesn't already exist.
if !n.localStorage.NodeDB().HasRoot(thisRoot) {
result.fetched = true
if thisRoot.Hash.Equal(&prevRoot.Hash) {
// Even if HasRoot returns false the root can still exist if it is equal
// to the previous root and the root was emitted by the consensus committee
// directly (e.g., during an epoch transition). In this case we need to
// still apply the (empty) write log.
result.writeLog = storageApi.WriteLog{}
} else {
// New root does not yet exist in storage and we need to fetch it from a
// remote node.
n.logger.Debug("calling GetDiff",
"old_root", prevRoot,
"new_root", thisRoot,
)
// Prioritize committee nodes.
var selectedNode *node.Node
ctx := storageApi.WithNodeSelectionCallback(n.ctx, func(n *node.Node) {
selectedNode = n
})
if committee := n.commonNode.Group.GetEpochSnapshot().GetStorageCommittee(); committee != nil {
ctx = storageApi.WithNodePriorityHintFromMap(ctx, committee.PublicKeys)
}
it, err := n.storageClient.GetDiff(ctx, &storageApi.GetDiffRequest{StartRoot: prevRoot, EndRoot: thisRoot})
result.srcNode = selectedNode
if err != nil {
result.err = err
return
}
for {
more, err := it.Next()
if err != nil {
result.err = err
return
}
if !more {
break
}
chunk, err := it.Value()
if err != nil {
result.err = err
return
}
result.writeLog = append(result.writeLog, chunk)
}
}
}
}
func (n *Node) finalize(summary *blockSummary) {
err := n.localStorage.NodeDB().Finalize(n.ctx, summary.Roots)
switch err {
case nil:
n.logger.Debug("storage round finalized",
"round", summary.Round,
)
case storageApi.ErrAlreadyFinalized:
// This can happen if we are restoring after a roothash migration or if
// we crashed before updating the sync state.
n.logger.Warn("storage round already finalized",
"round", summary.Round,
)
err = nil
default:
n.logger.Error("failed to finalize storage round",
"err", err,
"round", summary.Round,
)
}
n.finalizeCh <- finalizeResult{
summary: summary,
err: err,
}
}
func (n *Node) initGenesis(rt *registryApi.Runtime, genesisBlock *block.Block) error {
n.logger.Info("initializing storage at genesis")
// Check what the latest finalized version in the database is as we may be using a database
// from a previous version or network.
latestVersion, err := n.localStorage.NodeDB().GetLatestVersion(n.ctx)
if err != nil {
return fmt.Errorf("failed to get latest version: %w", err)
}
stateRoot := storageApi.Root{
Namespace: rt.ID,
Version: genesisBlock.Header.Round,
Type: storageApi.RootTypeState,
Hash: genesisBlock.Header.StateRoot,
}
var compatible bool
switch {
case latestVersion < stateRoot.Version:
// Latest version is earlier than the genesis state root. In case it has the same hash
// we can fill in all the missing versions.
maybeRoot := stateRoot
maybeRoot.Version = latestVersion
if n.localStorage.NodeDB().HasRoot(maybeRoot) {
n.logger.Debug("latest version earlier than genesis state root, filling in versions",
"genesis_state_root", genesisBlock.Header.StateRoot,
"genesis_round", genesisBlock.Header.Round,
"latest_version", latestVersion,
)
for v := latestVersion; v < stateRoot.Version; v++ {
_, err = n.localStorage.Apply(n.ctx, &storageApi.ApplyRequest{
Namespace: rt.ID,
RootType: storageApi.RootTypeState,
SrcRound: v,
SrcRoot: stateRoot.Hash,
DstRound: v + 1,
DstRoot: stateRoot.Hash,
WriteLog: nil, // No changes.
})
if err != nil {
return fmt.Errorf("failed to fill in version %d: %w", v, err)
}
err = n.localStorage.NodeDB().Finalize(n.ctx, []storageApi.Root{{
Namespace: rt.ID,
Version: v + 1,
Type: storageApi.RootTypeState,
Hash: stateRoot.Hash,
// We can ignore I/O roots.
}})
if err != nil {
return fmt.Errorf("failed to finalize version %d: %w", v, err)
}
}
compatible = true
}
default:
// Latest finalized version is the same or ahead, root must exist.
compatible = n.localStorage.NodeDB().HasRoot(stateRoot)
}
// If we are incompatible and the database is not empty, we cannot do anything. If the database
// is empty we can either apply genesis state from the runtime descriptor (if relevant) or we
// assume the node will sync from a different node.
if !compatible && latestVersion > 0 {
n.logger.Error("existing state is incompatible with runtime genesis state",
"genesis_state_root", genesisBlock.Header.StateRoot,
"genesis_round", genesisBlock.Header.Round,
"latest_version", latestVersion,
)
return fmt.Errorf("existing state is incompatible with runtime genesis state")
}
// Check if the genesis round in the descriptor matches the current genesis round and if so,
// whether genesis state exists in the descriptor. Note that the rounds may not match in case a
// dump/restore of consensus layer state has been performed.
if genesisBlock.Header.Round == rt.Genesis.Round && rt.Genesis.State != nil {
var emptyRoot hash.Hash
emptyRoot.Empty()
n.logger.Info("applying genesis state",
"state_root", rt.Genesis.StateRoot,
)
_, err := n.localStorage.Apply(n.ctx, &storageApi.ApplyRequest{
Namespace: rt.ID,
RootType: storageApi.RootTypeState,
SrcRound: rt.Genesis.Round,
SrcRoot: emptyRoot,
DstRound: rt.Genesis.Round,
DstRoot: rt.Genesis.StateRoot,
WriteLog: rt.Genesis.State,
})
if err != nil {
return fmt.Errorf("failed to apply genesis state: %w", err)
}
compatible = true
}
if !compatible {
// Database is empty, so assume the state will be replicated from another node.
n.logger.Warn("non-empty state root but no state specified, assuming replication",
"state_root", genesisBlock.Header.StateRoot,
)
n.checkpointSyncForced = true
}
return nil
}
func (n *Node) flushSyncedState(summary *blockSummary) uint64 {
n.syncedLock.Lock()
defer n.syncedLock.Unlock()
n.syncedState.LastBlock = *summary
rtID := n.commonNode.Runtime.ID()
if err := n.stateStore.PutCBOR(rtID[:], &n.syncedState); err != nil {
n.logger.Error("can't store watcher state to database", "err", err)
}
// Wake up any round waiters.
filtered := make([]roundWaiter, 0, len(n.roundWaiters))
for _, w := range n.roundWaiters {
if w.round <= n.syncedState.LastBlock.Round {
w.ch <- n.syncedState.LastBlock.Round
close(w.ch)
} else {
filtered = append(filtered, w)
}
}
n.roundWaiters = filtered
return n.syncedState.LastBlock.Round
}
func (n *Node) updateExternalServicePolicy(rtComputeNodes nodes.NodeDescriptorLookup) {
// Create new storage gRPC access policy for the current runtime.
policy := accessctl.NewPolicy()
// Add policy for configured sentry nodes.
for _, addr := range n.workerCommonCfg.SentryAddresses {
sentryNodesPolicy.AddPublicKeyPolicy(&policy, addr.PubKey)
}
executorCommitteePolicy.AddRulesForNodeRoles(&policy, rtComputeNodes.GetNodes(), node.RoleComputeWorker)
switch {
// If public storage RPC was enabled in the config, then the normally gated methods need to be allowed
// for everyone.
case n.rpcRoleProvider != nil:
for _, act := range storageNodesPolicy.Actions {
policy.AllowAll(act)
}
// If not configured otherwise, state access should be restricted to storage committee members.
default:
// TODO: Query registry only for storage nodes after
// https://github.com/oasisprotocol/oasis-core/issues/1923 is implemented.
nodes, err := n.commonNode.Consensus.Registry().GetNodes(n.ctx, consensus.HeightLatest)
if err != nil {
n.logger.Error("couldn't get nodes from registry", "err", err)
}
if len(nodes) > 0 {
// Only include storage nodes for our runtime.
var storageNodes []*node.Node
for _, nd := range nodes {
if nd.GetRuntime(n.commonNode.Runtime.ID()) != nil && nd.HasRoles(node.RoleStorageWorker) {
storageNodes = append(storageNodes, nd)
}
}
storageNodesPolicy.AddRulesForNodeRoles(&policy, storageNodes, node.RoleStorageWorker)
}
}
// Update storage gRPC access policy for the current runtime.
n.grpcPolicy.SetAccessPolicy(policy, n.commonNode.Runtime.ID())
n.logger.Debug("set new storage gRPC access policy", "policy", policy)
}
func (n *Node) runtimeNodesWatcher() {
defer close(n.rtWatcherQuitCh)
// Watch registry for runtime node updates and update external gRPC policies.
// Policy updates are made on:
// * any updates to the runtime executor committee nodes
// * any updates to the registered storage nodes for the runtime
// (this includes nodes not in committee)
n.logger.Info("starting runtime nodes watcher")
committeeNodes := nodes.NewFilteredNodeLookup(
n.commonNode.Group.Nodes(),
nodes.TagFilter(committee.TagForCommittee(scheduler.KindComputeExecutor)),
)
// Start watching compute node updates for the current committee.
committeeNodeUps, committeeNodeUpsSub, err := committeeNodes.WatchNodeUpdates()
if err != nil {
n.logger.Error("failed to subscribe to node updates",
"err", err,
)
return
}
defer committeeNodeUpsSub.Close()
// Watch registered storage node updates for the runtime.
storageNodeUps, storageNodeUpsSub, err := n.storageNodes.WatchNodeUpdates()
if err != nil {
n.logger.Error("failed to subscribe to node storage node updates",
"err", err,
)
return
}
defer storageNodeUpsSub.Close()
for {
select {
case <-n.ctx.Done():
return
case u := <-committeeNodeUps:
if u.Update == nil {
continue
}
// Update policy (handled bellow).
case u := <-storageNodeUps:
if u.Update == nil {
continue
}
// Update policy (handled bellow).
}
n.updateExternalServicePolicy(committeeNodes)
}
}
func (n *Node) watchQuit() {
// Close quit channel on any worker quitting.
select {
case <-n.workerQuitCh:
case <-n.rtWatcherQuitCh:
}
close(n.quitCh)
}
// This is only called from the main worker goroutine, so no locking should be necessary.
func (n *Node) nudgeAvailability(lastSynced, latest uint64) {
if lastSynced == n.undefinedRound || latest == n.undefinedRound {
return
}
if latest-lastSynced < maximumRoundDelayForAvailability && !n.roleAvailable {
n.roleProvider.SetAvailable(func(nd *node.Node) error {
nd.AddOrUpdateRuntime(n.commonNode.Runtime.ID())
return nil
})
if n.rpcRoleProvider != nil {
n.rpcRoleProvider.SetAvailable(func(nd *node.Node) error {
nd.AddOrUpdateRuntime(n.commonNode.Runtime.ID())
return nil
})
}
n.roleAvailable = true
}
if latest-lastSynced > minimumRoundDelayForUnavailability && n.roleAvailable {
n.roleProvider.SetUnavailable()
if n.rpcRoleProvider != nil {
n.rpcRoleProvider.SetUnavailable()
}
n.roleAvailable = false
}
}
func (n *Node) worker() { // nolint: gocyclo
defer close(n.workerQuitCh)
defer close(n.diffCh)
// Wait for the common node to be initialized.
select {
case <-n.commonNode.Initialized():
case <-n.ctx.Done():
close(n.initCh)
return
}
// Start runtime node watcher.
go n.runtimeNodesWatcher()
n.logger.Info("starting committee node")
genesisBlock, err := n.commonNode.Consensus.RootHash().GetGenesisBlock(n.ctx, &roothashApi.RuntimeRequest{
RuntimeID: n.commonNode.Runtime.ID(),
Height: consensus.HeightLatest,
})
if err != nil {
n.logger.Error("can't retrieve genesis block", "err", err)
return
}
n.undefinedRound = genesisBlock.Header.Round - 1
var fetcherGroup sync.WaitGroup
n.syncedLock.RLock()
cachedLastRound := n.syncedState.LastBlock.Round
n.syncedLock.RUnlock()
if cachedLastRound == defaultUndefinedRound || cachedLastRound < genesisBlock.Header.Round {
cachedLastRound = n.undefinedRound
}
// Initialize genesis from the runtime descriptor.
if cachedLastRound == n.undefinedRound {
var rt *registryApi.Runtime
rt, err = n.commonNode.Runtime.ActiveDescriptor(n.ctx)
if err != nil {
n.logger.Error("failed to retrieve runtime registry descriptor",
"err", err,
)
return
}
if err = n.initGenesis(rt, genesisBlock); err != nil {
n.logger.Error("failed to initialize storage at genesis",
"err", err,
)
return
}
}
// Notify the checkpointer of the genesis round so it can be checkpointed.
if n.checkpointer != nil {
n.checkpointer.NotifyNewVersion(genesisBlock.Header.Round)
n.checkpointer.Flush()
}
n.logger.Info("worker initialized",
"genesis_round", genesisBlock.Header.Round,
"last_synced", cachedLastRound,
)
outOfOrderDoneDiffs := &outOfOrderRoundQueue{}
outOfOrderFinalizable := &outOfOrderRoundQueue{}
syncingRounds := make(map[uint64]*inFlight)
hashCache := make(map[uint64]*blockSummary)
lastFullyAppliedRound := cachedLastRound
heap.Init(outOfOrderDoneDiffs)
// Try to perform initial sync from state and io checkpoints.
if !n.checkpointSyncDisabled || n.checkpointSyncForced {
var (
summary *blockSummary
attempt int
)
CheckpointSyncRetry:
for {
summary, err = n.syncCheckpoints(genesisBlock.Header.Round)
if err == nil {
break
}
attempt++
switch n.checkpointSyncForced {
case true:
// We have no other options but to perform a checkpoint sync as we are missing
// genesis state.
n.logger.Info("checkpoint sync required as we don't have genesis state, retrying",
"err", err,
"attempt", attempt,
)
case false:
if attempt > 1 {
break CheckpointSyncRetry
}
// Try syncing again. The main reason for this is the sync failing due to a
// checkpoint pruning race condition (where nodes list a checkpoint which is
// then deleted just before we request its chunks). One retry is enough.
n.logger.Info("first checkpoint sync failed, trying once more", "err", err)
}
// Delay before retrying.
select {
case <-time.After(checkpointSyncRetryDelay):
case <-n.ctx.Done():
return
}
}
if err != nil {
n.logger.Info("checkpoint sync failed", "err", err)
} else {
cachedLastRound = n.flushSyncedState(summary)
lastFullyAppliedRound = cachedLastRound
n.logger.Info("checkpoint sync succeeded",
logging.LogEvent, LogEventCheckpointSyncSuccess,
)
}
}
close(n.initCh)
// Don't register availability immediately, we want to know first how far behind consensus we are.
latestBlockRound := n.undefinedRound
heartbeat := heartbeat{}
heartbeat.reset()
triggerRoundFetches := func() {
for i := lastFullyAppliedRound + 1; i <= latestBlockRound; i++ {
syncing, ok := syncingRounds[i]
if ok && syncing.outstanding.hasAll() {
continue
}
if !ok {