peer.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. "log"
  17. "net/http"
  18. "time"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  20. "github.com/coreos/etcd/etcdserver/stats"
  21. "github.com/coreos/etcd/pkg/types"
  22. "github.com/coreos/etcd/raft"
  23. "github.com/coreos/etcd/raft/raftpb"
  24. )
  25. const (
  26. DialTimeout = time.Second
  27. // ConnRead/WriteTimeout is the i/o timeout set on each connection rafthttp pkg creates.
  28. // A 5 seconds timeout is good enough for recycling bad connections. Or we have to wait for
  29. // tcp keepalive failing to detect a bad connection, which is at minutes level.
  30. // For long term streaming connections, rafthttp pkg sends application level linkHeartbeat
  31. // to keep the connection alive.
  32. // For short term pipeline connections, the connection MUST be killed to avoid it being
  33. // put back to http pkg connection pool.
  34. ConnReadTimeout = 5 * time.Second
  35. ConnWriteTimeout = 5 * time.Second
  36. recvBufSize = 4096
  37. // maxPendingProposals holds the proposals during one leader election process.
  38. // Generally one leader election takes at most 1 sec. It should have
  39. // 0-2 election conflicts, and each one takes 0.5 sec.
  40. // We assume the number of concurrent proposers is smaller than 4096.
  41. // One client blocks on its proposal for at least 1 sec, so 4096 is enough
  42. // to hold all proposals.
  43. maxPendingProposals = 4096
  44. streamApp = "streamMsgApp"
  45. streamAppV2 = "streamMsgAppV2"
  46. streamMsg = "streamMsg"
  47. pipelineMsg = "pipeline"
  48. )
  49. var (
  50. bufSizeMap = map[string]int{
  51. streamApp: streamBufSize,
  52. streamAppV2: streamBufSize,
  53. streamMsg: streamBufSize,
  54. pipelineMsg: pipelineBufSize,
  55. }
  56. )
  57. type Peer interface {
  58. // Send sends the message to the remote peer. The function is non-blocking
  59. // and has no promise that the message will be received by the remote.
  60. // When it fails to send message out, it will report the status to underlying
  61. // raft.
  62. Send(m raftpb.Message)
  63. // Update updates the urls of remote peer.
  64. Update(urls types.URLs)
  65. // setTerm sets the term of ongoing communication.
  66. setTerm(term uint64)
  67. // attachOutgoingConn attachs the outgoing connection to the peer for
  68. // stream usage. After the call, the ownership of the outgoing
  69. // connection hands over to the peer. The peer will close the connection
  70. // when it is no longer used.
  71. attachOutgoingConn(conn *outgoingConn)
  72. // Stop performs any necessary finalization and terminates the peer
  73. // elegantly.
  74. Stop()
  75. }
  76. // peer is the representative of a remote raft node. Local raft node sends
  77. // messages to the remote through peer.
  78. // Each peer has two underlying mechanisms to send out a message: stream and
  79. // pipeline.
  80. // A stream is a receiver initialized long-polling connection, which
  81. // is always open to transfer messages. Besides general stream, peer also has
  82. // a optimized stream for sending msgApp since msgApp accounts for large part
  83. // of all messages. Only raft leader uses the optimized stream to send msgApp
  84. // to the remote follower node.
  85. // A pipeline is a series of http clients that send http requests to the remote.
  86. // It is only used when the stream has not been established.
  87. type peer struct {
  88. // id of the remote raft peer node
  89. id types.ID
  90. r Raft
  91. msgAppWriter *streamWriter
  92. writer *streamWriter
  93. pipeline *pipeline
  94. msgAppReader *streamReader
  95. sendc chan raftpb.Message
  96. recvc chan raftpb.Message
  97. propc chan raftpb.Message
  98. newURLsC chan types.URLs
  99. termc chan uint64
  100. // for testing
  101. pausec chan struct{}
  102. resumec chan struct{}
  103. stopc chan struct{}
  104. done chan struct{}
  105. }
  106. func startPeer(tr http.RoundTripper, urls types.URLs, local, to, cid types.ID, r Raft, fs *stats.FollowerStats, errorc chan error) *peer {
  107. picker := newURLPicker(urls)
  108. p := &peer{
  109. id: to,
  110. r: r,
  111. msgAppWriter: startStreamWriter(to, fs, r),
  112. writer: startStreamWriter(to, fs, r),
  113. pipeline: newPipeline(tr, picker, local, to, cid, fs, r, errorc),
  114. sendc: make(chan raftpb.Message),
  115. recvc: make(chan raftpb.Message, recvBufSize),
  116. propc: make(chan raftpb.Message, maxPendingProposals),
  117. newURLsC: make(chan types.URLs),
  118. termc: make(chan uint64),
  119. pausec: make(chan struct{}),
  120. resumec: make(chan struct{}),
  121. stopc: make(chan struct{}),
  122. done: make(chan struct{}),
  123. }
  124. // Use go-routine for process of MsgProp because it is
  125. // blocking when there is no leader.
  126. ctx, cancel := context.WithCancel(context.Background())
  127. go func() {
  128. for {
  129. select {
  130. case mm := <-p.propc:
  131. if err := r.Process(ctx, mm); err != nil {
  132. log.Printf("peer: process raft message error: %v", err)
  133. }
  134. case <-p.stopc:
  135. return
  136. }
  137. }
  138. }()
  139. go func() {
  140. var paused bool
  141. p.msgAppReader = startStreamReader(tr, picker, streamTypeMsgAppV2, local, to, cid, p.recvc, p.propc, errorc)
  142. reader := startStreamReader(tr, picker, streamTypeMessage, local, to, cid, p.recvc, p.propc, errorc)
  143. for {
  144. select {
  145. case m := <-p.sendc:
  146. if paused {
  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. log.Printf("peer: dropping %s to %s since %s with %d-size buffer is blocked",
  158. m.Type, p.id, name, bufSizeMap[name])
  159. }
  160. case mm := <-p.recvc:
  161. if err := r.Process(context.TODO(), mm); err != nil {
  162. log.Printf("peer: process raft message error: %v", err)
  163. }
  164. case urls := <-p.newURLsC:
  165. picker.update(urls)
  166. case <-p.pausec:
  167. paused = true
  168. case <-p.resumec:
  169. paused = false
  170. case <-p.stopc:
  171. cancel()
  172. p.msgAppWriter.stop()
  173. p.writer.stop()
  174. p.pipeline.stop()
  175. p.msgAppReader.stop()
  176. reader.stop()
  177. close(p.done)
  178. return
  179. }
  180. }
  181. }()
  182. return p
  183. }
  184. func (p *peer) Send(m raftpb.Message) {
  185. select {
  186. case p.sendc <- m:
  187. case <-p.done:
  188. }
  189. }
  190. func (p *peer) Update(urls types.URLs) {
  191. select {
  192. case p.newURLsC <- urls:
  193. case <-p.done:
  194. }
  195. }
  196. func (p *peer) setTerm(term uint64) { p.msgAppReader.updateMsgAppTerm(term) }
  197. func (p *peer) attachOutgoingConn(conn *outgoingConn) {
  198. var ok bool
  199. switch conn.t {
  200. case streamTypeMsgApp, streamTypeMsgAppV2:
  201. ok = p.msgAppWriter.attach(conn)
  202. case streamTypeMessage:
  203. ok = p.writer.attach(conn)
  204. default:
  205. log.Panicf("rafthttp: unhandled stream type %s", conn.t)
  206. }
  207. if !ok {
  208. conn.Close()
  209. }
  210. }
  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 }