stream.go 9.3 KB

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