peer.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. r Raft
  86. msgAppWriter *streamWriter
  87. writer *streamWriter
  88. pipeline *pipeline
  89. sendc chan raftpb.Message
  90. recvc chan raftpb.Message
  91. propc chan raftpb.Message
  92. newURLsC chan types.URLs
  93. // for testing
  94. pausec chan struct{}
  95. resumec chan struct{}
  96. stopc chan struct{}
  97. done chan struct{}
  98. }
  99. func startPeer(tr http.RoundTripper, urls types.URLs, local, to, cid types.ID, r Raft, fs *stats.FollowerStats, errorc chan error) *peer {
  100. picker := newURLPicker(urls)
  101. p := &peer{
  102. id: to,
  103. r: r,
  104. msgAppWriter: startStreamWriter(to, fs, r),
  105. writer: startStreamWriter(to, fs, r),
  106. pipeline: newPipeline(tr, picker, to, cid, fs, r, errorc),
  107. sendc: make(chan raftpb.Message),
  108. recvc: make(chan raftpb.Message, recvBufSize),
  109. propc: make(chan raftpb.Message, maxPendingProposals),
  110. newURLsC: make(chan types.URLs),
  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. log.Printf("peer: process raft message error: %v", err)
  125. }
  126. case <-p.stopc:
  127. return
  128. }
  129. }
  130. }()
  131. go func() {
  132. var paused bool
  133. msgAppReader := startStreamReader(tr, picker, streamTypeMsgApp, local, to, cid, p.recvc, p.propc)
  134. reader := startStreamReader(tr, picker, streamTypeMessage, local, to, cid, p.recvc, p.propc)
  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. log.Printf("peer: dropping %s to %s since %s with %d-size buffer is blocked",
  147. m.Type, p.id, name, bufSizeMap[name])
  148. }
  149. case mm := <-p.recvc:
  150. if mm.Type == raftpb.MsgApp {
  151. msgAppReader.updateMsgAppTerm(mm.Term)
  152. }
  153. if err := r.Process(context.TODO(), mm); err != nil {
  154. log.Printf("peer: process raft message error: %v", err)
  155. }
  156. case urls := <-p.newURLsC:
  157. picker.update(urls)
  158. case <-p.pausec:
  159. paused = true
  160. case <-p.resumec:
  161. paused = false
  162. case <-p.stopc:
  163. cancel()
  164. p.msgAppWriter.stop()
  165. p.writer.stop()
  166. p.pipeline.stop()
  167. msgAppReader.stop()
  168. reader.stop()
  169. close(p.done)
  170. return
  171. }
  172. }
  173. }()
  174. return p
  175. }
  176. func (p *peer) Send(m raftpb.Message) {
  177. select {
  178. case p.sendc <- m:
  179. case <-p.done:
  180. }
  181. }
  182. func (p *peer) Update(urls types.URLs) {
  183. select {
  184. case p.newURLsC <- urls:
  185. case <-p.done:
  186. }
  187. }
  188. func (p *peer) attachOutgoingConn(conn *outgoingConn) {
  189. var ok bool
  190. switch conn.t {
  191. case streamTypeMsgApp:
  192. ok = p.msgAppWriter.attach(conn)
  193. case streamTypeMessage:
  194. ok = p.writer.attach(conn)
  195. default:
  196. log.Panicf("rafthttp: unhandled stream type %s", conn.t)
  197. }
  198. if !ok {
  199. conn.Close()
  200. }
  201. }
  202. // Pause pauses the peer. The peer will simply drops all incoming
  203. // messages without retruning an error.
  204. func (p *peer) Pause() {
  205. select {
  206. case p.pausec <- struct{}{}:
  207. case <-p.done:
  208. }
  209. }
  210. // Resume resumes a paused peer.
  211. func (p *peer) Resume() {
  212. select {
  213. case p.resumec <- struct{}{}:
  214. case <-p.done:
  215. }
  216. }
  217. func (p *peer) Stop() {
  218. close(p.stopc)
  219. <-p.done
  220. }
  221. // pick picks a chan for sending the given message. The picked chan and the picked chan
  222. // string name are returned.
  223. func (p *peer) pick(m raftpb.Message) (writec chan<- raftpb.Message, picked string) {
  224. var ok bool
  225. // Considering MsgSnap may have a big size, e.g., 1G, and will block
  226. // stream for a long time, only use one of the N pipelines to send MsgSnap.
  227. if isMsgSnap(m) {
  228. return p.pipeline.msgc, pipelineMsg
  229. } else if writec, ok = p.msgAppWriter.writec(); ok && canUseMsgAppStream(m) {
  230. return writec, streamApp
  231. } else if writec, ok = p.writer.writec(); ok {
  232. return writec, streamMsg
  233. }
  234. return p.pipeline.msgc, pipelineMsg
  235. }
  236. func isMsgSnap(m raftpb.Message) bool { return m.Type == raftpb.MsgSnap }