sender.go 6.2 KB

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