stream.go 13 KB

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