-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
112 lines (102 loc) · 2.47 KB
/
api.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
package raft
import (
"context"
"github.com/dzdx/raft/raftpb"
"time"
"github.com/dzdx/raft/util"
)
type RaftConfig struct {
Servers []string
LocalID string
MaxInflightingEntries int
MaxBatchAppendEntries int
MaxBatchApplyEntries int
ElectionTimeout time.Duration
SnapshotInterval time.Duration
SnapshotThreshold int
MaxReplicationBackoffTimeout time.Duration
CommitTimeout time.Duration
VerboseLog bool
}
func DefaultConfig(servers []string, localID string) RaftConfig {
return RaftConfig{
MaxInflightingEntries: 2048,
MaxBatchAppendEntries: 64,
MaxBatchApplyEntries: 64,
SnapshotInterval: 10 * time.Minute,
SnapshotThreshold: 2048,
ElectionTimeout: 300 * time.Millisecond,
CommitTimeout: 50 * time.Millisecond,
MaxReplicationBackoffTimeout: 3 * time.Second,
Servers: servers,
LocalID: localID,
VerboseLog: false,
}
}
func (r *RaftNode) Apply(ctx context.Context, data []byte) (interface{}, error) {
future := ApplyFuture{
Entry: &raftpb.LogEntry{
Data: data,
LogType: raftpb.LogEntry_LogCommand,
},
ctx: ctx,
}
future.init()
select {
case r.applyCh <- future:
case <-ctx.Done():
return nil, ctx.Err()
}
select {
case respWithError := <-future.Response():
return respWithError.Resp, respWithError.Err
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (r *RaftNode) GetLeader() string {
return r.leader
}
func (r *RaftNode) Snapshot() {
util.AsyncNotify(r.notifySnapshotCh)
}
func (r *RaftNode) AddVoter(ctx context.Context, serverID string) error {
future := ConfChangeFuture{
action: &raftpb.ConfChange{
Type: raftpb.ConfChange_AddNode,
ServerID: serverID,
},
}
future.init()
select {
case r.confChangeCh <- future:
case <-ctx.Done():
return ctx.Err()
}
select {
case respWithError := <-future.Response():
return respWithError.Err
case <-ctx.Done():
return ctx.Err()
}
}
func (r *RaftNode) RemoveNode(ctx context.Context, serverID string) error {
future := ConfChangeFuture{
action: &raftpb.ConfChange{
Type: raftpb.ConfChange_RemoveNode,
ServerID: serverID,
},
}
future.init()
select {
case r.confChangeCh <- future:
case <-ctx.Done():
return ctx.Err()
}
select {
case respWithError := <-future.Response():
return respWithError.Err
case <-ctx.Done():
return ctx.Err()
}
}