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. w WriteFlusher
  140. to types.ID
  141. term uint64
  142. fs *stats.FollowerStats
  143. q chan []raftpb.Entry
  144. done chan struct{}
  145. }
  146. // newStreamWriter starts and returns a new unstarted stream writer.
  147. // The caller should call stop when finished, to shut it down.
  148. func newStreamWriter(w WriteFlusher, to types.ID, term uint64) *streamWriter {
  149. s := &streamWriter{
  150. w: w,
  151. to: to,
  152. term: term,
  153. q: make(chan []raftpb.Entry, streamBufSize),
  154. done: make(chan struct{}),
  155. }
  156. return s
  157. }
  158. func (s *streamWriter) send(ents []raftpb.Entry) error {
  159. select {
  160. case <-s.done:
  161. return fmt.Errorf("stopped")
  162. default:
  163. }
  164. select {
  165. case s.q <- ents:
  166. return nil
  167. default:
  168. log.Printf("rafthttp: maximum number of stream buffer entries to %d has been reached", s.to)
  169. return fmt.Errorf("maximum number of stream buffer entries has been reached")
  170. }
  171. }
  172. func (s *streamWriter) handle() {
  173. defer func() {
  174. close(s.done)
  175. log.Printf("rafthttp: server streaming to %s at term %d has been stopped", s.to, s.term)
  176. }()
  177. ew := newEntryWriter(s.w, s.to)
  178. for ents := range s.q {
  179. // Considering Commit in MsgApp is not recovered when received,
  180. // zero-entry appendEntry messages have no use to raft state machine.
  181. // Drop it here because it is useless.
  182. if len(ents) == 0 {
  183. continue
  184. }
  185. start := time.Now()
  186. if err := ew.writeEntries(ents); err != nil {
  187. log.Printf("rafthttp: encountered error writing to server log stream: %v", err)
  188. return
  189. }
  190. s.w.Flush()
  191. s.fs.Succ(time.Since(start))
  192. }
  193. }
  194. func (s *streamWriter) stop() {
  195. close(s.q)
  196. <-s.done
  197. }
  198. func (s *streamWriter) stopNotify() <-chan struct{} { return s.done }
  199. // TODO: move the raft interface out of the reader.
  200. type streamReader struct {
  201. id types.ID
  202. to types.ID
  203. term uint64
  204. r Raft
  205. closer io.Closer
  206. done chan struct{}
  207. }
  208. // newStreamClient starts and returns a new started stream client.
  209. // The caller should call stop when finished, to shut it down.
  210. func newStreamReader(id, to, cid types.ID, term uint64, tr http.RoundTripper, u string, r Raft) (*streamReader, error) {
  211. s := &streamReader{
  212. id: id,
  213. to: to,
  214. term: term,
  215. r: r,
  216. done: make(chan struct{}),
  217. }
  218. uu, err := url.Parse(u)
  219. if err != nil {
  220. return nil, fmt.Errorf("parse url %s error: %v", u, err)
  221. }
  222. uu.Path = path.Join(RaftStreamPrefix, s.id.String())
  223. req, err := http.NewRequest("GET", uu.String(), nil)
  224. if err != nil {
  225. return nil, fmt.Errorf("new request to %s error: %v", u, err)
  226. }
  227. req.Header.Set("X-Etcd-Cluster-ID", cid.String())
  228. req.Header.Set("X-Raft-To", s.to.String())
  229. req.Header.Set("X-Raft-Term", strconv.FormatUint(s.term, 10))
  230. resp, err := tr.RoundTrip(req)
  231. if err != nil {
  232. return nil, fmt.Errorf("error posting to %q: %v", u, err)
  233. }
  234. if resp.StatusCode != http.StatusOK {
  235. resp.Body.Close()
  236. return nil, fmt.Errorf("unhandled http status %d", resp.StatusCode)
  237. }
  238. s.closer = resp.Body
  239. go s.handle(resp.Body)
  240. log.Printf("rafthttp: starting client stream to %s at term %d", s.to, s.term)
  241. return s, nil
  242. }
  243. func (s *streamReader) stop() {
  244. s.closer.Close()
  245. <-s.done
  246. }
  247. func (s *streamReader) isStopped() bool {
  248. select {
  249. case <-s.done:
  250. return true
  251. default:
  252. return false
  253. }
  254. }
  255. func (s *streamReader) handle(r io.Reader) {
  256. defer func() {
  257. close(s.done)
  258. log.Printf("rafthttp: client streaming to %s at term %d has been stopped", s.to, s.term)
  259. }()
  260. er := newEntryReader(r, s.to)
  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. }