peer.go 8.7 KB

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