peer.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. // Copyright 2015 The etcd Authors
  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. "sync"
  17. "time"
  18. "github.com/coreos/etcd/etcdserver/stats"
  19. "github.com/coreos/etcd/pkg/types"
  20. "github.com/coreos/etcd/raft"
  21. "github.com/coreos/etcd/raft/raftpb"
  22. "github.com/coreos/etcd/snap"
  23. "golang.org/x/net/context"
  24. )
  25. const (
  26. // ConnReadTimeout and ConnWriteTimeout are 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 linkHeartbeatMessage
  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. // maxPendingProposals holds the proposals during one leader election process.
  37. // Generally one leader election takes at most 1 sec. It should have
  38. // 0-2 election conflicts, and each one takes 0.5 sec.
  39. // We assume the number of concurrent proposers is smaller than 4096.
  40. // One client blocks on its proposal for at least 1 sec, so 4096 is enough
  41. // to hold all proposals.
  42. maxPendingProposals = 4096
  43. streamAppV2 = "streamMsgAppV2"
  44. streamMsg = "streamMsg"
  45. pipelineMsg = "pipeline"
  46. sendSnap = "sendMsgSnap"
  47. )
  48. type Peer interface {
  49. // send sends the message to the remote peer. The function is non-blocking
  50. // and has no promise that the message will be received by the remote.
  51. // When it fails to send message out, it will report the status to underlying
  52. // raft.
  53. send(m raftpb.Message)
  54. // sendSnap sends the merged snapshot message to the remote peer. Its behavior
  55. // is similar to send.
  56. sendSnap(m snap.Message)
  57. // update updates the urls of remote peer.
  58. update(urls types.URLs)
  59. // attachOutgoingConn attaches the outgoing connection to the peer for
  60. // stream usage. After the call, the ownership of the outgoing
  61. // connection hands over to the peer. The peer will close the connection
  62. // when it is no longer used.
  63. attachOutgoingConn(conn *outgoingConn)
  64. // activeSince returns the time that the connection with the
  65. // peer becomes active.
  66. activeSince() time.Time
  67. // stop performs any necessary finalization and terminates the peer
  68. // elegantly.
  69. stop()
  70. }
  71. // peer is the representative of a remote raft node. Local raft node sends
  72. // messages to the remote through peer.
  73. // Each peer has two underlying mechanisms to send out a message: stream and
  74. // pipeline.
  75. // A stream is a receiver initialized long-polling connection, which
  76. // is always open to transfer messages. Besides general stream, peer also has
  77. // a optimized stream for sending msgApp since msgApp accounts for large part
  78. // of all messages. Only raft leader uses the optimized stream to send msgApp
  79. // to the remote follower node.
  80. // A pipeline is a series of http clients that send http requests to the remote.
  81. // It is only used when the stream has not been established.
  82. type peer struct {
  83. // id of the remote raft peer node
  84. id types.ID
  85. r Raft
  86. status *peerStatus
  87. picker *urlPicker
  88. msgAppV2Writer *streamWriter
  89. writer *streamWriter
  90. pipeline *pipeline
  91. snapSender *snapshotSender // snapshot sender to send v3 snapshot messages
  92. msgAppV2Reader *streamReader
  93. msgAppReader *streamReader
  94. sendc chan raftpb.Message
  95. recvc chan raftpb.Message
  96. propc chan raftpb.Message
  97. mu sync.Mutex
  98. paused bool
  99. cancel context.CancelFunc // cancel pending works in go routine created by peer.
  100. stopc chan struct{}
  101. }
  102. func startPeer(transport *Transport, urls types.URLs, peerID types.ID, fs *stats.FollowerStats) *peer {
  103. plog.Infof("starting peer %s...", peerID)
  104. defer plog.Infof("started peer %s", peerID)
  105. status := newPeerStatus(peerID)
  106. picker := newURLPicker(urls)
  107. errorc := transport.ErrorC
  108. r := transport.Raft
  109. pipeline := &pipeline{
  110. peerID: peerID,
  111. tr: transport,
  112. picker: picker,
  113. status: status,
  114. followerStats: fs,
  115. raft: r,
  116. errorc: errorc,
  117. }
  118. pipeline.start()
  119. p := &peer{
  120. id: peerID,
  121. r: r,
  122. status: status,
  123. picker: picker,
  124. msgAppV2Writer: startStreamWriter(peerID, status, fs, r),
  125. writer: startStreamWriter(peerID, status, fs, r),
  126. pipeline: pipeline,
  127. snapSender: newSnapshotSender(transport, picker, peerID, status),
  128. sendc: make(chan raftpb.Message),
  129. recvc: make(chan raftpb.Message, recvBufSize),
  130. propc: make(chan raftpb.Message, maxPendingProposals),
  131. stopc: make(chan struct{}),
  132. }
  133. ctx, cancel := context.WithCancel(context.Background())
  134. p.cancel = cancel
  135. go func() {
  136. for {
  137. select {
  138. case mm := <-p.recvc:
  139. if err := r.Process(ctx, mm); err != nil {
  140. plog.Warningf("failed to process raft message (%v)", err)
  141. }
  142. case <-p.stopc:
  143. return
  144. }
  145. }
  146. }()
  147. // r.Process might block for processing proposal when there is no leader.
  148. // Thus propc must be put into a separate routine with recvc to avoid blocking
  149. // processing other raft messages.
  150. go func() {
  151. for {
  152. select {
  153. case mm := <-p.propc:
  154. if err := r.Process(ctx, mm); err != nil {
  155. plog.Warningf("failed to process raft message (%v)", err)
  156. }
  157. case <-p.stopc:
  158. return
  159. }
  160. }
  161. }()
  162. p.msgAppV2Reader = &streamReader{
  163. peerID: peerID,
  164. typ: streamTypeMsgAppV2,
  165. tr: transport,
  166. picker: picker,
  167. status: status,
  168. recvc: p.recvc,
  169. propc: p.propc,
  170. }
  171. p.msgAppReader = &streamReader{
  172. peerID: peerID,
  173. typ: streamTypeMessage,
  174. tr: transport,
  175. picker: picker,
  176. status: status,
  177. recvc: p.recvc,
  178. propc: p.propc,
  179. }
  180. p.msgAppV2Reader.start()
  181. p.msgAppReader.start()
  182. return p
  183. }
  184. func (p *peer) send(m raftpb.Message) {
  185. p.mu.Lock()
  186. paused := p.paused
  187. p.mu.Unlock()
  188. if paused {
  189. return
  190. }
  191. writec, name := p.pick(m)
  192. select {
  193. case writec <- m:
  194. default:
  195. p.r.ReportUnreachable(m.To)
  196. if isMsgSnap(m) {
  197. p.r.ReportSnapshot(m.To, raft.SnapshotFailure)
  198. }
  199. if p.status.isActive() {
  200. plog.MergeWarningf("dropped internal raft message to %s since %s's sending buffer is full (bad/overloaded network)", p.id, name)
  201. }
  202. plog.Debugf("dropped %s to %s since %s's sending buffer is full", m.Type, p.id, name)
  203. }
  204. }
  205. func (p *peer) sendSnap(m snap.Message) {
  206. go p.snapSender.send(m)
  207. }
  208. func (p *peer) update(urls types.URLs) {
  209. p.picker.update(urls)
  210. }
  211. func (p *peer) attachOutgoingConn(conn *outgoingConn) {
  212. var ok bool
  213. switch conn.t {
  214. case streamTypeMsgAppV2:
  215. ok = p.msgAppV2Writer.attach(conn)
  216. case streamTypeMessage:
  217. ok = p.writer.attach(conn)
  218. default:
  219. plog.Panicf("unhandled stream type %s", conn.t)
  220. }
  221. if !ok {
  222. conn.Close()
  223. }
  224. }
  225. func (p *peer) activeSince() time.Time { return p.status.activeSince() }
  226. // Pause pauses the peer. The peer will simply drops all incoming
  227. // messages without returning an error.
  228. func (p *peer) Pause() {
  229. p.mu.Lock()
  230. defer p.mu.Unlock()
  231. p.paused = true
  232. p.msgAppReader.pause()
  233. p.msgAppV2Reader.pause()
  234. }
  235. // Resume resumes a paused peer.
  236. func (p *peer) Resume() {
  237. p.mu.Lock()
  238. defer p.mu.Unlock()
  239. p.paused = false
  240. p.msgAppReader.resume()
  241. p.msgAppV2Reader.resume()
  242. }
  243. func (p *peer) stop() {
  244. plog.Infof("stopping peer %s...", p.id)
  245. defer plog.Infof("stopped peer %s", p.id)
  246. close(p.stopc)
  247. p.cancel()
  248. p.msgAppV2Writer.stop()
  249. p.writer.stop()
  250. p.pipeline.stop()
  251. p.snapSender.stop()
  252. p.msgAppV2Reader.stop()
  253. p.msgAppReader.stop()
  254. }
  255. // pick picks a chan for sending the given message. The picked chan and the picked chan
  256. // string name are returned.
  257. func (p *peer) pick(m raftpb.Message) (writec chan<- raftpb.Message, picked string) {
  258. var ok bool
  259. // Considering MsgSnap may have a big size, e.g., 1G, and will block
  260. // stream for a long time, only use one of the N pipelines to send MsgSnap.
  261. if isMsgSnap(m) {
  262. return p.pipeline.msgc, pipelineMsg
  263. } else if writec, ok = p.msgAppV2Writer.writec(); ok && isMsgApp(m) {
  264. return writec, streamAppV2
  265. } else if writec, ok = p.writer.writec(); ok {
  266. return writec, streamMsg
  267. }
  268. return p.pipeline.msgc, pipelineMsg
  269. }
  270. func isMsgApp(m raftpb.Message) bool { return m.Type == raftpb.MsgApp }
  271. func isMsgSnap(m raftpb.Message) bool { return m.Type == raftpb.MsgSnap }