stream.go 9.0 KB

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