stream.go 13 KB

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