node.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. package raft
  2. import (
  3. "encoding/json"
  4. golog "log"
  5. "math/rand"
  6. "sync/atomic"
  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 (n *Node) Id() int64 {
  44. return atomic.LoadInt64(&n.sm.id)
  45. }
  46. func (n *Node) Index() int64 { return n.sm.index.Get() }
  47. func (n *Node) Term() int64 { return n.sm.term.Get() }
  48. func (n *Node) Applied() int64 { return n.sm.log.applied }
  49. func (n *Node) HasLeader() bool { return n.Leader() != none }
  50. func (n *Node) IsLeader() bool { return n.Leader() == n.Id() }
  51. func (n *Node) Leader() int64 { return n.sm.lead.Get() }
  52. func (n *Node) IsRemoved() bool { return n.removed }
  53. // Propose asynchronously proposes data be applied to the underlying state machine.
  54. func (n *Node) Propose(data []byte) { n.propose(Normal, data) }
  55. func (n *Node) propose(t int64, data []byte) {
  56. n.Step(Message{Type: msgProp, Entries: []Entry{{Type: t, Data: data}}})
  57. }
  58. func (n *Node) Campaign() { n.Step(Message{Type: msgHup}) }
  59. func (n *Node) Add(id int64, addr string, context []byte) {
  60. n.UpdateConf(AddNode, &Config{NodeId: id, Addr: addr, Context: context})
  61. }
  62. func (n *Node) Remove(id int64) { n.UpdateConf(RemoveNode, &Config{NodeId: id}) }
  63. func (n *Node) Msgs() []Message { return n.sm.Msgs() }
  64. func (n *Node) Step(m Message) bool {
  65. if m.Type == msgDenied {
  66. n.removed = true
  67. return false
  68. }
  69. if m.Term != 0 {
  70. if _, ok := n.rmNodes[m.From]; ok {
  71. n.sm.send(Message{To: m.From, Type: msgDenied})
  72. return true
  73. }
  74. }
  75. l := len(n.sm.msgs)
  76. if !n.sm.Step(m) {
  77. return false
  78. }
  79. for _, m := range n.sm.msgs[l:] {
  80. switch m.Type {
  81. case msgAppResp:
  82. // We just heard from the leader of the same term.
  83. n.elapsed = 0
  84. case msgVoteResp:
  85. // We just heard from the candidate the node voted for.
  86. if m.Index >= 0 {
  87. n.elapsed = 0
  88. }
  89. }
  90. }
  91. return true
  92. }
  93. // Next returns all the appliable entries
  94. func (n *Node) Next() []Entry {
  95. ents := n.sm.nextEnts()
  96. for i := range ents {
  97. switch ents[i].Type {
  98. case Normal:
  99. case AddNode:
  100. c := new(Config)
  101. if err := json.Unmarshal(ents[i].Data, c); err != nil {
  102. golog.Println(err)
  103. continue
  104. }
  105. n.sm.addNode(c.NodeId)
  106. delete(n.rmNodes, c.NodeId)
  107. case RemoveNode:
  108. c := new(Config)
  109. if err := json.Unmarshal(ents[i].Data, c); err != nil {
  110. golog.Println(err)
  111. continue
  112. }
  113. n.sm.removeNode(c.NodeId)
  114. n.rmNodes[c.NodeId] = struct{}{}
  115. if c.NodeId == n.sm.id {
  116. n.removed = true
  117. }
  118. default:
  119. panic("unexpected entry type")
  120. }
  121. }
  122. return ents
  123. }
  124. // Tick triggers the node to do a tick.
  125. // If the current elapsed is greater or equal than the timeout,
  126. // node will send corresponding message to the statemachine.
  127. func (n *Node) Tick() {
  128. if !n.sm.promotable() {
  129. return
  130. }
  131. timeout, msgType := n.electionRand, msgHup
  132. if n.sm.state == stateLeader {
  133. timeout, msgType = n.heartbeat, msgBeat
  134. }
  135. if n.elapsed >= timeout {
  136. n.Step(Message{Type: msgType})
  137. n.elapsed = 0
  138. if n.sm.state != stateLeader {
  139. n.electionRand = n.election + tick(rand.Int31())%n.election
  140. }
  141. } else {
  142. n.elapsed++
  143. }
  144. }
  145. func (n *Node) UpdateConf(t int64, c *Config) {
  146. data, err := json.Marshal(c)
  147. if err != nil {
  148. panic(err)
  149. }
  150. n.propose(t, data)
  151. }