raft.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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/fileutil"
  25. "github.com/coreos/etcd/pkg/types"
  26. "github.com/coreos/etcd/raft"
  27. "github.com/coreos/etcd/raft/raftpb"
  28. "github.com/coreos/etcd/rafthttp"
  29. "github.com/coreos/etcd/snap"
  30. "github.com/coreos/etcd/wal"
  31. "github.com/coreos/etcd/wal/walpb"
  32. "golang.org/x/net/context"
  33. )
  34. // A key-value stream backed by raft
  35. type raftNode struct {
  36. proposeC <-chan string // proposed messages (k,v)
  37. confChangeC <-chan raftpb.ConfChange // proposed cluster config changes
  38. commitC chan<- *string // entries committed to log (k,v)
  39. errorC chan<- error // errors from raft session
  40. id int // client ID for raft session
  41. peers []string // raft peer URLs
  42. join bool // node is joining an existing cluster
  43. waldir string // path to WAL directory
  44. snapdir string // path to snapshot directory
  45. getSnapshot func() ([]byte, error)
  46. lastIndex uint64 // index of log at start
  47. confState raftpb.ConfState
  48. snapshotIndex uint64
  49. appliedIndex uint64
  50. // raft backing for the commit/error channel
  51. node raft.Node
  52. raftStorage *raft.MemoryStorage
  53. wal *wal.WAL
  54. snapshotter *snap.Snapshotter
  55. snapshotterReady chan *snap.Snapshotter // signals when snapshotter is ready
  56. snapCount uint64
  57. transport *rafthttp.Transport
  58. stopc chan struct{} // signals proposal channel closed
  59. httpstopc chan struct{} // signals http server to shutdown
  60. httpdonec chan struct{} // signals http server shutdown complete
  61. }
  62. var defaultSnapCount uint64 = 10000
  63. // newRaftNode initiates a raft instance and returns a committed log entry
  64. // channel and error channel. Proposals for log updates are sent over the
  65. // provided the proposal channel. All log entries are replayed over the
  66. // commit channel, followed by a nil message (to indicate the channel is
  67. // current), then new log entries. To shutdown, close proposeC and read errorC.
  68. func newRaftNode(id int, peers []string, join bool, getSnapshot func() ([]byte, error), proposeC <-chan string,
  69. confChangeC <-chan raftpb.ConfChange) (<-chan *string, <-chan error, <-chan *snap.Snapshotter) {
  70. commitC := make(chan *string)
  71. errorC := make(chan error)
  72. rc := &raftNode{
  73. proposeC: proposeC,
  74. confChangeC: confChangeC,
  75. commitC: commitC,
  76. errorC: errorC,
  77. id: id,
  78. peers: peers,
  79. join: join,
  80. waldir: fmt.Sprintf("raftexample-%d", id),
  81. snapdir: fmt.Sprintf("raftexample-%d-snap", id),
  82. getSnapshot: getSnapshot,
  83. snapCount: defaultSnapCount,
  84. stopc: make(chan struct{}),
  85. httpstopc: make(chan struct{}),
  86. httpdonec: make(chan struct{}),
  87. snapshotterReady: make(chan *snap.Snapshotter, 1),
  88. // rest of structure populated after WAL replay
  89. }
  90. go rc.startRaft()
  91. return commitC, errorC, rc.snapshotterReady
  92. }
  93. func (rc *raftNode) saveSnap(snap raftpb.Snapshot) error {
  94. if err := rc.snapshotter.SaveSnap(snap); err != nil {
  95. return err
  96. }
  97. walSnap := walpb.Snapshot{
  98. Index: snap.Metadata.Index,
  99. Term: snap.Metadata.Term,
  100. }
  101. if err := rc.wal.SaveSnapshot(walSnap); err != nil {
  102. return err
  103. }
  104. return rc.wal.ReleaseLockTo(snap.Metadata.Index)
  105. }
  106. func (rc *raftNode) entriesToApply(ents []raftpb.Entry) (nents []raftpb.Entry) {
  107. if len(ents) == 0 {
  108. return
  109. }
  110. firstIdx := ents[0].Index
  111. if firstIdx > rc.appliedIndex+1 {
  112. log.Fatalf("first index of committed entry[%d] should <= progress.appliedIndex[%d] 1", firstIdx, rc.appliedIndex)
  113. }
  114. if rc.appliedIndex-firstIdx+1 < uint64(len(ents)) {
  115. nents = ents[rc.appliedIndex-firstIdx+1:]
  116. }
  117. return
  118. }
  119. // publishEntries writes committed log entries to commit channel and returns
  120. // whether all entries could be published.
  121. func (rc *raftNode) publishEntries(ents []raftpb.Entry) bool {
  122. for i := range ents {
  123. switch ents[i].Type {
  124. case raftpb.EntryNormal:
  125. if len(ents[i].Data) == 0 {
  126. // ignore empty messages
  127. break
  128. }
  129. s := string(ents[i].Data)
  130. select {
  131. case rc.commitC <- &s:
  132. case <-rc.stopc:
  133. return false
  134. }
  135. case raftpb.EntryConfChange:
  136. var cc raftpb.ConfChange
  137. cc.Unmarshal(ents[i].Data)
  138. rc.confState = *rc.node.ApplyConfChange(cc)
  139. switch cc.Type {
  140. case raftpb.ConfChangeAddNode:
  141. if len(cc.Context) > 0 {
  142. rc.transport.AddPeer(types.ID(cc.NodeID), []string{string(cc.Context)})
  143. }
  144. case raftpb.ConfChangeRemoveNode:
  145. if cc.NodeID == uint64(rc.id) {
  146. log.Println("I've been removed from the cluster! Shutting down.")
  147. return false
  148. }
  149. rc.transport.RemovePeer(types.ID(cc.NodeID))
  150. }
  151. }
  152. // after commit, update appliedIndex
  153. rc.appliedIndex = ents[i].Index
  154. // special nil commit to signal replay has finished
  155. if ents[i].Index == rc.lastIndex {
  156. select {
  157. case rc.commitC <- nil:
  158. case <-rc.stopc:
  159. return false
  160. }
  161. }
  162. }
  163. return true
  164. }
  165. func (rc *raftNode) loadSnapshot() *raftpb.Snapshot {
  166. snapshot, err := rc.snapshotter.Load()
  167. if err != nil && err != snap.ErrNoSnapshot {
  168. log.Fatalf("raftexample: error loading snapshot (%v)", err)
  169. }
  170. return snapshot
  171. }
  172. // openWAL returns a WAL ready for reading.
  173. func (rc *raftNode) openWAL(snapshot *raftpb.Snapshot) *wal.WAL {
  174. if !wal.Exist(rc.waldir) {
  175. if err := os.Mkdir(rc.waldir, 0750); err != nil {
  176. log.Fatalf("raftexample: cannot create dir for wal (%v)", err)
  177. }
  178. w, err := wal.Create(rc.waldir, nil)
  179. if err != nil {
  180. log.Fatalf("raftexample: create wal error (%v)", err)
  181. }
  182. w.Close()
  183. }
  184. walsnap := walpb.Snapshot{}
  185. if snapshot != nil {
  186. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  187. }
  188. log.Printf("loading WAL at term %d and index %d", walsnap.Term, walsnap.Index)
  189. w, err := wal.Open(rc.waldir, walsnap)
  190. if err != nil {
  191. log.Fatalf("raftexample: error loading wal (%v)", err)
  192. }
  193. return w
  194. }
  195. // replayWAL replays WAL entries into the raft instance.
  196. func (rc *raftNode) replayWAL() *wal.WAL {
  197. log.Printf("replaying WAL of member %d", rc.id)
  198. snapshot := rc.loadSnapshot()
  199. w := rc.openWAL(snapshot)
  200. _, st, ents, err := w.ReadAll()
  201. if err != nil {
  202. log.Fatalf("raftexample: failed to read WAL (%v)", err)
  203. }
  204. rc.raftStorage = raft.NewMemoryStorage()
  205. if snapshot != nil {
  206. rc.raftStorage.ApplySnapshot(*snapshot)
  207. }
  208. rc.raftStorage.SetHardState(st)
  209. // append to storage so raft starts at the right place in log
  210. rc.raftStorage.Append(ents)
  211. // send nil once lastIndex is published so client knows commit channel is current
  212. if len(ents) > 0 {
  213. rc.lastIndex = ents[len(ents)-1].Index
  214. } else {
  215. rc.commitC <- nil
  216. }
  217. return w
  218. }
  219. func (rc *raftNode) writeError(err error) {
  220. rc.stopHTTP()
  221. close(rc.commitC)
  222. rc.errorC <- err
  223. close(rc.errorC)
  224. rc.node.Stop()
  225. }
  226. func (rc *raftNode) startRaft() {
  227. if !fileutil.Exist(rc.snapdir) {
  228. if err := os.Mkdir(rc.snapdir, 0750); err != nil {
  229. log.Fatalf("raftexample: cannot create dir for snapshot (%v)", err)
  230. }
  231. }
  232. rc.snapshotter = snap.New(rc.snapdir)
  233. rc.snapshotterReady <- rc.snapshotter
  234. oldwal := wal.Exist(rc.waldir)
  235. rc.wal = rc.replayWAL()
  236. rpeers := make([]raft.Peer, len(rc.peers))
  237. for i := range rpeers {
  238. rpeers[i] = raft.Peer{ID: uint64(i + 1)}
  239. }
  240. c := &raft.Config{
  241. ID: uint64(rc.id),
  242. ElectionTick: 10,
  243. HeartbeatTick: 1,
  244. Storage: rc.raftStorage,
  245. MaxSizePerMsg: 1024 * 1024,
  246. MaxInflightMsgs: 256,
  247. }
  248. if oldwal {
  249. rc.node = raft.RestartNode(c)
  250. } else {
  251. startPeers := rpeers
  252. if rc.join {
  253. startPeers = nil
  254. }
  255. rc.node = raft.StartNode(c, startPeers)
  256. }
  257. ss := &stats.ServerStats{}
  258. ss.Initialize()
  259. rc.transport = &rafthttp.Transport{
  260. ID: types.ID(rc.id),
  261. ClusterID: 0x1000,
  262. Raft: rc,
  263. ServerStats: ss,
  264. LeaderStats: stats.NewLeaderStats(strconv.Itoa(rc.id)),
  265. ErrorC: make(chan error),
  266. }
  267. rc.transport.Start()
  268. for i := range rc.peers {
  269. if i+1 != rc.id {
  270. rc.transport.AddPeer(types.ID(i+1), []string{rc.peers[i]})
  271. }
  272. }
  273. go rc.serveRaft()
  274. go rc.serveChannels()
  275. }
  276. // stop closes http, closes all channels, and stops raft.
  277. func (rc *raftNode) stop() {
  278. rc.stopHTTP()
  279. close(rc.commitC)
  280. close(rc.errorC)
  281. rc.node.Stop()
  282. }
  283. func (rc *raftNode) stopHTTP() {
  284. rc.transport.Stop()
  285. close(rc.httpstopc)
  286. <-rc.httpdonec
  287. }
  288. func (rc *raftNode) publishSnapshot(snapshotToSave raftpb.Snapshot) {
  289. if raft.IsEmptySnap(snapshotToSave) {
  290. return
  291. }
  292. log.Printf("publishing snapshot at index %d", rc.snapshotIndex)
  293. defer log.Printf("finished publishing snapshot at index %d", rc.snapshotIndex)
  294. if snapshotToSave.Metadata.Index <= rc.appliedIndex {
  295. log.Fatalf("snapshot index [%d] should > progress.appliedIndex [%d] + 1", snapshotToSave.Metadata.Index, rc.appliedIndex)
  296. }
  297. rc.commitC <- nil // trigger kvstore to load snapshot
  298. rc.confState = snapshotToSave.Metadata.ConfState
  299. rc.snapshotIndex = snapshotToSave.Metadata.Index
  300. rc.appliedIndex = snapshotToSave.Metadata.Index
  301. }
  302. var snapshotCatchUpEntriesN uint64 = 10000
  303. func (rc *raftNode) maybeTriggerSnapshot() {
  304. if rc.appliedIndex-rc.snapshotIndex <= rc.snapCount {
  305. return
  306. }
  307. log.Printf("start snapshot [applied index: %d | last snapshot index: %d]", rc.appliedIndex, rc.snapshotIndex)
  308. data, err := rc.getSnapshot()
  309. if err != nil {
  310. log.Panic(err)
  311. }
  312. snap, err := rc.raftStorage.CreateSnapshot(rc.appliedIndex, &rc.confState, data)
  313. if err != nil {
  314. panic(err)
  315. }
  316. if err := rc.saveSnap(snap); err != nil {
  317. panic(err)
  318. }
  319. compactIndex := uint64(1)
  320. if rc.appliedIndex > snapshotCatchUpEntriesN {
  321. compactIndex = rc.appliedIndex - snapshotCatchUpEntriesN
  322. }
  323. if err := rc.raftStorage.Compact(compactIndex); err != nil {
  324. panic(err)
  325. }
  326. log.Printf("compacted log at index %d", compactIndex)
  327. rc.snapshotIndex = rc.appliedIndex
  328. }
  329. func (rc *raftNode) serveChannels() {
  330. snap, err := rc.raftStorage.Snapshot()
  331. if err != nil {
  332. panic(err)
  333. }
  334. rc.confState = snap.Metadata.ConfState
  335. rc.snapshotIndex = snap.Metadata.Index
  336. rc.appliedIndex = snap.Metadata.Index
  337. defer rc.wal.Close()
  338. ticker := time.NewTicker(100 * time.Millisecond)
  339. defer ticker.Stop()
  340. // send proposals over raft
  341. go func() {
  342. var confChangeCount uint64 = 0
  343. for rc.proposeC != nil && rc.confChangeC != nil {
  344. select {
  345. case prop, ok := <-rc.proposeC:
  346. if !ok {
  347. rc.proposeC = nil
  348. } else {
  349. // blocks until accepted by raft state machine
  350. rc.node.Propose(context.TODO(), []byte(prop))
  351. }
  352. case cc, ok := <-rc.confChangeC:
  353. if !ok {
  354. rc.confChangeC = nil
  355. } else {
  356. confChangeCount += 1
  357. cc.ID = confChangeCount
  358. rc.node.ProposeConfChange(context.TODO(), cc)
  359. }
  360. }
  361. }
  362. // client closed channel; shutdown raft if not already
  363. close(rc.stopc)
  364. }()
  365. // event loop on raft state machine updates
  366. for {
  367. select {
  368. case <-ticker.C:
  369. rc.node.Tick()
  370. // store raft entries to wal, then publish over commit channel
  371. case rd := <-rc.node.Ready():
  372. rc.wal.Save(rd.HardState, rd.Entries)
  373. if !raft.IsEmptySnap(rd.Snapshot) {
  374. rc.saveSnap(rd.Snapshot)
  375. rc.raftStorage.ApplySnapshot(rd.Snapshot)
  376. rc.publishSnapshot(rd.Snapshot)
  377. }
  378. rc.raftStorage.Append(rd.Entries)
  379. rc.transport.Send(rd.Messages)
  380. if ok := rc.publishEntries(rc.entriesToApply(rd.CommittedEntries)); !ok {
  381. rc.stop()
  382. return
  383. }
  384. rc.maybeTriggerSnapshot()
  385. rc.node.Advance()
  386. case err := <-rc.transport.ErrorC:
  387. rc.writeError(err)
  388. return
  389. case <-rc.stopc:
  390. rc.stop()
  391. return
  392. }
  393. }
  394. }
  395. func (rc *raftNode) serveRaft() {
  396. url, err := url.Parse(rc.peers[rc.id-1])
  397. if err != nil {
  398. log.Fatalf("raftexample: Failed parsing URL (%v)", err)
  399. }
  400. ln, err := newStoppableListener(url.Host, rc.httpstopc)
  401. if err != nil {
  402. log.Fatalf("raftexample: Failed to listen rafthttp (%v)", err)
  403. }
  404. err = (&http.Server{Handler: rc.transport.Handler()}).Serve(ln)
  405. select {
  406. case <-rc.httpstopc:
  407. default:
  408. log.Fatalf("raftexample: Failed to serve rafthttp (%v)", err)
  409. }
  410. close(rc.httpdonec)
  411. }
  412. func (rc *raftNode) Process(ctx context.Context, m raftpb.Message) error {
  413. return rc.node.Step(ctx, m)
  414. }
  415. func (rc *raftNode) IsIDRemoved(id uint64) bool { return false }
  416. func (rc *raftNode) ReportUnreachable(id uint64) {}
  417. func (rc *raftNode) ReportSnapshot(id uint64, status raft.SnapshotStatus) {}