peer.go 7.5 KB

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