peer.go 5.9 KB

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