node.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. package raft
  2. import (
  3. "encoding/binary"
  4. "encoding/json"
  5. "log"
  6. "math/rand"
  7. "time"
  8. )
  9. type Interface interface {
  10. Step(m Message) bool
  11. Msgs() []Message
  12. }
  13. type tick int64
  14. type Config struct {
  15. NodeId int64
  16. Addr string
  17. Context []byte
  18. }
  19. type Node struct {
  20. sm *stateMachine
  21. elapsed tick
  22. electionRand tick
  23. election tick
  24. heartbeat tick
  25. // TODO: it needs garbage collection later
  26. rmNodes map[int64]struct{}
  27. removed bool
  28. }
  29. func New(id int64, heartbeat, election tick) *Node {
  30. if election < heartbeat*3 {
  31. panic("election is least three times as heartbeat [election: %d, heartbeat: %d]")
  32. }
  33. rand.Seed(time.Now().UnixNano())
  34. n := &Node{
  35. heartbeat: heartbeat,
  36. election: election,
  37. electionRand: election + tick(rand.Int31())%election,
  38. sm: newStateMachine(id, []int64{id}),
  39. rmNodes: make(map[int64]struct{}),
  40. }
  41. return n
  42. }
  43. func Recover(id int64, ents []Entry, state State, heartbeat, election tick) *Node {
  44. n := New(id, heartbeat, election)
  45. n.sm.loadEnts(ents)
  46. n.sm.loadState(state)
  47. return n
  48. }
  49. func (n *Node) Id() int64 { return n.sm.id }
  50. func (n *Node) ClusterId() int64 { return n.sm.clusterId }
  51. func (n *Node) Index() int64 { return n.sm.index.Get() }
  52. func (n *Node) Term() int64 { return n.sm.term.Get() }
  53. func (n *Node) Applied() int64 { return n.sm.raftLog.applied }
  54. func (n *Node) HasLeader() bool { return n.Leader() != none }
  55. func (n *Node) IsLeader() bool { return n.Leader() == n.Id() }
  56. func (n *Node) Leader() int64 { return n.sm.lead.Get() }
  57. func (n *Node) IsRemoved() bool { return n.removed }
  58. // Propose asynchronously proposes data be applied to the underlying state machine.
  59. func (n *Node) Propose(data []byte) { n.propose(Normal, data) }
  60. func (n *Node) propose(t int64, data []byte) {
  61. n.Step(Message{From: n.sm.id, ClusterId: n.ClusterId(), Type: msgProp, Entries: []Entry{{Type: t, Data: data}}})
  62. }
  63. func (n *Node) Campaign() { n.Step(Message{From: n.sm.id, ClusterId: n.ClusterId(), Type: msgHup}) }
  64. func (n *Node) InitCluster(clusterId int64) {
  65. d := make([]byte, 10)
  66. wn := binary.PutVarint(d, clusterId)
  67. n.propose(ClusterInit, d[:wn])
  68. }
  69. func (n *Node) Add(id int64, addr string, context []byte) {
  70. n.UpdateConf(AddNode, &Config{NodeId: id, Addr: addr, Context: context})
  71. }
  72. func (n *Node) Remove(id int64) {
  73. n.UpdateConf(RemoveNode, &Config{NodeId: id})
  74. }
  75. func (n *Node) Msgs() []Message { return n.sm.Msgs() }
  76. func (n *Node) Step(m Message) bool {
  77. if m.Type == msgDenied {
  78. n.removed = true
  79. return false
  80. }
  81. if n.ClusterId() != none && m.ClusterId != none && m.ClusterId != n.ClusterId() {
  82. log.Printf("denied a message from node %d, cluster %d. accept cluster: %d\n", m.From, m.ClusterId, n.ClusterId())
  83. n.sm.send(Message{To: m.From, ClusterId: n.ClusterId(), Type: msgDenied})
  84. return true
  85. }
  86. if _, ok := n.rmNodes[m.From]; ok {
  87. if m.From != n.sm.id {
  88. n.sm.send(Message{To: m.From, ClusterId: n.ClusterId(), Type: msgDenied})
  89. }
  90. return true
  91. }
  92. l := len(n.sm.msgs)
  93. if !n.sm.Step(m) {
  94. return false
  95. }
  96. for _, m := range n.sm.msgs[l:] {
  97. switch m.Type {
  98. case msgAppResp:
  99. // We just heard from the leader of the same term.
  100. n.elapsed = 0
  101. case msgVoteResp:
  102. // We just heard from the candidate the node voted for.
  103. if m.Index >= 0 {
  104. n.elapsed = 0
  105. }
  106. }
  107. }
  108. return true
  109. }
  110. // Next returns all the appliable entries
  111. func (n *Node) Next() []Entry {
  112. ents := n.sm.nextEnts()
  113. for i := range ents {
  114. switch ents[i].Type {
  115. case Normal:
  116. case ClusterInit:
  117. cid, nr := binary.Varint(ents[i].Data)
  118. if nr <= 0 {
  119. panic("init cluster failed: cannot read clusterId")
  120. }
  121. if n.ClusterId() != -1 {
  122. panic("cannot init a started cluster")
  123. }
  124. n.sm.clusterId = cid
  125. case AddNode:
  126. c := new(Config)
  127. if err := json.Unmarshal(ents[i].Data, c); err != nil {
  128. log.Println(err)
  129. continue
  130. }
  131. n.sm.addNode(c.NodeId)
  132. delete(n.rmNodes, c.NodeId)
  133. case RemoveNode:
  134. c := new(Config)
  135. if err := json.Unmarshal(ents[i].Data, c); err != nil {
  136. log.Println(err)
  137. continue
  138. }
  139. n.sm.removeNode(c.NodeId)
  140. n.rmNodes[c.NodeId] = struct{}{}
  141. if c.NodeId == n.sm.id {
  142. n.removed = true
  143. }
  144. default:
  145. panic("unexpected entry type")
  146. }
  147. }
  148. return ents
  149. }
  150. // Tick triggers the node to do a tick.
  151. // If the current elapsed is greater or equal than the timeout,
  152. // node will send corresponding message to the statemachine.
  153. func (n *Node) Tick() {
  154. if !n.sm.promotable() {
  155. return
  156. }
  157. timeout, msgType := n.electionRand, msgHup
  158. if n.sm.state == stateLeader {
  159. timeout, msgType = n.heartbeat, msgBeat
  160. }
  161. if n.elapsed >= timeout {
  162. n.Step(Message{From: n.sm.id, ClusterId: n.ClusterId(), Type: msgType})
  163. n.elapsed = 0
  164. if n.sm.state != stateLeader {
  165. n.electionRand = n.election + tick(rand.Int31())%n.election
  166. }
  167. } else {
  168. n.elapsed++
  169. }
  170. }
  171. // IsEmpty returns ture if the log of the node is empty.
  172. func (n *Node) IsEmpty() bool {
  173. return n.sm.raftLog.isEmpty()
  174. }
  175. func (n *Node) UpdateConf(t int64, c *Config) {
  176. data, err := json.Marshal(c)
  177. if err != nil {
  178. panic(err)
  179. }
  180. n.propose(t, data)
  181. }
  182. // UnstableEnts retuens all the entries that need to be persistent.
  183. // The first return value is offset, and the second one is unstable entries.
  184. func (n *Node) UnstableEnts() []Entry {
  185. return n.sm.raftLog.unstableEnts()
  186. }
  187. func (n *Node) UnstableState() State {
  188. if n.sm.unstableState == EmptyState {
  189. return EmptyState
  190. }
  191. s := n.sm.unstableState
  192. n.sm.clearState()
  193. return s
  194. }