stream.go 13 KB

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