stream.go 13 KB

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