peer.go 8.1 KB

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