-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathraft.go
193 lines (154 loc) · 3.67 KB
/
raft.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
package main
import (
"bytes"
"encoding/json"
"github.com/hashicorp/raft"
"github.com/hashicorp/raft-boltdb"
"io"
"math"
"net/http"
"os"
"path"
"time"
)
const (
applyRetries = 10
)
func (fsm *fsm) Apply(l *raft.Log) interface{} {
var a action
if err := json.Unmarshal(l.Data, &a); err != nil {
log.Error("could not unmarshal raft log: %v", err)
return err
}
fsm.handleAction(&a)
return nil
}
func (fsm *fsm) Snapshot() (raft.FSMSnapshot, error) {
return fsm, nil
}
func (fsm *fsm) Restore(data io.ReadCloser) error {
fsm.Lock()
defer fsm.Unlock()
defer data.Close()
d := json.NewDecoder(data)
if err := d.Decode(fsm); err != nil {
return err
}
return nil
}
func (fsm *fsm) Persist(sink raft.SnapshotSink) error {
fsm.Lock()
defer fsm.Unlock()
data, _ := json.Marshal(fsm)
_, err := sink.Write(data)
if err != nil {
sink.Cancel()
}
return err
}
func (fsm *fsm) Release() {}
type peer struct {
r *raft.Raft
dbStore *raftboltdb.BoltStore
trans *raft.NetworkTransport
peerStore *raft.JSONPeers
fsm *fsm
addr string
}
func newPeer(c *Config, fsm *fsm) (*peer, error) {
r := &peer{}
var err error = nil
r.addr = c.Raft.Addr
os.MkdirAll(c.Raft.DataDir, 0755)
cfg := raft.DefaultConfig()
raftDBPath := path.Join(c.Raft.DataDir, "raft_db")
r.dbStore, err = raftboltdb.NewBoltStore(raftDBPath)
if err != nil {
return nil, err
}
fileStore, err := raft.NewFileSnapshotStore(c.Raft.DataDir, 1, os.Stderr)
if err != nil {
return nil, err
}
r.trans, err = raft.NewTCPTransport(r.addr, nil, 3, 5*time.Second, os.Stderr)
if err != nil {
return nil, err
}
r.peerStore = raft.NewJSONPeers(c.Raft.DataDir, r.trans)
if c.Raft.ClusterState == ClusterStateNew {
log.Info("cluster state is new, use new cluster config")
r.peerStore.SetPeers(c.Raft.Cluster)
} else {
log.Info("cluster state is existing, use previous + new cluster config")
ps, err := r.peerStore.Peers()
if err != nil {
log.Error("get store peers error %v", err)
return nil, err
}
for _, peer := range c.Raft.Cluster {
ps = raft.AddUniquePeer(ps, peer)
}
r.peerStore.SetPeers(ps)
}
if peers, _ := r.peerStore.Peers(); len(peers) <= 1 {
cfg.EnableSingleNode = true
log.Notice("raft running in single node mode")
}
r.fsm = fsm
r.r, err = raft.NewRaft(cfg, fsm, r.dbStore, r.dbStore, fileStore, r.peerStore, r.trans)
if err != nil {
return nil, err
}
// watch for leadership changes
go func() {
for isLeader := range r.r.LeaderCh() {
if isLeader {
log.Info("new leader http: %v", c.Addr)
r.apply(&action{Cmd: CmdNewLeader, Leader: c.Addr}, applyRetries)
}
}
}()
return r, nil
}
func (r *peer) isLeader() bool {
addr := r.r.Leader()
return addr != "" && addr == r.addr
}
func (r *peer) apply(a *action, retries int) {
if retries == 0 {
log.Critical("too many retries trying to apply %v", a)
return
}
if retries < applyRetries {
sleep := time.Duration(math.Pow(float64((applyRetries-retries)*10), 2)) * time.Millisecond
log.Error("retrying %v after %v", a, sleep)
time.Sleep(sleep)
}
data, _ := json.Marshal(a)
if r.isLeader() {
r.r.Apply(data, 0)
} else {
resp, err := http.Post("http://"+r.fsm.leader+"/apply", "application/json", bytes.NewBuffer(data))
if err != nil {
log.Error(err.Error())
r.apply(a, retries-1)
} else if resp.StatusCode != 200 {
log.Error("http apply status not 200: %v", resp.StatusCode)
r.apply(a, retries-1)
}
}
}
func (r *peer) Close() {
if r.trans != nil {
r.trans.Close()
}
if r.r != nil {
future := r.r.Shutdown()
if err := future.Error(); err != nil {
log.Error("Error shutting down raft: %v", err)
}
}
if r.dbStore != nil {
r.dbStore.Close()
}
}