sender.go 8.2 KB

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