sender.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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, id types.ID, cid types.ID, p Processor, fs *stats.FollowerStats, shouldstop chan struct{}) *sender {
  56. s := &sender{
  57. id: id,
  58. active: true,
  59. tr: tr,
  60. u: u,
  61. cid: cid,
  62. p: p,
  63. fs: fs,
  64. shouldstop: shouldstop,
  65. batcher: NewBatcher(100, appRespBatchMs*time.Millisecond),
  66. propBatcher: NewProposalBatcher(100, propBatchMs*time.Millisecond),
  67. q: make(chan []byte, senderBufSize),
  68. }
  69. s.wg.Add(connPerSender)
  70. for i := 0; i < connPerSender; i++ {
  71. go s.handle()
  72. }
  73. return s
  74. }
  75. type sender struct {
  76. id types.ID
  77. cid types.ID
  78. tr http.RoundTripper
  79. p Processor
  80. fs *stats.FollowerStats
  81. shouldstop chan struct{}
  82. strmCln *streamClient
  83. batcher *Batcher
  84. propBatcher *ProposalBatcher
  85. strmSrv *streamServer
  86. strmSrvMu sync.Mutex
  87. q chan []byte
  88. // wait for the handling routines
  89. wg sync.WaitGroup
  90. mu sync.RWMutex
  91. u string // the url this sender post to
  92. // if the last send was successful, thi sender is active.
  93. // Or it is inactive
  94. active bool
  95. errored error
  96. paused bool
  97. }
  98. func (s *sender) StartStreaming(w WriteFlusher, to types.ID, term uint64) (<-chan struct{}, error) {
  99. s.strmSrvMu.Lock()
  100. defer s.strmSrvMu.Unlock()
  101. if s.strmSrv != nil {
  102. // ignore lower-term streaming request
  103. if term < s.strmSrv.term {
  104. return nil, fmt.Errorf("out of data streaming request: term %d, request term %d", term, s.strmSrv.term)
  105. }
  106. // stop the existing one
  107. s.strmSrv.stop()
  108. }
  109. s.strmSrv = startStreamServer(w, to, term, s.fs)
  110. return s.strmSrv.stopNotify(), nil
  111. }
  112. func (s *sender) Update(u string) {
  113. s.mu.Lock()
  114. defer s.mu.Unlock()
  115. s.u = u
  116. }
  117. // TODO (xiangli): reasonable retry logic
  118. func (s *sender) Send(m raftpb.Message) error {
  119. s.mu.RLock()
  120. pause := s.paused
  121. s.mu.RUnlock()
  122. if pause {
  123. return nil
  124. }
  125. s.maybeStopStream(m.Term)
  126. if shouldInitStream(m) && !s.hasStreamClient() {
  127. s.initStream(types.ID(m.From), types.ID(m.To), m.Term)
  128. s.batcher.Reset(time.Now())
  129. }
  130. var err error
  131. switch {
  132. case isProposal(m):
  133. s.propBatcher.Batch(m)
  134. case canBatch(m) && s.hasStreamClient():
  135. if !s.batcher.ShouldBatch(time.Now()) {
  136. err = s.send(m)
  137. }
  138. case canUseStream(m):
  139. if ok := s.tryStream(m); !ok {
  140. err = s.send(m)
  141. }
  142. default:
  143. err = s.send(m)
  144. }
  145. // send out batched MsgProp if needed
  146. // TODO: it is triggered by all outcoming send now, and it needs
  147. // more clear solution. Either use separate goroutine to trigger it
  148. // or use streaming.
  149. if !s.propBatcher.IsEmpty() {
  150. t := time.Now()
  151. if !s.propBatcher.ShouldBatch(t) {
  152. s.send(s.propBatcher.Message)
  153. s.propBatcher.Reset(t)
  154. }
  155. }
  156. return err
  157. }
  158. func (s *sender) send(m raftpb.Message) error {
  159. // TODO: don't block. we should be able to have 1000s
  160. // of messages out at a time.
  161. data := pbutil.MustMarshal(&m)
  162. select {
  163. case s.q <- data:
  164. return nil
  165. default:
  166. log.Printf("sender: dropping %s because maximal number %d of sender buffer entries to %s has been reached",
  167. m.Type, senderBufSize, s.u)
  168. return fmt.Errorf("reach maximal serving")
  169. }
  170. }
  171. func (s *sender) Stop() {
  172. close(s.q)
  173. s.wg.Wait()
  174. s.strmSrvMu.Lock()
  175. if s.strmSrv != nil {
  176. s.strmSrv.stop()
  177. }
  178. s.strmSrvMu.Unlock()
  179. if s.strmCln != nil {
  180. s.strmCln.stop()
  181. }
  182. }
  183. func (s *sender) Pause() {
  184. s.mu.Lock()
  185. defer s.mu.Unlock()
  186. s.paused = true
  187. }
  188. func (s *sender) Resume() {
  189. s.mu.Lock()
  190. defer s.mu.Unlock()
  191. s.paused = false
  192. }
  193. func (s *sender) maybeStopStream(term uint64) {
  194. if s.strmCln != nil && term > s.strmCln.term {
  195. s.strmCln.stop()
  196. s.strmCln = nil
  197. }
  198. s.strmSrvMu.Lock()
  199. defer s.strmSrvMu.Unlock()
  200. if s.strmSrv != nil && term > s.strmSrv.term {
  201. s.strmSrv.stop()
  202. s.strmSrv = nil
  203. }
  204. }
  205. func (s *sender) hasStreamClient() bool {
  206. return s.strmCln != nil && !s.strmCln.isStopped()
  207. }
  208. func (s *sender) initStream(from, to types.ID, term uint64) {
  209. strmCln := newStreamClient(from, to, term, s.p)
  210. s.mu.Lock()
  211. u := s.u
  212. s.mu.Unlock()
  213. if err := strmCln.start(s.tr, u, s.cid); err != nil {
  214. log.Printf("rafthttp: start stream client error: %v", err)
  215. return
  216. }
  217. s.strmCln = strmCln
  218. }
  219. func (s *sender) tryStream(m raftpb.Message) bool {
  220. s.strmSrvMu.Lock()
  221. defer s.strmSrvMu.Unlock()
  222. if s.strmSrv == nil || m.Term != s.strmSrv.term {
  223. return false
  224. }
  225. if err := s.strmSrv.send(m.Entries); err != nil {
  226. log.Printf("rafthttp: send stream message error: %v", err)
  227. s.strmSrv.stop()
  228. s.strmSrv = nil
  229. return false
  230. }
  231. return true
  232. }
  233. func (s *sender) handle() {
  234. defer s.wg.Done()
  235. for d := range s.q {
  236. start := time.Now()
  237. err := s.post(d)
  238. end := time.Now()
  239. s.mu.Lock()
  240. if err != nil {
  241. if s.errored == nil || s.errored.Error() != err.Error() {
  242. log.Printf("sender: error posting to %s: %v", s.id, err)
  243. s.errored = err
  244. }
  245. if s.active {
  246. log.Printf("sender: the connection with %s becomes inactive", s.id)
  247. s.active = false
  248. }
  249. s.fs.Fail()
  250. } else {
  251. if !s.active {
  252. log.Printf("sender: the connection with %s becomes active", s.id)
  253. s.active = true
  254. s.errored = nil
  255. }
  256. s.fs.Succ(end.Sub(start))
  257. }
  258. s.mu.Unlock()
  259. }
  260. }
  261. // post POSTs a data payload to a url. Returns nil if the POST succeeds,
  262. // error on any failure.
  263. func (s *sender) post(data []byte) error {
  264. s.mu.RLock()
  265. req, err := http.NewRequest("POST", s.u, bytes.NewBuffer(data))
  266. s.mu.RUnlock()
  267. if err != nil {
  268. return err
  269. }
  270. req.Header.Set("Content-Type", "application/protobuf")
  271. req.Header.Set("X-Etcd-Cluster-ID", s.cid.String())
  272. resp, err := s.tr.RoundTrip(req)
  273. if err != nil {
  274. return err
  275. }
  276. resp.Body.Close()
  277. switch resp.StatusCode {
  278. case http.StatusPreconditionFailed:
  279. select {
  280. case s.shouldstop <- struct{}{}:
  281. default:
  282. }
  283. log.Printf("rafthttp: conflicting cluster ID with the target cluster (%s != %s)", resp.Header.Get("X-Etcd-Cluster-ID"), s.cid)
  284. return nil
  285. case http.StatusForbidden:
  286. select {
  287. case s.shouldstop <- struct{}{}:
  288. default:
  289. }
  290. log.Println("rafthttp: this member has been permanently removed from the cluster")
  291. log.Println("rafthttp: the data-dir used by this member must be removed so that this host can be re-added with a new member ID")
  292. return nil
  293. case http.StatusNoContent:
  294. return nil
  295. default:
  296. return fmt.Errorf("unexpected http status %s while posting to %q", http.StatusText(resp.StatusCode), req.URL.String())
  297. }
  298. }
  299. func isProposal(m raftpb.Message) bool { return m.Type == raftpb.MsgProp }