streamer.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package rafthttp
  15. import (
  16. "errors"
  17. "fmt"
  18. "io"
  19. "log"
  20. "math"
  21. "net/http"
  22. "net/url"
  23. "path"
  24. "strconv"
  25. "sync"
  26. "time"
  27. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  28. "github.com/coreos/etcd/etcdserver/stats"
  29. "github.com/coreos/etcd/pkg/types"
  30. "github.com/coreos/etcd/raft/raftpb"
  31. )
  32. const (
  33. streamBufSize = 4096
  34. )
  35. // TODO: a stream might hava one stream server or one stream client, but not both.
  36. type stream struct {
  37. sync.Mutex
  38. w *streamWriter
  39. r *streamReader
  40. stopped bool
  41. }
  42. func (s *stream) open(from, to, cid types.ID, term uint64, tr http.RoundTripper, u string, r Raft) error {
  43. rd, err := newStreamReader(from, to, cid, term, tr, u, r)
  44. if err != nil {
  45. log.Printf("stream: error opening stream: %v", err)
  46. return err
  47. }
  48. s.Lock()
  49. defer s.Unlock()
  50. if s.stopped {
  51. rd.stop()
  52. return errors.New("stream: stopped")
  53. }
  54. if s.r != nil {
  55. panic("open: stream is open")
  56. }
  57. s.r = rd
  58. return nil
  59. }
  60. func (s *stream) attach(sw *streamWriter) error {
  61. s.Lock()
  62. defer s.Unlock()
  63. if s.stopped {
  64. return errors.New("stream: stopped")
  65. }
  66. if s.w != nil {
  67. // ignore lower-term streaming request
  68. if sw.term < s.w.term {
  69. return fmt.Errorf("cannot attach out of data stream server [%d / %d]", sw.term, s.w.term)
  70. }
  71. s.w.stop()
  72. }
  73. s.w = sw
  74. return nil
  75. }
  76. func (s *stream) write(m raftpb.Message) bool {
  77. s.Lock()
  78. defer s.Unlock()
  79. if s.stopped {
  80. return false
  81. }
  82. if s.w == nil {
  83. return false
  84. }
  85. if m.Term != s.w.term {
  86. if m.Term > s.w.term {
  87. panic("expected server to be invalidated when there is a higher term message")
  88. }
  89. return false
  90. }
  91. // todo: early unlock?
  92. if err := s.w.send(m.Entries); err != nil {
  93. log.Printf("stream: error sending message: %v", err)
  94. log.Printf("stream: stopping the stream server...")
  95. s.w.stop()
  96. s.w = nil
  97. return false
  98. }
  99. return true
  100. }
  101. // invalidate stops the sever/client that is running at
  102. // a term lower than the given term.
  103. func (s *stream) invalidate(term uint64) {
  104. s.Lock()
  105. defer s.Unlock()
  106. if s.w != nil {
  107. if s.w.term < term {
  108. s.w.stop()
  109. s.w = nil
  110. }
  111. }
  112. if s.r != nil {
  113. if s.r.term < term {
  114. s.r.stop()
  115. s.r = nil
  116. }
  117. }
  118. if term == math.MaxUint64 {
  119. s.stopped = true
  120. }
  121. }
  122. func (s *stream) stop() {
  123. s.invalidate(math.MaxUint64)
  124. }
  125. func (s *stream) isOpen() bool {
  126. s.Lock()
  127. defer s.Unlock()
  128. if s.r != nil && s.r.isStopped() {
  129. s.r = nil
  130. }
  131. return s.r != nil
  132. }
  133. type WriteFlusher interface {
  134. io.Writer
  135. http.Flusher
  136. }
  137. // TODO: replace fs with stream stats
  138. type streamWriter struct {
  139. to types.ID
  140. term uint64
  141. fs *stats.FollowerStats
  142. q chan []raftpb.Entry
  143. done chan struct{}
  144. }
  145. // newStreamWriter starts and returns a new unstarted stream writer.
  146. // The caller should call stop when finished, to shut it down.
  147. func newStreamWriter(to types.ID, term uint64) *streamWriter {
  148. s := &streamWriter{
  149. to: to,
  150. term: term,
  151. q: make(chan []raftpb.Entry, streamBufSize),
  152. done: make(chan struct{}),
  153. }
  154. return s
  155. }
  156. func (s *streamWriter) send(ents []raftpb.Entry) error {
  157. select {
  158. case <-s.done:
  159. return fmt.Errorf("stopped")
  160. default:
  161. }
  162. select {
  163. case s.q <- ents:
  164. return nil
  165. default:
  166. log.Printf("rafthttp: maximum number of stream buffer entries to %d has been reached", s.to)
  167. return fmt.Errorf("maximum number of stream buffer entries has been reached")
  168. }
  169. }
  170. func (s *streamWriter) handle(w WriteFlusher) {
  171. defer func() {
  172. close(s.done)
  173. log.Printf("rafthttp: server streaming to %s at term %d has been stopped", s.to, s.term)
  174. }()
  175. ew := newEntryWriter(w, s.to)
  176. defer ew.stop()
  177. for ents := range s.q {
  178. // Considering Commit in MsgApp is not recovered when received,
  179. // zero-entry appendEntry messages have no use to raft state machine.
  180. // Drop it here because it is useless.
  181. if len(ents) == 0 {
  182. continue
  183. }
  184. start := time.Now()
  185. if err := ew.writeEntries(ents); err != nil {
  186. log.Printf("rafthttp: encountered error writing to server log stream: %v", err)
  187. return
  188. }
  189. w.Flush()
  190. s.fs.Succ(time.Since(start))
  191. }
  192. }
  193. func (s *streamWriter) stop() {
  194. close(s.q)
  195. <-s.done
  196. }
  197. func (s *streamWriter) stopNotify() <-chan struct{} { return s.done }
  198. // TODO: move the raft interface out of the reader.
  199. type streamReader struct {
  200. id types.ID
  201. to types.ID
  202. term uint64
  203. r Raft
  204. closer io.Closer
  205. done chan struct{}
  206. }
  207. // newStreamClient starts and returns a new started stream client.
  208. // The caller should call stop when finished, to shut it down.
  209. func newStreamReader(id, to, cid types.ID, term uint64, tr http.RoundTripper, u string, r Raft) (*streamReader, error) {
  210. s := &streamReader{
  211. id: id,
  212. to: to,
  213. term: term,
  214. r: r,
  215. done: make(chan struct{}),
  216. }
  217. uu, err := url.Parse(u)
  218. if err != nil {
  219. return nil, fmt.Errorf("parse url %s error: %v", u, err)
  220. }
  221. uu.Path = path.Join(RaftStreamPrefix, s.id.String())
  222. req, err := http.NewRequest("GET", uu.String(), nil)
  223. if err != nil {
  224. return nil, fmt.Errorf("new request to %s error: %v", u, err)
  225. }
  226. req.Header.Set("X-Etcd-Cluster-ID", cid.String())
  227. req.Header.Set("X-Raft-To", s.to.String())
  228. req.Header.Set("X-Raft-Term", strconv.FormatUint(s.term, 10))
  229. resp, err := tr.RoundTrip(req)
  230. if err != nil {
  231. return nil, fmt.Errorf("error posting to %q: %v", u, err)
  232. }
  233. if resp.StatusCode != http.StatusOK {
  234. resp.Body.Close()
  235. return nil, fmt.Errorf("unhandled http status %d", resp.StatusCode)
  236. }
  237. s.closer = resp.Body
  238. go s.handle(resp.Body)
  239. log.Printf("rafthttp: starting client stream to %s at term %d", s.to, s.term)
  240. return s, nil
  241. }
  242. func (s *streamReader) stop() {
  243. s.closer.Close()
  244. <-s.done
  245. }
  246. func (s *streamReader) isStopped() bool {
  247. select {
  248. case <-s.done:
  249. return true
  250. default:
  251. return false
  252. }
  253. }
  254. func (s *streamReader) handle(r io.Reader) {
  255. defer func() {
  256. close(s.done)
  257. log.Printf("rafthttp: client streaming to %s at term %d has been stopped", s.to, s.term)
  258. }()
  259. er := newEntryReader(r, s.to)
  260. defer er.stop()
  261. for {
  262. ents, err := er.readEntries()
  263. if err != nil {
  264. if err != io.EOF {
  265. log.Printf("rafthttp: encountered error reading the client log stream: %v", err)
  266. }
  267. return
  268. }
  269. if len(ents) == 0 {
  270. continue
  271. }
  272. // The commit index field in appendEntry message is not recovered.
  273. // The follower updates its commit index through heartbeat.
  274. msg := raftpb.Message{
  275. Type: raftpb.MsgApp,
  276. From: uint64(s.to),
  277. To: uint64(s.id),
  278. Term: s.term,
  279. LogTerm: s.term,
  280. Index: ents[0].Index - 1,
  281. Entries: ents,
  282. }
  283. if err := s.r.Process(context.TODO(), msg); err != nil {
  284. log.Printf("rafthttp: process raft message error: %v", err)
  285. return
  286. }
  287. }
  288. }
  289. func shouldInitStream(m raftpb.Message) bool {
  290. return m.Type == raftpb.MsgAppResp && m.Reject == false
  291. }
  292. func canUseStream(m raftpb.Message) bool {
  293. return m.Type == raftpb.MsgApp && m.Index > 0 && m.Term == m.LogTerm
  294. }