peer.go 8.5 KB

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