forked from lni/dragonboat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnodehost.go
2019 lines (1910 loc) · 68.5 KB
/
nodehost.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 2017-2019 Lei Ni ([email protected]) and other Dragonboat authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
Package dragonboat is a multi-group Raft implementation.
The NodeHost struct is the facade interface for all features provided by the
dragonboat package. Each NodeHost instance, identified by its RaftAddress
property, usually runs on a separate host managing its CPU, storage and network
resources. Each NodeHost can manage Raft nodes from many different Raft groups
known as Raft clusters. Each Raft cluster is identified by its ClusterID Each
Raft cluster usually consists of multiple nodes, identified by their NodeID
values. Nodes from the same Raft cluster are suppose to be distributed on
different NodeHost instances across the network, this brings fault tolerance
to node failures as application data stored in such a Raft cluster can be
available as long as the majority of its managing NodeHost instances (i.e. its
underlying hosts) are available.
User applications can leverage the power of the Raft protocol implemented in
dragonboat by implementing its IStateMachine or IOnDiskStateMachine component.
IStateMachine and IOnDiskStateMachine is defined in
github.com/lni/dragonboat/v3/statemachine. Each cluster node is associated with an
IStateMachine or IOnDiskStateMachine instance, it is in charge of updating,
querying and snapshotting application data, with minimum exposure to the
complexity of the Raft protocol implementation.
User applications can use NodeHost's APIs to update the state of their
IStateMachine or IOnDiskStateMachine instances, this is called making proposals.
Once accepted by the majority nodes of a Raft cluster, the proposal is considered
as committed and it will be applied on all member nodes of the Raft cluster.
Applications can also make linearizable reads to query the state of their
IStateMachine or IOnDiskStateMachine instances. Dragonboat employs the ReadIndex
protocol invented by Diego Ongaro to implement linearizable reads. Both read and
write operations can be initiated on any member nodes, although initiating from
the leader nodes incurs the lowest overhead.
Dragonboat guarantees the linearizability of your I/O when interacting with the
IStateMachine or IOnDiskStateMachine instances. In plain English, writes (via
making proposal) to your Raft cluster appears to be instantaneous, once a write
is completed, all later reads (linearizable read using the ReadIndex protocol
as implemented and provided in dragonboat) should return the value of that write
or a later write. Once a value is returned by a linearizable read, all later
reads should return the same value or the result of a later write.
To strictly provide such guarantee, we need to implement the at-most-once
semantic required by linearizability. For a client, when it retries the proposal
that failed to complete before its deadline during the previous attempt, it has
the risk to have the same proposal committed and applied twice into the user
state machine. Dragonboat prevents this by implementing the client session
concept described in Diego Ongaro's PhD thesis.
NodeHost APIs for making the above mentioned application requests can be loosely
classified into two categories, synchronous and asynchronous APIs. Synchronous
APIs which will not return until the completion of the requested operation.
Their method names all start with Sync*. The asynchronous counterpart of those
asynchronous APIs, on the other hand, usually return immediately without waiting
on any significant delays caused by networking or disk IO. This allows users to
concurrently initiate multiple such asynchronous operations to save the total
amount of time required to complete them. Users are free to choose whether they
prefer to use the synchronous APIs for its simplicity or their asynchronous
variants for better performance and flexibility.
Dragonboat is a feature complete Multi-Group Raft implementation - snapshotting,
membership change, leadership transfer, non-voting members and disk based state
machine are all provided.
Dragonboat is also extensively optimized. The Raft protocol implementation is
fully pipelined, meaning proposals can start before the completion of previous
proposals. This is critical for system throughput in high latency environment.
Dragonboat is also fully batched, it batches internal operations whenever
possible to maximize system throughput.
*/
package dragonboat // github.com/lni/dragonboat/v3
import (
"context"
"errors"
"reflect"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/lni/dragonboat/v3/client"
"github.com/lni/dragonboat/v3/config"
"github.com/lni/dragonboat/v3/internal/logdb"
"github.com/lni/dragonboat/v3/internal/rsm"
"github.com/lni/dragonboat/v3/internal/server"
"github.com/lni/dragonboat/v3/internal/settings"
"github.com/lni/dragonboat/v3/internal/transport"
"github.com/lni/dragonboat/v3/internal/utils/logutil"
"github.com/lni/dragonboat/v3/internal/utils/syncutil"
"github.com/lni/dragonboat/v3/raftio"
pb "github.com/lni/dragonboat/v3/raftpb"
sm "github.com/lni/dragonboat/v3/statemachine"
)
const (
unmanagedDeploymentID = transport.UnmanagedDeploymentID
// DragonboatMajor is the major version number
DragonboatMajor = 3
// DragonboatMinor is the minor version number
DragonboatMinor = 2
// DragonboatPatch is the patch version number
DragonboatPatch = 0
// DEVVersion is a boolean flag indicating whether this is a dev version
DEVVersion = true
)
var (
receiveQueueLen = settings.Soft.ReceiveQueueLength
delaySampleRatio = settings.Soft.LatencySampleRatio
rsPoolSize = settings.Soft.NodeHostSyncPoolSize
streamConnections = settings.Soft.StreamConnections
monitorInterval = 100 * time.Millisecond
)
var (
// ErrNodeRemoved indictes that the requested node has been removed.
ErrNodeRemoved = errors.New("node removed")
// ErrClusterNotFound indicates that the specified cluster is not found.
ErrClusterNotFound = errors.New("cluster not found")
// ErrClusterAlreadyExist indicates that the specified cluster already exist.
ErrClusterAlreadyExist = errors.New("cluster already exist")
// ErrClusterNotStopped indicates that the specified cluster is still running
// and thus prevented the requested operation to be completed.
ErrClusterNotStopped = errors.New("cluster not stopped")
// ErrInvalidClusterSettings indicates that cluster settings specified for
// the StartCluster method are invalid.
ErrInvalidClusterSettings = errors.New("cluster settings are invalid")
// ErrDeadlineNotSet indicates that the context parameter provided does not
// carry a deadline.
ErrDeadlineNotSet = errors.New("deadline not set")
// ErrInvalidDeadline indicates that the specified deadline is invalid, e.g.
// time in the past.
ErrInvalidDeadline = errors.New("invalid deadline")
// ErrDirNotExist indicates that the specified dir does not exist.
ErrDirNotExist = errors.New("specified dir does not exist")
)
// ClusterInfo is a record for representing the state of a Raft cluster based
// on the knowledge of the local NodeHost instance.
type ClusterInfo struct {
// ClusterID is the cluster ID of the Raft cluster node.
ClusterID uint64
// NodeID is the node ID of the Raft cluster node.
NodeID uint64
// IsLeader indicates whether this is a leader node.
IsLeader bool
// IsObserver indicates whether this is a non-voting observer node.
IsObserver bool
// StateMachineType is the type of the state machine.
StateMachineType sm.Type
// Nodes is a map of member node IDs to their Raft addresses.
Nodes map[uint64]string
// ConfigChangeIndex is the current config change index of the Raft node.
// ConfigChangeIndex is Raft Log index of the last applied membership
// change entry.
ConfigChangeIndex uint64
// Pending is a boolean flag indicating whether details of the cluster node
// is not available. The Pending flag is set to true usually because the node
// has not had anything applied yet.
Pending bool
}
// NodeHostInfo provides info about the NodeHost, including its managed Raft
// cluster nodes and available Raft logs saved in its local persistent storage.
type NodeHostInfo struct {
// RaftAddress is the public address and the identifier of the NodeHost.
RaftAddress string
// ClusterInfo is a list of all Raft clusters managed by the NodeHost
ClusterInfoList []ClusterInfo
// LogInfo is a list of raftio.NodeInfo values representing all Raft logs
// stored on the NodeHost.
LogInfo []raftio.NodeInfo
}
// NodeHostInfoOption is the option type used when querying NodeHostInfo.
type NodeHostInfoOption struct {
// SkipLogInfo is the boolean flag indicating whether Raft Log info should be
// skipped when querying the NodeHostInfo.
SkipLogInfo bool
}
// DefaultNodeHostInfoOption is the default NodeHostInfoOption value. It
// requests the GetNodeHostInfo method to return all supported info.
var DefaultNodeHostInfoOption NodeHostInfoOption
// SnapshotOption is the options users can specify when requesting a snapshot
// to be generated.
type SnapshotOption struct {
// Exported is a boolean flag indicating whether the snapshot requested to
// be generated should be exported. For an exported snapshot, it is users'
// responsibility to manage the snapshot files. By default, a requested
// snapshot is not considered as exported, such a regular snapshot is managed
// the system.
Exported bool
// ExportPath is the path where the exported snapshot should be stored, it
// must point to an existing directory for which the current user has write
// permission to it.
ExportPath string
}
// DefaultSnapshotOption is the default SnapshotOption value to use when
// requesting a snapshot to be generated by using NodeHost's RequestSnapshot
// method. DefaultSnapshotOption causes a regular snapshot to be generated
// and the generated snapshot is managed by the system.
var DefaultSnapshotOption SnapshotOption
// NodeHost manages Raft clusters and enables them to share resources such as
// transport and persistent storage etc. NodeHost is also the central access
// point for Dragonboat functionalities provided to applications.
type NodeHost struct {
tick uint64
msgCount uint64
testPartitionState
clusterMu struct {
sync.RWMutex
stopped bool
csi uint64
clusters sync.Map
requests map[uint64]*server.MessageQueue
}
snapshotStatus *snapshotFeedback
serverCtx *server.Context
nhConfig config.NodeHostConfig
stopper *syncutil.Stopper
duStopper *syncutil.Stopper
nodes *transport.Nodes
deploymentID uint64
rsPool []*sync.Pool
execEngine *execEngine
logdb raftio.ILogDB
transport transport.ITransport
msgHandler *messageHandler
liQueue *leaderInfoQueue
userListener raftio.IRaftEventListener
transportLatency *sample
}
// NewNodeHost creates a new NodeHost instance. The returned NodeHost instance
// is configured using the specified NodeHostConfig instance. In a typical
// application, it is expected to have one NodeHost on each server.
func NewNodeHost(nhConfig config.NodeHostConfig) (*NodeHost, error) {
logBuildTagsAndVersion()
if err := nhConfig.Validate(); err != nil {
return nil, err
}
serverCtx, err := server.NewContext(nhConfig)
if err != nil {
return nil, err
}
nh := &NodeHost{
serverCtx: serverCtx,
nhConfig: nhConfig,
stopper: syncutil.NewStopper(),
duStopper: syncutil.NewStopper(),
nodes: transport.NewNodes(streamConnections),
transportLatency: newSample(),
userListener: nhConfig.RaftEventListener,
}
nh.snapshotStatus = newSnapshotFeedback(nh.pushSnapshotStatus)
nh.msgHandler = newNodeHostMessageHandler(nh)
nh.clusterMu.requests = make(map[uint64]*server.MessageQueue)
nh.createPools()
if err := nh.createTransport(); err != nil {
nh.Stop()
return nil, err
}
did := unmanagedDeploymentID
if nhConfig.DeploymentID == 0 {
plog.Warningf("DeploymentID not set in NodeHostConfig, default to %d",
transport.UnmanagedDeploymentID)
nh.transport.SetUnmanagedDeploymentID()
} else {
did = nhConfig.DeploymentID
nh.transport.SetDeploymentID(did)
}
plog.Infof("DeploymentID set to %d", did)
nh.deploymentID = did
if err := nh.createLogDB(nhConfig, did); err != nil {
nh.Stop()
return nil, err
}
plog.Infof("LogDB created")
nh.execEngine = newExecEngine(nh, nh.serverCtx, nh.logdb)
nh.stopper.RunWorker(func() {
nh.nodeMonitorMain(nhConfig)
})
nh.stopper.RunWorker(func() {
nh.tickWorkerMain()
})
if nhConfig.RaftEventListener != nil {
nh.liQueue = newLeaderInfoQueue()
nh.stopper.RunWorker(func() {
nh.handleLeaderUpdatedEvents()
})
}
nh.logNodeHostDetails()
return nh, nil
}
// NodeHostConfig returns the NodeHostConfig instance used for configuring this
// NodeHost instance.
func (nh *NodeHost) NodeHostConfig() config.NodeHostConfig {
return nh.nhConfig
}
// RaftAddress returns the Raft address of the NodeHost instance. The
// returned RaftAddress value is used to identify this NodeHost instance. It is
// also the address used for exchanging Raft messages and snapshots between
// distributed NodeHost instances.
func (nh *NodeHost) RaftAddress() string {
return nh.nhConfig.RaftAddress
}
// Stop stops all Raft nodes managed by the NodeHost instance, closes the
// transport and persistent storage modules.
func (nh *NodeHost) Stop() {
nh.clusterMu.Lock()
nh.clusterMu.stopped = true
nh.clusterMu.Unlock()
if nh.transport != nil {
nh.transport.RemoveMessageHandler()
}
allNodes := make([]raftio.NodeInfo, 0)
nh.forEachCluster(func(cid uint64, node *node) bool {
nodeInfo := raftio.NodeInfo{
ClusterID: node.clusterID,
NodeID: node.nodeID,
}
allNodes = append(allNodes, nodeInfo)
return true
})
for _, node := range allNodes {
if err := nh.StopNode(node.ClusterID, node.NodeID); err != nil {
plog.Errorf("failed to remove cluster %s",
logutil.ClusterID(node.ClusterID))
}
}
plog.Debugf("%s is going to stop the nh stopper", nh.id())
if nh.duStopper != nil {
nh.duStopper.Stop()
}
nh.stopper.Stop()
plog.Debugf("%s is going to stop the exec engine", nh.id())
if nh.execEngine != nil {
nh.execEngine.stop()
}
plog.Debugf("%s is going to stop the tranport module", nh.id())
if nh.transport != nil {
nh.transport.Stop()
}
plog.Debugf("%s transport module stopped", nh.id())
if nh.logdb != nil {
nh.logdb.Close()
} else {
// in standalone mode, when Stop() is called in the same goroutine as
// NewNodeHost, is nh.longdb == nil above is not going to happen
plog.Warningf("logdb is nil")
}
plog.Debugf("logdb closed, %s is now stopped", nh.id())
nh.serverCtx.Stop()
plog.Debugf("serverCtx stopped on %s", nh.id())
if delaySampleRatio > 0 {
nh.logTransportLatency()
}
}
// StartCluster adds the specified Raft cluster node to the NodeHost and starts
// the node to make it ready for accepting incoming requests.
//
// The input parameter nodes is a map of node ID to RaftAddress for indicating
// what are initial nodes when the Raft cluster is first created. The join flag
// indicates whether the node is a new node joining an existing cluster.
// createStateMachine is a factory function for creating the IStateMachine
// instance, config is the configuration instance that will be passed to the
// underlying Raft node object, the cluster ID and node ID of the involved node
// is given in the ClusterID and NodeID fields of the config object.
//
// Note that this method is not for changing the membership of the specified
// Raft cluster, it launches a node that is already a member of the Raft
// cluster.
//
// As a summary, when -
// - starting a brand new Raft cluster with initial member nodes, set join to
// false and specify all initial member node details in the nodes map.
// - restarting an crashed or stopped node, set join to false. the content of
// the nodes map is ignored.
// - joining a new node to an existing Raft cluster, set join to true and leave
// the nodes map empty. This requires the joining node to have already been
// added as a member of the Raft cluster.
func (nh *NodeHost) StartCluster(nodes map[uint64]string,
join bool, createStateMachine func(uint64, uint64) sm.IStateMachine,
config config.Config) error {
stopc := make(chan struct{})
cf := func(clusterID uint64, nodeID uint64,
done <-chan struct{}) rsm.IManagedStateMachine {
sm := createStateMachine(clusterID, nodeID)
return rsm.NewNativeStateMachine(clusterID,
nodeID, rsm.NewRegularStateMachine(sm), done)
}
return nh.startCluster(nodes, join, cf, stopc, config, pb.RegularStateMachine)
}
// StartConcurrentCluster is similar to the StartCluster method but it is used
// to add and start a Raft node backed by a concurrent state machine.
func (nh *NodeHost) StartConcurrentCluster(nodes map[uint64]string,
join bool,
createStateMachine func(uint64, uint64) sm.IConcurrentStateMachine,
config config.Config) error {
stopc := make(chan struct{})
cf := func(clusterID uint64, nodeID uint64,
done <-chan struct{}) rsm.IManagedStateMachine {
sm := createStateMachine(clusterID, nodeID)
return rsm.NewNativeStateMachine(clusterID,
nodeID, rsm.NewConcurrentStateMachine(sm), done)
}
return nh.startCluster(nodes, join, cf, stopc, config, pb.ConcurrentStateMachine)
}
// StartOnDiskCluster is similar to the StartCluster method but it is used to
// add and start a Raft node backed by an IOnDiskStateMachine.
func (nh *NodeHost) StartOnDiskCluster(nodes map[uint64]string,
join bool,
createStateMachine func(uint64, uint64) sm.IOnDiskStateMachine,
config config.Config) error {
stopc := make(chan struct{})
cf := func(clusterID uint64, nodeID uint64,
done <-chan struct{}) rsm.IManagedStateMachine {
sm := createStateMachine(clusterID, nodeID)
return rsm.NewNativeStateMachine(clusterID,
nodeID, rsm.NewOnDiskStateMachine(sm), done)
}
return nh.startCluster(nodes, join, cf, stopc, config, pb.OnDiskStateMachine)
}
// StopCluster removes and stops the Raft node associated with the specified
// Raft cluster from the NodeHost. The node to be removed and stopped is
// identified by the clusterID value.
//
// Note that this is not the membership change operation to remove the node
// from the Raft cluster.
func (nh *NodeHost) StopCluster(clusterID uint64) error {
return nh.stopNode(clusterID, 0, false)
}
// StopNode removes the specified Raft cluster node from the NodeHost and
// stops that running Raft node.
//
// Note that this is not the membership change operation to remove the node
// from the Raft cluster.
func (nh *NodeHost) StopNode(clusterID uint64, nodeID uint64) error {
return nh.stopNode(clusterID, nodeID, true)
}
// SyncPropose makes a synchronous proposal on the Raft cluster specified by
// the input client session object. The specified context parameter must has
// the timeout value set.
//
// SyncPropose returns the result returned by IStateMachine or
// IOnDiskStateMachine's Update method, or the error encountered. The input
// byte slice can be reused for other purposes immediate after the return of
// this method.
//
// After calling SyncPropose, unless NO-OP client session is used, it is
// caller's responsibility to update the client session instance accordingly
// based on SyncPropose's outcome. Basically, when a ErrTimeout error is
// returned, application can retry the same proposal without updating the
// client session instance. When ErrInvalidSession error is returned, it
// usually means the session instance has been evicted from the server side,
// the Raft paper recommends to crash the client in this highly unlikely
// event. When the proposal completed successfully, caller must call
// client.ProposalCompleted() to get it ready to be used in future proposals.
func (nh *NodeHost) SyncPropose(ctx context.Context,
session *client.Session, cmd []byte) (sm.Result, error) {
timeout, err := getTimeoutFromContext(ctx)
if err != nil {
return sm.Result{}, err
}
rs, err := nh.Propose(session, cmd, timeout)
if err != nil {
return sm.Result{}, err
}
result, err := checkRequestState(ctx, rs)
if err != nil {
return sm.Result{}, err
}
rs.Release()
return result, nil
}
// SyncRead performs a synchronous linearizable read on the specified Raft
// cluster. The specified context parameter must has the timeout value set. The
// query byte slice specifies what to query, it will be passed to the Lookup
// method of the IStateMachine or IOnDiskStateMachine after the system
// determines that it is safe to perform the local read on IStateMachine or
// IOnDiskStateMachine. It returns the query result from the Lookup method or
// the error encountered.
func (nh *NodeHost) SyncRead(ctx context.Context, clusterID uint64,
query interface{}) (interface{}, error) {
v, err := nh.linearizableRead(ctx, clusterID,
func(node *node) (interface{}, error) {
data, err := node.sm.Lookup(query)
if err == rsm.ErrClusterClosed {
return nil, ErrClusterClosed
}
return data, err
})
if err != nil {
return nil, err
}
return v, nil
}
// Membership is the struct used to describe Raft cluster membership query
// results.
type Membership struct {
// ConfigChangeID is the Raft entry index of the last applied membership
// change entry.
ConfigChangeID uint64
// Nodes is a map of NodeID values to NodeHost Raft addresses for all regular
// Raft nodes.
Nodes map[uint64]string
// Observers is a map of NodeID values to NodeHost Raft addresses for all
// observers.
Observers map[uint64]string
// Removed is a set of NodeID values that have been removed from the Raft
// cluster. They are not allowed to be added back to the cluster.
Removed map[uint64]struct{}
}
// SyncGetClusterMembership is a rsynchronous method that queries the membership
// information from the specified Raft cluster. The specified context parameter
// must has the timeout value set.
//
// SyncGetClusterMembership guarantees that the returned membership information
// is linearizable.
func (nh *NodeHost) SyncGetClusterMembership(ctx context.Context,
clusterID uint64) (*Membership, error) {
v, err := nh.linearizableRead(ctx, clusterID,
func(node *node) (interface{}, error) {
members, observers, removed, confChangeID := node.sm.GetMembership()
membership := &Membership{
Nodes: members,
Observers: observers,
Removed: removed,
ConfigChangeID: confChangeID,
}
return membership, nil
})
if err != nil {
return nil, err
}
r := v.(*Membership)
return r, nil
}
// GetClusterMembership returns the membership information from the specified
// Raft cluster. The specified context parameter must has the timeout value
// set.
//
// GetClusterMembership guarantees that the returned membership information is
// linearizable. This is a synchronous method meaning it will only return after
// its confirmed completion, failure or timeout.
//
// Deprecated: Use NodeHost.SyncGetClusterMembership instead.
// NodeHost.GetClusterMembership will be removed in v3.2.
func (nh *NodeHost) GetClusterMembership(ctx context.Context,
clusterID uint64) (*Membership, error) {
return nh.SyncGetClusterMembership(ctx, clusterID)
}
// GetLeaderID returns the leader node ID of the specified Raft cluster based
// on local node's knowledge. The returned boolean value indicates whether the
// leader information is available.
func (nh *NodeHost) GetLeaderID(clusterID uint64) (uint64, bool, error) {
v, ok := nh.getCluster(clusterID)
if !ok {
return 0, false, ErrClusterNotFound
}
nodeID, valid := v.getLeaderID()
return nodeID, valid, nil
}
// GetNoOPSession returns a NO-OP client session ready to be used for making
// proposals. The NO-OP client session is a dummy client session that will not
// be checked or enforced. Use this No-OP client session when you want to ignore
// features provided by client sessions. A NO-OP client session is not
// registered on the server side and thus not required to be closed at the end
// of its life cycle.
//
// Returned NO-OP client session instance can be concurrently used in multiple
// goroutines.
//
// Use this NO-OP client session when your IStateMachine provides idempotence in
// its own implementation.
//
// NO-OP client session must be used for making proposals on IOnDiskStateMachine
// based state machine.
func (nh *NodeHost) GetNoOPSession(clusterID uint64) *client.Session {
return client.NewNoOPSession(clusterID, nh.serverCtx.GetRandomSource())
}
// GetNewSession starts a synchronous proposal to create, register and return
// a new client session object for the specified Raft cluster. The specified
// context parameter must has the timeout value set.
//
// A client session object is used to ensure that a retried proposal, e.g.
// proposal retried after timeout, will not be applied more than once into the
// IStateMachine.
//
// Returned client session instance should not be used concurrently. Use
// multiple client sessions when making concurrent proposals.
//
// Deprecated: Use NodeHost.SyncGetSession instead. NodeHost.GetNewSession will
// be removed in v3.2.
func (nh *NodeHost) GetNewSession(ctx context.Context,
clusterID uint64) (*client.Session, error) {
return nh.SyncGetSession(ctx, clusterID)
}
// CloseSession closes the specified client session by unregistering it
// from the system. The specified context parameter must has the timeout value
// set. This is a synchronous method meaning it will only return after its
// confirmed completion, failure or timeout.
//
// Closed client session should no longer be used in future proposals.
//
// Deprecated: Use NodeHost.SyncCloseSession instead. NodeHost.CloseSession will
// be removed in v3.2
func (nh *NodeHost) CloseSession(ctx context.Context,
session *client.Session) error {
return nh.SyncCloseSession(ctx, session)
}
// SyncGetSession starts a synchronous proposal to create, register and return
// a new client session object for the specified Raft cluster. The specified
// context parameter must has the timeout value set.
//
// A client session object is used to ensure that a retried proposal, e.g.
// proposal retried after timeout, will not be applied more than once into the
// state machine.
//
// Returned client session instance should not be used concurrently. Use
// multiple client sessions when you need to concurrently start multiple
// proposals.
//
// Client session is not supported by IOnDiskStateMachine based state machine.
// NO-OP client session must be used for making proposals on IOnDiskStateMachine
// based state machine.
func (nh *NodeHost) SyncGetSession(ctx context.Context,
clusterID uint64) (*client.Session, error) {
timeout, err := getTimeoutFromContext(ctx)
if err != nil {
return nil, err
}
cs := client.NewSession(clusterID, nh.serverCtx.GetRandomSource())
cs.PrepareForRegister()
rs, err := nh.ProposeSession(cs, timeout)
if err != nil {
return nil, err
}
result, err := checkRequestState(ctx, rs)
if err != nil {
return nil, err
}
if result.Value != cs.ClientID {
plog.Panicf("unexpected result %d, want %d", result.Value, cs.ClientID)
}
cs.PrepareForPropose()
return cs, nil
}
// SyncCloseSession closes the specified client session by unregistering it
// from the system. The specified context parameter must has the timeout value
// set. This is a synchronous method meaning it will only return after its
// confirmed completion, failure or timeout.
//
// Closed client session should no longer be used in future proposals.
func (nh *NodeHost) SyncCloseSession(ctx context.Context,
cs *client.Session) error {
timeout, err := getTimeoutFromContext(ctx)
if err != nil {
return err
}
cs.PrepareForUnregister()
rs, err := nh.ProposeSession(cs, timeout)
if err != nil {
return err
}
result, err := checkRequestState(ctx, rs)
if err != nil {
return err
}
if result.Value != cs.ClientID {
plog.Panicf("unexpected result %d, want %d", result.Value, cs.ClientID)
}
return nil
}
// Propose starts an asynchronous proposal on the Raft cluster specified by the
// Session object. The input byte slice can be reused for other purposes
// immediate after the return of this method.
//
// This method returns a RequestState instance or an error immediately.
// Application can wait on the CompletedC member channel of the returned
// RequestState instance to get notified for the outcome of the proposal and
// access to the result of the proposal.
//
// After the proposal is completed, i.e. RequestResult is received from the
// CompletedC channel of the returned RequestState, unless NO-OP client session
// is used, it is caller's responsibility to update the Session instance
// accordingly based on the RequestResult.Code value. Basically, when
// RequestTimeout is returned, you can retry the same proposal without updating
// your client session instance, when a RequestRejected value is returned, it
// usually means the session instance has been evicted from the server side,
// the Raft paper recommends you to crash your client in this highly unlikely
// event. When the proposal completed successfully with a RequestCompleted
// value, application must call client.ProposalCompleted() to get the client
// session ready to be used in future proposals.
func (nh *NodeHost) Propose(session *client.Session, cmd []byte,
timeout time.Duration) (*RequestState, error) {
return nh.propose(session, cmd, nil, timeout)
}
// ProposeSession starts an asynchronous proposal on the specified cluster
// for client session related operations. Depending on the state of the specified
// client session object, the supported operations are for registering or
// unregistering a client session. Application can select on the CompletedC
// member channel of the returned RequestState instance to get notified for the
// outcome of the operation.
func (nh *NodeHost) ProposeSession(session *client.Session,
timeout time.Duration) (*RequestState, error) {
v, ok := nh.getCluster(session.ClusterID)
if !ok {
return nil, ErrClusterNotFound
}
if !v.supportClientSession() && !session.IsNoOPSession() {
plog.Panicf("IOnDiskStateMachine based nodes must use NoOPSession")
}
req, err := v.proposeSession(session, nil, timeout)
nh.execEngine.setNodeReady(session.ClusterID)
return req, err
}
// ReadIndex starts the asynchronous ReadIndex protocol used for linearizable
// read on the specified cluster. This method returns a RequestState instance
// or an error immediately. Application should wait on the CompletedC channel
// of the returned RequestState object to get notified on the outcome of the
// ReadIndex operation. On a successful completion, the ReadLocal method can
// then be invoked to query the state of the IStateMachine or
// IOnDiskStateMachine to complete the read operation with linearizability
// guarantee.
func (nh *NodeHost) ReadIndex(clusterID uint64,
timeout time.Duration) (*RequestState, error) {
rs, _, err := nh.readIndex(clusterID, nil, timeout)
return rs, err
}
// ReadLocalNode queries the Raft node identified by the input RequestState
// instance. To ensure the IO linearizability, ReadLocalNode should only be
// called after receiving a RequestCompleted notification from the ReadIndex
// method. See ReadIndex's example for more details.
func (nh *NodeHost) ReadLocalNode(rs *RequestState,
query interface{}) (interface{}, error) {
rs.mustBeReadyForLocalRead()
// translate the rsm.ErrClusterClosed to ErrClusterClosed
// internally, the IManagedStateMachine might obtain a RLock before performing
// the local read. The critical section is used to make sure we don't read
// from a destroyed C++ StateMachine object
data, err := rs.node.sm.Lookup(query)
if err == rsm.ErrClusterClosed {
return nil, ErrClusterClosed
}
return data, err
}
// NAReadLocalNode is a variant of ReadLocalNode, it uses byte slice as its
// input and output data for read only queries to minimize extra heap
// allocations caused by using interface{}. Users are recommended to use
// ReadLocalNode unless performance is the top priority.
//
// As an optional method, the underlying state machine must implement the
// statemachine.IExtended interface. NAReadLocalNode returns
// statemachine.ErrNotImplemented if the underlying state machine does not
// implement the statemachine.IExtended interface.
func (nh *NodeHost) NAReadLocalNode(rs *RequestState,
query []byte) ([]byte, error) {
rs.mustBeReadyForLocalRead()
data, err := rs.node.sm.NALookup(query)
if err == rsm.ErrClusterClosed {
return nil, ErrClusterClosed
}
return data, err
}
var staleReadCalled uint32
// StaleRead queries the specified Raft node directly without any
// linearizability guarantee.
//
// Users are recommended to use the SyncRead method or a combination of the
// ReadIndex and ReadLocalNode method to achieve linearizable read.
func (nh *NodeHost) StaleRead(clusterID uint64,
query interface{}) (interface{}, error) {
if atomic.CompareAndSwapUint32(&staleReadCalled, 0, 1) {
plog.Warningf("StaleRead called, linearizability not guaranteed for stale read")
}
v, ok := nh.getClusterNotLocked(clusterID)
if !ok {
return nil, ErrClusterNotFound
}
if !v.initialized() {
return nil, ErrClusterNotInitialized
}
data, err := v.sm.Lookup(query)
if err == rsm.ErrClusterClosed {
return nil, ErrClusterClosed
}
return data, err
}
// SyncRequestSnapshot is the synchronous variant of the RequestSnapshot
// method. See RequestSnapshot for more details.
//
// The input ctx must has deadline set.
//
// SyncRequestSnapshot returns the index of the created snapshot or the error
// encountered.
func (nh *NodeHost) SyncRequestSnapshot(ctx context.Context,
clusterID uint64, opt SnapshotOption) (uint64, error) {
timeout, err := getTimeoutFromContext(ctx)
if err != nil {
return 0, err
}
rs, err := nh.RequestSnapshot(clusterID, opt, timeout)
if err != nil {
return 0, err
}
select {
case r := <-rs.CompletedC:
if r.Completed() {
return r.GetResult().Value, nil
} else if r.Rejected() {
return 0, ErrRejected
} else if r.Timeout() {
return 0, ErrTimeout
} else if r.Terminated() {
return 0, ErrClusterClosed
}
plog.Panicf("unknown v code %v", r)
case <-ctx.Done():
if ctx.Err() == context.Canceled {
return 0, ErrCanceled
} else if ctx.Err() == context.DeadlineExceeded {
return 0, ErrTimeout
}
}
panic("unknown state")
}
// RequestSnapshot requests a snapshot to be created asynchronously for the
// specified cluster node. For each node, only one pending requested snapshot
// operation is allowed.
//
// Users can use an option parameter to specify details of the requested
// snapshot. For example, when the input SnapshotOption's Exported field is
// True, a snapshot will be exported to the directory pointed by the ExportPath
// field of the SnapshotOption instance. Such an exported snapshot is not
// managed by the system and it is mainly used to repair the cluster when it
// permanently lose its majority quorum. See the ImportSnapshot method in the
// tools package for more details.
//
// When the Exported field of the input SnapshotOption instance is set to false,
// snapshots created as the result of RequestSnapshot are managed by Dragonboat.
// Users are not suppose to move, copy, modify or delete the generated snapshot.
// Such requested snapshot will also trigger Raft log and snapshot compactions.
// Similar to automatic snapshots, when a snapshot is requested on a node backed
// by an IOnDiskStateMachine, only the metadata portion of the state machine
// will be captured and saved. Requesting snapshots on IOnDiskStateMachine based
// nodes are typically used to trigger Raft log and snapshot compactions.
//
// RequestSnapshot returns a RequestState instance or an error immediately.
// Applications can wait on the CompletedC member channel of the returned
// RequestState instance to get notified for the outcome of the create snasphot
// operation. The RequestResult instance returned by the CompletedC channel
// tells the outcome of the snapshot operation, when successful, the
// SnapshotIndex method of the returned RequestResult instance reports the index
// of the created snapshot.
//
// Requested snapshot operation will be rejected if there is already an existing
// snapshot in the system at the same Raft log index.
func (nh *NodeHost) RequestSnapshot(clusterID uint64,
opt SnapshotOption, timeout time.Duration) (*RequestState, error) {
v, ok := nh.getCluster(clusterID)
if !ok {
return nil, ErrClusterNotFound
}
req, err := v.requestSnapshot(opt, timeout)
nh.execEngine.setNodeReady(clusterID)
return req, err
}
// SyncRequestDeleteNode is the synchronous variant of the RequestDeleteNode
// method. See RequestDeleteNode for more details.
//
// The input ctx must have its deadline set.
func (nh *NodeHost) SyncRequestDeleteNode(ctx context.Context,
clusterID uint64, nodeID uint64, configChangeIndex uint64) error {
timeout, err := getTimeoutFromContext(ctx)
if err != nil {
return err
}
rs, err := nh.RequestDeleteNode(clusterID, nodeID, configChangeIndex, timeout)
if err != nil {
return err
}
_, err = checkRequestState(ctx, rs)
return err
}
// SyncRequestAddNode is the synchronous variant of the RequestAddNode method.
// See RequestAddNode for more details.
//
// The input ctx must have its deadline set.
func (nh *NodeHost) SyncRequestAddNode(ctx context.Context,
clusterID uint64, nodeID uint64,
address string, configChangeIndex uint64) error {
timeout, err := getTimeoutFromContext(ctx)
if err != nil {
return err
}
rs, err := nh.RequestAddNode(clusterID,
nodeID, address, configChangeIndex, timeout)
if err != nil {
return err
}
_, err = checkRequestState(ctx, rs)
return err
}
// SyncRequestAddObserver is the synchronous variant of the RequestAddObserver
// method. See RequestAddObserver for more details.
//
// The input ctx must have its deadline set.
func (nh *NodeHost) SyncRequestAddObserver(ctx context.Context,
clusterID uint64, nodeID uint64,
address string, configChangeIndex uint64) error {
timeout, err := getTimeoutFromContext(ctx)
if err != nil {
return err
}
rs, err := nh.RequestAddObserver(clusterID,
nodeID, address, configChangeIndex, timeout)
if err != nil {
return err
}
_, err = checkRequestState(ctx, rs)
return err
}
// RequestDeleteNode is a Raft cluster membership change method for requesting
// the specified node to be removed from the specified Raft cluster. It starts
// an asynchronous request to remove the node from the Raft cluster membership
// list. Application can wait on the CompletedC member of the returned
// RequestState instance to get notified for the outcome.
//
// It is not guaranteed that deleted node will automatically close itself and
// be removed from its managing NodeHost instance. It is application's
// responsibility to call RemoveCluster on the right NodeHost instance to
// actually have the cluster node removed from its managing NodeHost instance.
//
// Once a node is successfully deleted from a Raft cluster, it will not be
// allowed to be added back to the cluster with the same node identity.
//
// When the raft cluster is created with the OrderedConfigChange config flag
// set as false, the configChangeIndex parameter is ignored. Otherwise, it
// should be set to the most recent Config Change Index value returned by the
// SyncGetClusterMembership method. The requested delete node operation will be
// rejected if other membership change has been applied since the call to
// the SyncGetClusterMembership method.
func (nh *NodeHost) RequestDeleteNode(clusterID uint64,
nodeID uint64,
configChangeIndex uint64, timeout time.Duration) (*RequestState, error) {
v, ok := nh.getCluster(clusterID)
if !ok {
return nil, ErrClusterNotFound
}