stream.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. // Copyright 2015 The etcd Authors
  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. "strings"
  23. "sync"
  24. "time"
  25. "github.com/coreos/etcd/etcdserver/stats"
  26. "github.com/coreos/etcd/pkg/httputil"
  27. "github.com/coreos/etcd/pkg/types"
  28. "github.com/coreos/etcd/raft/raftpb"
  29. "github.com/coreos/etcd/version"
  30. "github.com/coreos/go-semver/semver"
  31. )
  32. const (
  33. streamTypeMessage streamType = "message"
  34. streamTypeMsgAppV2 streamType = "msgappv2"
  35. streamBufSize = 4096
  36. )
  37. var (
  38. errUnsupportedStreamType = fmt.Errorf("unsupported stream type")
  39. // the key is in string format "major.minor.patch"
  40. supportedStream = map[string][]streamType{
  41. "2.0.0": {},
  42. "2.1.0": {streamTypeMsgAppV2, streamTypeMessage},
  43. "2.2.0": {streamTypeMsgAppV2, streamTypeMessage},
  44. "2.3.0": {streamTypeMsgAppV2, streamTypeMessage},
  45. "3.0.0": {streamTypeMsgAppV2, streamTypeMessage},
  46. "3.1.0": {streamTypeMsgAppV2, streamTypeMessage},
  47. "3.2.0": {streamTypeMsgAppV2, streamTypeMessage},
  48. }
  49. )
  50. type streamType string
  51. func (t streamType) endpoint() string {
  52. switch t {
  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 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. io.Writer
  84. http.Flusher
  85. io.Closer
  86. }
  87. // streamWriter writes messages to the attached outgoingConn.
  88. type streamWriter struct {
  89. peerID types.ID
  90. status *peerStatus
  91. fs *stats.FollowerStats
  92. r Raft
  93. mu sync.Mutex // guard field working and closer
  94. closer io.Closer
  95. working bool
  96. msgc chan raftpb.Message
  97. connc chan *outgoingConn
  98. stopc chan struct{}
  99. done chan struct{}
  100. }
  101. // startStreamWriter creates a streamWrite and starts a long running go-routine that accepts
  102. // messages and writes to the attached outgoing connection.
  103. func startStreamWriter(id types.ID, status *peerStatus, fs *stats.FollowerStats, r Raft) *streamWriter {
  104. w := &streamWriter{
  105. peerID: 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 (
  119. msgc chan raftpb.Message
  120. heartbeatc <-chan time.Time
  121. t streamType
  122. enc encoder
  123. flusher http.Flusher
  124. batched int
  125. )
  126. tickc := time.Tick(ConnReadTimeout / 3)
  127. unflushed := 0
  128. plog.Infof("started streaming with peer %s (writer)", cw.peerID)
  129. for {
  130. select {
  131. case <-heartbeatc:
  132. err := enc.encode(&linkHeartbeatMessage)
  133. unflushed += linkHeartbeatMessage.Size()
  134. if err == nil {
  135. flusher.Flush()
  136. batched = 0
  137. sentBytes.WithLabelValues(cw.peerID.String()).Add(float64(unflushed))
  138. unflushed = 0
  139. continue
  140. }
  141. cw.status.deactivate(failureType{source: t.String(), action: "heartbeat"}, err.Error())
  142. sentFailures.WithLabelValues(cw.peerID.String()).Inc()
  143. cw.close()
  144. plog.Warningf("lost the TCP streaming connection with peer %s (%s writer)", cw.peerID, t)
  145. heartbeatc, msgc = nil, nil
  146. case m := <-msgc:
  147. err := enc.encode(&m)
  148. if err == nil {
  149. unflushed += m.Size()
  150. if len(msgc) == 0 || batched > streamBufSize/2 {
  151. flusher.Flush()
  152. sentBytes.WithLabelValues(cw.peerID.String()).Add(float64(unflushed))
  153. unflushed = 0
  154. batched = 0
  155. } else {
  156. batched++
  157. }
  158. continue
  159. }
  160. cw.status.deactivate(failureType{source: t.String(), action: "write"}, err.Error())
  161. cw.close()
  162. plog.Warningf("lost the TCP streaming connection with peer %s (%s writer)", cw.peerID, t)
  163. heartbeatc, msgc = nil, nil
  164. cw.r.ReportUnreachable(m.To)
  165. sentFailures.WithLabelValues(cw.peerID.String()).Inc()
  166. case conn := <-cw.connc:
  167. cw.mu.Lock()
  168. closed := cw.closeUnlocked()
  169. t = conn.t
  170. switch conn.t {
  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. unflushed = 0
  180. cw.status.activate()
  181. cw.closer = conn.Closer
  182. cw.working = true
  183. cw.mu.Unlock()
  184. if closed {
  185. plog.Warningf("closed an existing TCP streaming connection with peer %s (%s writer)", cw.peerID, t)
  186. }
  187. plog.Infof("established a TCP streaming connection with peer %s (%s writer)", cw.peerID, t)
  188. heartbeatc, msgc = tickc, cw.msgc
  189. case <-cw.stopc:
  190. if cw.close() {
  191. plog.Infof("closed the TCP streaming connection with peer %s (%s writer)", cw.peerID, t)
  192. }
  193. plog.Infof("stopped streaming with peer %s (writer)", cw.peerID)
  194. close(cw.done)
  195. return
  196. }
  197. }
  198. }
  199. func (cw *streamWriter) writec() (chan<- raftpb.Message, bool) {
  200. cw.mu.Lock()
  201. defer cw.mu.Unlock()
  202. return cw.msgc, cw.working
  203. }
  204. func (cw *streamWriter) close() bool {
  205. cw.mu.Lock()
  206. defer cw.mu.Unlock()
  207. return cw.closeUnlocked()
  208. }
  209. func (cw *streamWriter) closeUnlocked() bool {
  210. if !cw.working {
  211. return false
  212. }
  213. cw.closer.Close()
  214. if len(cw.msgc) > 0 {
  215. cw.r.ReportUnreachable(uint64(cw.peerID))
  216. }
  217. cw.msgc = make(chan raftpb.Message, streamBufSize)
  218. cw.working = false
  219. return true
  220. }
  221. func (cw *streamWriter) attach(conn *outgoingConn) bool {
  222. select {
  223. case cw.connc <- conn:
  224. return true
  225. case <-cw.done:
  226. return false
  227. }
  228. }
  229. func (cw *streamWriter) stop() {
  230. close(cw.stopc)
  231. <-cw.done
  232. }
  233. // streamReader is a long-running go-routine that dials to the remote stream
  234. // endpoint and reads messages from the response body returned.
  235. type streamReader struct {
  236. peerID types.ID
  237. typ streamType
  238. tr *Transport
  239. picker *urlPicker
  240. status *peerStatus
  241. recvc chan<- raftpb.Message
  242. propc chan<- raftpb.Message
  243. errorc chan<- error
  244. mu sync.Mutex
  245. paused bool
  246. cancel func()
  247. closer io.Closer
  248. stopc chan struct{}
  249. done chan struct{}
  250. }
  251. func (r *streamReader) start() {
  252. r.stopc = make(chan struct{})
  253. r.done = make(chan struct{})
  254. if r.errorc == nil {
  255. r.errorc = r.tr.ErrorC
  256. }
  257. go r.run()
  258. }
  259. func (cr *streamReader) run() {
  260. t := cr.typ
  261. plog.Infof("started streaming with peer %s (%s reader)", cr.peerID, t)
  262. for {
  263. rc, err := cr.dial(t)
  264. if err != nil {
  265. if err != errUnsupportedStreamType {
  266. cr.status.deactivate(failureType{source: t.String(), action: "dial"}, err.Error())
  267. }
  268. } else {
  269. cr.status.activate()
  270. plog.Infof("established a TCP streaming connection with peer %s (%s reader)", cr.peerID, cr.typ)
  271. err := cr.decodeLoop(rc, t)
  272. plog.Warningf("lost the TCP streaming connection with peer %s (%s reader)", cr.peerID, cr.typ)
  273. switch {
  274. // all data is read out
  275. case err == io.EOF:
  276. // connection is closed by the remote
  277. case isClosedConnectionError(err):
  278. default:
  279. cr.status.deactivate(failureType{source: t.String(), action: "read"}, err.Error())
  280. }
  281. }
  282. select {
  283. // Wait 100ms to create a new stream, so it doesn't bring too much
  284. // overhead when retry.
  285. case <-time.After(100 * time.Millisecond):
  286. case <-cr.stopc:
  287. plog.Infof("stopped streaming with peer %s (%s reader)", cr.peerID, t)
  288. close(cr.done)
  289. return
  290. }
  291. }
  292. }
  293. func (cr *streamReader) decodeLoop(rc io.ReadCloser, t streamType) error {
  294. var dec decoder
  295. cr.mu.Lock()
  296. switch t {
  297. case streamTypeMsgAppV2:
  298. dec = newMsgAppV2Decoder(rc, cr.tr.ID, cr.peerID)
  299. case streamTypeMessage:
  300. dec = &messageDecoder{r: rc}
  301. default:
  302. plog.Panicf("unhandled stream type %s", t)
  303. }
  304. select {
  305. case <-cr.stopc:
  306. cr.mu.Unlock()
  307. if err := rc.Close(); err != nil {
  308. return err
  309. }
  310. return io.EOF
  311. default:
  312. cr.closer = rc
  313. }
  314. cr.mu.Unlock()
  315. for {
  316. m, err := dec.decode()
  317. if err != nil {
  318. cr.mu.Lock()
  319. cr.close()
  320. cr.mu.Unlock()
  321. return err
  322. }
  323. receivedBytes.WithLabelValues(types.ID(m.From).String()).Add(float64(m.Size()))
  324. cr.mu.Lock()
  325. paused := cr.paused
  326. cr.mu.Unlock()
  327. if paused {
  328. continue
  329. }
  330. if isLinkHeartbeatMessage(&m) {
  331. // raft is not interested in link layer
  332. // heartbeat message, so we should ignore
  333. // it.
  334. continue
  335. }
  336. recvc := cr.recvc
  337. if m.Type == raftpb.MsgProp {
  338. recvc = cr.propc
  339. }
  340. select {
  341. case recvc <- m:
  342. default:
  343. if cr.status.isActive() {
  344. plog.MergeWarningf("dropped internal raft message from %s since receiving buffer is full (overloaded network)", types.ID(m.From))
  345. }
  346. plog.Debugf("dropped %s from %s since receiving buffer is full", m.Type, types.ID(m.From))
  347. recvFailures.WithLabelValues(types.ID(m.From).String()).Inc()
  348. }
  349. }
  350. }
  351. func (cr *streamReader) stop() {
  352. close(cr.stopc)
  353. cr.mu.Lock()
  354. if cr.cancel != nil {
  355. cr.cancel()
  356. }
  357. cr.close()
  358. cr.mu.Unlock()
  359. <-cr.done
  360. }
  361. func (cr *streamReader) dial(t streamType) (io.ReadCloser, error) {
  362. u := cr.picker.pick()
  363. uu := u
  364. uu.Path = path.Join(t.endpoint(), cr.tr.ID.String())
  365. req, err := http.NewRequest("GET", uu.String(), nil)
  366. if err != nil {
  367. cr.picker.unreachable(u)
  368. return nil, fmt.Errorf("failed to make http request to %v (%v)", u, err)
  369. }
  370. req.Header.Set("X-Server-From", cr.tr.ID.String())
  371. req.Header.Set("X-Server-Version", version.Version)
  372. req.Header.Set("X-Min-Cluster-Version", version.MinClusterVersion)
  373. req.Header.Set("X-Etcd-Cluster-ID", cr.tr.ClusterID.String())
  374. req.Header.Set("X-Raft-To", cr.peerID.String())
  375. setPeerURLsHeader(req, cr.tr.URLs)
  376. cr.mu.Lock()
  377. select {
  378. case <-cr.stopc:
  379. cr.mu.Unlock()
  380. return nil, fmt.Errorf("stream reader is stopped")
  381. default:
  382. }
  383. cr.cancel = httputil.RequestCanceler(req)
  384. cr.mu.Unlock()
  385. resp, err := cr.tr.streamRt.RoundTrip(req)
  386. if err != nil {
  387. cr.picker.unreachable(u)
  388. return nil, err
  389. }
  390. rv := serverVersion(resp.Header)
  391. lv := semver.Must(semver.NewVersion(version.Version))
  392. if compareMajorMinorVersion(rv, lv) == -1 && !checkStreamSupport(rv, t) {
  393. httputil.GracefulClose(resp)
  394. cr.picker.unreachable(u)
  395. return nil, errUnsupportedStreamType
  396. }
  397. switch resp.StatusCode {
  398. case http.StatusGone:
  399. httputil.GracefulClose(resp)
  400. cr.picker.unreachable(u)
  401. reportCriticalError(errMemberRemoved, cr.errorc)
  402. return nil, errMemberRemoved
  403. case http.StatusOK:
  404. return resp.Body, nil
  405. case http.StatusNotFound:
  406. httputil.GracefulClose(resp)
  407. cr.picker.unreachable(u)
  408. return nil, fmt.Errorf("peer %s failed to find local node %s", cr.peerID, cr.tr.ID)
  409. case http.StatusPreconditionFailed:
  410. b, err := ioutil.ReadAll(resp.Body)
  411. if err != nil {
  412. cr.picker.unreachable(u)
  413. return nil, err
  414. }
  415. httputil.GracefulClose(resp)
  416. cr.picker.unreachable(u)
  417. switch strings.TrimSuffix(string(b), "\n") {
  418. case errIncompatibleVersion.Error():
  419. plog.Errorf("request sent was ignored by peer %s (server version incompatible)", cr.peerID)
  420. return nil, errIncompatibleVersion
  421. case errClusterIDMismatch.Error():
  422. plog.Errorf("request sent was ignored (cluster ID mismatch: peer[%s]=%s, local=%s)",
  423. cr.peerID, resp.Header.Get("X-Etcd-Cluster-ID"), cr.tr.ClusterID)
  424. return nil, errClusterIDMismatch
  425. default:
  426. return nil, fmt.Errorf("unhandled error %q when precondition failed", string(b))
  427. }
  428. default:
  429. httputil.GracefulClose(resp)
  430. cr.picker.unreachable(u)
  431. return nil, fmt.Errorf("unhandled http status %d", resp.StatusCode)
  432. }
  433. }
  434. func (cr *streamReader) close() {
  435. if cr.closer != nil {
  436. cr.closer.Close()
  437. }
  438. cr.closer = nil
  439. }
  440. func (cr *streamReader) pause() {
  441. cr.mu.Lock()
  442. defer cr.mu.Unlock()
  443. cr.paused = true
  444. }
  445. func (cr *streamReader) resume() {
  446. cr.mu.Lock()
  447. defer cr.mu.Unlock()
  448. cr.paused = false
  449. }
  450. func isClosedConnectionError(err error) bool {
  451. operr, ok := err.(*net.OpError)
  452. return ok && operr.Err.Error() == "use of closed network connection"
  453. }
  454. // checkStreamSupport checks whether the stream type is supported in the
  455. // given version.
  456. func checkStreamSupport(v *semver.Version, t streamType) bool {
  457. nv := &semver.Version{Major: v.Major, Minor: v.Minor}
  458. for _, s := range supportedStream[nv.String()] {
  459. if s == t {
  460. return true
  461. }
  462. }
  463. return false
  464. }