/
rift.go
194 lines (167 loc) · 4.63 KB
/
rift.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
package main
import (
"bytes"
"fmt"
"log"
"math"
"strings"
"time"
"github.com/coreos/etcd/raft"
"github.com/coreos/etcd/raft/raftpb"
"golang.org/x/net/context"
)
const hb = 1
type node struct {
id int
store *raft.MemoryStorage
pstore map[string]string
ctx context.Context
ctxCancel context.CancelFunc
cfg *raft.Config
node raft.Node
ticker <-chan time.Time
done <-chan struct{}
}
func newNode(id int, peers []raft.Peer) *node {
n := &node{}
ctx, cancel := context.WithCancel(context.Background())
n.ctx = ctx
n.ctxCancel = cancel
n.store = raft.NewMemoryStorage()
n.cfg = &raft.Config{
ID: uint64(id),
ElectionTick: 10 * hb,
HeartbeatTick: hb,
Storage: n.store,
MaxSizePerMsg: math.MaxUint16,
MaxInflightMsgs: 256,
}
n.pstore = make(map[string]string)
n.id = id
n.node = raft.StartNode(n.cfg, peers)
return n
}
func (n *node) run() {
n.ticker = time.Tick(time.Second)
for {
select {
case <-n.ticker:
n.node.Tick()
case rd := <-n.node.Ready():
n.saveToStorage(rd, rd.Entries, rd.Snapshot)
n.send(rd.Messages)
if !raft.IsEmptySnap(rd.Snapshot) {
n.processSnapshot(rd.Snapshot)
}
for _, entry := range rd.CommittedEntries {
n.process(entry)
if entry.Type == raftpb.EntryConfChange {
var cc raftpb.ConfChange
cc.Unmarshal(entry.Data)
n.node.ApplyConfChange(cc)
}
}
n.node.Advance()
case <-n.done:
return
}
}
}
func (n *node) saveToStorage(rd raft.Ready, entries []raftpb.Entry, snapshot raftpb.Snapshot) {
fmt.Println("Storing entries, node =", n.id)
n.store.Append(entries)
if !raft.IsEmptyHardState(rd.HardState) {
fmt.Println("Setting hard state, node =", n.id)
n.store.SetHardState(rd.HardState)
}
if !raft.IsEmptySnap(snapshot) {
fmt.Println("Applying snapshot, node =", n.id)
n.store.ApplySnapshot(snapshot)
}
}
func (n *node) send(messages []raftpb.Message) {
fmt.Println("*** Messages from NODE ", n.id, "***")
fmt.Println("Count:", len(messages))
for _, m := range messages {
fmt.Println(raft.DescribeMessage(m, nil))
// send message to other node
nodes[int(m.To)].receive(n.ctx, m)
}
fmt.Println("***************")
}
func (n *node) processSnapshot(snapshot raftpb.Snapshot) {
fmt.Println("Applying snapshot on", n.id, ":", snapshot)
n.store.ApplySnapshot(snapshot)
}
func (n *node) process(entry raftpb.Entry) {
fmt.Println("processing entry on ", n.id, ":", entry)
if entry.Type == raftpb.EntryNormal && entry.Data != nil {
fmt.Println("normal message:", string(entry.Data))
parts := bytes.SplitN(entry.Data, []byte(":"), 2)
fmt.Println(string(parts[0]), " = ", string(parts[1]))
n.pstore[string(parts[0])] = string(parts[1])
}
}
func (n *node) receive(ctx context.Context, message raftpb.Message) {
fmt.Println("Received message, node =", n.id)
n.node.Step(ctx, message)
}
var (
nodes = make(map[int]*node)
)
func main() {
// start a small cluster
nodes[1] = newNode(1, []raft.Peer{{ID: 1}, {ID: 2}, {ID: 3}})
nodes[1].node.Campaign(nodes[1].ctx)
go nodes[1].run()
nodes[2] = newNode(2, []raft.Peer{{ID: 1}, {ID: 2}, {ID: 3}})
go nodes[2].run()
nodes[3] = newNode(3, []raft.Peer{{ID: 1}, {ID: 2}, {ID: 3}})
go nodes[3].run()
// Wait for leader, is there a better way to do this
for nodes[1].node.Status().Lead != 1 {
time.Sleep(100 * time.Millisecond)
}
err := nodes[1].node.Propose(nodes[2].ctx, []byte("mykey1:myvalue1"))
err = nodes[2].node.Propose(nodes[2].ctx, []byte("mykey2:myvalue2"))
err = nodes[3].node.Propose(nodes[2].ctx, []byte("mykey3:myvalue3"))
if err != nil {
log.Fatal(err)
}
// Wait for proposed entry to be commited in cluster
// Probably a better way to check this
time.Sleep(100 * time.Millisecond)
// Just check that data has been persited
fmt.Println(strings.Repeat("#", 20))
for i, node := range nodes {
fmt.Println("Node", i)
for k, v := range node.pstore {
fmt.Println(k, " = ", v)
}
fmt.Println("")
}
fmt.Println(strings.Repeat("#", 20))
// Add a new node to the cluster
nodes[4] = newNode(4, []raft.Peer{})
go nodes[4].run()
nodes[2].node.ProposeConfChange(nodes[2].ctx, raftpb.ConfChange{
ID: 3,
Type: raftpb.ConfChangeAddNode,
NodeID: 4,
Context: []byte(""),
})
// write throug the new node
err = nodes[4].node.Propose(nodes[2].ctx, []byte("mykey4:myvalue4"))
time.Sleep(100 * time.Millisecond)
// Check that cluster has been synced
time.Sleep(2 * time.Second)
fmt.Println(strings.Repeat("#", 20))
for i, node := range nodes {
fmt.Println("Node", i)
for k, v := range node.pstore {
fmt.Println(k, " = ", v)
}
fmt.Println("")
}
fmt.Println(strings.Repeat("#", 20))
}