stream.go 8.5 KB

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