peer.go 7.9 KB

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