peer.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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)
  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. p.stopChan <- flush
  77. }
  78. //--------------------------------------
  79. // Copying
  80. //--------------------------------------
  81. // Clones the state of the peer. The clone is not attached to a server and
  82. // the heartbeat timer will not exist.
  83. func (p *Peer) clone() *Peer {
  84. p.mutex.Lock()
  85. defer p.mutex.Unlock()
  86. return &Peer{
  87. Name: p.Name,
  88. ConnectionString: p.ConnectionString,
  89. prevLogIndex: p.prevLogIndex,
  90. }
  91. }
  92. //--------------------------------------
  93. // Heartbeat
  94. //--------------------------------------
  95. // Listens to the heartbeat timeout and flushes an AppendEntries RPC.
  96. func (p *Peer) heartbeat(c chan bool) {
  97. stopChan := p.stopChan
  98. c <- true
  99. ticker := time.Tick(p.heartbeatTimeout)
  100. debugln("peer.heartbeat: ", p.Name, p.heartbeatTimeout)
  101. for {
  102. select {
  103. case flush := <-stopChan:
  104. if !flush {
  105. debugln("peer.heartbeat.stop: ", p.Name)
  106. return
  107. } else {
  108. // before we can safely remove a node
  109. // we must flush the remove command to the node first
  110. p.flush()
  111. debugln("peer.heartbeat.stop.with.flush: ", p.Name)
  112. return
  113. }
  114. case <-ticker:
  115. start := time.Now()
  116. p.flush()
  117. duration := time.Now().Sub(start)
  118. p.server.DispatchEvent(newEvent(HeartbeatEventType, duration, nil))
  119. }
  120. }
  121. }
  122. func (p *Peer) flush() {
  123. debugln("peer.heartbeat.flush: ", p.Name)
  124. prevLogIndex := p.getPrevLogIndex()
  125. entries, prevLogTerm := p.server.log.getEntriesAfter(prevLogIndex, p.server.maxLogEntriesPerRequest)
  126. if p.server.State() != Leader {
  127. return
  128. }
  129. if entries != nil {
  130. p.sendAppendEntriesRequest(newAppendEntriesRequest(p.server.currentTerm, prevLogIndex, prevLogTerm, p.server.log.CommitIndex(), p.server.name, entries))
  131. } else {
  132. p.sendSnapshotRequest(newSnapshotRequest(p.server.name, p.server.lastSnapshot))
  133. }
  134. }
  135. //--------------------------------------
  136. // Append Entries
  137. //--------------------------------------
  138. // Sends an AppendEntries request to the peer through the transport.
  139. func (p *Peer) sendAppendEntriesRequest(req *AppendEntriesRequest) {
  140. tracef("peer.append.send: %s->%s [prevLog:%v length: %v]\n",
  141. p.server.Name(), p.Name, req.PrevLogIndex, len(req.Entries))
  142. resp := p.server.Transporter().SendAppendEntriesRequest(p.server, p, req)
  143. if resp == nil {
  144. p.server.DispatchEvent(newEvent(HeartbeatTimeoutEventType, p, nil))
  145. debugln("peer.append.timeout: ", p.server.Name(), "->", p.Name)
  146. return
  147. }
  148. traceln("peer.append.resp: ", p.server.Name(), "<-", p.Name)
  149. // If successful then update the previous log index.
  150. p.mutex.Lock()
  151. if resp.Success {
  152. if len(req.Entries) > 0 {
  153. p.prevLogIndex = req.Entries[len(req.Entries)-1].Index
  154. // if peer append a log entry from the current term
  155. // we set append to true
  156. if req.Entries[len(req.Entries)-1].Term == p.server.currentTerm {
  157. resp.append = true
  158. }
  159. }
  160. traceln("peer.append.resp.success: ", p.Name, "; idx =", p.prevLogIndex)
  161. // If it was unsuccessful then decrement the previous log index and
  162. // we'll try again next time.
  163. } else {
  164. if resp.CommitIndex >= p.prevLogIndex {
  165. // we may miss a response from peer
  166. // so maybe the peer has committed the logs we just sent
  167. // but we did not receive the successful reply and did not increase
  168. // the prevLogIndex
  169. // peer failed to truncate the log and sent a fail reply at this time
  170. // we just need to update peer's prevLog index to commitIndex
  171. p.prevLogIndex = resp.CommitIndex
  172. debugln("peer.append.resp.update: ", p.Name, "; idx =", p.prevLogIndex)
  173. } else if p.prevLogIndex > 0 {
  174. // Decrement the previous log index down until we find a match. Don't
  175. // let it go below where the peer's commit index is though. That's a
  176. // problem.
  177. p.prevLogIndex--
  178. // if it not enough, we directly decrease to the index of the
  179. if p.prevLogIndex > resp.Index {
  180. p.prevLogIndex = resp.Index
  181. }
  182. debugln("peer.append.resp.decrement: ", p.Name, "; idx =", p.prevLogIndex)
  183. }
  184. }
  185. p.mutex.Unlock()
  186. // Attach the peer to resp, thus server can know where it comes from
  187. resp.peer = p.Name
  188. // Send response to server for processing.
  189. p.server.sendAsync(resp)
  190. }
  191. // Sends an Snapshot request to the peer through the transport.
  192. func (p *Peer) sendSnapshotRequest(req *SnapshotRequest) {
  193. debugln("peer.snap.send: ", p.Name)
  194. resp := p.server.Transporter().SendSnapshotRequest(p.server, p, req)
  195. if resp == nil {
  196. debugln("peer.snap.timeout: ", p.Name)
  197. return
  198. }
  199. debugln("peer.snap.recv: ", p.Name)
  200. // If successful, the peer should have been to snapshot state
  201. // Send it the snapshot!
  202. if resp.Success {
  203. p.sendSnapshotRecoveryRequest()
  204. } else {
  205. debugln("peer.snap.failed: ", p.Name)
  206. return
  207. }
  208. }
  209. // Sends an Snapshot Recovery request to the peer through the transport.
  210. func (p *Peer) sendSnapshotRecoveryRequest() {
  211. req := newSnapshotRecoveryRequest(p.server.name, p.server.lastSnapshot)
  212. debugln("peer.snap.recovery.send: ", p.Name)
  213. resp := p.server.Transporter().SendSnapshotRecoveryRequest(p.server, p, req)
  214. if resp == nil {
  215. debugln("peer.snap.recovery.timeout: ", p.Name)
  216. return
  217. }
  218. if resp.Success {
  219. p.prevLogIndex = req.LastIndex
  220. } else {
  221. debugln("peer.snap.recovery.failed: ", p.Name)
  222. return
  223. }
  224. // Send response to server for processing.
  225. p.server.sendAsync(&AppendEntriesResponse{Term: resp.Term, Success: resp.Success, append: (resp.Term == p.server.currentTerm)})
  226. }
  227. //--------------------------------------
  228. // Vote Requests
  229. //--------------------------------------
  230. // send VoteRequest Request
  231. func (p *Peer) sendVoteRequest(req *RequestVoteRequest, c chan *RequestVoteResponse) {
  232. debugln("peer.vote: ", p.server.Name(), "->", p.Name)
  233. req.peer = p
  234. if resp := p.server.Transporter().SendVoteRequest(p.server, p, req); resp != nil {
  235. debugln("peer.vote.recv: ", p.server.Name(), "<-", p.Name)
  236. resp.peer = p
  237. c <- resp
  238. } else {
  239. debugln("peer.vote.failed: ", p.server.Name(), "<-", p.Name)
  240. }
  241. }