stream.go 19 KB

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