stream.go 8.6 KB

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