stream.go 12 KB

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