stream.go 13 KB

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