peer.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package rafthttp
  15. import (
  16. "log"
  17. "net/http"
  18. "time"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  20. "github.com/coreos/etcd/etcdserver/stats"
  21. "github.com/coreos/etcd/pkg/types"
  22. "github.com/coreos/etcd/raft"
  23. "github.com/coreos/etcd/raft/raftpb"
  24. )
  25. const (
  26. DialTimeout = time.Second
  27. // ConnRead/WriteTimeout is the i/o timeout set on each connection rafthttp pkg creates.
  28. // A 5 seconds timeout is good enough for recycling bad connections. Or we have to wait for
  29. // tcp keepalive failing to detect a bad connection, which is at minutes level.
  30. // For long term streaming connections, rafthttp pkg sends application level linkHeartbeat
  31. // to keep the connection alive.
  32. // For short term pipeline connections, the connection MUST be killed to avoid it being
  33. // put back to http pkg connection pool.
  34. ConnReadTimeout = 5 * time.Second
  35. ConnWriteTimeout = 5 * time.Second
  36. recvBufSize = 4096
  37. // maxPendingProposals holds the proposals during one leader election process.
  38. // Generally one leader election takes at most 1 sec. It should have
  39. // 0-2 election conflicts, and each one takes 0.5 sec.
  40. // We assume the number of concurrent proposers is smaller than 4096.
  41. // One client blocks on its proposal for at least 1 sec, so 4096 is enough
  42. // to hold all proposals.
  43. maxPendingProposals = 4096
  44. streamApp = "streamMsgApp"
  45. streamAppV2 = "streamMsgAppV2"
  46. streamMsg = "streamMsg"
  47. pipelineMsg = "pipeline"
  48. )
  49. type Peer interface {
  50. // Send sends the message to the remote peer. The function is non-blocking
  51. // and has no promise that the message will be received by the remote.
  52. // When it fails to send message out, it will report the status to underlying
  53. // raft.
  54. Send(m raftpb.Message)
  55. // Update updates the urls of remote peer.
  56. Update(urls types.URLs)
  57. // setTerm sets the term of ongoing communication.
  58. setTerm(term uint64)
  59. // attachOutgoingConn attachs the outgoing connection to the peer for
  60. // stream usage. After the call, the ownership of the outgoing
  61. // connection hands over to the peer. The peer will close the connection
  62. // when it is no longer used.
  63. attachOutgoingConn(conn *outgoingConn)
  64. // Stop performs any necessary finalization and terminates the peer
  65. // elegantly.
  66. Stop()
  67. }
  68. // peer is the representative of a remote raft node. Local raft node sends
  69. // messages to the remote through peer.
  70. // Each peer has two underlying mechanisms to send out a message: stream and
  71. // pipeline.
  72. // A stream is a receiver initialized long-polling connection, which
  73. // is always open to transfer messages. Besides general stream, peer also has
  74. // a optimized stream for sending msgApp since msgApp accounts for large part
  75. // of all messages. Only raft leader uses the optimized stream to send msgApp
  76. // to the remote follower node.
  77. // A pipeline is a series of http clients that send http requests to the remote.
  78. // It is only used when the stream has not been established.
  79. type peer struct {
  80. // id of the remote raft peer node
  81. id types.ID
  82. r Raft
  83. msgAppWriter *streamWriter
  84. writer *streamWriter
  85. pipeline *pipeline
  86. msgAppReader *streamReader
  87. sendc chan raftpb.Message
  88. recvc chan raftpb.Message
  89. propc chan raftpb.Message
  90. newURLsC chan types.URLs
  91. termc chan uint64
  92. // for testing
  93. pausec chan struct{}
  94. resumec chan struct{}
  95. stopc chan struct{}
  96. done chan struct{}
  97. }
  98. func startPeer(tr http.RoundTripper, urls types.URLs, local, to, cid types.ID, r Raft, fs *stats.FollowerStats, errorc chan error) *peer {
  99. picker := newURLPicker(urls)
  100. p := &peer{
  101. id: to,
  102. r: r,
  103. msgAppWriter: startStreamWriter(to, fs, r),
  104. writer: startStreamWriter(to, fs, r),
  105. pipeline: newPipeline(tr, picker, local, to, cid, fs, r, errorc),
  106. sendc: make(chan raftpb.Message),
  107. recvc: make(chan raftpb.Message, recvBufSize),
  108. propc: make(chan raftpb.Message, maxPendingProposals),
  109. newURLsC: make(chan types.URLs),
  110. termc: make(chan uint64),
  111. pausec: make(chan struct{}),
  112. resumec: make(chan struct{}),
  113. stopc: make(chan struct{}),
  114. done: make(chan struct{}),
  115. }
  116. // Use go-routine for process of MsgProp because it is
  117. // blocking when there is no leader.
  118. ctx, cancel := context.WithCancel(context.Background())
  119. go func() {
  120. for {
  121. select {
  122. case mm := <-p.propc:
  123. if err := r.Process(ctx, mm); err != nil {
  124. log.Printf("peer: process raft message error: %v", err)
  125. }
  126. case <-p.stopc:
  127. return
  128. }
  129. }
  130. }()
  131. go func() {
  132. var paused bool
  133. p.msgAppReader = startStreamReader(tr, picker, streamTypeMsgAppV2, local, to, cid, p.recvc, p.propc, errorc)
  134. reader := startStreamReader(tr, picker, streamTypeMessage, local, to, cid, p.recvc, p.propc, errorc)
  135. for {
  136. select {
  137. case m := <-p.sendc:
  138. if paused {
  139. continue
  140. }
  141. writec, name := p.pick(m)
  142. select {
  143. case writec <- m:
  144. default:
  145. p.r.ReportUnreachable(m.To)
  146. if isMsgSnap(m) {
  147. p.r.ReportSnapshot(m.To, raft.SnapshotFailure)
  148. }
  149. log.Printf("peer: dropping %s to %s since %s's sending buffer is full", m.Type, p.id, name)
  150. }
  151. case mm := <-p.recvc:
  152. if err := r.Process(context.TODO(), mm); err != nil {
  153. log.Printf("peer: process raft message error: %v", err)
  154. }
  155. case urls := <-p.newURLsC:
  156. picker.update(urls)
  157. case <-p.pausec:
  158. paused = true
  159. case <-p.resumec:
  160. paused = false
  161. case <-p.stopc:
  162. cancel()
  163. p.msgAppWriter.stop()
  164. p.writer.stop()
  165. p.pipeline.stop()
  166. p.msgAppReader.stop()
  167. reader.stop()
  168. close(p.done)
  169. return
  170. }
  171. }
  172. }()
  173. return p
  174. }
  175. func (p *peer) Send(m raftpb.Message) {
  176. select {
  177. case p.sendc <- m:
  178. case <-p.done:
  179. }
  180. }
  181. func (p *peer) Update(urls types.URLs) {
  182. select {
  183. case p.newURLsC <- urls:
  184. case <-p.done:
  185. }
  186. }
  187. func (p *peer) setTerm(term uint64) { p.msgAppReader.updateMsgAppTerm(term) }
  188. func (p *peer) attachOutgoingConn(conn *outgoingConn) {
  189. var ok bool
  190. switch conn.t {
  191. case streamTypeMsgApp, streamTypeMsgAppV2:
  192. ok = p.msgAppWriter.attach(conn)
  193. case streamTypeMessage:
  194. ok = p.writer.attach(conn)
  195. default:
  196. log.Panicf("rafthttp: unhandled stream type %s", conn.t)
  197. }
  198. if !ok {
  199. conn.Close()
  200. }
  201. }
  202. // Pause pauses the peer. The peer will simply drops all incoming
  203. // messages without retruning an error.
  204. func (p *peer) Pause() {
  205. select {
  206. case p.pausec <- struct{}{}:
  207. case <-p.done:
  208. }
  209. }
  210. // Resume resumes a paused peer.
  211. func (p *peer) Resume() {
  212. select {
  213. case p.resumec <- struct{}{}:
  214. case <-p.done:
  215. }
  216. }
  217. func (p *peer) Stop() {
  218. close(p.stopc)
  219. <-p.done
  220. }
  221. // pick picks a chan for sending the given message. The picked chan and the picked chan
  222. // string name are returned.
  223. func (p *peer) pick(m raftpb.Message) (writec chan<- raftpb.Message, picked string) {
  224. var ok bool
  225. // Considering MsgSnap may have a big size, e.g., 1G, and will block
  226. // stream for a long time, only use one of the N pipelines to send MsgSnap.
  227. if isMsgSnap(m) {
  228. return p.pipeline.msgc, pipelineMsg
  229. } else if writec, ok = p.msgAppWriter.writec(); ok && canUseMsgAppStream(m) {
  230. return writec, streamApp
  231. } else if writec, ok = p.writer.writec(); ok {
  232. return writec, streamMsg
  233. }
  234. return p.pipeline.msgc, pipelineMsg
  235. }
  236. func isMsgSnap(m raftpb.Message) bool { return m.Type == raftpb.MsgSnap }