stream.go 12 KB

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