peer.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. streamAppV2 = "streamMsgAppV2"
  43. streamMsg = "streamMsg"
  44. pipelineMsg = "pipeline"
  45. sendSnap = "sendMsgSnap"
  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. // attachOutgoingConn attachs the outgoing connection to the peer for
  56. // stream usage. After the call, the ownership of the outgoing
  57. // connection hands over to the peer. The peer will close the connection
  58. // when it is no longer used.
  59. attachOutgoingConn(conn *outgoingConn)
  60. // activeSince returns the time that the connection with the
  61. // peer becomes active.
  62. activeSince() time.Time
  63. // stop performs any necessary finalization and terminates the peer
  64. // elegantly.
  65. stop()
  66. }
  67. // peer is the representative of a remote raft node. Local raft node sends
  68. // messages to the remote through peer.
  69. // Each peer has two underlying mechanisms to send out a message: stream and
  70. // pipeline.
  71. // A stream is a receiver initialized long-polling connection, which
  72. // is always open to transfer messages. Besides general stream, peer also has
  73. // a optimized stream for sending msgApp since msgApp accounts for large part
  74. // of all messages. Only raft leader uses the optimized stream to send msgApp
  75. // to the remote follower node.
  76. // A pipeline is a series of http clients that send http requests to the remote.
  77. // It is only used when the stream has not been established.
  78. type peer struct {
  79. // id of the remote raft peer node
  80. id types.ID
  81. r Raft
  82. v3demo bool
  83. status *peerStatus
  84. msgAppV2Writer *streamWriter
  85. writer *streamWriter
  86. pipeline *pipeline
  87. snapSender *snapshotSender // snapshot sender to send v3 snapshot messages
  88. msgAppV2Reader *streamReader
  89. sendc chan raftpb.Message
  90. recvc chan raftpb.Message
  91. propc chan raftpb.Message
  92. newURLsC chan types.URLs
  93. // for testing
  94. pausec chan struct{}
  95. resumec chan struct{}
  96. stopc chan struct{}
  97. done chan struct{}
  98. }
  99. func startPeer(streamRt, pipelineRt http.RoundTripper, urls types.URLs, local, to, cid types.ID, snapst *snapshotStore, r Raft, fs *stats.FollowerStats, errorc chan error, v3demo bool) *peer {
  100. picker := newURLPicker(urls)
  101. status := newPeerStatus(to)
  102. p := &peer{
  103. id: to,
  104. r: r,
  105. v3demo: v3demo,
  106. status: status,
  107. msgAppV2Writer: startStreamWriter(to, status, fs, r),
  108. writer: startStreamWriter(to, status, fs, r),
  109. pipeline: newPipeline(pipelineRt, picker, local, to, cid, status, fs, r, errorc),
  110. snapSender: newSnapshotSender(pipelineRt, picker, local, to, cid, status, snapst, r, errorc),
  111. sendc: make(chan raftpb.Message),
  112. recvc: make(chan raftpb.Message, recvBufSize),
  113. propc: make(chan raftpb.Message, maxPendingProposals),
  114. newURLsC: make(chan types.URLs),
  115. pausec: make(chan struct{}),
  116. resumec: make(chan struct{}),
  117. stopc: make(chan struct{}),
  118. done: make(chan struct{}),
  119. }
  120. // Use go-routine for process of MsgProp because it is
  121. // blocking when there is no leader.
  122. ctx, cancel := context.WithCancel(context.Background())
  123. go func() {
  124. for {
  125. select {
  126. case mm := <-p.propc:
  127. if err := r.Process(ctx, mm); err != nil {
  128. plog.Warningf("failed to process raft message (%v)", err)
  129. }
  130. case <-p.stopc:
  131. return
  132. }
  133. }
  134. }()
  135. p.msgAppV2Reader = startStreamReader(streamRt, picker, streamTypeMsgAppV2, local, to, cid, status, p.recvc, p.propc, errorc)
  136. reader := startStreamReader(streamRt, picker, streamTypeMessage, local, to, cid, status, p.recvc, p.propc, errorc)
  137. go func() {
  138. var paused bool
  139. for {
  140. select {
  141. case m := <-p.sendc:
  142. if paused {
  143. continue
  144. }
  145. if p.v3demo && isMsgSnap(m) {
  146. go p.snapSender.send(m)
  147. continue
  148. }
  149. writec, name := p.pick(m)
  150. select {
  151. case writec <- m:
  152. default:
  153. p.r.ReportUnreachable(m.To)
  154. if isMsgSnap(m) {
  155. p.r.ReportSnapshot(m.To, raft.SnapshotFailure)
  156. }
  157. if status.isActive() {
  158. plog.MergeWarningf("dropped %s to %s since %s's sending buffer is full", m.Type, p.id, name)
  159. } else {
  160. plog.Debugf("dropped %s to %s since %s's sending buffer is full", m.Type, p.id, name)
  161. }
  162. }
  163. case mm := <-p.recvc:
  164. if err := r.Process(context.TODO(), mm); err != nil {
  165. plog.Warningf("failed to process raft message (%v)", err)
  166. }
  167. case urls := <-p.newURLsC:
  168. picker.update(urls)
  169. case <-p.pausec:
  170. paused = true
  171. case <-p.resumec:
  172. paused = false
  173. case <-p.stopc:
  174. cancel()
  175. p.msgAppV2Writer.stop()
  176. p.writer.stop()
  177. p.pipeline.stop()
  178. p.snapSender.stop()
  179. p.msgAppV2Reader.stop()
  180. reader.stop()
  181. close(p.done)
  182. return
  183. }
  184. }
  185. }()
  186. return p
  187. }
  188. func (p *peer) send(m raftpb.Message) {
  189. select {
  190. case p.sendc <- m:
  191. case <-p.done:
  192. }
  193. }
  194. func (p *peer) update(urls types.URLs) {
  195. select {
  196. case p.newURLsC <- urls:
  197. case <-p.done:
  198. }
  199. }
  200. func (p *peer) attachOutgoingConn(conn *outgoingConn) {
  201. var ok bool
  202. switch conn.t {
  203. case streamTypeMsgAppV2:
  204. ok = p.msgAppV2Writer.attach(conn)
  205. case streamTypeMessage:
  206. ok = p.writer.attach(conn)
  207. default:
  208. plog.Panicf("unhandled stream type %s", conn.t)
  209. }
  210. if !ok {
  211. conn.Close()
  212. }
  213. }
  214. func (p *peer) activeSince() time.Time { return p.status.activeSince }
  215. // Pause pauses the peer. The peer will simply drops all incoming
  216. // messages without retruning an error.
  217. func (p *peer) Pause() {
  218. select {
  219. case p.pausec <- struct{}{}:
  220. case <-p.done:
  221. }
  222. }
  223. // Resume resumes a paused peer.
  224. func (p *peer) Resume() {
  225. select {
  226. case p.resumec <- struct{}{}:
  227. case <-p.done:
  228. }
  229. }
  230. func (p *peer) stop() {
  231. close(p.stopc)
  232. <-p.done
  233. }
  234. // pick picks a chan for sending the given message. The picked chan and the picked chan
  235. // string name are returned.
  236. func (p *peer) pick(m raftpb.Message) (writec chan<- raftpb.Message, picked string) {
  237. var ok bool
  238. // Considering MsgSnap may have a big size, e.g., 1G, and will block
  239. // stream for a long time, only use one of the N pipelines to send MsgSnap.
  240. if isMsgSnap(m) {
  241. return p.pipeline.msgc, pipelineMsg
  242. } else if writec, ok = p.msgAppV2Writer.writec(); ok && isMsgApp(m) {
  243. return writec, streamAppV2
  244. } else if writec, ok = p.writer.writec(); ok {
  245. return writec, streamMsg
  246. }
  247. return p.pipeline.msgc, pipelineMsg
  248. }
  249. func isMsgApp(m raftpb.Message) bool { return m.Type == raftpb.MsgApp }
  250. func isMsgSnap(m raftpb.Message) bool { return m.Type == raftpb.MsgSnap }