stream.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. errorc chan<- error
  207. mu sync.Mutex
  208. msgAppTerm uint64
  209. req *http.Request
  210. closer io.Closer
  211. stopc chan struct{}
  212. done chan struct{}
  213. }
  214. func startStreamReader(tr http.RoundTripper, picker *urlPicker, t streamType, from, to, cid types.ID, recvc chan<- raftpb.Message, propc chan<- raftpb.Message, errorc chan<- error) *streamReader {
  215. r := &streamReader{
  216. tr: tr,
  217. picker: picker,
  218. t: t,
  219. from: from,
  220. to: to,
  221. cid: cid,
  222. recvc: recvc,
  223. propc: propc,
  224. errorc: errorc,
  225. stopc: make(chan struct{}),
  226. done: make(chan struct{}),
  227. }
  228. go r.run()
  229. return r
  230. }
  231. func (cr *streamReader) run() {
  232. for {
  233. rc, err := cr.dial()
  234. if err != nil {
  235. log.Printf("rafthttp: roundtripping error: %v", err)
  236. } else {
  237. err := cr.decodeLoop(rc)
  238. if err != io.EOF && !isClosedConnectionError(err) {
  239. log.Printf("rafthttp: failed to read message on stream %s due to %v", cr.t, err)
  240. }
  241. }
  242. select {
  243. // Wait 100ms to create a new stream, so it doesn't bring too much
  244. // overhead when retry.
  245. case <-time.After(100 * time.Millisecond):
  246. case <-cr.stopc:
  247. close(cr.done)
  248. return
  249. }
  250. }
  251. }
  252. func (cr *streamReader) decodeLoop(rc io.ReadCloser) error {
  253. var dec decoder
  254. cr.mu.Lock()
  255. switch cr.t {
  256. case streamTypeMsgApp:
  257. dec = &msgAppDecoder{r: rc, local: cr.from, remote: cr.to, term: cr.msgAppTerm}
  258. case streamTypeMsgAppV2:
  259. dec = &msgAppV2Decoder{r: rc, local: cr.from, remote: cr.to}
  260. case streamTypeMessage:
  261. dec = &messageDecoder{r: rc}
  262. default:
  263. log.Panicf("rafthttp: unhandled stream type %s", cr.t)
  264. }
  265. cr.closer = rc
  266. cr.mu.Unlock()
  267. for {
  268. m, err := dec.decode()
  269. switch {
  270. case err != nil:
  271. cr.mu.Lock()
  272. cr.resetCloser()
  273. cr.mu.Unlock()
  274. return err
  275. case isLinkHeartbeatMessage(m):
  276. // do nothing for linkHeartbeatMessage
  277. default:
  278. recvc := cr.recvc
  279. if m.Type == raftpb.MsgProp {
  280. recvc = cr.propc
  281. }
  282. select {
  283. case recvc <- m:
  284. default:
  285. log.Printf("rafthttp: dropping %s from %x because receive buffer is blocked",
  286. m.Type, m.From)
  287. }
  288. }
  289. }
  290. }
  291. func (cr *streamReader) updateMsgAppTerm(term uint64) {
  292. cr.mu.Lock()
  293. defer cr.mu.Unlock()
  294. if cr.msgAppTerm == term {
  295. return
  296. }
  297. cr.msgAppTerm = term
  298. cr.resetCloser()
  299. }
  300. // TODO: always cancel in-flight dial and decode
  301. func (cr *streamReader) stop() {
  302. close(cr.stopc)
  303. cr.mu.Lock()
  304. cr.cancelRequest()
  305. cr.resetCloser()
  306. cr.mu.Unlock()
  307. <-cr.done
  308. }
  309. func (cr *streamReader) isWorking() bool {
  310. cr.mu.Lock()
  311. defer cr.mu.Unlock()
  312. return cr.closer != nil
  313. }
  314. func (cr *streamReader) dial() (io.ReadCloser, error) {
  315. u := cr.picker.pick()
  316. cr.mu.Lock()
  317. term := cr.msgAppTerm
  318. cr.mu.Unlock()
  319. uu := u
  320. uu.Path = path.Join(cr.t.endpoint(), cr.from.String())
  321. req, err := http.NewRequest("GET", uu.String(), nil)
  322. if err != nil {
  323. cr.picker.unreachable(u)
  324. return nil, fmt.Errorf("new request to %s error: %v", u, err)
  325. }
  326. req.Header.Set("X-Etcd-Cluster-ID", cr.cid.String())
  327. req.Header.Set("X-Raft-To", cr.to.String())
  328. if cr.t == streamTypeMsgApp {
  329. req.Header.Set("X-Raft-Term", strconv.FormatUint(term, 10))
  330. }
  331. cr.mu.Lock()
  332. cr.req = req
  333. cr.mu.Unlock()
  334. resp, err := cr.tr.RoundTrip(req)
  335. if err != nil {
  336. cr.picker.unreachable(u)
  337. return nil, fmt.Errorf("error roundtripping to %s: %v", req.URL, err)
  338. }
  339. switch resp.StatusCode {
  340. case http.StatusGone:
  341. resp.Body.Close()
  342. err := fmt.Errorf("the member has been permanently removed from the cluster")
  343. select {
  344. case cr.errorc <- err:
  345. default:
  346. }
  347. return nil, err
  348. case http.StatusOK:
  349. return resp.Body, nil
  350. default:
  351. resp.Body.Close()
  352. return nil, fmt.Errorf("unhandled http status %d", resp.StatusCode)
  353. }
  354. }
  355. func (cr *streamReader) cancelRequest() {
  356. if canceller, ok := cr.tr.(*http.Transport); ok {
  357. canceller.CancelRequest(cr.req)
  358. }
  359. }
  360. func (cr *streamReader) resetCloser() {
  361. if cr.closer != nil {
  362. cr.closer.Close()
  363. }
  364. cr.closer = nil
  365. }
  366. func canUseMsgAppStream(m raftpb.Message) bool {
  367. return m.Type == raftpb.MsgApp && m.Term == m.LogTerm
  368. }
  369. func isClosedConnectionError(err error) bool {
  370. operr, ok := err.(*net.OpError)
  371. return ok && operr.Err.Error() == "use of closed network connection"
  372. }