stream.go 13 KB

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