peer.go 7.7 KB

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