streamer.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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/etcdserver/stats"
  28. "github.com/coreos/etcd/pkg/types"
  29. "github.com/coreos/etcd/raft/raftpb"
  30. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  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. } else if sw.term == s.w.term {
  71. s.w.stopWithoutLog()
  72. } else {
  73. s.w.stop()
  74. }
  75. }
  76. s.w = sw
  77. return nil
  78. }
  79. func (s *stream) write(m raftpb.Message) bool {
  80. s.Lock()
  81. defer s.Unlock()
  82. if s.stopped {
  83. return false
  84. }
  85. if s.w == nil {
  86. return false
  87. }
  88. if m.Term != s.w.term {
  89. if m.Term > s.w.term {
  90. panic("expected server to be invalidated when there is a higher term message")
  91. }
  92. return false
  93. }
  94. // todo: early unlock?
  95. if err := s.w.send(m.Entries); err != nil {
  96. log.Printf("stream: error sending message: %v", err)
  97. log.Printf("stream: stopping the stream server...")
  98. s.w.stop()
  99. s.w = nil
  100. return false
  101. }
  102. return true
  103. }
  104. // invalidate stops the sever/client that is running at
  105. // a term lower than the given term.
  106. func (s *stream) invalidate(term uint64) {
  107. s.Lock()
  108. defer s.Unlock()
  109. if s.w != nil {
  110. if s.w.term < term {
  111. s.w.stop()
  112. s.w = nil
  113. }
  114. }
  115. if s.r != nil {
  116. if s.r.term < term {
  117. s.r.stop()
  118. s.r = nil
  119. }
  120. }
  121. if term == math.MaxUint64 {
  122. s.stopped = true
  123. }
  124. }
  125. func (s *stream) stop() {
  126. s.invalidate(math.MaxUint64)
  127. }
  128. func (s *stream) isOpen() bool {
  129. s.Lock()
  130. defer s.Unlock()
  131. if s.r != nil && s.r.isStopped() {
  132. s.r = nil
  133. }
  134. return s.r != nil
  135. }
  136. type WriteFlusher interface {
  137. io.Writer
  138. http.Flusher
  139. }
  140. // TODO: replace fs with stream stats
  141. type streamWriter struct {
  142. to types.ID
  143. term uint64
  144. fs *stats.FollowerStats
  145. q chan []raftpb.Entry
  146. done chan struct{}
  147. printLog bool
  148. }
  149. // newStreamWriter starts and returns a new unstarted stream writer.
  150. // The caller should call stop when finished, to shut it down.
  151. func newStreamWriter(to types.ID, term uint64) *streamWriter {
  152. s := &streamWriter{
  153. to: to,
  154. term: term,
  155. q: make(chan []raftpb.Entry, streamBufSize),
  156. done: make(chan struct{}),
  157. printLog: true,
  158. }
  159. return s
  160. }
  161. func (s *streamWriter) send(ents []raftpb.Entry) error {
  162. select {
  163. case <-s.done:
  164. return fmt.Errorf("stopped")
  165. default:
  166. }
  167. select {
  168. case s.q <- ents:
  169. return nil
  170. default:
  171. log.Printf("rafthttp: maximum number of stream buffer entries to %d has been reached", s.to)
  172. return fmt.Errorf("maximum number of stream buffer entries has been reached")
  173. }
  174. }
  175. func (s *streamWriter) handle(w WriteFlusher) {
  176. defer func() {
  177. close(s.done)
  178. if s.printLog {
  179. log.Printf("rafthttp: server streaming to %s at term %d has been stopped", s.to, s.term)
  180. }
  181. }()
  182. ew := newEntryWriter(w, s.to)
  183. defer ew.stop()
  184. for ents := range s.q {
  185. // Considering Commit in MsgApp is not recovered when received,
  186. // zero-entry appendEntry messages have no use to raft state machine.
  187. // Drop it here because it is useless.
  188. if len(ents) == 0 {
  189. continue
  190. }
  191. start := time.Now()
  192. if err := ew.writeEntries(ents); err != nil {
  193. log.Printf("rafthttp: encountered error writing to server log stream: %v", err)
  194. return
  195. }
  196. w.Flush()
  197. s.fs.Succ(time.Since(start))
  198. }
  199. }
  200. func (s *streamWriter) stop() {
  201. close(s.q)
  202. <-s.done
  203. }
  204. func (s *streamWriter) stopWithoutLog() {
  205. s.printLog = false
  206. s.stop()
  207. }
  208. func (s *streamWriter) stopNotify() <-chan struct{} { return s.done }
  209. // TODO: move the raft interface out of the reader.
  210. type streamReader struct {
  211. id types.ID
  212. to types.ID
  213. term uint64
  214. r Raft
  215. closer io.Closer
  216. done chan struct{}
  217. }
  218. // newStreamClient starts and returns a new started stream client.
  219. // The caller should call stop when finished, to shut it down.
  220. func newStreamReader(id, to, cid types.ID, term uint64, tr http.RoundTripper, u string, r Raft) (*streamReader, error) {
  221. s := &streamReader{
  222. id: id,
  223. to: to,
  224. term: term,
  225. r: r,
  226. done: make(chan struct{}),
  227. }
  228. uu, err := url.Parse(u)
  229. if err != nil {
  230. return nil, fmt.Errorf("parse url %s error: %v", u, err)
  231. }
  232. uu.Path = path.Join(RaftStreamPrefix, s.id.String())
  233. req, err := http.NewRequest("GET", uu.String(), nil)
  234. if err != nil {
  235. return nil, fmt.Errorf("new request to %s error: %v", u, err)
  236. }
  237. req.Header.Set("X-Etcd-Cluster-ID", cid.String())
  238. req.Header.Set("X-Raft-To", s.to.String())
  239. req.Header.Set("X-Raft-Term", strconv.FormatUint(s.term, 10))
  240. resp, err := tr.RoundTrip(req)
  241. if err != nil {
  242. return nil, fmt.Errorf("error posting to %q: %v", u, err)
  243. }
  244. if resp.StatusCode != http.StatusOK {
  245. resp.Body.Close()
  246. return nil, fmt.Errorf("unhandled http status %d", resp.StatusCode)
  247. }
  248. s.closer = resp.Body
  249. go s.handle(resp.Body)
  250. log.Printf("rafthttp: starting client stream to %s at term %d", s.to, s.term)
  251. return s, nil
  252. }
  253. func (s *streamReader) stop() {
  254. s.closer.Close()
  255. <-s.done
  256. }
  257. func (s *streamReader) isStopped() bool {
  258. select {
  259. case <-s.done:
  260. return true
  261. default:
  262. return false
  263. }
  264. }
  265. func (s *streamReader) handle(r io.Reader) {
  266. defer func() {
  267. close(s.done)
  268. log.Printf("rafthttp: client streaming to %s at term %d has been stopped", s.to, s.term)
  269. }()
  270. er := newEntryReader(r, s.to)
  271. defer er.stop()
  272. for {
  273. ents, err := er.readEntries()
  274. if err != nil {
  275. if err != io.EOF {
  276. log.Printf("rafthttp: encountered error reading the client log stream: %v", err)
  277. }
  278. return
  279. }
  280. if len(ents) == 0 {
  281. continue
  282. }
  283. // The commit index field in appendEntry message is not recovered.
  284. // The follower updates its commit index through heartbeat.
  285. msg := raftpb.Message{
  286. Type: raftpb.MsgApp,
  287. From: uint64(s.to),
  288. To: uint64(s.id),
  289. Term: s.term,
  290. LogTerm: s.term,
  291. Index: ents[0].Index - 1,
  292. Entries: ents,
  293. }
  294. if err := s.r.Process(context.TODO(), msg); err != nil {
  295. log.Printf("rafthttp: process raft message error: %v", err)
  296. return
  297. }
  298. }
  299. }
  300. func shouldInitStream(m raftpb.Message) bool {
  301. return m.Type == raftpb.MsgAppResp && m.Reject == false
  302. }
  303. func canUseStream(m raftpb.Message) bool {
  304. return m.Type == raftpb.MsgApp && m.Index > 0 && m.Term == m.LogTerm
  305. }