peer.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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(u string)
  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. newURLc chan string
  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, u string, local, to, cid types.ID, r Raft, fs *stats.FollowerStats, errorc chan error) *peer {
  91. p := &peer{
  92. id: to,
  93. msgAppWriter: startStreamWriter(fs, r),
  94. writer: startStreamWriter(fs, r),
  95. pipeline: newPipeline(tr, u, to, cid, fs, r, errorc),
  96. sendc: make(chan raftpb.Message),
  97. recvc: make(chan raftpb.Message, recvBufSize),
  98. newURLc: make(chan string),
  99. pausec: make(chan struct{}),
  100. resumec: make(chan struct{}),
  101. stopc: make(chan struct{}),
  102. done: make(chan struct{}),
  103. }
  104. go func() {
  105. var paused bool
  106. msgAppReader := startStreamReader(tr, u, streamTypeMsgApp, local, to, cid, p.recvc)
  107. reader := startStreamReader(tr, u, streamTypeMessage, local, to, cid, p.recvc)
  108. for {
  109. select {
  110. case m := <-p.sendc:
  111. if paused {
  112. continue
  113. }
  114. writec, name := p.pick(m)
  115. select {
  116. case writec <- m:
  117. default:
  118. log.Printf("peer: dropping %s to %s since %s with %d-size buffer is blocked",
  119. m.Type, p.id, name, bufSizeMap[name])
  120. }
  121. case mm := <-p.recvc:
  122. if mm.Type == raftpb.MsgApp {
  123. msgAppReader.updateMsgAppTerm(mm.Term)
  124. }
  125. if err := r.Process(context.TODO(), mm); err != nil {
  126. log.Printf("peer: process raft message error: %v", err)
  127. }
  128. case u := <-p.newURLc:
  129. msgAppReader.update(u)
  130. reader.update(u)
  131. p.pipeline.update(u)
  132. case <-p.pausec:
  133. paused = true
  134. case <-p.resumec:
  135. paused = false
  136. case <-p.stopc:
  137. p.msgAppWriter.stop()
  138. p.writer.stop()
  139. p.pipeline.stop()
  140. msgAppReader.stop()
  141. reader.stop()
  142. close(p.done)
  143. return
  144. }
  145. }
  146. }()
  147. return p
  148. }
  149. func (p *peer) Send(m raftpb.Message) {
  150. select {
  151. case p.sendc <- m:
  152. case <-p.done:
  153. log.Panicf("peer: unexpected stopped")
  154. }
  155. }
  156. func (p *peer) Update(u string) {
  157. select {
  158. case p.newURLc <- u:
  159. case <-p.done:
  160. log.Panicf("peer: unexpected stopped")
  161. }
  162. }
  163. func (p *peer) attachOutgoingConn(conn *outgoingConn) {
  164. var ok bool
  165. switch conn.t {
  166. case streamTypeMsgApp:
  167. ok = p.msgAppWriter.attach(conn)
  168. case streamTypeMessage:
  169. ok = p.writer.attach(conn)
  170. default:
  171. log.Panicf("rafthttp: unhandled stream type %s", conn.t)
  172. }
  173. if !ok {
  174. conn.Close()
  175. }
  176. }
  177. // Pause pauses the peer. The peer will simply drops all incoming
  178. // messages without retruning an error.
  179. func (p *peer) Pause() {
  180. select {
  181. case p.pausec <- struct{}{}:
  182. case <-p.done:
  183. }
  184. }
  185. // Resume resumes a paused peer.
  186. func (p *peer) Resume() {
  187. select {
  188. case p.resumec <- struct{}{}:
  189. case <-p.done:
  190. }
  191. }
  192. func (p *peer) Stop() {
  193. close(p.stopc)
  194. <-p.done
  195. }
  196. // pick picks a chan for sending the given message. The picked chan and the picked chan
  197. // string name are returned.
  198. func (p *peer) pick(m raftpb.Message) (writec chan raftpb.Message, picked string) {
  199. switch {
  200. // Considering MsgSnap may have a big size, e.g., 1G, and will block
  201. // stream for a long time, only use one of the N pipelines to send MsgSnap.
  202. case isMsgSnap(m):
  203. return p.pipeline.msgc, pipelineMsg
  204. case p.msgAppWriter.isWorking() && canUseMsgAppStream(m):
  205. return p.msgAppWriter.msgc, streamApp
  206. case p.writer.isWorking():
  207. return p.writer.msgc, streamMsg
  208. default:
  209. return p.pipeline.msgc, pipelineMsg
  210. }
  211. return
  212. }
  213. func isMsgSnap(m raftpb.Message) bool { return m.Type == raftpb.MsgSnap }