peer.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. DialTimeout = time.Second
  26. // ConnRead/WriteTimeout is the i/o timeout set on each connection rafthttp pkg creates.
  27. // A 5 seconds timeout is good enough for recycling bad connections. Or we have to wait for
  28. // tcp keepalive failing to detect a bad connection, which is at minutes level.
  29. // For long term streaming connections, rafthttp pkg sends application level linkHeartbeat
  30. // to keep the connection alive.
  31. // For short term pipeline connections, the connection MUST be killed to avoid it being
  32. // put back to http pkg connection pool.
  33. ConnReadTimeout = 5 * time.Second
  34. ConnWriteTimeout = 5 * time.Second
  35. recvBufSize = 4096
  36. // maxPendingProposals holds the proposals during one leader election process.
  37. // Generally one leader election takes at most 1 sec. It should have
  38. // 0-2 election conflicts, and each one takes 0.5 sec.
  39. // We assume the number of concurrent proposers is smaller than 4096.
  40. // One client blocks on its proposal for at least 1 sec, so 4096 is enough
  41. // to hold all proposals.
  42. maxPendingProposals = 4096
  43. streamApp = "streamMsgApp"
  44. streamAppV2 = "streamMsgAppV2"
  45. streamMsg = "streamMsg"
  46. pipelineMsg = "pipeline"
  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. // 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. msgAppWriter *streamWriter
  83. writer *streamWriter
  84. pipeline *pipeline
  85. msgAppReader *streamReader
  86. sendc chan raftpb.Message
  87. recvc chan raftpb.Message
  88. propc chan raftpb.Message
  89. newURLsC chan types.URLs
  90. termc chan uint64
  91. // for testing
  92. pausec chan struct{}
  93. resumec chan struct{}
  94. stopc chan struct{}
  95. done chan struct{}
  96. }
  97. func startPeer(tr http.RoundTripper, urls types.URLs, local, to, cid types.ID, r Raft, fs *stats.FollowerStats, errorc chan error, term uint64) *peer {
  98. picker := newURLPicker(urls)
  99. status := newPeerStatus(to)
  100. p := &peer{
  101. id: to,
  102. r: r,
  103. msgAppWriter: startStreamWriter(to, status, fs, r),
  104. writer: startStreamWriter(to, status, fs, r),
  105. pipeline: newPipeline(tr, picker, local, to, cid, status, fs, r, errorc),
  106. sendc: make(chan raftpb.Message),
  107. recvc: make(chan raftpb.Message, recvBufSize),
  108. propc: make(chan raftpb.Message, maxPendingProposals),
  109. newURLsC: make(chan types.URLs),
  110. termc: make(chan uint64),
  111. pausec: make(chan struct{}),
  112. resumec: make(chan struct{}),
  113. stopc: make(chan struct{}),
  114. done: make(chan struct{}),
  115. }
  116. // Use go-routine for process of MsgProp because it is
  117. // blocking when there is no leader.
  118. ctx, cancel := context.WithCancel(context.Background())
  119. go func() {
  120. for {
  121. select {
  122. case mm := <-p.propc:
  123. if err := r.Process(ctx, mm); err != nil {
  124. plog.Warningf("failed to process raft message (%v)", err)
  125. }
  126. case <-p.stopc:
  127. return
  128. }
  129. }
  130. }()
  131. p.msgAppReader = startStreamReader(tr, picker, streamTypeMsgAppV2, local, to, cid, status, p.recvc, p.propc, errorc, term)
  132. reader := startStreamReader(tr, picker, streamTypeMessage, local, to, cid, status, p.recvc, p.propc, errorc, term)
  133. go func() {
  134. var paused bool
  135. for {
  136. select {
  137. case m := <-p.sendc:
  138. if paused {
  139. continue
  140. }
  141. writec, name := p.pick(m)
  142. select {
  143. case writec <- m:
  144. default:
  145. p.r.ReportUnreachable(m.To)
  146. if isMsgSnap(m) {
  147. p.r.ReportSnapshot(m.To, raft.SnapshotFailure)
  148. }
  149. if status.isActive() {
  150. plog.Warningf("dropped %s to %s since %s's sending buffer is full", m.Type, p.id, name)
  151. } else {
  152. plog.Debugf("dropped %s to %s since %s's sending buffer is full", m.Type, p.id, name)
  153. }
  154. }
  155. case mm := <-p.recvc:
  156. if err := r.Process(context.TODO(), mm); err != nil {
  157. plog.Warningf("failed to process raft message (%v)", err)
  158. }
  159. case urls := <-p.newURLsC:
  160. picker.update(urls)
  161. case <-p.pausec:
  162. paused = true
  163. case <-p.resumec:
  164. paused = false
  165. case <-p.stopc:
  166. cancel()
  167. p.msgAppWriter.stop()
  168. p.writer.stop()
  169. p.pipeline.stop()
  170. p.msgAppReader.stop()
  171. reader.stop()
  172. close(p.done)
  173. return
  174. }
  175. }
  176. }()
  177. return p
  178. }
  179. func (p *peer) Send(m raftpb.Message) {
  180. select {
  181. case p.sendc <- m:
  182. case <-p.done:
  183. }
  184. }
  185. func (p *peer) Update(urls types.URLs) {
  186. select {
  187. case p.newURLsC <- urls:
  188. case <-p.done:
  189. }
  190. }
  191. func (p *peer) setTerm(term uint64) { p.msgAppReader.updateMsgAppTerm(term) }
  192. func (p *peer) attachOutgoingConn(conn *outgoingConn) {
  193. var ok bool
  194. switch conn.t {
  195. case streamTypeMsgApp, streamTypeMsgAppV2:
  196. ok = p.msgAppWriter.attach(conn)
  197. case streamTypeMessage:
  198. ok = p.writer.attach(conn)
  199. default:
  200. plog.Panicf("unhandled stream type %s", conn.t)
  201. }
  202. if !ok {
  203. conn.Close()
  204. }
  205. }
  206. // Pause pauses the peer. The peer will simply drops all incoming
  207. // messages without retruning an error.
  208. func (p *peer) Pause() {
  209. select {
  210. case p.pausec <- struct{}{}:
  211. case <-p.done:
  212. }
  213. }
  214. // Resume resumes a paused peer.
  215. func (p *peer) Resume() {
  216. select {
  217. case p.resumec <- struct{}{}:
  218. case <-p.done:
  219. }
  220. }
  221. func (p *peer) Stop() {
  222. close(p.stopc)
  223. <-p.done
  224. }
  225. // pick picks a chan for sending the given message. The picked chan and the picked chan
  226. // string name are returned.
  227. func (p *peer) pick(m raftpb.Message) (writec chan<- raftpb.Message, picked string) {
  228. var ok bool
  229. // Considering MsgSnap may have a big size, e.g., 1G, and will block
  230. // stream for a long time, only use one of the N pipelines to send MsgSnap.
  231. if isMsgSnap(m) {
  232. return p.pipeline.msgc, pipelineMsg
  233. } else if writec, ok = p.msgAppWriter.writec(); ok && canUseMsgAppStream(m) {
  234. return writec, streamApp
  235. } else if writec, ok = p.writer.writec(); ok {
  236. return writec, streamMsg
  237. }
  238. return p.pipeline.msgc, pipelineMsg
  239. }
  240. func isMsgSnap(m raftpb.Message) bool { return m.Type == raftpb.MsgSnap }