peer.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. "fmt"
  17. "log"
  18. "net/http"
  19. "sync"
  20. "time"
  21. "github.com/coreos/etcd/etcdserver/stats"
  22. "github.com/coreos/etcd/pkg/types"
  23. "github.com/coreos/etcd/raft/raftpb"
  24. )
  25. const (
  26. appRespBatchMs = 50
  27. propBatchMs = 10
  28. DialTimeout = time.Second
  29. ConnReadTimeout = 5 * time.Second
  30. ConnWriteTimeout = 5 * time.Second
  31. )
  32. type peer struct {
  33. sync.Mutex
  34. id types.ID
  35. cid types.ID
  36. tr http.RoundTripper
  37. // the url this sender post to
  38. u string
  39. r Raft
  40. fs *stats.FollowerStats
  41. batcher *Batcher
  42. propBatcher *ProposalBatcher
  43. pipeline *pipeline
  44. stream *stream
  45. sendc chan raftpb.Message
  46. updatec chan string
  47. attachc chan *streamWriter
  48. pausec chan struct{}
  49. resumec chan struct{}
  50. stopc chan struct{}
  51. done chan struct{}
  52. }
  53. func NewPeer(tr http.RoundTripper, u string, id types.ID, cid types.ID, r Raft, fs *stats.FollowerStats, errorc chan error) *peer {
  54. p := &peer{
  55. id: id,
  56. cid: cid,
  57. tr: tr,
  58. u: u,
  59. r: r,
  60. fs: fs,
  61. pipeline: newPipeline(tr, u, id, cid, fs, errorc),
  62. stream: &stream{},
  63. batcher: NewBatcher(100, appRespBatchMs*time.Millisecond),
  64. propBatcher: NewProposalBatcher(100, propBatchMs*time.Millisecond),
  65. sendc: make(chan raftpb.Message),
  66. updatec: make(chan string),
  67. attachc: make(chan *streamWriter),
  68. pausec: make(chan struct{}),
  69. resumec: make(chan struct{}),
  70. stopc: make(chan struct{}),
  71. done: make(chan struct{}),
  72. }
  73. go p.run()
  74. return p
  75. }
  76. func (p *peer) run() {
  77. var paused bool
  78. // non-blocking main loop
  79. for {
  80. select {
  81. case m := <-p.sendc:
  82. if paused {
  83. continue
  84. }
  85. p.send(m)
  86. case u := <-p.updatec:
  87. p.u = u
  88. p.pipeline.update(u)
  89. case sw := <-p.attachc:
  90. sw.fs = p.fs
  91. if err := p.stream.attach(sw); err != nil {
  92. sw.stop()
  93. continue
  94. }
  95. go sw.handle()
  96. case <-p.pausec:
  97. paused = true
  98. case <-p.resumec:
  99. paused = false
  100. case <-p.stopc:
  101. p.pipeline.stop()
  102. p.stream.stop()
  103. close(p.done)
  104. return
  105. }
  106. }
  107. }
  108. func (p *peer) Send(m raftpb.Message) {
  109. select {
  110. case p.sendc <- m:
  111. case <-p.done:
  112. log.Panicf("peer: unexpected stopped")
  113. }
  114. }
  115. func (p *peer) Update(u string) {
  116. select {
  117. case p.updatec <- u:
  118. case <-p.done:
  119. log.Panicf("peer: unexpected stopped")
  120. }
  121. }
  122. // attachStream attaches a streamWriter to the peer.
  123. // If attach succeeds, peer will take charge of the given streamWriter.
  124. func (p *peer) attachStream(sw *streamWriter) error {
  125. select {
  126. case p.attachc <- sw:
  127. return nil
  128. case <-p.done:
  129. return fmt.Errorf("peer: stopped")
  130. }
  131. }
  132. // Pause pauses the peer. The peer will simply drops all incoming
  133. // messages without retruning an error.
  134. func (p *peer) Pause() {
  135. select {
  136. case p.pausec <- struct{}{}:
  137. case <-p.done:
  138. }
  139. }
  140. // Resume resumes a paused peer.
  141. func (p *peer) Resume() {
  142. select {
  143. case p.resumec <- struct{}{}:
  144. case <-p.done:
  145. }
  146. }
  147. // Stop performs any necessary finalization and terminates the peer
  148. // elegantly.
  149. func (p *peer) Stop() {
  150. select {
  151. case p.stopc <- struct{}{}:
  152. case <-p.done:
  153. return
  154. }
  155. <-p.done
  156. }
  157. // send sends the data to the remote node. It is always non-blocking.
  158. // It may be fail to send data if it returns nil error.
  159. // TODO (xiangli): reasonable retry logic
  160. func (p *peer) send(m raftpb.Message) error {
  161. // move all the stream related stuff into stream
  162. p.stream.invalidate(m.Term)
  163. if shouldInitStream(m) && !p.stream.isOpen() {
  164. u := p.u
  165. // todo: steam open should not block.
  166. p.stream.open(types.ID(m.From), p.id, p.cid, m.Term, p.tr, u, p.r)
  167. p.batcher.Reset(time.Now())
  168. }
  169. var err error
  170. switch {
  171. case isProposal(m):
  172. p.propBatcher.Batch(m)
  173. case canBatch(m) && p.stream.isOpen():
  174. if !p.batcher.ShouldBatch(time.Now()) {
  175. err = p.pipeline.send(m)
  176. }
  177. case canUseStream(m):
  178. if ok := p.stream.write(m); !ok {
  179. err = p.pipeline.send(m)
  180. }
  181. default:
  182. err = p.pipeline.send(m)
  183. }
  184. // send out batched MsgProp if needed
  185. // TODO: it is triggered by all outcoming send now, and it needs
  186. // more clear solution. Either use separate goroutine to trigger it
  187. // or use streaming.
  188. if !p.propBatcher.IsEmpty() {
  189. t := time.Now()
  190. if !p.propBatcher.ShouldBatch(t) {
  191. p.pipeline.send(p.propBatcher.Message)
  192. p.propBatcher.Reset(t)
  193. }
  194. }
  195. return err
  196. }
  197. func isProposal(m raftpb.Message) bool { return m.Type == raftpb.MsgProp }