stream.go 12 KB

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