peer.go 6.1 KB

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