stream.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. "fmt"
  17. "io"
  18. "log"
  19. "net"
  20. "net/http"
  21. "net/url"
  22. "path"
  23. "strconv"
  24. "sync"
  25. "time"
  26. "github.com/coreos/etcd/etcdserver/stats"
  27. "github.com/coreos/etcd/pkg/types"
  28. "github.com/coreos/etcd/raft/raftpb"
  29. )
  30. type streamType string
  31. const (
  32. streamTypeMessage streamType = "message"
  33. streamTypeMsgApp streamType = "msgapp"
  34. streamBufSize = 4096
  35. )
  36. var (
  37. // linkHeartbeatMessage is a special message used as heartbeat message in
  38. // link layer. It never conflicts with messages from raft because raft
  39. // doesn't send out messages without From and To fields.
  40. linkHeartbeatMessage = raftpb.Message{Type: raftpb.MsgHeartbeat}
  41. )
  42. func isLinkHeartbeatMessage(m raftpb.Message) bool {
  43. return m.Type == raftpb.MsgHeartbeat && m.From == 0 && m.To == 0
  44. }
  45. type outgoingConn struct {
  46. t streamType
  47. termStr string
  48. io.Writer
  49. http.Flusher
  50. io.Closer
  51. }
  52. // streamWriter is a long-running worker that writes messages into the
  53. // attached outgoingConn.
  54. type streamWriter struct {
  55. fs *stats.FollowerStats
  56. mu sync.Mutex // guard field working and closer
  57. closer io.Closer
  58. working bool
  59. msgc chan raftpb.Message
  60. connc chan *outgoingConn
  61. stopc chan struct{}
  62. done chan struct{}
  63. }
  64. func startStreamWriter(fs *stats.FollowerStats) *streamWriter {
  65. w := &streamWriter{
  66. fs: fs,
  67. msgc: make(chan raftpb.Message, streamBufSize),
  68. connc: make(chan *outgoingConn),
  69. stopc: make(chan struct{}),
  70. done: make(chan struct{}),
  71. }
  72. go w.run()
  73. return w
  74. }
  75. func (cw *streamWriter) run() {
  76. var msgc chan raftpb.Message
  77. var heartbeatc <-chan time.Time
  78. var t streamType
  79. var msgAppTerm uint64
  80. var enc encoder
  81. var flusher http.Flusher
  82. tickc := time.Tick(ConnReadTimeout / 3)
  83. for {
  84. select {
  85. case <-heartbeatc:
  86. if err := enc.encode(linkHeartbeatMessage); err != nil {
  87. log.Printf("rafthttp: failed to heartbeat on stream %s due to %v. waiting for a new stream to be established.", t, err)
  88. cw.resetCloser()
  89. heartbeatc, msgc = nil, nil
  90. continue
  91. }
  92. flusher.Flush()
  93. case m := <-msgc:
  94. if t == streamTypeMsgApp && m.Term != msgAppTerm {
  95. // TODO: reasonable retry logic
  96. if m.Term > msgAppTerm {
  97. cw.resetCloser()
  98. heartbeatc, msgc = nil, nil
  99. }
  100. continue
  101. }
  102. if err := enc.encode(m); err != nil {
  103. log.Printf("rafthttp: failed to send message on stream %s due to %v. waiting for a new stream to be established.", t, err)
  104. cw.resetCloser()
  105. heartbeatc, msgc = nil, nil
  106. continue
  107. }
  108. flusher.Flush()
  109. case conn := <-cw.connc:
  110. cw.resetCloser()
  111. t = conn.t
  112. switch conn.t {
  113. case streamTypeMsgApp:
  114. var err error
  115. msgAppTerm, err = strconv.ParseUint(conn.termStr, 10, 64)
  116. if err != nil {
  117. log.Panicf("rafthttp: unexpected parse term %s error: %v", conn.termStr, err)
  118. }
  119. enc = &msgAppEncoder{w: conn.Writer, fs: cw.fs}
  120. case streamTypeMessage:
  121. enc = &messageEncoder{w: conn.Writer}
  122. default:
  123. log.Panicf("rafthttp: unhandled stream type %s", conn.t)
  124. }
  125. flusher = conn.Flusher
  126. cw.mu.Lock()
  127. cw.closer = conn.Closer
  128. cw.working = true
  129. cw.mu.Unlock()
  130. heartbeatc, msgc = tickc, cw.msgc
  131. case <-cw.stopc:
  132. cw.resetCloser()
  133. close(cw.done)
  134. return
  135. }
  136. }
  137. }
  138. func (cw *streamWriter) isWorking() bool {
  139. cw.mu.Lock()
  140. defer cw.mu.Unlock()
  141. return cw.working
  142. }
  143. func (cw *streamWriter) resetCloser() {
  144. cw.mu.Lock()
  145. defer cw.mu.Unlock()
  146. if cw.working {
  147. cw.closer.Close()
  148. }
  149. cw.working = false
  150. }
  151. func (cw *streamWriter) attach(conn *outgoingConn) bool {
  152. select {
  153. case cw.connc <- conn:
  154. return true
  155. case <-cw.done:
  156. return false
  157. }
  158. }
  159. func (cw *streamWriter) stop() {
  160. close(cw.stopc)
  161. <-cw.done
  162. }
  163. // streamReader is a long-running go-routine that dials to the remote stream
  164. // endponit and reads messages from the response body returned.
  165. type streamReader struct {
  166. tr http.RoundTripper
  167. u string
  168. t streamType
  169. from, to types.ID
  170. cid types.ID
  171. recvc chan<- raftpb.Message
  172. mu sync.Mutex
  173. msgAppTerm uint64
  174. req *http.Request
  175. closer io.Closer
  176. stopc chan struct{}
  177. done chan struct{}
  178. }
  179. func startStreamReader(tr http.RoundTripper, u string, t streamType, from, to, cid types.ID, recvc chan<- raftpb.Message) *streamReader {
  180. r := &streamReader{
  181. tr: tr,
  182. u: u,
  183. t: t,
  184. from: from,
  185. to: to,
  186. cid: cid,
  187. recvc: recvc,
  188. stopc: make(chan struct{}),
  189. done: make(chan struct{}),
  190. }
  191. go r.run()
  192. return r
  193. }
  194. func (cr *streamReader) run() {
  195. for {
  196. rc, err := cr.roundtrip()
  197. if err != nil {
  198. log.Printf("rafthttp: roundtripping error: %v", err)
  199. } else {
  200. err := cr.decodeLoop(rc)
  201. if err != io.EOF && !isClosedConnectionError(err) {
  202. log.Printf("rafthttp: failed to read message on stream %s due to %v", cr.t, err)
  203. }
  204. }
  205. select {
  206. // Wait 100ms to create a new stream, so it doesn't bring too much
  207. // overhead when retry.
  208. case <-time.After(100 * time.Millisecond):
  209. case <-cr.stopc:
  210. close(cr.done)
  211. return
  212. }
  213. }
  214. }
  215. func (cr *streamReader) decodeLoop(rc io.ReadCloser) error {
  216. var dec decoder
  217. cr.mu.Lock()
  218. switch cr.t {
  219. case streamTypeMsgApp:
  220. dec = &msgAppDecoder{r: rc, local: cr.from, remote: cr.to, term: cr.msgAppTerm}
  221. case streamTypeMessage:
  222. dec = &messageDecoder{r: rc}
  223. default:
  224. log.Panicf("rafthttp: unhandled stream type %s", cr.t)
  225. }
  226. cr.closer = rc
  227. cr.mu.Unlock()
  228. for {
  229. m, err := dec.decode()
  230. switch {
  231. case err != nil:
  232. cr.mu.Lock()
  233. cr.resetCloser()
  234. cr.mu.Unlock()
  235. return err
  236. case isLinkHeartbeatMessage(m):
  237. // do nothing for linkHeartbeatMessage
  238. default:
  239. select {
  240. case cr.recvc <- m:
  241. default:
  242. log.Printf("rafthttp: dropping %s from %x because receive buffer is blocked",
  243. m.Type, m.From)
  244. }
  245. }
  246. }
  247. }
  248. func (cr *streamReader) update(u string) {
  249. cr.mu.Lock()
  250. defer cr.mu.Unlock()
  251. cr.u = u
  252. cr.resetCloser()
  253. }
  254. func (cr *streamReader) updateMsgAppTerm(term uint64) {
  255. cr.mu.Lock()
  256. defer cr.mu.Unlock()
  257. if cr.msgAppTerm == term {
  258. return
  259. }
  260. cr.msgAppTerm = term
  261. cr.resetCloser()
  262. }
  263. // TODO: always cancel in-flight dial and decode
  264. func (cr *streamReader) stop() {
  265. close(cr.stopc)
  266. cr.mu.Lock()
  267. cr.cancelRequest()
  268. cr.resetCloser()
  269. cr.mu.Unlock()
  270. <-cr.done
  271. }
  272. func (cr *streamReader) isWorking() bool {
  273. cr.mu.Lock()
  274. defer cr.mu.Unlock()
  275. return cr.closer != nil
  276. }
  277. func (cr *streamReader) roundtrip() (io.ReadCloser, error) {
  278. cr.mu.Lock()
  279. u := cr.u
  280. term := cr.msgAppTerm
  281. cr.mu.Unlock()
  282. uu, err := url.Parse(u)
  283. if err != nil {
  284. return nil, fmt.Errorf("parse url %s error: %v", u, err)
  285. }
  286. switch cr.t {
  287. case streamTypeMsgApp:
  288. // for backward compatibility of v2.0
  289. uu.Path = path.Join(RaftStreamPrefix, cr.from.String())
  290. case streamTypeMessage:
  291. uu.Path = path.Join(RaftStreamPrefix, string(streamTypeMessage), cr.from.String())
  292. default:
  293. log.Panicf("rafthttp: unhandled stream type %v", cr.t)
  294. }
  295. req, err := http.NewRequest("GET", uu.String(), nil)
  296. if err != nil {
  297. return nil, fmt.Errorf("new request to %s error: %v", u, err)
  298. }
  299. req.Header.Set("X-Etcd-Cluster-ID", cr.cid.String())
  300. req.Header.Set("X-Raft-To", cr.to.String())
  301. if cr.t == streamTypeMsgApp {
  302. req.Header.Set("X-Raft-Term", strconv.FormatUint(term, 10))
  303. }
  304. cr.mu.Lock()
  305. cr.req = req
  306. cr.mu.Unlock()
  307. resp, err := cr.tr.RoundTrip(req)
  308. if err != nil {
  309. return nil, fmt.Errorf("error roundtripping to %s: %v", req.URL, err)
  310. }
  311. if resp.StatusCode != http.StatusOK {
  312. resp.Body.Close()
  313. return nil, fmt.Errorf("unhandled http status %d", resp.StatusCode)
  314. }
  315. return resp.Body, nil
  316. }
  317. func (cr *streamReader) cancelRequest() {
  318. if canceller, ok := cr.tr.(*http.Transport); ok {
  319. canceller.CancelRequest(cr.req)
  320. }
  321. }
  322. func (cr *streamReader) resetCloser() {
  323. if cr.closer != nil {
  324. cr.closer.Close()
  325. }
  326. cr.closer = nil
  327. }
  328. func canUseMsgAppStream(m raftpb.Message) bool {
  329. return m.Type == raftpb.MsgApp && m.Term == m.LogTerm
  330. }
  331. func isClosedConnectionError(err error) bool {
  332. operr, ok := err.(*net.OpError)
  333. return ok && operr.Err.Error() == "use of closed network connection"
  334. }