node.go 5.9 KB

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