stream.go 13 KB

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