stream.go 12 KB

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