stream.go 12 KB

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