node.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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 raft
  15. import (
  16. "context"
  17. "errors"
  18. pb "go.etcd.io/etcd/raft/raftpb"
  19. )
  20. type SnapshotStatus int
  21. const (
  22. SnapshotFinish SnapshotStatus = 1
  23. SnapshotFailure SnapshotStatus = 2
  24. )
  25. var (
  26. emptyState = pb.HardState{}
  27. // ErrStopped is returned by methods on Nodes that have been stopped.
  28. ErrStopped = errors.New("raft: stopped")
  29. )
  30. // SoftState provides state that is useful for logging and debugging.
  31. // The state is volatile and does not need to be persisted to the WAL.
  32. type SoftState struct {
  33. Lead uint64 // must use atomic operations to access; keep 64-bit aligned.
  34. RaftState StateType
  35. }
  36. func (a *SoftState) equal(b *SoftState) bool {
  37. return a.Lead == b.Lead && a.RaftState == b.RaftState
  38. }
  39. // Ready encapsulates the entries and messages that are ready to read,
  40. // be saved to stable storage, committed or sent to other peers.
  41. // All fields in Ready are read-only.
  42. type Ready struct {
  43. // The current volatile state of a Node.
  44. // SoftState will be nil if there is no update.
  45. // It is not required to consume or store SoftState.
  46. *SoftState
  47. // The current state of a Node to be saved to stable storage BEFORE
  48. // Messages are sent.
  49. // HardState will be equal to empty state if there is no update.
  50. pb.HardState
  51. // ReadStates can be used for node to serve linearizable read requests locally
  52. // when its applied index is greater than the index in ReadState.
  53. // Note that the readState will be returned when raft receives msgReadIndex.
  54. // The returned is only valid for the request that requested to read.
  55. ReadStates []ReadState
  56. // Entries specifies entries to be saved to stable storage BEFORE
  57. // Messages are sent.
  58. Entries []pb.Entry
  59. // Snapshot specifies the snapshot to be saved to stable storage.
  60. Snapshot pb.Snapshot
  61. // CommittedEntries specifies entries to be committed to a
  62. // store/state-machine. These have previously been committed to stable
  63. // store.
  64. CommittedEntries []pb.Entry
  65. // Messages specifies outbound messages to be sent AFTER Entries are
  66. // committed to stable storage.
  67. // If it contains a MsgSnap message, the application MUST report back to raft
  68. // when the snapshot has been received or has failed by calling ReportSnapshot.
  69. Messages []pb.Message
  70. // MustSync indicates whether the HardState and Entries must be synchronously
  71. // written to disk or if an asynchronous write is permissible.
  72. MustSync bool
  73. }
  74. func isHardStateEqual(a, b pb.HardState) bool {
  75. return a.Term == b.Term && a.Vote == b.Vote && a.Commit == b.Commit
  76. }
  77. // IsEmptyHardState returns true if the given HardState is empty.
  78. func IsEmptyHardState(st pb.HardState) bool {
  79. return isHardStateEqual(st, emptyState)
  80. }
  81. // IsEmptySnap returns true if the given Snapshot is empty.
  82. func IsEmptySnap(sp pb.Snapshot) bool {
  83. return sp.Metadata.Index == 0
  84. }
  85. func (rd Ready) containsUpdates() bool {
  86. return rd.SoftState != nil || !IsEmptyHardState(rd.HardState) ||
  87. !IsEmptySnap(rd.Snapshot) || len(rd.Entries) > 0 ||
  88. len(rd.CommittedEntries) > 0 || len(rd.Messages) > 0 || len(rd.ReadStates) != 0
  89. }
  90. // appliedCursor extracts from the Ready the highest index the client has
  91. // applied (once the Ready is confirmed via Advance). If no information is
  92. // contained in the Ready, returns zero.
  93. func (rd Ready) appliedCursor() uint64 {
  94. if n := len(rd.CommittedEntries); n > 0 {
  95. return rd.CommittedEntries[n-1].Index
  96. }
  97. if index := rd.Snapshot.Metadata.Index; index > 0 {
  98. return index
  99. }
  100. return 0
  101. }
  102. // Node represents a node in a raft cluster.
  103. type Node interface {
  104. // Tick increments the internal logical clock for the Node by a single tick. Election
  105. // timeouts and heartbeat timeouts are in units of ticks.
  106. Tick()
  107. // Campaign causes the Node to transition to candidate state and start campaigning to become leader.
  108. Campaign(ctx context.Context) error
  109. // Propose proposes that data be appended to the log. Note that proposals can be lost without
  110. // notice, therefore it is user's job to ensure proposal retries.
  111. Propose(ctx context.Context, data []byte) error
  112. // ProposeConfChange proposes config change.
  113. // At most one ConfChange can be in the process of going through consensus.
  114. // Application needs to call ApplyConfChange when applying EntryConfChange type entry.
  115. ProposeConfChange(ctx context.Context, cc pb.ConfChange) error
  116. // Step advances the state machine using the given message. ctx.Err() will be returned, if any.
  117. Step(ctx context.Context, msg pb.Message) error
  118. // Ready returns a channel that returns the current point-in-time state.
  119. // Users of the Node must call Advance after retrieving the state returned by Ready.
  120. //
  121. // NOTE: No committed entries from the next Ready may be applied until all committed entries
  122. // and snapshots from the previous one have finished.
  123. Ready() <-chan Ready
  124. // Advance notifies the Node that the application has saved progress up to the last Ready.
  125. // It prepares the node to return the next available Ready.
  126. //
  127. // The application should generally call Advance after it applies the entries in last Ready.
  128. //
  129. // However, as an optimization, the application may call Advance while it is applying the
  130. // commands. For example. when the last Ready contains a snapshot, the application might take
  131. // a long time to apply the snapshot data. To continue receiving Ready without blocking raft
  132. // progress, it can call Advance before finishing applying the last ready.
  133. Advance()
  134. // ApplyConfChange applies config change to the local node.
  135. // Returns an opaque ConfState protobuf which must be recorded
  136. // in snapshots. Will never return nil; it returns a pointer only
  137. // to match MemoryStorage.Compact.
  138. ApplyConfChange(cc pb.ConfChange) *pb.ConfState
  139. // TransferLeadership attempts to transfer leadership to the given transferee.
  140. TransferLeadership(ctx context.Context, lead, transferee uint64)
  141. // ReadIndex request a read state. The read state will be set in the ready.
  142. // Read state has a read index. Once the application advances further than the read
  143. // index, any linearizable read requests issued before the read request can be
  144. // processed safely. The read state will have the same rctx attached.
  145. ReadIndex(ctx context.Context, rctx []byte) error
  146. // Status returns the current status of the raft state machine.
  147. Status() Status
  148. // ReportUnreachable reports the given node is not reachable for the last send.
  149. ReportUnreachable(id uint64)
  150. // ReportSnapshot reports the status of the sent snapshot. The id is the raft ID of the follower
  151. // who is meant to receive the snapshot, and the status is SnapshotFinish or SnapshotFailure.
  152. // Calling ReportSnapshot with SnapshotFinish is a no-op. But, any failure in applying a
  153. // snapshot (for e.g., while streaming it from leader to follower), should be reported to the
  154. // leader with SnapshotFailure. When leader sends a snapshot to a follower, it pauses any raft
  155. // log probes until the follower can apply the snapshot and advance its state. If the follower
  156. // can't do that, for e.g., due to a crash, it could end up in a limbo, never getting any
  157. // updates from the leader. Therefore, it is crucial that the application ensures that any
  158. // failure in snapshot sending is caught and reported back to the leader; so it can resume raft
  159. // log probing in the follower.
  160. ReportSnapshot(id uint64, status SnapshotStatus)
  161. // Stop performs any necessary termination of the Node.
  162. Stop()
  163. }
  164. type Peer struct {
  165. ID uint64
  166. Context []byte
  167. }
  168. // StartNode returns a new Node given configuration and a list of raft peers.
  169. // It appends a ConfChangeAddNode entry for each given peer to the initial log.
  170. func StartNode(c *Config, peers []Peer) Node {
  171. rn, err := NewRawNode(c, peers)
  172. if err != nil {
  173. panic(err)
  174. }
  175. n := newNode()
  176. n.logger = c.Logger
  177. go n.run(rn)
  178. return &n
  179. }
  180. // RestartNode is similar to StartNode but does not take a list of peers.
  181. // The current membership of the cluster will be restored from the Storage.
  182. // If the caller has an existing state machine, pass in the last log index that
  183. // has been applied to it; otherwise use zero.
  184. func RestartNode(c *Config) Node {
  185. return StartNode(c, nil)
  186. }
  187. type msgWithResult struct {
  188. m pb.Message
  189. result chan error
  190. }
  191. // node is the canonical implementation of the Node interface
  192. type node struct {
  193. propc chan msgWithResult
  194. recvc chan pb.Message
  195. confc chan pb.ConfChange
  196. confstatec chan pb.ConfState
  197. readyc chan Ready
  198. advancec chan struct{}
  199. tickc chan struct{}
  200. done chan struct{}
  201. stop chan struct{}
  202. status chan chan Status
  203. logger Logger
  204. }
  205. func newNode() node {
  206. return node{
  207. propc: make(chan msgWithResult),
  208. recvc: make(chan pb.Message),
  209. confc: make(chan pb.ConfChange),
  210. confstatec: make(chan pb.ConfState),
  211. readyc: make(chan Ready),
  212. advancec: make(chan struct{}),
  213. // make tickc a buffered chan, so raft node can buffer some ticks when the node
  214. // is busy processing raft messages. Raft node will resume process buffered
  215. // ticks when it becomes idle.
  216. tickc: make(chan struct{}, 128),
  217. done: make(chan struct{}),
  218. stop: make(chan struct{}),
  219. status: make(chan chan Status),
  220. }
  221. }
  222. func (n *node) Stop() {
  223. select {
  224. case n.stop <- struct{}{}:
  225. // Not already stopped, so trigger it
  226. case <-n.done:
  227. // Node has already been stopped - no need to do anything
  228. return
  229. }
  230. // Block until the stop has been acknowledged by run()
  231. <-n.done
  232. }
  233. func (n *node) run(rn *RawNode) {
  234. var propc chan msgWithResult
  235. var readyc chan Ready
  236. var advancec chan struct{}
  237. var rd Ready
  238. r := rn.raft
  239. lead := None
  240. for {
  241. if advancec != nil {
  242. readyc = nil
  243. } else if rn.HasReady() {
  244. // Populate a Ready. Note that this Ready is not guaranteed to
  245. // actually be handled. We will arm readyc, but there's no guarantee
  246. // that we will actually send on it. It's possible that we will
  247. // service another channel instead, loop around, and then populate
  248. // the Ready again. We could instead force the previous Ready to be
  249. // handled first, but it's generally good to emit larger Readys plus
  250. // it simplifies testing (by emitting less frequently and more
  251. // predictably).
  252. rd = rn.Ready()
  253. readyc = n.readyc
  254. }
  255. if lead != r.lead {
  256. if r.hasLeader() {
  257. if lead == None {
  258. r.logger.Infof("raft.node: %x elected leader %x at term %d", r.id, r.lead, r.Term)
  259. } else {
  260. r.logger.Infof("raft.node: %x changed leader from %x to %x at term %d", r.id, lead, r.lead, r.Term)
  261. }
  262. propc = n.propc
  263. } else {
  264. r.logger.Infof("raft.node: %x lost leader %x at term %d", r.id, lead, r.Term)
  265. propc = nil
  266. }
  267. lead = r.lead
  268. }
  269. select {
  270. // TODO: maybe buffer the config propose if there exists one (the way
  271. // described in raft dissertation)
  272. // Currently it is dropped in Step silently.
  273. case pm := <-propc:
  274. m := pm.m
  275. m.From = r.id
  276. err := r.Step(m)
  277. if pm.result != nil {
  278. pm.result <- err
  279. close(pm.result)
  280. }
  281. case m := <-n.recvc:
  282. // filter out response message from unknown From.
  283. if pr := r.prs.Progress[m.From]; pr != nil || !IsResponseMsg(m.Type) {
  284. r.Step(m)
  285. }
  286. case cc := <-n.confc:
  287. cs := r.applyConfChange(cc)
  288. if _, ok := r.prs.Progress[r.id]; !ok {
  289. // block incoming proposal when local node is
  290. // removed
  291. if cc.NodeID == r.id {
  292. propc = nil
  293. }
  294. }
  295. select {
  296. case n.confstatec <- cs:
  297. case <-n.done:
  298. }
  299. case <-n.tickc:
  300. rn.Tick()
  301. case readyc <- rd:
  302. rn.acceptReady(rd)
  303. advancec = n.advancec
  304. case <-advancec:
  305. rn.commitReady(rd)
  306. rd = Ready{}
  307. advancec = nil
  308. case c := <-n.status:
  309. c <- getStatus(r)
  310. case <-n.stop:
  311. close(n.done)
  312. return
  313. }
  314. }
  315. }
  316. // Tick increments the internal logical clock for this Node. Election timeouts
  317. // and heartbeat timeouts are in units of ticks.
  318. func (n *node) Tick() {
  319. select {
  320. case n.tickc <- struct{}{}:
  321. case <-n.done:
  322. default:
  323. n.logger.Warningf("A tick missed to fire. Node blocks too long!")
  324. }
  325. }
  326. func (n *node) Campaign(ctx context.Context) error { return n.step(ctx, pb.Message{Type: pb.MsgHup}) }
  327. func (n *node) Propose(ctx context.Context, data []byte) error {
  328. return n.stepWait(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  329. }
  330. func (n *node) Step(ctx context.Context, m pb.Message) error {
  331. // ignore unexpected local messages receiving over network
  332. if IsLocalMsg(m.Type) {
  333. // TODO: return an error?
  334. return nil
  335. }
  336. return n.step(ctx, m)
  337. }
  338. func (n *node) ProposeConfChange(ctx context.Context, cc pb.ConfChange) error {
  339. data, err := cc.Marshal()
  340. if err != nil {
  341. return err
  342. }
  343. return n.Step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange, Data: data}}})
  344. }
  345. func (n *node) step(ctx context.Context, m pb.Message) error {
  346. return n.stepWithWaitOption(ctx, m, false)
  347. }
  348. func (n *node) stepWait(ctx context.Context, m pb.Message) error {
  349. return n.stepWithWaitOption(ctx, m, true)
  350. }
  351. // Step advances the state machine using msgs. The ctx.Err() will be returned,
  352. // if any.
  353. func (n *node) stepWithWaitOption(ctx context.Context, m pb.Message, wait bool) error {
  354. if m.Type != pb.MsgProp {
  355. select {
  356. case n.recvc <- m:
  357. return nil
  358. case <-ctx.Done():
  359. return ctx.Err()
  360. case <-n.done:
  361. return ErrStopped
  362. }
  363. }
  364. ch := n.propc
  365. pm := msgWithResult{m: m}
  366. if wait {
  367. pm.result = make(chan error, 1)
  368. }
  369. select {
  370. case ch <- pm:
  371. if !wait {
  372. return nil
  373. }
  374. case <-ctx.Done():
  375. return ctx.Err()
  376. case <-n.done:
  377. return ErrStopped
  378. }
  379. select {
  380. case err := <-pm.result:
  381. if err != nil {
  382. return err
  383. }
  384. case <-ctx.Done():
  385. return ctx.Err()
  386. case <-n.done:
  387. return ErrStopped
  388. }
  389. return nil
  390. }
  391. func (n *node) Ready() <-chan Ready { return n.readyc }
  392. func (n *node) Advance() {
  393. select {
  394. case n.advancec <- struct{}{}:
  395. case <-n.done:
  396. }
  397. }
  398. func (n *node) ApplyConfChange(cc pb.ConfChange) *pb.ConfState {
  399. var cs pb.ConfState
  400. select {
  401. case n.confc <- cc:
  402. case <-n.done:
  403. }
  404. select {
  405. case cs = <-n.confstatec:
  406. case <-n.done:
  407. }
  408. return &cs
  409. }
  410. func (n *node) Status() Status {
  411. c := make(chan Status)
  412. select {
  413. case n.status <- c:
  414. return <-c
  415. case <-n.done:
  416. return Status{}
  417. }
  418. }
  419. func (n *node) ReportUnreachable(id uint64) {
  420. select {
  421. case n.recvc <- pb.Message{Type: pb.MsgUnreachable, From: id}:
  422. case <-n.done:
  423. }
  424. }
  425. func (n *node) ReportSnapshot(id uint64, status SnapshotStatus) {
  426. rej := status == SnapshotFailure
  427. select {
  428. case n.recvc <- pb.Message{Type: pb.MsgSnapStatus, From: id, Reject: rej}:
  429. case <-n.done:
  430. }
  431. }
  432. func (n *node) TransferLeadership(ctx context.Context, lead, transferee uint64) {
  433. select {
  434. // manually set 'from' and 'to', so that leader can voluntarily transfers its leadership
  435. case n.recvc <- pb.Message{Type: pb.MsgTransferLeader, From: transferee, To: lead}:
  436. case <-n.done:
  437. case <-ctx.Done():
  438. }
  439. }
  440. func (n *node) ReadIndex(ctx context.Context, rctx []byte) error {
  441. return n.step(ctx, pb.Message{Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: rctx}}})
  442. }
  443. func newReady(r *raft, prevSoftSt *SoftState, prevHardSt pb.HardState) Ready {
  444. rd := Ready{
  445. Entries: r.raftLog.unstableEntries(),
  446. CommittedEntries: r.raftLog.nextEnts(),
  447. Messages: r.msgs,
  448. }
  449. if softSt := r.softState(); !softSt.equal(prevSoftSt) {
  450. rd.SoftState = softSt
  451. }
  452. if hardSt := r.hardState(); !isHardStateEqual(hardSt, prevHardSt) {
  453. rd.HardState = hardSt
  454. }
  455. if r.raftLog.unstable.snapshot != nil {
  456. rd.Snapshot = *r.raftLog.unstable.snapshot
  457. }
  458. if len(r.readStates) != 0 {
  459. rd.ReadStates = r.readStates
  460. }
  461. rd.MustSync = MustSync(r.hardState(), prevHardSt, len(rd.Entries))
  462. return rd
  463. }
  464. // MustSync returns true if the hard state and count of Raft entries indicate
  465. // that a synchronous write to persistent storage is required.
  466. func MustSync(st, prevst pb.HardState, entsnum int) bool {
  467. // Persistent state on all servers:
  468. // (Updated on stable storage before responding to RPCs)
  469. // currentTerm
  470. // votedFor
  471. // log entries[]
  472. return entsnum != 0 || st.Vote != prevst.Vote || st.Term != prevst.Term
  473. }