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