stream.go 13 KB

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