stream.go 8.6 KB

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