stream.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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. "context"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  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/transport"
  28. "github.com/coreos/etcd/pkg/types"
  29. "github.com/coreos/etcd/raft/raftpb"
  30. "github.com/coreos/etcd/version"
  31. "github.com/coreos/go-semver/semver"
  32. "go.uber.org/zap"
  33. "golang.org/x/time/rate"
  34. )
  35. const (
  36. streamTypeMessage streamType = "message"
  37. streamTypeMsgAppV2 streamType = "msgappv2"
  38. streamBufSize = 4096
  39. )
  40. var (
  41. errUnsupportedStreamType = fmt.Errorf("unsupported stream type")
  42. // the key is in string format "major.minor.patch"
  43. supportedStream = map[string][]streamType{
  44. "2.0.0": {},
  45. "2.1.0": {streamTypeMsgAppV2, streamTypeMessage},
  46. "2.2.0": {streamTypeMsgAppV2, streamTypeMessage},
  47. "2.3.0": {streamTypeMsgAppV2, streamTypeMessage},
  48. "3.0.0": {streamTypeMsgAppV2, streamTypeMessage},
  49. "3.1.0": {streamTypeMsgAppV2, streamTypeMessage},
  50. "3.2.0": {streamTypeMsgAppV2, streamTypeMessage},
  51. "3.3.0": {streamTypeMsgAppV2, streamTypeMessage},
  52. }
  53. )
  54. type streamType string
  55. func (t streamType) endpoint() string {
  56. switch t {
  57. case streamTypeMsgAppV2:
  58. return path.Join(RaftStreamPrefix, "msgapp")
  59. case streamTypeMessage:
  60. return path.Join(RaftStreamPrefix, "message")
  61. default:
  62. plog.Panicf("unhandled stream type %v", t)
  63. return ""
  64. }
  65. }
  66. func (t streamType) String() string {
  67. switch t {
  68. case streamTypeMsgAppV2:
  69. return "stream MsgApp v2"
  70. case streamTypeMessage:
  71. return "stream Message"
  72. default:
  73. return "unknown stream"
  74. }
  75. }
  76. var (
  77. // linkHeartbeatMessage is a special message used as heartbeat message in
  78. // link layer. It never conflicts with messages from raft because raft
  79. // doesn't send out messages without From and To fields.
  80. linkHeartbeatMessage = raftpb.Message{Type: raftpb.MsgHeartbeat}
  81. )
  82. func isLinkHeartbeatMessage(m *raftpb.Message) bool {
  83. return m.Type == raftpb.MsgHeartbeat && m.From == 0 && m.To == 0
  84. }
  85. type outgoingConn struct {
  86. t streamType
  87. io.Writer
  88. http.Flusher
  89. io.Closer
  90. }
  91. // streamWriter writes messages to the attached outgoingConn.
  92. type streamWriter struct {
  93. lg *zap.Logger
  94. localID types.ID
  95. peerID types.ID
  96. status *peerStatus
  97. fs *stats.FollowerStats
  98. r Raft
  99. mu sync.Mutex // guard field working and closer
  100. closer io.Closer
  101. working bool
  102. msgc chan raftpb.Message
  103. connc chan *outgoingConn
  104. stopc chan struct{}
  105. done chan struct{}
  106. }
  107. // startStreamWriter creates a streamWrite and starts a long running go-routine that accepts
  108. // messages and writes to the attached outgoing connection.
  109. func startStreamWriter(lg *zap.Logger, local, id types.ID, status *peerStatus, fs *stats.FollowerStats, r Raft) *streamWriter {
  110. w := &streamWriter{
  111. lg: lg,
  112. localID: local,
  113. peerID: id,
  114. status: status,
  115. fs: fs,
  116. r: r,
  117. msgc: make(chan raftpb.Message, streamBufSize),
  118. connc: make(chan *outgoingConn),
  119. stopc: make(chan struct{}),
  120. done: make(chan struct{}),
  121. }
  122. go w.run()
  123. return w
  124. }
  125. func (cw *streamWriter) run() {
  126. var (
  127. msgc chan raftpb.Message
  128. heartbeatc <-chan time.Time
  129. t streamType
  130. enc encoder
  131. flusher http.Flusher
  132. batched int
  133. )
  134. tickc := time.NewTicker(ConnReadTimeout / 3)
  135. defer tickc.Stop()
  136. unflushed := 0
  137. if cw.lg != nil {
  138. cw.lg.Info(
  139. "started stream writer with remote peer",
  140. zap.String("local-member-id", cw.localID.String()),
  141. zap.String("remote-peer-id", cw.peerID.String()),
  142. )
  143. } else {
  144. plog.Infof("started streaming with peer %s (writer)", cw.peerID)
  145. }
  146. for {
  147. select {
  148. case <-heartbeatc:
  149. err := enc.encode(&linkHeartbeatMessage)
  150. unflushed += linkHeartbeatMessage.Size()
  151. if err == nil {
  152. flusher.Flush()
  153. batched = 0
  154. sentBytes.WithLabelValues(cw.peerID.String()).Add(float64(unflushed))
  155. unflushed = 0
  156. continue
  157. }
  158. cw.status.deactivate(failureType{source: t.String(), action: "heartbeat"}, err.Error())
  159. sentFailures.WithLabelValues(cw.peerID.String()).Inc()
  160. cw.close()
  161. if cw.lg != nil {
  162. cw.lg.Warn(
  163. "lost TCP streaming connection with remote peer",
  164. zap.String("stream-writer-type", t.String()),
  165. zap.String("local-member-id", cw.localID.String()),
  166. zap.String("remote-peer-id", cw.peerID.String()),
  167. )
  168. } else {
  169. plog.Warningf("lost the TCP streaming connection with peer %s (%s writer)", cw.peerID, t)
  170. }
  171. heartbeatc, msgc = nil, nil
  172. case m := <-msgc:
  173. err := enc.encode(&m)
  174. if err == nil {
  175. unflushed += m.Size()
  176. if len(msgc) == 0 || batched > streamBufSize/2 {
  177. flusher.Flush()
  178. sentBytes.WithLabelValues(cw.peerID.String()).Add(float64(unflushed))
  179. unflushed = 0
  180. batched = 0
  181. } else {
  182. batched++
  183. }
  184. continue
  185. }
  186. cw.status.deactivate(failureType{source: t.String(), action: "write"}, err.Error())
  187. cw.close()
  188. if cw.lg != nil {
  189. cw.lg.Warn(
  190. "lost TCP streaming connection with remote peer",
  191. zap.String("stream-writer-type", t.String()),
  192. zap.String("local-member-id", cw.localID.String()),
  193. zap.String("remote-peer-id", cw.peerID.String()),
  194. )
  195. } else {
  196. plog.Warningf("lost the TCP streaming connection with peer %s (%s writer)", cw.peerID, t)
  197. }
  198. heartbeatc, msgc = nil, nil
  199. cw.r.ReportUnreachable(m.To)
  200. sentFailures.WithLabelValues(cw.peerID.String()).Inc()
  201. case conn := <-cw.connc:
  202. cw.mu.Lock()
  203. closed := cw.closeUnlocked()
  204. t = conn.t
  205. switch conn.t {
  206. case streamTypeMsgAppV2:
  207. enc = newMsgAppV2Encoder(conn.Writer, cw.fs)
  208. case streamTypeMessage:
  209. enc = &messageEncoder{w: conn.Writer}
  210. default:
  211. plog.Panicf("unhandled stream type %s", conn.t)
  212. }
  213. flusher = conn.Flusher
  214. unflushed = 0
  215. cw.status.activate()
  216. cw.closer = conn.Closer
  217. cw.working = true
  218. cw.mu.Unlock()
  219. if closed {
  220. if cw.lg != nil {
  221. cw.lg.Warn(
  222. "closed TCP streaming connection with remote peer",
  223. zap.String("stream-writer-type", t.String()),
  224. zap.String("local-member-id", cw.localID.String()),
  225. zap.String("remote-peer-id", cw.peerID.String()),
  226. )
  227. } else {
  228. plog.Warningf("closed an existing TCP streaming connection with peer %s (%s writer)", cw.peerID, t)
  229. }
  230. }
  231. if cw.lg != nil {
  232. cw.lg.Warn(
  233. "established TCP streaming connection with remote peer",
  234. zap.String("stream-writer-type", t.String()),
  235. zap.String("local-member-id", cw.localID.String()),
  236. zap.String("remote-peer-id", cw.peerID.String()),
  237. )
  238. } else {
  239. plog.Infof("established a TCP streaming connection with peer %s (%s writer)", cw.peerID, t)
  240. }
  241. heartbeatc, msgc = tickc.C, cw.msgc
  242. case <-cw.stopc:
  243. if cw.close() {
  244. if cw.lg != nil {
  245. cw.lg.Warn(
  246. "closed TCP streaming connection with remote peer",
  247. zap.String("stream-writer-type", t.String()),
  248. zap.String("remote-peer-id", cw.peerID.String()),
  249. )
  250. } else {
  251. plog.Infof("closed the TCP streaming connection with peer %s (%s writer)", cw.peerID, t)
  252. }
  253. }
  254. if cw.lg != nil {
  255. cw.lg.Warn(
  256. "stopped TCP streaming connection with remote peer",
  257. zap.String("stream-writer-type", t.String()),
  258. zap.String("remote-peer-id", cw.peerID.String()),
  259. )
  260. } else {
  261. plog.Infof("stopped streaming with peer %s (writer)", cw.peerID)
  262. }
  263. close(cw.done)
  264. return
  265. }
  266. }
  267. }
  268. func (cw *streamWriter) writec() (chan<- raftpb.Message, bool) {
  269. cw.mu.Lock()
  270. defer cw.mu.Unlock()
  271. return cw.msgc, cw.working
  272. }
  273. func (cw *streamWriter) close() bool {
  274. cw.mu.Lock()
  275. defer cw.mu.Unlock()
  276. return cw.closeUnlocked()
  277. }
  278. func (cw *streamWriter) closeUnlocked() bool {
  279. if !cw.working {
  280. return false
  281. }
  282. if err := cw.closer.Close(); err != nil {
  283. if cw.lg != nil {
  284. cw.lg.Warn(
  285. "failed to close connection with remote peer",
  286. zap.String("remote-peer-id", cw.peerID.String()),
  287. zap.Error(err),
  288. )
  289. } else {
  290. plog.Errorf("peer %s (writer) connection close error: %v", cw.peerID, err)
  291. }
  292. }
  293. if len(cw.msgc) > 0 {
  294. cw.r.ReportUnreachable(uint64(cw.peerID))
  295. }
  296. cw.msgc = make(chan raftpb.Message, streamBufSize)
  297. cw.working = false
  298. return true
  299. }
  300. func (cw *streamWriter) attach(conn *outgoingConn) bool {
  301. select {
  302. case cw.connc <- conn:
  303. return true
  304. case <-cw.done:
  305. return false
  306. }
  307. }
  308. func (cw *streamWriter) stop() {
  309. close(cw.stopc)
  310. <-cw.done
  311. }
  312. // streamReader is a long-running go-routine that dials to the remote stream
  313. // endpoint and reads messages from the response body returned.
  314. type streamReader struct {
  315. lg *zap.Logger
  316. peerID types.ID
  317. typ streamType
  318. tr *Transport
  319. picker *urlPicker
  320. status *peerStatus
  321. recvc chan<- raftpb.Message
  322. propc chan<- raftpb.Message
  323. rl *rate.Limiter // alters the frequency of dial retrial attempts
  324. errorc chan<- error
  325. mu sync.Mutex
  326. paused bool
  327. closer io.Closer
  328. ctx context.Context
  329. cancel context.CancelFunc
  330. done chan struct{}
  331. }
  332. func (cr *streamReader) start() {
  333. cr.done = make(chan struct{})
  334. if cr.errorc == nil {
  335. cr.errorc = cr.tr.ErrorC
  336. }
  337. if cr.ctx == nil {
  338. cr.ctx, cr.cancel = context.WithCancel(context.Background())
  339. }
  340. go cr.run()
  341. }
  342. func (cr *streamReader) run() {
  343. t := cr.typ
  344. if cr.lg != nil {
  345. cr.lg.Info(
  346. "started stream reader with remote peer",
  347. zap.String("stream-reader-type", t.String()),
  348. zap.String("local-member-id", cr.tr.ID.String()),
  349. zap.String("remote-peer-id", cr.peerID.String()),
  350. )
  351. } else {
  352. plog.Infof("started streaming with peer %s (%s reader)", cr.peerID, t)
  353. }
  354. for {
  355. rc, err := cr.dial(t)
  356. if err != nil {
  357. if err != errUnsupportedStreamType {
  358. cr.status.deactivate(failureType{source: t.String(), action: "dial"}, err.Error())
  359. }
  360. } else {
  361. cr.status.activate()
  362. if cr.lg != nil {
  363. cr.lg.Info(
  364. "established TCP streaming connection with remote peer",
  365. zap.String("stream-reader-type", cr.typ.String()),
  366. zap.String("local-member-id", cr.tr.ID.String()),
  367. zap.String("remote-peer-id", cr.peerID.String()),
  368. )
  369. } else {
  370. plog.Infof("established a TCP streaming connection with peer %s (%s reader)", cr.peerID, cr.typ)
  371. }
  372. err = cr.decodeLoop(rc, t)
  373. if cr.lg != nil {
  374. cr.lg.Warn(
  375. "lost TCP streaming connection with remote peer",
  376. zap.String("stream-reader-type", cr.typ.String()),
  377. zap.String("local-member-id", cr.tr.ID.String()),
  378. zap.String("remote-peer-id", cr.peerID.String()),
  379. zap.Error(err),
  380. )
  381. } else {
  382. plog.Warningf("lost the TCP streaming connection with peer %s (%s reader)", cr.peerID, cr.typ)
  383. }
  384. switch {
  385. // all data is read out
  386. case err == io.EOF:
  387. // connection is closed by the remote
  388. case transport.IsClosedConnError(err):
  389. default:
  390. cr.status.deactivate(failureType{source: t.String(), action: "read"}, err.Error())
  391. }
  392. }
  393. // Wait for a while before new dial attempt
  394. err = cr.rl.Wait(cr.ctx)
  395. if cr.ctx.Err() != nil {
  396. if cr.lg != nil {
  397. cr.lg.Info(
  398. "stopped stream reader with remote peer",
  399. zap.String("stream-reader-type", t.String()),
  400. zap.String("local-member-id", cr.tr.ID.String()),
  401. zap.String("remote-peer-id", cr.peerID.String()),
  402. )
  403. } else {
  404. plog.Infof("stopped streaming with peer %s (%s reader)", cr.peerID, t)
  405. }
  406. close(cr.done)
  407. return
  408. }
  409. if err != nil {
  410. if cr.lg != nil {
  411. cr.lg.Warn(
  412. "rate limit on stream reader with remote peer",
  413. zap.String("stream-reader-type", t.String()),
  414. zap.String("local-member-id", cr.tr.ID.String()),
  415. zap.String("remote-peer-id", cr.peerID.String()),
  416. zap.Error(err),
  417. )
  418. } else {
  419. plog.Errorf("streaming with peer %s (%s reader) rate limiter error: %v", cr.peerID, t, err)
  420. }
  421. }
  422. }
  423. }
  424. func (cr *streamReader) decodeLoop(rc io.ReadCloser, t streamType) error {
  425. var dec decoder
  426. cr.mu.Lock()
  427. switch t {
  428. case streamTypeMsgAppV2:
  429. dec = newMsgAppV2Decoder(rc, cr.tr.ID, cr.peerID)
  430. case streamTypeMessage:
  431. dec = &messageDecoder{r: rc}
  432. default:
  433. if cr.lg != nil {
  434. cr.lg.Panic("unknown stream type", zap.String("type", t.String()))
  435. } else {
  436. plog.Panicf("unhandled stream type %s", t)
  437. }
  438. }
  439. select {
  440. case <-cr.ctx.Done():
  441. cr.mu.Unlock()
  442. if err := rc.Close(); err != nil {
  443. return err
  444. }
  445. return io.EOF
  446. default:
  447. cr.closer = rc
  448. }
  449. cr.mu.Unlock()
  450. for {
  451. m, err := dec.decode()
  452. if err != nil {
  453. cr.mu.Lock()
  454. cr.close()
  455. cr.mu.Unlock()
  456. return err
  457. }
  458. receivedBytes.WithLabelValues(types.ID(m.From).String()).Add(float64(m.Size()))
  459. cr.mu.Lock()
  460. paused := cr.paused
  461. cr.mu.Unlock()
  462. if paused {
  463. continue
  464. }
  465. if isLinkHeartbeatMessage(&m) {
  466. // raft is not interested in link layer
  467. // heartbeat message, so we should ignore
  468. // it.
  469. continue
  470. }
  471. recvc := cr.recvc
  472. if m.Type == raftpb.MsgProp {
  473. recvc = cr.propc
  474. }
  475. select {
  476. case recvc <- m:
  477. default:
  478. if cr.status.isActive() {
  479. if cr.lg != nil {
  480. cr.lg.Warn(
  481. "dropped internal Raft message since receiving buffer is full (overloaded network)",
  482. zap.String("message-type", m.Type.String()),
  483. zap.String("local-member-id", cr.tr.ID.String()),
  484. zap.String("from", types.ID(m.From).String()),
  485. zap.String("remote-peer-id", types.ID(m.To).String()),
  486. zap.Bool("remote-peer-active", cr.status.isActive()),
  487. )
  488. } else {
  489. plog.MergeWarningf("dropped internal raft message from %s since receiving buffer is full (overloaded network)", types.ID(m.From))
  490. }
  491. } else {
  492. if cr.lg != nil {
  493. cr.lg.Warn(
  494. "dropped Raft message since receiving buffer is full (overloaded network)",
  495. zap.String("message-type", m.Type.String()),
  496. zap.String("local-member-id", cr.tr.ID.String()),
  497. zap.String("from", types.ID(m.From).String()),
  498. zap.String("remote-peer-id", types.ID(m.To).String()),
  499. zap.Bool("remote-peer-active", cr.status.isActive()),
  500. )
  501. } else {
  502. plog.Debugf("dropped %s from %s since receiving buffer is full", m.Type, types.ID(m.From))
  503. }
  504. }
  505. recvFailures.WithLabelValues(types.ID(m.From).String()).Inc()
  506. }
  507. }
  508. }
  509. func (cr *streamReader) stop() {
  510. cr.mu.Lock()
  511. cr.cancel()
  512. cr.close()
  513. cr.mu.Unlock()
  514. <-cr.done
  515. }
  516. func (cr *streamReader) dial(t streamType) (io.ReadCloser, error) {
  517. u := cr.picker.pick()
  518. uu := u
  519. uu.Path = path.Join(t.endpoint(), cr.tr.ID.String())
  520. req, err := http.NewRequest("GET", uu.String(), nil)
  521. if err != nil {
  522. cr.picker.unreachable(u)
  523. return nil, fmt.Errorf("failed to make http request to %v (%v)", u, err)
  524. }
  525. req.Header.Set("X-Server-From", cr.tr.ID.String())
  526. req.Header.Set("X-Server-Version", version.Version)
  527. req.Header.Set("X-Min-Cluster-Version", version.MinClusterVersion)
  528. req.Header.Set("X-Etcd-Cluster-ID", cr.tr.ClusterID.String())
  529. req.Header.Set("X-Raft-To", cr.peerID.String())
  530. setPeerURLsHeader(req, cr.tr.URLs)
  531. req = req.WithContext(cr.ctx)
  532. cr.mu.Lock()
  533. select {
  534. case <-cr.ctx.Done():
  535. cr.mu.Unlock()
  536. return nil, fmt.Errorf("stream reader is stopped")
  537. default:
  538. }
  539. cr.mu.Unlock()
  540. resp, err := cr.tr.streamRt.RoundTrip(req)
  541. if err != nil {
  542. cr.picker.unreachable(u)
  543. return nil, err
  544. }
  545. rv := serverVersion(resp.Header)
  546. lv := semver.Must(semver.NewVersion(version.Version))
  547. if compareMajorMinorVersion(rv, lv) == -1 && !checkStreamSupport(rv, t) {
  548. httputil.GracefulClose(resp)
  549. cr.picker.unreachable(u)
  550. return nil, errUnsupportedStreamType
  551. }
  552. switch resp.StatusCode {
  553. case http.StatusGone:
  554. httputil.GracefulClose(resp)
  555. cr.picker.unreachable(u)
  556. reportCriticalError(errMemberRemoved, cr.errorc)
  557. return nil, errMemberRemoved
  558. case http.StatusOK:
  559. return resp.Body, nil
  560. case http.StatusNotFound:
  561. httputil.GracefulClose(resp)
  562. cr.picker.unreachable(u)
  563. return nil, fmt.Errorf("peer %s failed to find local node %s", cr.peerID, cr.tr.ID)
  564. case http.StatusPreconditionFailed:
  565. b, err := ioutil.ReadAll(resp.Body)
  566. if err != nil {
  567. cr.picker.unreachable(u)
  568. return nil, err
  569. }
  570. httputil.GracefulClose(resp)
  571. cr.picker.unreachable(u)
  572. switch strings.TrimSuffix(string(b), "\n") {
  573. case errIncompatibleVersion.Error():
  574. if cr.lg != nil {
  575. cr.lg.Warn(
  576. "request sent was ignored by remote peer due to server version incompatibility",
  577. zap.String("local-member-id", cr.tr.ID.String()),
  578. zap.String("remote-peer-id", cr.peerID.String()),
  579. zap.Error(errIncompatibleVersion),
  580. )
  581. } else {
  582. plog.Errorf("request sent was ignored by peer %s (server version incompatible)", cr.peerID)
  583. }
  584. return nil, errIncompatibleVersion
  585. case errClusterIDMismatch.Error():
  586. if cr.lg != nil {
  587. cr.lg.Warn(
  588. "request sent was ignored by remote peer due to cluster ID mismatch",
  589. zap.String("remote-peer-id", cr.peerID.String()),
  590. zap.String("remote-peer-cluster-id", resp.Header.Get("X-Etcd-Cluster-ID")),
  591. zap.String("local-member-id", cr.tr.ID.String()),
  592. zap.String("local-member-cluster-id", cr.tr.ClusterID.String()),
  593. zap.Error(errClusterIDMismatch),
  594. )
  595. } else {
  596. plog.Errorf("request sent was ignored (cluster ID mismatch: peer[%s]=%s, local=%s)",
  597. cr.peerID, resp.Header.Get("X-Etcd-Cluster-ID"), cr.tr.ClusterID)
  598. }
  599. return nil, errClusterIDMismatch
  600. default:
  601. return nil, fmt.Errorf("unhandled error %q when precondition failed", string(b))
  602. }
  603. default:
  604. httputil.GracefulClose(resp)
  605. cr.picker.unreachable(u)
  606. return nil, fmt.Errorf("unhandled http status %d", resp.StatusCode)
  607. }
  608. }
  609. func (cr *streamReader) close() {
  610. if cr.closer != nil {
  611. if err := cr.closer.Close(); err != nil {
  612. if cr.lg != nil {
  613. cr.lg.Warn(
  614. "failed to close remote peer connection",
  615. zap.String("local-member-id", cr.tr.ID.String()),
  616. zap.String("remote-peer-id", cr.peerID.String()),
  617. zap.Error(err),
  618. )
  619. } else {
  620. plog.Errorf("peer %s (reader) connection close error: %v", cr.peerID, err)
  621. }
  622. }
  623. }
  624. cr.closer = nil
  625. }
  626. func (cr *streamReader) pause() {
  627. cr.mu.Lock()
  628. defer cr.mu.Unlock()
  629. cr.paused = true
  630. }
  631. func (cr *streamReader) resume() {
  632. cr.mu.Lock()
  633. defer cr.mu.Unlock()
  634. cr.paused = false
  635. }
  636. // checkStreamSupport checks whether the stream type is supported in the
  637. // given version.
  638. func checkStreamSupport(v *semver.Version, t streamType) bool {
  639. nv := &semver.Version{Major: v.Major, Minor: v.Minor}
  640. for _, s := range supportedStream[nv.String()] {
  641. if s == t {
  642. return true
  643. }
  644. }
  645. return false
  646. }