stream.go 19 KB

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