stream.go 12 KB

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