peer.go 6.6 KB

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