sender.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 = connPerSender * 4
  29. appRespBatchMs = 50
  30. ConnReadTimeout = 5 * time.Second
  31. ConnWriteTimeout = 5 * time.Second
  32. )
  33. type Sender interface {
  34. // StartStreaming enables streaming in the sender using the given writer,
  35. // which provides a fast and efficient way to send appendEntry messages.
  36. StartStreaming(w WriteFlusher, to types.ID, term uint64) (done <-chan struct{}, err error)
  37. Update(u string)
  38. // Send sends the data to the remote node. It is always non-blocking.
  39. // It may be fail to send data if it returns nil error.
  40. Send(m raftpb.Message) error
  41. // Stop performs any necessary finalization and terminates the Sender
  42. // elegantly.
  43. Stop()
  44. // Pause pauses the sender. The sender will simply drops all incoming
  45. // messages without retruning an error.
  46. Pause()
  47. // Resume resumes a paused sender.
  48. Resume()
  49. }
  50. func NewSender(tr http.RoundTripper, u string, cid types.ID, p Processor, fs *stats.FollowerStats, shouldstop chan struct{}) *sender {
  51. s := &sender{
  52. tr: tr,
  53. u: u,
  54. cid: cid,
  55. p: p,
  56. fs: fs,
  57. shouldstop: shouldstop,
  58. batcher: NewBatcher(100, appRespBatchMs*time.Millisecond),
  59. q: make(chan []byte, senderBufSize),
  60. }
  61. s.wg.Add(connPerSender)
  62. for i := 0; i < connPerSender; i++ {
  63. go s.handle()
  64. }
  65. return s
  66. }
  67. type sender struct {
  68. tr http.RoundTripper
  69. u string
  70. cid types.ID
  71. p Processor
  72. fs *stats.FollowerStats
  73. shouldstop chan struct{}
  74. strmCln *streamClient
  75. batcher *Batcher
  76. strmSrv *streamServer
  77. strmSrvMu sync.Mutex
  78. q chan []byte
  79. paused bool
  80. mu sync.RWMutex
  81. wg sync.WaitGroup
  82. }
  83. func (s *sender) StartStreaming(w WriteFlusher, to types.ID, term uint64) (<-chan struct{}, error) {
  84. s.strmSrvMu.Lock()
  85. defer s.strmSrvMu.Unlock()
  86. if s.strmSrv != nil {
  87. // ignore lower-term streaming request
  88. if term < s.strmSrv.term {
  89. return nil, fmt.Errorf("out of data streaming request: term %d, request term %d", term, s.strmSrv.term)
  90. }
  91. // stop the existing one
  92. s.strmSrv.stop()
  93. }
  94. s.strmSrv = startStreamServer(w, to, term, s.fs)
  95. return s.strmSrv.stopNotify(), nil
  96. }
  97. func (s *sender) Update(u string) {
  98. s.mu.Lock()
  99. defer s.mu.Unlock()
  100. s.u = u
  101. }
  102. // TODO (xiangli): reasonable retry logic
  103. func (s *sender) Send(m raftpb.Message) error {
  104. s.mu.RLock()
  105. pause := s.paused
  106. s.mu.RUnlock()
  107. if pause {
  108. return nil
  109. }
  110. s.maybeStopStream(m.Term)
  111. if shouldInitStream(m) && !s.hasStreamClient() {
  112. s.initStream(types.ID(m.From), types.ID(m.To), m.Term)
  113. s.batcher.Reset(time.Now())
  114. }
  115. if canBatch(m) && s.hasStreamClient() {
  116. if s.batcher.ShouldBatch(time.Now()) {
  117. return nil
  118. }
  119. }
  120. if canUseStream(m) {
  121. if ok := s.tryStream(m); ok {
  122. return nil
  123. }
  124. }
  125. // TODO: don't block. we should be able to have 1000s
  126. // of messages out at a time.
  127. data := pbutil.MustMarshal(&m)
  128. select {
  129. case s.q <- data:
  130. return nil
  131. default:
  132. log.Printf("sender: reach the maximal serving to %s", s.u)
  133. return fmt.Errorf("reach maximal serving")
  134. }
  135. }
  136. func (s *sender) Stop() {
  137. close(s.q)
  138. s.wg.Wait()
  139. s.strmSrvMu.Lock()
  140. if s.strmSrv != nil {
  141. s.strmSrv.stop()
  142. }
  143. s.strmSrvMu.Unlock()
  144. if s.strmCln != nil {
  145. s.strmCln.stop()
  146. }
  147. }
  148. func (s *sender) Pause() {
  149. s.mu.Lock()
  150. defer s.mu.Unlock()
  151. s.paused = true
  152. }
  153. func (s *sender) Resume() {
  154. s.mu.Lock()
  155. defer s.mu.Unlock()
  156. s.paused = false
  157. }
  158. func (s *sender) maybeStopStream(term uint64) {
  159. if s.strmCln != nil && term > s.strmCln.term {
  160. s.strmCln.stop()
  161. s.strmCln = nil
  162. }
  163. s.strmSrvMu.Lock()
  164. defer s.strmSrvMu.Unlock()
  165. if s.strmSrv != nil && term > s.strmSrv.term {
  166. s.strmSrv.stop()
  167. s.strmSrv = nil
  168. }
  169. }
  170. func (s *sender) hasStreamClient() bool {
  171. return s.strmCln != nil && !s.strmCln.isStopped()
  172. }
  173. func (s *sender) initStream(from, to types.ID, term uint64) {
  174. strmCln := newStreamClient(from, to, term, s.p)
  175. s.mu.Lock()
  176. u := s.u
  177. s.mu.Unlock()
  178. if err := strmCln.start(s.tr, u, s.cid); err != nil {
  179. log.Printf("rafthttp: start stream client error: %v", err)
  180. return
  181. }
  182. s.strmCln = strmCln
  183. }
  184. func (s *sender) tryStream(m raftpb.Message) bool {
  185. s.strmSrvMu.Lock()
  186. defer s.strmSrvMu.Unlock()
  187. if s.strmSrv == nil || m.Term != s.strmSrv.term {
  188. return false
  189. }
  190. if err := s.strmSrv.send(m.Entries); err != nil {
  191. log.Printf("rafthttp: send stream message error: %v", err)
  192. s.strmSrv.stop()
  193. s.strmSrv = nil
  194. return false
  195. }
  196. return true
  197. }
  198. func (s *sender) handle() {
  199. defer s.wg.Done()
  200. for d := range s.q {
  201. start := time.Now()
  202. err := s.post(d)
  203. end := time.Now()
  204. if err != nil {
  205. s.fs.Fail()
  206. log.Printf("sender: %v", err)
  207. continue
  208. }
  209. s.fs.Succ(end.Sub(start))
  210. }
  211. }
  212. // post POSTs a data payload to a url. Returns nil if the POST succeeds,
  213. // error on any failure.
  214. func (s *sender) post(data []byte) error {
  215. s.mu.RLock()
  216. req, err := http.NewRequest("POST", s.u, bytes.NewBuffer(data))
  217. s.mu.RUnlock()
  218. if err != nil {
  219. return fmt.Errorf("new request to %s error: %v", s.u, err)
  220. }
  221. req.Header.Set("Content-Type", "application/protobuf")
  222. req.Header.Set("X-Etcd-Cluster-ID", s.cid.String())
  223. resp, err := s.tr.RoundTrip(req)
  224. if err != nil {
  225. return fmt.Errorf("error posting to %q: %v", req.URL.String(), err)
  226. }
  227. resp.Body.Close()
  228. switch resp.StatusCode {
  229. case http.StatusPreconditionFailed:
  230. select {
  231. case s.shouldstop <- struct{}{}:
  232. default:
  233. }
  234. log.Printf("etcdserver: conflicting cluster ID with the target cluster (%s != %s)", resp.Header.Get("X-Etcd-Cluster-ID"), s.cid)
  235. return nil
  236. case http.StatusForbidden:
  237. select {
  238. case s.shouldstop <- struct{}{}:
  239. default:
  240. }
  241. log.Println("etcdserver: this member has been permanently removed from the cluster")
  242. 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")
  243. return nil
  244. case http.StatusNoContent:
  245. return nil
  246. default:
  247. return fmt.Errorf("unhandled status %s", http.StatusText(resp.StatusCode))
  248. }
  249. }