peer.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. debugln("peer.flush.timeout: ", p.server.Name(), "->", p.Name)
  150. return
  151. }
  152. traceln("peer.flush.recv: ", p.Name)
  153. // If successful then update the previous log index.
  154. p.mutex.Lock()
  155. if resp.Success {
  156. if len(req.Entries) > 0 {
  157. p.prevLogIndex = req.Entries[len(req.Entries)-1].Index
  158. // if peer append a log entry from the current term
  159. // we set append to true
  160. if req.Entries[len(req.Entries)-1].Term == p.server.currentTerm {
  161. resp.append = true
  162. }
  163. }
  164. traceln("peer.flush.success: ", p.server.Name(), "->", p.Name, "; idx =", p.prevLogIndex)
  165. // If it was unsuccessful then decrement the previous log index and
  166. // we'll try again next time.
  167. } else {
  168. if resp.CommitIndex >= p.prevLogIndex {
  169. // we may miss a response from peer
  170. // so maybe the peer has commited the logs we sent
  171. // but we did not receive the success reply and did not increase
  172. // the prevLogIndex
  173. p.prevLogIndex = resp.CommitIndex
  174. debugln("peer.flush.commitIndex: ", p.server.Name(), "->", p.Name, " idx =", p.prevLogIndex)
  175. } else if p.prevLogIndex > 0 {
  176. // Decrement the previous log index down until we find a match. Don't
  177. // let it go below where the peer's commit index is though. That's a
  178. // problem.
  179. p.prevLogIndex--
  180. // if it not enough, we directly decrease to the index of the
  181. if p.prevLogIndex > resp.Index {
  182. p.prevLogIndex = resp.Index
  183. }
  184. debugln("peer.flush.decrement: ", p.server.Name(), "->", p.Name, " idx =", p.prevLogIndex)
  185. }
  186. }
  187. p.mutex.Unlock()
  188. // Attach the peer to resp, thus server can know where it comes from
  189. resp.peer = p.Name
  190. // Send response to server for processing.
  191. p.server.send(resp)
  192. }
  193. // Sends an Snapshot request to the peer through the transport.
  194. func (p *Peer) sendSnapshotRequest(req *SnapshotRequest) {
  195. debugln("peer.snap.send: ", p.Name)
  196. resp := p.server.Transporter().SendSnapshotRequest(p.server, p, req)
  197. if resp == nil {
  198. debugln("peer.snap.timeout: ", p.Name)
  199. return
  200. }
  201. debugln("peer.snap.recv: ", p.Name)
  202. // If successful, the peer should have been to snapshot state
  203. // Send it the snapshot!
  204. if resp.Success {
  205. p.sendSnapshotRecoveryRequest()
  206. } else {
  207. debugln("peer.snap.failed: ", p.Name)
  208. return
  209. }
  210. }
  211. // Sends an Snapshot Recovery request to the peer through the transport.
  212. func (p *Peer) sendSnapshotRecoveryRequest() {
  213. req := newSnapshotRecoveryRequest(p.server.name, p.server.lastSnapshot)
  214. debugln("peer.snap.recovery.send: ", p.Name)
  215. resp := p.server.Transporter().SendSnapshotRecoveryRequest(p.server, p, req)
  216. if resp == nil {
  217. debugln("peer.snap.recovery.timeout: ", p.Name)
  218. return
  219. }
  220. if resp.Success {
  221. p.prevLogIndex = req.LastIndex
  222. } else {
  223. debugln("peer.snap.recovery.failed: ", p.Name)
  224. return
  225. }
  226. // Send response to server for processing.
  227. p.server.send(&AppendEntriesResponse{Term: resp.Term, Success: resp.Success, append: (resp.Term == p.server.currentTerm)})
  228. }
  229. //--------------------------------------
  230. // Vote Requests
  231. //--------------------------------------
  232. // send VoteRequest Request
  233. func (p *Peer) sendVoteRequest(req *RequestVoteRequest, c chan *RequestVoteResponse) {
  234. debugln("peer.vote: ", p.server.Name(), "->", p.Name)
  235. req.peer = p
  236. if resp := p.server.Transporter().SendVoteRequest(p.server, p, req); resp != nil {
  237. debugln("peer.vote: recv", p.server.Name(), "<-", p.Name)
  238. resp.peer = p
  239. c <- resp
  240. }
  241. }