stream.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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/Godeps/_workspace/src/github.com/coreos/go-semver/semver"
  26. "github.com/coreos/etcd/etcdserver/stats"
  27. "github.com/coreos/etcd/pkg/types"
  28. "github.com/coreos/etcd/raft/raftpb"
  29. "github.com/coreos/etcd/version"
  30. )
  31. const (
  32. streamTypeMessage streamType = "message"
  33. streamTypeMsgAppV2 streamType = "msgappv2"
  34. streamTypeMsgApp streamType = "msgapp"
  35. streamBufSize = 4096
  36. )
  37. var (
  38. errUnsupportedStreamType = fmt.Errorf("unsupported stream type")
  39. // the key is in string format "major.minor.patch"
  40. supportedStream = map[string][]streamType{
  41. "2.0.0": []streamType{streamTypeMsgApp},
  42. "2.1.0": []streamType{streamTypeMsgApp, streamTypeMsgAppV2, streamTypeMessage},
  43. }
  44. )
  45. type streamType string
  46. func (t streamType) endpoint() string {
  47. switch t {
  48. case streamTypeMsgApp: // for backward compatibility of v2.0
  49. return RaftStreamPrefix
  50. case streamTypeMsgAppV2:
  51. return path.Join(RaftStreamPrefix, "msgapp")
  52. case streamTypeMessage:
  53. return path.Join(RaftStreamPrefix, "message")
  54. default:
  55. log.Panicf("rafthttp: unhandled stream type %v", t)
  56. return ""
  57. }
  58. }
  59. var (
  60. // linkHeartbeatMessage is a special message used as heartbeat message in
  61. // link layer. It never conflicts with messages from raft because raft
  62. // doesn't send out messages without From and To fields.
  63. linkHeartbeatMessage = raftpb.Message{Type: raftpb.MsgHeartbeat}
  64. )
  65. func isLinkHeartbeatMessage(m raftpb.Message) bool {
  66. return m.Type == raftpb.MsgHeartbeat && m.From == 0 && m.To == 0
  67. }
  68. type outgoingConn struct {
  69. t streamType
  70. termStr string
  71. io.Writer
  72. http.Flusher
  73. io.Closer
  74. }
  75. // streamWriter is a long-running go-routine that writes messages into the
  76. // attached outgoingConn.
  77. type streamWriter struct {
  78. id types.ID
  79. fs *stats.FollowerStats
  80. r Raft
  81. mu sync.Mutex // guard field working and closer
  82. closer io.Closer
  83. working bool
  84. msgc chan raftpb.Message
  85. connc chan *outgoingConn
  86. stopc chan struct{}
  87. done chan struct{}
  88. }
  89. func startStreamWriter(id types.ID, fs *stats.FollowerStats, r Raft) *streamWriter {
  90. w := &streamWriter{
  91. id: id,
  92. fs: fs,
  93. r: r,
  94. msgc: make(chan raftpb.Message, streamBufSize),
  95. connc: make(chan *outgoingConn),
  96. stopc: make(chan struct{}),
  97. done: make(chan struct{}),
  98. }
  99. go w.run()
  100. return w
  101. }
  102. func (cw *streamWriter) run() {
  103. var msgc chan raftpb.Message
  104. var heartbeatc <-chan time.Time
  105. var t streamType
  106. var msgAppTerm uint64
  107. var enc encoder
  108. var flusher http.Flusher
  109. tickc := time.Tick(ConnReadTimeout / 3)
  110. for {
  111. select {
  112. case <-heartbeatc:
  113. start := time.Now()
  114. if err := enc.encode(linkHeartbeatMessage); err != nil {
  115. reportSentFailure(string(t), linkHeartbeatMessage)
  116. log.Printf("rafthttp: failed to heartbeat on stream %s due to %v. waiting for a new stream to be established.", t, err)
  117. cw.close()
  118. heartbeatc, msgc = nil, nil
  119. continue
  120. }
  121. flusher.Flush()
  122. reportSentDuration(string(t), linkHeartbeatMessage, time.Since(start))
  123. case m := <-msgc:
  124. if t == streamTypeMsgApp && m.Term != msgAppTerm {
  125. // TODO: reasonable retry logic
  126. if m.Term > msgAppTerm {
  127. cw.close()
  128. heartbeatc, msgc = nil, nil
  129. // TODO: report to raft at peer level
  130. cw.r.ReportUnreachable(m.To)
  131. }
  132. continue
  133. }
  134. start := time.Now()
  135. if err := enc.encode(m); err != nil {
  136. reportSentFailure(string(t), m)
  137. log.Printf("rafthttp: failed to send message on stream %s due to %v. waiting for a new stream to be established.", t, err)
  138. cw.close()
  139. heartbeatc, msgc = nil, nil
  140. cw.r.ReportUnreachable(m.To)
  141. continue
  142. }
  143. flusher.Flush()
  144. reportSentDuration(string(t), m, time.Since(start))
  145. case conn := <-cw.connc:
  146. cw.close()
  147. t = conn.t
  148. switch conn.t {
  149. case streamTypeMsgApp:
  150. var err error
  151. msgAppTerm, err = strconv.ParseUint(conn.termStr, 10, 64)
  152. if err != nil {
  153. log.Panicf("rafthttp: unexpected parse term %s error: %v", conn.termStr, err)
  154. }
  155. enc = &msgAppEncoder{w: conn.Writer, fs: cw.fs}
  156. case streamTypeMsgAppV2:
  157. enc = newMsgAppV2Encoder(conn.Writer, cw.fs)
  158. case streamTypeMessage:
  159. enc = &messageEncoder{w: conn.Writer}
  160. default:
  161. log.Panicf("rafthttp: unhandled stream type %s", conn.t)
  162. }
  163. flusher = conn.Flusher
  164. cw.mu.Lock()
  165. cw.closer = conn.Closer
  166. cw.working = true
  167. cw.mu.Unlock()
  168. heartbeatc, msgc = tickc, cw.msgc
  169. case <-cw.stopc:
  170. cw.close()
  171. close(cw.done)
  172. return
  173. }
  174. }
  175. }
  176. func (cw *streamWriter) writec() (chan<- raftpb.Message, bool) {
  177. cw.mu.Lock()
  178. defer cw.mu.Unlock()
  179. return cw.msgc, cw.working
  180. }
  181. func (cw *streamWriter) close() {
  182. cw.mu.Lock()
  183. defer cw.mu.Unlock()
  184. if !cw.working {
  185. return
  186. }
  187. cw.closer.Close()
  188. if len(cw.msgc) > 0 {
  189. cw.r.ReportUnreachable(uint64(cw.id))
  190. }
  191. cw.msgc = make(chan raftpb.Message, streamBufSize)
  192. cw.working = false
  193. }
  194. func (cw *streamWriter) attach(conn *outgoingConn) bool {
  195. select {
  196. case cw.connc <- conn:
  197. return true
  198. case <-cw.done:
  199. return false
  200. }
  201. }
  202. func (cw *streamWriter) stop() {
  203. close(cw.stopc)
  204. <-cw.done
  205. }
  206. // streamReader is a long-running go-routine that dials to the remote stream
  207. // endponit and reads messages from the response body returned.
  208. type streamReader struct {
  209. tr http.RoundTripper
  210. picker *urlPicker
  211. t streamType
  212. from, to types.ID
  213. cid types.ID
  214. recvc chan<- raftpb.Message
  215. propc chan<- raftpb.Message
  216. errorc chan<- error
  217. mu sync.Mutex
  218. msgAppTerm uint64
  219. req *http.Request
  220. closer io.Closer
  221. stopc chan struct{}
  222. done chan struct{}
  223. }
  224. 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 {
  225. r := &streamReader{
  226. tr: tr,
  227. picker: picker,
  228. t: t,
  229. from: from,
  230. to: to,
  231. cid: cid,
  232. recvc: recvc,
  233. propc: propc,
  234. errorc: errorc,
  235. stopc: make(chan struct{}),
  236. done: make(chan struct{}),
  237. }
  238. go r.run()
  239. return r
  240. }
  241. func (cr *streamReader) run() {
  242. for {
  243. t := cr.t
  244. rc, err := cr.dial(t)
  245. // downgrade to streamTypeMsgApp if the remote doesn't support
  246. // streamTypeMsgAppV2
  247. if t == streamTypeMsgAppV2 && err == errUnsupportedStreamType {
  248. t = streamTypeMsgApp
  249. rc, err = cr.dial(t)
  250. }
  251. if err != nil {
  252. if err != errUnsupportedStreamType {
  253. log.Printf("rafthttp: roundtripping error: %v", err)
  254. }
  255. } else {
  256. err := cr.decodeLoop(rc, t)
  257. switch {
  258. // all data is read out
  259. case err == io.EOF:
  260. // connection is closed by the remote
  261. case isClosedConnectionError(err):
  262. // stream msgapp is only used for etcd 2.0, and etcd 2.0 doesn't
  263. // heartbeat on the idle stream, so it is expected to time out.
  264. case t == streamTypeMsgApp && isNetworkTimeoutError(err):
  265. default:
  266. log.Printf("rafthttp: failed to read message on stream %s due to %v", t, err)
  267. }
  268. }
  269. select {
  270. // Wait 100ms to create a new stream, so it doesn't bring too much
  271. // overhead when retry.
  272. case <-time.After(100 * time.Millisecond):
  273. case <-cr.stopc:
  274. close(cr.done)
  275. return
  276. }
  277. }
  278. }
  279. func (cr *streamReader) decodeLoop(rc io.ReadCloser, t streamType) error {
  280. var dec decoder
  281. cr.mu.Lock()
  282. switch t {
  283. case streamTypeMsgApp:
  284. dec = &msgAppDecoder{r: rc, local: cr.from, remote: cr.to, term: cr.msgAppTerm}
  285. case streamTypeMsgAppV2:
  286. dec = newMsgAppV2Decoder(rc, cr.from, cr.to)
  287. case streamTypeMessage:
  288. dec = &messageDecoder{r: rc}
  289. default:
  290. log.Panicf("rafthttp: unhandled stream type %s", t)
  291. }
  292. cr.closer = rc
  293. cr.mu.Unlock()
  294. for {
  295. m, err := dec.decode()
  296. switch {
  297. case err != nil:
  298. cr.mu.Lock()
  299. cr.close()
  300. cr.mu.Unlock()
  301. return err
  302. case isLinkHeartbeatMessage(m):
  303. // do nothing for linkHeartbeatMessage
  304. default:
  305. recvc := cr.recvc
  306. if m.Type == raftpb.MsgProp {
  307. recvc = cr.propc
  308. }
  309. select {
  310. case recvc <- m:
  311. default:
  312. log.Printf("rafthttp: dropping %s from %x because receive buffer is blocked",
  313. m.Type, m.From)
  314. }
  315. }
  316. }
  317. }
  318. // updateMsgAppTerm updates the term for MsgApp stream, and closes
  319. // the existing MsgApp stream if term is updated.
  320. func (cr *streamReader) updateMsgAppTerm(term uint64) {
  321. cr.mu.Lock()
  322. defer cr.mu.Unlock()
  323. if cr.msgAppTerm >= term {
  324. return
  325. }
  326. cr.msgAppTerm = term
  327. if cr.t == streamTypeMsgApp {
  328. cr.close()
  329. }
  330. }
  331. // TODO: always cancel in-flight dial and decode
  332. func (cr *streamReader) stop() {
  333. close(cr.stopc)
  334. cr.mu.Lock()
  335. cr.cancelRequest()
  336. cr.close()
  337. cr.mu.Unlock()
  338. <-cr.done
  339. }
  340. func (cr *streamReader) isWorking() bool {
  341. cr.mu.Lock()
  342. defer cr.mu.Unlock()
  343. return cr.closer != nil
  344. }
  345. func (cr *streamReader) dial(t streamType) (io.ReadCloser, error) {
  346. u := cr.picker.pick()
  347. cr.mu.Lock()
  348. term := cr.msgAppTerm
  349. cr.mu.Unlock()
  350. uu := u
  351. uu.Path = path.Join(t.endpoint(), cr.from.String())
  352. req, err := http.NewRequest("GET", uu.String(), nil)
  353. if err != nil {
  354. cr.picker.unreachable(u)
  355. return nil, fmt.Errorf("new request to %s error: %v", u, err)
  356. }
  357. req.Header.Set("X-Etcd-Cluster-ID", cr.cid.String())
  358. req.Header.Set("X-Raft-To", cr.to.String())
  359. if t == streamTypeMsgApp {
  360. req.Header.Set("X-Raft-Term", strconv.FormatUint(term, 10))
  361. }
  362. cr.mu.Lock()
  363. cr.req = req
  364. cr.mu.Unlock()
  365. resp, err := cr.tr.RoundTrip(req)
  366. if err != nil {
  367. cr.picker.unreachable(u)
  368. return nil, fmt.Errorf("error roundtripping to %s: %v", req.URL, err)
  369. }
  370. rv := serverVersion(resp.Header)
  371. lv := semver.Must(semver.NewVersion(version.Version))
  372. if compareMajorMinorVersion(rv, lv) == -1 && !checkStreamSupport(rv, t) {
  373. resp.Body.Close()
  374. return nil, errUnsupportedStreamType
  375. }
  376. switch resp.StatusCode {
  377. case http.StatusGone:
  378. resp.Body.Close()
  379. err := fmt.Errorf("the member has been permanently removed from the cluster")
  380. select {
  381. case cr.errorc <- err:
  382. default:
  383. }
  384. return nil, err
  385. case http.StatusOK:
  386. return resp.Body, nil
  387. case http.StatusNotFound:
  388. resp.Body.Close()
  389. return nil, fmt.Errorf("local member has not been added to the peer list of member %s", cr.to)
  390. default:
  391. resp.Body.Close()
  392. return nil, fmt.Errorf("unhandled http status %d", resp.StatusCode)
  393. }
  394. }
  395. func (cr *streamReader) cancelRequest() {
  396. if canceller, ok := cr.tr.(*http.Transport); ok {
  397. canceller.CancelRequest(cr.req)
  398. }
  399. }
  400. func (cr *streamReader) close() {
  401. if cr.closer != nil {
  402. cr.closer.Close()
  403. }
  404. cr.closer = nil
  405. }
  406. func canUseMsgAppStream(m raftpb.Message) bool {
  407. return m.Type == raftpb.MsgApp && m.Term == m.LogTerm
  408. }
  409. func isClosedConnectionError(err error) bool {
  410. operr, ok := err.(*net.OpError)
  411. return ok && operr.Err.Error() == "use of closed network connection"
  412. }
  413. // serverVersion returns the version from the given header.
  414. func serverVersion(h http.Header) *semver.Version {
  415. verStr := h.Get("X-Server-Version")
  416. // backward compatibility with etcd 2.0
  417. if verStr == "" {
  418. verStr = "2.0.0"
  419. }
  420. return semver.Must(semver.NewVersion(verStr))
  421. }
  422. // compareMajorMinorVersion returns an integer comparing two versions based on
  423. // their major and minor version. The result will be 0 if a==b, -1 if a < b,
  424. // and 1 if a > b.
  425. func compareMajorMinorVersion(a, b *semver.Version) int {
  426. na := &semver.Version{Major: a.Major, Minor: a.Minor}
  427. nb := &semver.Version{Major: b.Major, Minor: b.Minor}
  428. switch {
  429. case na.LessThan(*nb):
  430. return -1
  431. case nb.LessThan(*na):
  432. return 1
  433. default:
  434. return 0
  435. }
  436. }
  437. // checkStreamSupport checks whether the stream type is supported in the
  438. // given version.
  439. func checkStreamSupport(v *semver.Version, t streamType) bool {
  440. nv := &semver.Version{Major: v.Major, Minor: v.Minor}
  441. for _, s := range supportedStream[nv.String()] {
  442. if s == t {
  443. return true
  444. }
  445. }
  446. return false
  447. }
  448. func isNetworkTimeoutError(err error) bool {
  449. nerr, ok := err.(net.Error)
  450. return ok && nerr.Timeout()
  451. }