stream.go 12 KB

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