stream.go 12 KB

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