stream.go 11 KB

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