stream.go 11 KB

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