raft.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "fmt"
  17. "log"
  18. "os"
  19. "strconv"
  20. "time"
  21. "net/http"
  22. "net/url"
  23. "github.com/coreos/etcd/etcdserver/stats"
  24. "github.com/coreos/etcd/pkg/types"
  25. "github.com/coreos/etcd/raft"
  26. "github.com/coreos/etcd/raft/raftpb"
  27. "github.com/coreos/etcd/rafthttp"
  28. "github.com/coreos/etcd/wal"
  29. "github.com/coreos/etcd/wal/walpb"
  30. "golang.org/x/net/context"
  31. )
  32. // A key-value stream backed by raft
  33. type raftNode struct {
  34. proposeC <-chan string // proposed messages (k,v)
  35. confChangeC <-chan raftpb.ConfChange // proposed cluster config changes
  36. commitC chan *string // entries committed to log (k,v)
  37. errorC chan error // errors from raft session
  38. id int // client ID for raft session
  39. peers []string // raft peer URLs
  40. join bool // node is joining an existing cluster
  41. waldir string // path to WAL directory
  42. lastIndex uint64 // index of log at start
  43. // raft backing for the commit/error channel
  44. node raft.Node
  45. raftStorage *raft.MemoryStorage
  46. wal *wal.WAL
  47. transport *rafthttp.Transport
  48. stopc chan struct{} // signals proposal channel closed
  49. httpstopc chan struct{} // signals http server to shutdown
  50. httpdonec chan struct{} // signals http server shutdown complete
  51. }
  52. // newRaftNode initiates a raft instance and returns a committed log entry
  53. // channel and error channel. Proposals for log updates are sent over the
  54. // provided the proposal channel. All log entries are replayed over the
  55. // commit channel, followed by a nil message (to indicate the channel is
  56. // current), then new log entries. To shutdown, close proposeC and read errorC.
  57. func newRaftNode(id int, peers []string, join bool, proposeC <-chan string,
  58. confChangeC <-chan raftpb.ConfChange) (<-chan *string, <-chan error) {
  59. rc := &raftNode{
  60. proposeC: proposeC,
  61. confChangeC: confChangeC,
  62. commitC: make(chan *string),
  63. errorC: make(chan error),
  64. id: id,
  65. peers: peers,
  66. join: join,
  67. waldir: fmt.Sprintf("raftexample-%d", id),
  68. raftStorage: raft.NewMemoryStorage(),
  69. stopc: make(chan struct{}),
  70. httpstopc: make(chan struct{}),
  71. httpdonec: make(chan struct{}),
  72. // rest of structure populated after WAL replay
  73. }
  74. go rc.startRaft()
  75. return rc.commitC, rc.errorC
  76. }
  77. // publishEntries writes committed log entries to commit channel and returns
  78. // whether all entries could be published.
  79. func (rc *raftNode) publishEntries(ents []raftpb.Entry) bool {
  80. for i := range ents {
  81. switch ents[i].Type {
  82. case raftpb.EntryNormal:
  83. if len(ents[i].Data) == 0 {
  84. // ignore empty messages
  85. break
  86. }
  87. s := string(ents[i].Data)
  88. select {
  89. case rc.commitC <- &s:
  90. case <-rc.stopc:
  91. return false
  92. }
  93. case raftpb.EntryConfChange:
  94. var cc raftpb.ConfChange
  95. cc.Unmarshal(ents[i].Data)
  96. rc.node.ApplyConfChange(cc)
  97. switch cc.Type {
  98. case raftpb.ConfChangeAddNode:
  99. if len(cc.Context) > 0 {
  100. rc.transport.AddPeer(types.ID(cc.NodeID), []string{string(cc.Context)})
  101. }
  102. case raftpb.ConfChangeRemoveNode:
  103. if cc.NodeID == uint64(rc.id) {
  104. log.Println("I've been removed from the cluster! Shutting down.")
  105. return false
  106. }
  107. rc.transport.RemovePeer(types.ID(cc.NodeID))
  108. }
  109. }
  110. // special nil commit to signal replay has finished
  111. if ents[i].Index == rc.lastIndex {
  112. select {
  113. case rc.commitC <- nil:
  114. case <-rc.stopc:
  115. return false
  116. }
  117. }
  118. }
  119. return true
  120. }
  121. // openWAL returns a WAL ready for reading.
  122. func (rc *raftNode) openWAL() *wal.WAL {
  123. if wal.Exist(rc.waldir) == false {
  124. if err := os.Mkdir(rc.waldir, 0750); err != nil {
  125. log.Fatalf("raftexample: cannot create dir for wal (%v)", err)
  126. }
  127. w, err := wal.Create(rc.waldir, nil)
  128. if err != nil {
  129. log.Fatalf("raftexample: create wal error (%v)", err)
  130. }
  131. w.Close()
  132. }
  133. w, err := wal.Open(rc.waldir, walpb.Snapshot{})
  134. if err != nil {
  135. log.Fatalf("raftexample: error loading wal (%v)", err)
  136. }
  137. return w
  138. }
  139. // replayWAL replays WAL entries into the raft instance.
  140. func (rc *raftNode) replayWAL() *wal.WAL {
  141. w := rc.openWAL()
  142. _, st, ents, err := w.ReadAll()
  143. if err != nil {
  144. log.Fatalf("raftexample: failed to read WAL (%v)", err)
  145. }
  146. // append to storage so raft starts at the right place in log
  147. rc.raftStorage.Append(ents)
  148. // send nil once lastIndex is published so client knows commit channel is current
  149. if len(ents) > 0 {
  150. rc.lastIndex = ents[len(ents)-1].Index
  151. } else {
  152. rc.commitC <- nil
  153. }
  154. rc.raftStorage.SetHardState(st)
  155. return w
  156. }
  157. func (rc *raftNode) writeError(err error) {
  158. rc.stopHTTP()
  159. close(rc.commitC)
  160. rc.errorC <- err
  161. close(rc.errorC)
  162. rc.node.Stop()
  163. }
  164. func (rc *raftNode) startRaft() {
  165. oldwal := wal.Exist(rc.waldir)
  166. rc.wal = rc.replayWAL()
  167. rpeers := make([]raft.Peer, len(rc.peers))
  168. for i := range rpeers {
  169. rpeers[i] = raft.Peer{ID: uint64(i + 1)}
  170. }
  171. c := &raft.Config{
  172. ID: uint64(rc.id),
  173. ElectionTick: 10,
  174. HeartbeatTick: 1,
  175. Storage: rc.raftStorage,
  176. MaxSizePerMsg: 1024 * 1024,
  177. MaxInflightMsgs: 256,
  178. }
  179. if oldwal {
  180. rc.node = raft.RestartNode(c)
  181. } else {
  182. startPeers := rpeers
  183. if rc.join {
  184. startPeers = nil
  185. }
  186. rc.node = raft.StartNode(c, startPeers)
  187. }
  188. ss := &stats.ServerStats{}
  189. ss.Initialize()
  190. rc.transport = &rafthttp.Transport{
  191. ID: types.ID(rc.id),
  192. ClusterID: 0x1000,
  193. Raft: rc,
  194. ServerStats: ss,
  195. LeaderStats: stats.NewLeaderStats(strconv.Itoa(rc.id)),
  196. ErrorC: make(chan error),
  197. }
  198. rc.transport.Start()
  199. for i := range rc.peers {
  200. if i+1 != rc.id {
  201. rc.transport.AddPeer(types.ID(i+1), []string{rc.peers[i]})
  202. }
  203. }
  204. go rc.serveRaft()
  205. go rc.serveChannels()
  206. }
  207. // stop closes http, closes all channels, and stops raft.
  208. func (rc *raftNode) stop() {
  209. rc.stopHTTP()
  210. close(rc.commitC)
  211. close(rc.errorC)
  212. rc.node.Stop()
  213. }
  214. func (rc *raftNode) stopHTTP() {
  215. rc.transport.Stop()
  216. close(rc.httpstopc)
  217. <-rc.httpdonec
  218. }
  219. func (rc *raftNode) serveChannels() {
  220. defer rc.wal.Close()
  221. ticker := time.NewTicker(100 * time.Millisecond)
  222. defer ticker.Stop()
  223. // send proposals over raft
  224. go func() {
  225. var confChangeCount uint64 = 0
  226. for rc.proposeC != nil && rc.confChangeC != nil {
  227. select {
  228. case prop, ok := <-rc.proposeC:
  229. if !ok {
  230. rc.proposeC = nil
  231. } else {
  232. // blocks until accepted by raft state machine
  233. rc.node.Propose(context.TODO(), []byte(prop))
  234. }
  235. case cc, ok := <-rc.confChangeC:
  236. if !ok {
  237. rc.confChangeC = nil
  238. } else {
  239. confChangeCount += 1
  240. cc.ID = confChangeCount
  241. rc.node.ProposeConfChange(context.TODO(), cc)
  242. }
  243. }
  244. }
  245. // client closed channel; shutdown raft if not already
  246. close(rc.stopc)
  247. }()
  248. // event loop on raft state machine updates
  249. for {
  250. select {
  251. case <-ticker.C:
  252. rc.node.Tick()
  253. // store raft entries to wal, then publish over commit channel
  254. case rd := <-rc.node.Ready():
  255. rc.wal.Save(rd.HardState, rd.Entries)
  256. rc.raftStorage.Append(rd.Entries)
  257. rc.transport.Send(rd.Messages)
  258. if ok := rc.publishEntries(rd.CommittedEntries); !ok {
  259. rc.stop()
  260. return
  261. }
  262. rc.node.Advance()
  263. case err := <-rc.transport.ErrorC:
  264. rc.writeError(err)
  265. return
  266. case <-rc.stopc:
  267. rc.stop()
  268. return
  269. }
  270. }
  271. }
  272. func (rc *raftNode) serveRaft() {
  273. url, err := url.Parse(rc.peers[rc.id-1])
  274. if err != nil {
  275. log.Fatalf("raftexample: Failed parsing URL (%v)", err)
  276. }
  277. ln, err := newStoppableListener(url.Host, rc.httpstopc)
  278. if err != nil {
  279. log.Fatalf("raftexample: Failed to listen rafthttp (%v)", err)
  280. }
  281. err = (&http.Server{Handler: rc.transport.Handler()}).Serve(ln)
  282. select {
  283. case <-rc.httpstopc:
  284. default:
  285. log.Fatalf("raftexample: Failed to serve rafthttp (%v)", err)
  286. }
  287. close(rc.httpdonec)
  288. }
  289. func (rc *raftNode) Process(ctx context.Context, m raftpb.Message) error {
  290. return rc.node.Step(ctx, m)
  291. }
  292. func (rc *raftNode) IsIDRemoved(id uint64) bool { return false }
  293. func (rc *raftNode) ReportUnreachable(id uint64) {}
  294. func (rc *raftNode) ReportSnapshot(id uint64, status raft.SnapshotStatus) {}