raft.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. // Copyright 2015 The etcd Authors
  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. commitC := make(chan *string)
  60. errorC := make(chan error)
  61. rc := &raftNode{
  62. proposeC: proposeC,
  63. confChangeC: confChangeC,
  64. commitC: commitC,
  65. errorC: errorC,
  66. id: id,
  67. peers: peers,
  68. join: join,
  69. waldir: fmt.Sprintf("raftexample-%d", id),
  70. raftStorage: raft.NewMemoryStorage(),
  71. stopc: make(chan struct{}),
  72. httpstopc: make(chan struct{}),
  73. httpdonec: make(chan struct{}),
  74. // rest of structure populated after WAL replay
  75. }
  76. go rc.startRaft()
  77. return commitC, errorC
  78. }
  79. // publishEntries writes committed log entries to commit channel and returns
  80. // whether all entries could be published.
  81. func (rc *raftNode) publishEntries(ents []raftpb.Entry) bool {
  82. for i := range ents {
  83. switch ents[i].Type {
  84. case raftpb.EntryNormal:
  85. if len(ents[i].Data) == 0 {
  86. // ignore empty messages
  87. break
  88. }
  89. s := string(ents[i].Data)
  90. select {
  91. case rc.commitC <- &s:
  92. case <-rc.stopc:
  93. return false
  94. }
  95. case raftpb.EntryConfChange:
  96. var cc raftpb.ConfChange
  97. cc.Unmarshal(ents[i].Data)
  98. rc.node.ApplyConfChange(cc)
  99. switch cc.Type {
  100. case raftpb.ConfChangeAddNode:
  101. if len(cc.Context) > 0 {
  102. rc.transport.AddPeer(types.ID(cc.NodeID), []string{string(cc.Context)})
  103. }
  104. case raftpb.ConfChangeRemoveNode:
  105. if cc.NodeID == uint64(rc.id) {
  106. log.Println("I've been removed from the cluster! Shutting down.")
  107. return false
  108. }
  109. rc.transport.RemovePeer(types.ID(cc.NodeID))
  110. }
  111. }
  112. // special nil commit to signal replay has finished
  113. if ents[i].Index == rc.lastIndex {
  114. select {
  115. case rc.commitC <- nil:
  116. case <-rc.stopc:
  117. return false
  118. }
  119. }
  120. }
  121. return true
  122. }
  123. // openWAL returns a WAL ready for reading.
  124. func (rc *raftNode) openWAL() *wal.WAL {
  125. if !wal.Exist(rc.waldir) {
  126. if err := os.Mkdir(rc.waldir, 0750); err != nil {
  127. log.Fatalf("raftexample: cannot create dir for wal (%v)", err)
  128. }
  129. w, err := wal.Create(rc.waldir, nil)
  130. if err != nil {
  131. log.Fatalf("raftexample: create wal error (%v)", err)
  132. }
  133. w.Close()
  134. }
  135. w, err := wal.Open(rc.waldir, walpb.Snapshot{})
  136. if err != nil {
  137. log.Fatalf("raftexample: error loading wal (%v)", err)
  138. }
  139. return w
  140. }
  141. // replayWAL replays WAL entries into the raft instance.
  142. func (rc *raftNode) replayWAL() *wal.WAL {
  143. w := rc.openWAL()
  144. _, st, ents, err := w.ReadAll()
  145. if err != nil {
  146. log.Fatalf("raftexample: failed to read WAL (%v)", err)
  147. }
  148. // append to storage so raft starts at the right place in log
  149. rc.raftStorage.Append(ents)
  150. // send nil once lastIndex is published so client knows commit channel is current
  151. if len(ents) > 0 {
  152. rc.lastIndex = ents[len(ents)-1].Index
  153. } else {
  154. rc.commitC <- nil
  155. }
  156. rc.raftStorage.SetHardState(st)
  157. return w
  158. }
  159. func (rc *raftNode) writeError(err error) {
  160. rc.stopHTTP()
  161. close(rc.commitC)
  162. rc.errorC <- err
  163. close(rc.errorC)
  164. rc.node.Stop()
  165. }
  166. func (rc *raftNode) startRaft() {
  167. oldwal := wal.Exist(rc.waldir)
  168. rc.wal = rc.replayWAL()
  169. rpeers := make([]raft.Peer, len(rc.peers))
  170. for i := range rpeers {
  171. rpeers[i] = raft.Peer{ID: uint64(i + 1)}
  172. }
  173. c := &raft.Config{
  174. ID: uint64(rc.id),
  175. ElectionTick: 10,
  176. HeartbeatTick: 1,
  177. Storage: rc.raftStorage,
  178. MaxSizePerMsg: 1024 * 1024,
  179. MaxInflightMsgs: 256,
  180. }
  181. if oldwal {
  182. rc.node = raft.RestartNode(c)
  183. } else {
  184. startPeers := rpeers
  185. if rc.join {
  186. startPeers = nil
  187. }
  188. rc.node = raft.StartNode(c, startPeers)
  189. }
  190. ss := &stats.ServerStats{}
  191. ss.Initialize()
  192. rc.transport = &rafthttp.Transport{
  193. ID: types.ID(rc.id),
  194. ClusterID: 0x1000,
  195. Raft: rc,
  196. ServerStats: ss,
  197. LeaderStats: stats.NewLeaderStats(strconv.Itoa(rc.id)),
  198. ErrorC: make(chan error),
  199. }
  200. rc.transport.Start()
  201. for i := range rc.peers {
  202. if i+1 != rc.id {
  203. rc.transport.AddPeer(types.ID(i+1), []string{rc.peers[i]})
  204. }
  205. }
  206. go rc.serveRaft()
  207. go rc.serveChannels()
  208. }
  209. // stop closes http, closes all channels, and stops raft.
  210. func (rc *raftNode) stop() {
  211. rc.stopHTTP()
  212. close(rc.commitC)
  213. close(rc.errorC)
  214. rc.node.Stop()
  215. }
  216. func (rc *raftNode) stopHTTP() {
  217. rc.transport.Stop()
  218. close(rc.httpstopc)
  219. <-rc.httpdonec
  220. }
  221. func (rc *raftNode) serveChannels() {
  222. defer rc.wal.Close()
  223. ticker := time.NewTicker(100 * time.Millisecond)
  224. defer ticker.Stop()
  225. // send proposals over raft
  226. go func() {
  227. var confChangeCount uint64 = 0
  228. for rc.proposeC != nil && rc.confChangeC != nil {
  229. select {
  230. case prop, ok := <-rc.proposeC:
  231. if !ok {
  232. rc.proposeC = nil
  233. } else {
  234. // blocks until accepted by raft state machine
  235. rc.node.Propose(context.TODO(), []byte(prop))
  236. }
  237. case cc, ok := <-rc.confChangeC:
  238. if !ok {
  239. rc.confChangeC = nil
  240. } else {
  241. confChangeCount += 1
  242. cc.ID = confChangeCount
  243. rc.node.ProposeConfChange(context.TODO(), cc)
  244. }
  245. }
  246. }
  247. // client closed channel; shutdown raft if not already
  248. close(rc.stopc)
  249. }()
  250. // event loop on raft state machine updates
  251. for {
  252. select {
  253. case <-ticker.C:
  254. rc.node.Tick()
  255. // store raft entries to wal, then publish over commit channel
  256. case rd := <-rc.node.Ready():
  257. rc.wal.Save(rd.HardState, rd.Entries)
  258. rc.raftStorage.Append(rd.Entries)
  259. rc.transport.Send(rd.Messages)
  260. if ok := rc.publishEntries(rd.CommittedEntries); !ok {
  261. rc.stop()
  262. return
  263. }
  264. rc.node.Advance()
  265. case err := <-rc.transport.ErrorC:
  266. rc.writeError(err)
  267. return
  268. case <-rc.stopc:
  269. rc.stop()
  270. return
  271. }
  272. }
  273. }
  274. func (rc *raftNode) serveRaft() {
  275. url, err := url.Parse(rc.peers[rc.id-1])
  276. if err != nil {
  277. log.Fatalf("raftexample: Failed parsing URL (%v)", err)
  278. }
  279. ln, err := newStoppableListener(url.Host, rc.httpstopc)
  280. if err != nil {
  281. log.Fatalf("raftexample: Failed to listen rafthttp (%v)", err)
  282. }
  283. err = (&http.Server{Handler: rc.transport.Handler()}).Serve(ln)
  284. select {
  285. case <-rc.httpstopc:
  286. default:
  287. log.Fatalf("raftexample: Failed to serve rafthttp (%v)", err)
  288. }
  289. close(rc.httpdonec)
  290. }
  291. func (rc *raftNode) Process(ctx context.Context, m raftpb.Message) error {
  292. return rc.node.Step(ctx, m)
  293. }
  294. func (rc *raftNode) IsIDRemoved(id uint64) bool { return false }
  295. func (rc *raftNode) ReportUnreachable(id uint64) {}
  296. func (rc *raftNode) ReportSnapshot(id uint64, status raft.SnapshotStatus) {}