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