peer.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package raft
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. //------------------------------------------------------------------------------
  7. //
  8. // Typedefs
  9. //
  10. //------------------------------------------------------------------------------
  11. // A peer is a reference to another server involved in the consensus protocol.
  12. type Peer struct {
  13. server *server
  14. Name string `json:"name"`
  15. ConnectionString string `json:"connectionString"`
  16. prevLogIndex uint64
  17. mutex sync.RWMutex
  18. stopChan chan bool
  19. heartbeatTimeout time.Duration
  20. }
  21. //------------------------------------------------------------------------------
  22. //
  23. // Constructor
  24. //
  25. //------------------------------------------------------------------------------
  26. // Creates a new peer.
  27. func newPeer(server *server, name string, connectionString string, heartbeatTimeout time.Duration) *Peer {
  28. return &Peer{
  29. server: server,
  30. Name: name,
  31. ConnectionString: connectionString,
  32. heartbeatTimeout: heartbeatTimeout,
  33. }
  34. }
  35. //------------------------------------------------------------------------------
  36. //
  37. // Accessors
  38. //
  39. //------------------------------------------------------------------------------
  40. // Sets the heartbeat timeout.
  41. func (p *Peer) setHeartbeatTimeout(duration time.Duration) {
  42. p.heartbeatTimeout = duration
  43. }
  44. //--------------------------------------
  45. // Prev log index
  46. //--------------------------------------
  47. // Retrieves the previous log index.
  48. func (p *Peer) getPrevLogIndex() uint64 {
  49. p.mutex.RLock()
  50. defer p.mutex.RUnlock()
  51. return p.prevLogIndex
  52. }
  53. // Sets the previous log index.
  54. func (p *Peer) setPrevLogIndex(value uint64) {
  55. p.mutex.Lock()
  56. defer p.mutex.Unlock()
  57. p.prevLogIndex = value
  58. }
  59. //------------------------------------------------------------------------------
  60. //
  61. // Methods
  62. //
  63. //------------------------------------------------------------------------------
  64. //--------------------------------------
  65. // Heartbeat
  66. //--------------------------------------
  67. // Starts the peer heartbeat.
  68. func (p *Peer) startHeartbeat() {
  69. p.stopChan = make(chan bool, 1)
  70. c := make(chan bool)
  71. go p.heartbeat(c)
  72. <-c
  73. }
  74. // Stops the peer heartbeat.
  75. func (p *Peer) stopHeartbeat(flush bool) {
  76. // here is a problem
  77. // the previous stop is no buffer leader may get blocked
  78. // when heartbeat returns
  79. // I make the channel with 1 buffer
  80. // and try to panic here
  81. select {
  82. case p.stopChan <- flush:
  83. default:
  84. panic("[" + p.server.Name() + "] cannot stop [" + p.Name + "] heartbeat")
  85. }
  86. }
  87. //--------------------------------------
  88. // Copying
  89. //--------------------------------------
  90. // Clones the state of the peer. The clone is not attached to a server and
  91. // the heartbeat timer will not exist.
  92. func (p *Peer) clone() *Peer {
  93. p.mutex.Lock()
  94. defer p.mutex.Unlock()
  95. return &Peer{
  96. Name: p.Name,
  97. ConnectionString: p.ConnectionString,
  98. prevLogIndex: p.prevLogIndex,
  99. }
  100. }
  101. //--------------------------------------
  102. // Heartbeat
  103. //--------------------------------------
  104. // Listens to the heartbeat timeout and flushes an AppendEntries RPC.
  105. func (p *Peer) heartbeat(c chan bool) {
  106. stopChan := p.stopChan
  107. c <- true
  108. ticker := time.Tick(p.heartbeatTimeout)
  109. debugln("peer.heartbeat: ", p.Name, p.heartbeatTimeout)
  110. for {
  111. select {
  112. case flush := <-stopChan:
  113. if !flush {
  114. debugln("peer.heartbeat.stop: ", p.Name)
  115. return
  116. } else {
  117. // before we can safely remove a node
  118. // we must flush the remove command to the node first
  119. p.flush()
  120. debugln("peer.heartbeat.stop: ", p.Name)
  121. return
  122. }
  123. case <-ticker:
  124. p.flush()
  125. }
  126. }
  127. }
  128. func (p *Peer) flush() {
  129. debugln("peer.heartbeat.run: ", p.Name)
  130. prevLogIndex := p.getPrevLogIndex()
  131. entries, prevLogTerm := p.server.log.getEntriesAfter(prevLogIndex, p.server.maxLogEntriesPerRequest)
  132. if p.server.State() != Leader {
  133. return
  134. }
  135. if entries != nil {
  136. p.sendAppendEntriesRequest(newAppendEntriesRequest(p.server.currentTerm, prevLogIndex, prevLogTerm, p.server.log.CommitIndex(), p.server.name, entries))
  137. } else {
  138. p.sendSnapshotRequest(newSnapshotRequest(p.server.name, p.server.lastSnapshot))
  139. }
  140. }
  141. //--------------------------------------
  142. // Append Entries
  143. //--------------------------------------
  144. // Sends an AppendEntries request to the peer through the transport.
  145. func (p *Peer) sendAppendEntriesRequest(req *AppendEntriesRequest) {
  146. traceln("peer.flush.send: ", p.server.Name(), "->", p.Name, " ", len(req.Entries))
  147. resp := p.server.Transporter().SendAppendEntriesRequest(p.server, p, req)
  148. if resp == nil {
  149. p.server.DispatchEvent(newEvent(HeartbeatTimeoutEventType, p, nil))
  150. debugln("peer.flush.timeout: ", p.server.Name(), "->", p.Name)
  151. return
  152. }
  153. traceln("peer.flush.recv: ", p.Name)
  154. // If successful then update the previous log index.
  155. p.mutex.Lock()
  156. if resp.Success {
  157. if len(req.Entries) > 0 {
  158. p.prevLogIndex = req.Entries[len(req.Entries)-1].Index
  159. // if peer append a log entry from the current term
  160. // we set append to true
  161. if req.Entries[len(req.Entries)-1].Term == p.server.currentTerm {
  162. resp.append = true
  163. }
  164. }
  165. traceln("peer.flush.success: ", p.server.Name(), "->", p.Name, "; idx =", p.prevLogIndex)
  166. // If it was unsuccessful then decrement the previous log index and
  167. // we'll try again next time.
  168. } else {
  169. if resp.CommitIndex >= p.prevLogIndex {
  170. // we may miss a response from peer
  171. // so maybe the peer has commited the logs we sent
  172. // but we did not receive the success reply and did not increase
  173. // the prevLogIndex
  174. p.prevLogIndex = resp.CommitIndex
  175. debugln("peer.flush.commitIndex: ", p.server.Name(), "->", p.Name, " idx =", p.prevLogIndex)
  176. } else if p.prevLogIndex > 0 {
  177. // Decrement the previous log index down until we find a match. Don't
  178. // let it go below where the peer's commit index is though. That's a
  179. // problem.
  180. p.prevLogIndex--
  181. // if it not enough, we directly decrease to the index of the
  182. if p.prevLogIndex > resp.Index {
  183. p.prevLogIndex = resp.Index
  184. }
  185. debugln("peer.flush.decrement: ", p.server.Name(), "->", p.Name, " idx =", p.prevLogIndex)
  186. }
  187. }
  188. p.mutex.Unlock()
  189. // Attach the peer to resp, thus server can know where it comes from
  190. resp.peer = p.Name
  191. // Send response to server for processing.
  192. p.server.send(resp)
  193. }
  194. // Sends an Snapshot request to the peer through the transport.
  195. func (p *Peer) sendSnapshotRequest(req *SnapshotRequest) {
  196. debugln("peer.snap.send: ", p.Name)
  197. resp := p.server.Transporter().SendSnapshotRequest(p.server, p, req)
  198. if resp == nil {
  199. debugln("peer.snap.timeout: ", p.Name)
  200. return
  201. }
  202. debugln("peer.snap.recv: ", p.Name)
  203. // If successful, the peer should have been to snapshot state
  204. // Send it the snapshot!
  205. if resp.Success {
  206. p.sendSnapshotRecoveryRequest()
  207. } else {
  208. debugln("peer.snap.failed: ", p.Name)
  209. return
  210. }
  211. }
  212. // Sends an Snapshot Recovery request to the peer through the transport.
  213. func (p *Peer) sendSnapshotRecoveryRequest() {
  214. req := newSnapshotRecoveryRequest(p.server.name, p.server.lastSnapshot)
  215. debugln("peer.snap.recovery.send: ", p.Name)
  216. resp := p.server.Transporter().SendSnapshotRecoveryRequest(p.server, p, req)
  217. if resp == nil {
  218. debugln("peer.snap.recovery.timeout: ", p.Name)
  219. return
  220. }
  221. if resp.Success {
  222. p.prevLogIndex = req.LastIndex
  223. } else {
  224. debugln("peer.snap.recovery.failed: ", p.Name)
  225. return
  226. }
  227. // Send response to server for processing.
  228. p.server.send(&AppendEntriesResponse{Term: resp.Term, Success: resp.Success, append: (resp.Term == p.server.currentTerm)})
  229. }
  230. //--------------------------------------
  231. // Vote Requests
  232. //--------------------------------------
  233. // send VoteRequest Request
  234. func (p *Peer) sendVoteRequest(req *RequestVoteRequest, c chan *RequestVoteResponse) {
  235. debugln("peer.vote: ", p.server.Name(), "->", p.Name)
  236. req.peer = p
  237. if resp := p.server.Transporter().SendVoteRequest(p.server, p, req); resp != nil {
  238. debugln("peer.vote: recv", p.server.Name(), "<-", p.Name)
  239. resp.peer = p
  240. c <- resp
  241. }
  242. }