stream.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. tr *Transport
  204. picker *urlPicker
  205. t streamType
  206. local, remote types.ID
  207. cid types.ID
  208. status *peerStatus
  209. recvc chan<- raftpb.Message
  210. propc chan<- raftpb.Message
  211. errorc chan<- error
  212. mu sync.Mutex
  213. cancel func()
  214. closer io.Closer
  215. stopc chan struct{}
  216. done chan struct{}
  217. }
  218. 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 {
  219. r := &streamReader{
  220. tr: tr,
  221. picker: picker,
  222. t: t,
  223. local: local,
  224. remote: remote,
  225. cid: cid,
  226. status: status,
  227. recvc: recvc,
  228. propc: propc,
  229. errorc: errorc,
  230. stopc: make(chan struct{}),
  231. done: make(chan struct{}),
  232. }
  233. go r.run()
  234. return r
  235. }
  236. func (cr *streamReader) run() {
  237. for {
  238. t := cr.t
  239. rc, err := cr.dial(t)
  240. if err != nil {
  241. if err != errUnsupportedStreamType {
  242. cr.status.deactivate(failureType{source: t.String(), action: "dial"}, err.Error())
  243. }
  244. } else {
  245. cr.status.activate()
  246. err := cr.decodeLoop(rc, t)
  247. switch {
  248. // all data is read out
  249. case err == io.EOF:
  250. // connection is closed by the remote
  251. case isClosedConnectionError(err):
  252. default:
  253. cr.status.deactivate(failureType{source: t.String(), action: "read"}, err.Error())
  254. }
  255. }
  256. select {
  257. // Wait 100ms to create a new stream, so it doesn't bring too much
  258. // overhead when retry.
  259. case <-time.After(100 * time.Millisecond):
  260. case <-cr.stopc:
  261. close(cr.done)
  262. return
  263. }
  264. }
  265. }
  266. func (cr *streamReader) decodeLoop(rc io.ReadCloser, t streamType) error {
  267. var dec decoder
  268. cr.mu.Lock()
  269. switch t {
  270. case streamTypeMsgAppV2:
  271. dec = newMsgAppV2Decoder(rc, cr.local, cr.remote)
  272. case streamTypeMessage:
  273. dec = &messageDecoder{r: rc}
  274. default:
  275. plog.Panicf("unhandled stream type %s", t)
  276. }
  277. cr.closer = rc
  278. cr.mu.Unlock()
  279. for {
  280. m, err := dec.decode()
  281. if err != nil {
  282. cr.mu.Lock()
  283. cr.close()
  284. cr.mu.Unlock()
  285. return err
  286. }
  287. if isLinkHeartbeatMessage(m) {
  288. // raft is not interested in link layer
  289. // heartbeat message, so we should ignore
  290. // it.
  291. continue
  292. }
  293. recvc := cr.recvc
  294. if m.Type == raftpb.MsgProp {
  295. recvc = cr.propc
  296. }
  297. select {
  298. case recvc <- m:
  299. default:
  300. if cr.status.isActive() {
  301. plog.MergeWarningf("dropped internal raft message from %s since receiving buffer is full (overloaded network)", types.ID(m.From))
  302. }
  303. plog.Debugf("dropped %s from %s since receiving buffer is full", m.Type, types.ID(m.From))
  304. }
  305. }
  306. }
  307. func (cr *streamReader) stop() {
  308. close(cr.stopc)
  309. cr.mu.Lock()
  310. if cr.cancel != nil {
  311. cr.cancel()
  312. }
  313. cr.close()
  314. cr.mu.Unlock()
  315. <-cr.done
  316. }
  317. func (cr *streamReader) isWorking() bool {
  318. cr.mu.Lock()
  319. defer cr.mu.Unlock()
  320. return cr.closer != nil
  321. }
  322. func (cr *streamReader) dial(t streamType) (io.ReadCloser, error) {
  323. u := cr.picker.pick()
  324. uu := u
  325. uu.Path = path.Join(t.endpoint(), cr.local.String())
  326. req, err := http.NewRequest("GET", uu.String(), nil)
  327. if err != nil {
  328. cr.picker.unreachable(u)
  329. return nil, fmt.Errorf("failed to make http request to %s (%v)", u, err)
  330. }
  331. req.Header.Set("X-Server-From", cr.local.String())
  332. req.Header.Set("X-Server-Version", version.Version)
  333. req.Header.Set("X-Min-Cluster-Version", version.MinClusterVersion)
  334. req.Header.Set("X-Etcd-Cluster-ID", cr.cid.String())
  335. req.Header.Set("X-Raft-To", cr.remote.String())
  336. setPeerURLsHeader(req, cr.tr.URLs)
  337. cr.mu.Lock()
  338. select {
  339. case <-cr.stopc:
  340. cr.mu.Unlock()
  341. return nil, fmt.Errorf("stream reader is stopped")
  342. default:
  343. }
  344. cr.cancel = httputil.RequestCanceler(cr.tr.streamRt, req)
  345. cr.mu.Unlock()
  346. resp, err := cr.tr.streamRt.RoundTrip(req)
  347. if err != nil {
  348. cr.picker.unreachable(u)
  349. return nil, err
  350. }
  351. rv := serverVersion(resp.Header)
  352. lv := semver.Must(semver.NewVersion(version.Version))
  353. if compareMajorMinorVersion(rv, lv) == -1 && !checkStreamSupport(rv, t) {
  354. resp.Body.Close()
  355. cr.picker.unreachable(u)
  356. return nil, errUnsupportedStreamType
  357. }
  358. switch resp.StatusCode {
  359. case http.StatusGone:
  360. resp.Body.Close()
  361. cr.picker.unreachable(u)
  362. err := fmt.Errorf("the member has been permanently removed from the cluster")
  363. select {
  364. case cr.errorc <- err:
  365. default:
  366. }
  367. return nil, err
  368. case http.StatusOK:
  369. return resp.Body, nil
  370. case http.StatusNotFound:
  371. resp.Body.Close()
  372. cr.picker.unreachable(u)
  373. return nil, fmt.Errorf("remote member %s could not recognize local member", cr.remote)
  374. case http.StatusPreconditionFailed:
  375. b, err := ioutil.ReadAll(resp.Body)
  376. if err != nil {
  377. cr.picker.unreachable(u)
  378. return nil, err
  379. }
  380. resp.Body.Close()
  381. cr.picker.unreachable(u)
  382. switch strings.TrimSuffix(string(b), "\n") {
  383. case errIncompatibleVersion.Error():
  384. plog.Errorf("request sent was ignored by peer %s (server version incompatible)", cr.remote)
  385. return nil, errIncompatibleVersion
  386. case errClusterIDMismatch.Error():
  387. plog.Errorf("request sent was ignored (cluster ID mismatch: remote[%s]=%s, local=%s)",
  388. cr.remote, resp.Header.Get("X-Etcd-Cluster-ID"), cr.cid)
  389. return nil, errClusterIDMismatch
  390. default:
  391. return nil, fmt.Errorf("unhandled error %q when precondition failed", string(b))
  392. }
  393. default:
  394. resp.Body.Close()
  395. cr.picker.unreachable(u)
  396. return nil, fmt.Errorf("unhandled http status %d", resp.StatusCode)
  397. }
  398. }
  399. func (cr *streamReader) close() {
  400. if cr.closer != nil {
  401. cr.closer.Close()
  402. }
  403. cr.closer = nil
  404. }
  405. func isClosedConnectionError(err error) bool {
  406. operr, ok := err.(*net.OpError)
  407. return ok && operr.Err.Error() == "use of closed network connection"
  408. }
  409. // checkStreamSupport checks whether the stream type is supported in the
  410. // given version.
  411. func checkStreamSupport(v *semver.Version, t streamType) bool {
  412. nv := &semver.Version{Major: v.Major, Minor: v.Minor}
  413. for _, s := range supportedStream[nv.String()] {
  414. if s == t {
  415. return true
  416. }
  417. }
  418. return false
  419. }
  420. func isNetworkTimeoutError(err error) bool {
  421. nerr, ok := err.(net.Error)
  422. return ok && nerr.Timeout()
  423. }