node.go 5.9 KB

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