sender.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package rafthttp
  14. import (
  15. "bytes"
  16. "fmt"
  17. "log"
  18. "net/http"
  19. "sync"
  20. "time"
  21. "github.com/coreos/etcd/etcdserver/stats"
  22. "github.com/coreos/etcd/pkg/pbutil"
  23. "github.com/coreos/etcd/pkg/types"
  24. "github.com/coreos/etcd/raft/raftpb"
  25. )
  26. const (
  27. connPerSender = 4
  28. // senderBufSize is the size of sender buffer, which helps hold the
  29. // temporary network latency.
  30. // The size ensures that sender does not drop messages when the network
  31. // is out of work for less than 1 second in good path.
  32. senderBufSize = 64
  33. appRespBatchMs = 50
  34. propBatchMs = 10
  35. ConnReadTimeout = 5 * time.Second
  36. ConnWriteTimeout = 5 * time.Second
  37. )
  38. type Sender interface {
  39. // StartStreaming enables streaming in the sender using the given writer,
  40. // which provides a fast and efficient way to send appendEntry messages.
  41. StartStreaming(w WriteFlusher, to types.ID, term uint64) (done <-chan struct{}, err error)
  42. Update(u string)
  43. // Send sends the data to the remote node. It is always non-blocking.
  44. // It may be fail to send data if it returns nil error.
  45. Send(m raftpb.Message) error
  46. // Stop performs any necessary finalization and terminates the Sender
  47. // elegantly.
  48. Stop()
  49. // Pause pauses the sender. The sender will simply drops all incoming
  50. // messages without retruning an error.
  51. Pause()
  52. // Resume resumes a paused sender.
  53. Resume()
  54. }
  55. func NewSender(tr http.RoundTripper, u string, cid types.ID, p Processor, fs *stats.FollowerStats, shouldstop chan struct{}) *sender {
  56. s := &sender{
  57. tr: tr,
  58. u: u,
  59. cid: cid,
  60. p: p,
  61. fs: fs,
  62. shouldstop: shouldstop,
  63. batcher: NewBatcher(100, appRespBatchMs*time.Millisecond),
  64. propBatcher: NewProposalBatcher(100, propBatchMs*time.Millisecond),
  65. q: make(chan []byte, senderBufSize),
  66. }
  67. s.wg.Add(connPerSender)
  68. for i := 0; i < connPerSender; i++ {
  69. go s.handle()
  70. }
  71. return s
  72. }
  73. type sender struct {
  74. tr http.RoundTripper
  75. u string
  76. cid types.ID
  77. p Processor
  78. fs *stats.FollowerStats
  79. shouldstop chan struct{}
  80. strmCln *streamClient
  81. batcher *Batcher
  82. propBatcher *ProposalBatcher
  83. strmSrv *streamServer
  84. strmSrvMu sync.Mutex
  85. q chan []byte
  86. paused bool
  87. mu sync.RWMutex
  88. wg sync.WaitGroup
  89. }
  90. func (s *sender) StartStreaming(w WriteFlusher, to types.ID, term uint64) (<-chan struct{}, error) {
  91. s.strmSrvMu.Lock()
  92. defer s.strmSrvMu.Unlock()
  93. if s.strmSrv != nil {
  94. // ignore lower-term streaming request
  95. if term < s.strmSrv.term {
  96. return nil, fmt.Errorf("out of data streaming request: term %d, request term %d", term, s.strmSrv.term)
  97. }
  98. // stop the existing one
  99. s.strmSrv.stop()
  100. }
  101. s.strmSrv = startStreamServer(w, to, term, s.fs)
  102. return s.strmSrv.stopNotify(), nil
  103. }
  104. func (s *sender) Update(u string) {
  105. s.mu.Lock()
  106. defer s.mu.Unlock()
  107. s.u = u
  108. }
  109. // TODO (xiangli): reasonable retry logic
  110. func (s *sender) Send(m raftpb.Message) error {
  111. s.mu.RLock()
  112. pause := s.paused
  113. s.mu.RUnlock()
  114. if pause {
  115. return nil
  116. }
  117. s.maybeStopStream(m.Term)
  118. if shouldInitStream(m) && !s.hasStreamClient() {
  119. s.initStream(types.ID(m.From), types.ID(m.To), m.Term)
  120. s.batcher.Reset(time.Now())
  121. }
  122. var err error
  123. switch {
  124. case isProposal(m):
  125. s.propBatcher.Batch(m)
  126. case canBatch(m) && s.hasStreamClient():
  127. if !s.batcher.ShouldBatch(time.Now()) {
  128. err = s.send(m)
  129. }
  130. case canUseStream(m):
  131. if ok := s.tryStream(m); !ok {
  132. err = s.send(m)
  133. }
  134. default:
  135. err = s.send(m)
  136. }
  137. // send out batched MsgProp if needed
  138. // TODO: it is triggered by all outcoming send now, and it needs
  139. // more clear solution. Either use separate goroutine to trigger it
  140. // or use streaming.
  141. if !s.propBatcher.IsEmpty() {
  142. t := time.Now()
  143. if !s.propBatcher.ShouldBatch(t) {
  144. s.send(s.propBatcher.Message)
  145. s.propBatcher.Reset(t)
  146. }
  147. }
  148. return err
  149. }
  150. func (s *sender) send(m raftpb.Message) error {
  151. // TODO: don't block. we should be able to have 1000s
  152. // of messages out at a time.
  153. data := pbutil.MustMarshal(&m)
  154. select {
  155. case s.q <- data:
  156. return nil
  157. default:
  158. log.Printf("sender: dropping %s because maximal number %d of sender buffer entries to %s has been reached",
  159. m.Type, senderBufSize, s.u)
  160. return fmt.Errorf("reach maximal serving")
  161. }
  162. }
  163. func (s *sender) Stop() {
  164. close(s.q)
  165. s.wg.Wait()
  166. s.strmSrvMu.Lock()
  167. if s.strmSrv != nil {
  168. s.strmSrv.stop()
  169. }
  170. s.strmSrvMu.Unlock()
  171. if s.strmCln != nil {
  172. s.strmCln.stop()
  173. }
  174. }
  175. func (s *sender) Pause() {
  176. s.mu.Lock()
  177. defer s.mu.Unlock()
  178. s.paused = true
  179. }
  180. func (s *sender) Resume() {
  181. s.mu.Lock()
  182. defer s.mu.Unlock()
  183. s.paused = false
  184. }
  185. func (s *sender) maybeStopStream(term uint64) {
  186. if s.strmCln != nil && term > s.strmCln.term {
  187. s.strmCln.stop()
  188. s.strmCln = nil
  189. }
  190. s.strmSrvMu.Lock()
  191. defer s.strmSrvMu.Unlock()
  192. if s.strmSrv != nil && term > s.strmSrv.term {
  193. s.strmSrv.stop()
  194. s.strmSrv = nil
  195. }
  196. }
  197. func (s *sender) hasStreamClient() bool {
  198. return s.strmCln != nil && !s.strmCln.isStopped()
  199. }
  200. func (s *sender) initStream(from, to types.ID, term uint64) {
  201. strmCln := newStreamClient(from, to, term, s.p)
  202. s.mu.Lock()
  203. u := s.u
  204. s.mu.Unlock()
  205. if err := strmCln.start(s.tr, u, s.cid); err != nil {
  206. log.Printf("rafthttp: start stream client error: %v", err)
  207. return
  208. }
  209. s.strmCln = strmCln
  210. }
  211. func (s *sender) tryStream(m raftpb.Message) bool {
  212. s.strmSrvMu.Lock()
  213. defer s.strmSrvMu.Unlock()
  214. if s.strmSrv == nil || m.Term != s.strmSrv.term {
  215. return false
  216. }
  217. if err := s.strmSrv.send(m.Entries); err != nil {
  218. log.Printf("rafthttp: send stream message error: %v", err)
  219. s.strmSrv.stop()
  220. s.strmSrv = nil
  221. return false
  222. }
  223. return true
  224. }
  225. func (s *sender) handle() {
  226. defer s.wg.Done()
  227. for d := range s.q {
  228. start := time.Now()
  229. err := s.post(d)
  230. end := time.Now()
  231. if err != nil {
  232. s.fs.Fail()
  233. log.Printf("sender: %v", err)
  234. continue
  235. }
  236. s.fs.Succ(end.Sub(start))
  237. }
  238. }
  239. // post POSTs a data payload to a url. Returns nil if the POST succeeds,
  240. // error on any failure.
  241. func (s *sender) post(data []byte) error {
  242. s.mu.RLock()
  243. req, err := http.NewRequest("POST", s.u, bytes.NewBuffer(data))
  244. s.mu.RUnlock()
  245. if err != nil {
  246. return fmt.Errorf("new request to %s error: %v", s.u, err)
  247. }
  248. req.Header.Set("Content-Type", "application/protobuf")
  249. req.Header.Set("X-Etcd-Cluster-ID", s.cid.String())
  250. resp, err := s.tr.RoundTrip(req)
  251. if err != nil {
  252. return fmt.Errorf("error posting to %q: %v", req.URL.String(), err)
  253. }
  254. resp.Body.Close()
  255. switch resp.StatusCode {
  256. case http.StatusPreconditionFailed:
  257. select {
  258. case s.shouldstop <- struct{}{}:
  259. default:
  260. }
  261. log.Printf("etcdserver: conflicting cluster ID with the target cluster (%s != %s)", resp.Header.Get("X-Etcd-Cluster-ID"), s.cid)
  262. return nil
  263. case http.StatusForbidden:
  264. select {
  265. case s.shouldstop <- struct{}{}:
  266. default:
  267. }
  268. log.Println("etcdserver: this member has been permanently removed from the cluster")
  269. log.Println("etcdserver: the data-dir used by this member must be removed so that this host can be re-added with a new member ID")
  270. return nil
  271. case http.StatusNoContent:
  272. return nil
  273. default:
  274. return fmt.Errorf("unexpected http status %s while posting to %q", http.StatusText(resp.StatusCode), req.URL.String())
  275. }
  276. }
  277. func isProposal(m raftpb.Message) bool { return m.Type == raftpb.MsgProp }