stream.go 13 KB

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