stream.go 8.5 KB

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