http.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. // Copyright 2015 The etcd Authors
  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. "context"
  17. "errors"
  18. "fmt"
  19. "io/ioutil"
  20. "net/http"
  21. "path"
  22. "strings"
  23. "time"
  24. "go.etcd.io/etcd/etcdserver/api/snap"
  25. pioutil "go.etcd.io/etcd/pkg/ioutil"
  26. "go.etcd.io/etcd/pkg/types"
  27. "go.etcd.io/etcd/raft/raftpb"
  28. "go.etcd.io/etcd/version"
  29. humanize "github.com/dustin/go-humanize"
  30. "go.uber.org/zap"
  31. )
  32. const (
  33. // connReadLimitByte limits the number of bytes
  34. // a single read can read out.
  35. //
  36. // 64KB should be large enough for not causing
  37. // throughput bottleneck as well as small enough
  38. // for not causing a read timeout.
  39. connReadLimitByte = 64 * 1024
  40. )
  41. var (
  42. RaftPrefix = "/raft"
  43. ProbingPrefix = path.Join(RaftPrefix, "probing")
  44. RaftStreamPrefix = path.Join(RaftPrefix, "stream")
  45. RaftSnapshotPrefix = path.Join(RaftPrefix, "snapshot")
  46. errIncompatibleVersion = errors.New("incompatible version")
  47. errClusterIDMismatch = errors.New("cluster ID mismatch")
  48. )
  49. type peerGetter interface {
  50. Get(id types.ID) Peer
  51. }
  52. type writerToResponse interface {
  53. WriteTo(w http.ResponseWriter)
  54. }
  55. type pipelineHandler struct {
  56. lg *zap.Logger
  57. localID types.ID
  58. tr Transporter
  59. r Raft
  60. cid types.ID
  61. }
  62. // newPipelineHandler returns a handler for handling raft messages
  63. // from pipeline for RaftPrefix.
  64. //
  65. // The handler reads out the raft message from request body,
  66. // and forwards it to the given raft state machine for processing.
  67. func newPipelineHandler(t *Transport, r Raft, cid types.ID) http.Handler {
  68. return &pipelineHandler{
  69. lg: t.Logger,
  70. localID: t.ID,
  71. tr: t,
  72. r: r,
  73. cid: cid,
  74. }
  75. }
  76. func (h *pipelineHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  77. if r.Method != "POST" {
  78. w.Header().Set("Allow", "POST")
  79. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  80. return
  81. }
  82. w.Header().Set("X-Etcd-Cluster-ID", h.cid.String())
  83. if err := checkClusterCompatibilityFromHeader(h.lg, h.localID, r.Header, h.cid); err != nil {
  84. http.Error(w, err.Error(), http.StatusPreconditionFailed)
  85. return
  86. }
  87. addRemoteFromRequest(h.tr, r)
  88. // Limit the data size that could be read from the request body, which ensures that read from
  89. // connection will not time out accidentally due to possible blocking in underlying implementation.
  90. limitedr := pioutil.NewLimitedBufferReader(r.Body, connReadLimitByte)
  91. b, err := ioutil.ReadAll(limitedr)
  92. if err != nil {
  93. if h.lg != nil {
  94. h.lg.Warn(
  95. "failed to read Raft message",
  96. zap.String("local-member-id", h.localID.String()),
  97. zap.Error(err),
  98. )
  99. } else {
  100. plog.Errorf("failed to read raft message (%v)", err)
  101. }
  102. http.Error(w, "error reading raft message", http.StatusBadRequest)
  103. recvFailures.WithLabelValues(r.RemoteAddr).Inc()
  104. return
  105. }
  106. var m raftpb.Message
  107. if err := m.Unmarshal(b); err != nil {
  108. if h.lg != nil {
  109. h.lg.Warn(
  110. "failed to unmarshal Raft message",
  111. zap.String("local-member-id", h.localID.String()),
  112. zap.Error(err),
  113. )
  114. } else {
  115. plog.Errorf("failed to unmarshal raft message (%v)", err)
  116. }
  117. http.Error(w, "error unmarshalling raft message", http.StatusBadRequest)
  118. recvFailures.WithLabelValues(r.RemoteAddr).Inc()
  119. return
  120. }
  121. receivedBytes.WithLabelValues(types.ID(m.From).String()).Add(float64(len(b)))
  122. if err := h.r.Process(context.TODO(), m); err != nil {
  123. switch v := err.(type) {
  124. case writerToResponse:
  125. v.WriteTo(w)
  126. default:
  127. if h.lg != nil {
  128. h.lg.Warn(
  129. "failed to process Raft message",
  130. zap.String("local-member-id", h.localID.String()),
  131. zap.Error(err),
  132. )
  133. } else {
  134. plog.Warningf("failed to process raft message (%v)", err)
  135. }
  136. http.Error(w, "error processing raft message", http.StatusInternalServerError)
  137. w.(http.Flusher).Flush()
  138. // disconnect the http stream
  139. panic(err)
  140. }
  141. return
  142. }
  143. // Write StatusNoContent header after the message has been processed by
  144. // raft, which facilitates the client to report MsgSnap status.
  145. w.WriteHeader(http.StatusNoContent)
  146. }
  147. type snapshotHandler struct {
  148. lg *zap.Logger
  149. tr Transporter
  150. r Raft
  151. snapshotter *snap.Snapshotter
  152. localID types.ID
  153. cid types.ID
  154. }
  155. func newSnapshotHandler(t *Transport, r Raft, snapshotter *snap.Snapshotter, cid types.ID) http.Handler {
  156. return &snapshotHandler{
  157. lg: t.Logger,
  158. tr: t,
  159. r: r,
  160. snapshotter: snapshotter,
  161. localID: t.ID,
  162. cid: cid,
  163. }
  164. }
  165. const unknownSnapshotSender = "UNKNOWN_SNAPSHOT_SENDER"
  166. // ServeHTTP serves HTTP request to receive and process snapshot message.
  167. //
  168. // If request sender dies without closing underlying TCP connection,
  169. // the handler will keep waiting for the request body until TCP keepalive
  170. // finds out that the connection is broken after several minutes.
  171. // This is acceptable because
  172. // 1. snapshot messages sent through other TCP connections could still be
  173. // received and processed.
  174. // 2. this case should happen rarely, so no further optimization is done.
  175. func (h *snapshotHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  176. start := time.Now()
  177. if r.Method != "POST" {
  178. w.Header().Set("Allow", "POST")
  179. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  180. snapshotReceiveFailures.WithLabelValues(unknownSnapshotSender).Inc()
  181. return
  182. }
  183. w.Header().Set("X-Etcd-Cluster-ID", h.cid.String())
  184. if err := checkClusterCompatibilityFromHeader(h.lg, h.localID, r.Header, h.cid); err != nil {
  185. http.Error(w, err.Error(), http.StatusPreconditionFailed)
  186. snapshotReceiveFailures.WithLabelValues(unknownSnapshotSender).Inc()
  187. return
  188. }
  189. addRemoteFromRequest(h.tr, r)
  190. dec := &messageDecoder{r: r.Body}
  191. // let snapshots be very large since they can exceed 512MB for large installations
  192. m, err := dec.decodeLimit(uint64(1 << 63))
  193. from := types.ID(m.From).String()
  194. if err != nil {
  195. msg := fmt.Sprintf("failed to decode raft message (%v)", err)
  196. if h.lg != nil {
  197. h.lg.Warn(
  198. "failed to decode Raft message",
  199. zap.String("local-member-id", h.localID.String()),
  200. zap.String("remote-snapshot-sender-id", from),
  201. zap.Error(err),
  202. )
  203. } else {
  204. plog.Error(msg)
  205. }
  206. http.Error(w, msg, http.StatusBadRequest)
  207. recvFailures.WithLabelValues(r.RemoteAddr).Inc()
  208. snapshotReceiveFailures.WithLabelValues(from).Inc()
  209. return
  210. }
  211. msgSize := m.Size()
  212. receivedBytes.WithLabelValues(from).Add(float64(msgSize))
  213. if m.Type != raftpb.MsgSnap {
  214. if h.lg != nil {
  215. h.lg.Warn(
  216. "unexpected Raft message type",
  217. zap.String("local-member-id", h.localID.String()),
  218. zap.String("remote-snapshot-sender-id", from),
  219. zap.String("message-type", m.Type.String()),
  220. )
  221. } else {
  222. plog.Errorf("unexpected raft message type %s on snapshot path", m.Type)
  223. }
  224. http.Error(w, "wrong raft message type", http.StatusBadRequest)
  225. snapshotReceiveFailures.WithLabelValues(from).Inc()
  226. return
  227. }
  228. if h.lg != nil {
  229. h.lg.Info(
  230. "receiving database snapshot",
  231. zap.String("local-member-id", h.localID.String()),
  232. zap.String("remote-snapshot-sender-id", from),
  233. zap.Uint64("incoming-snapshot-index", m.Snapshot.Metadata.Index),
  234. zap.Int("incoming-snapshot-message-size-bytes", msgSize),
  235. zap.String("incoming-snapshot-message-size", humanize.Bytes(uint64(msgSize))),
  236. )
  237. } else {
  238. plog.Infof("receiving database snapshot [index:%d, from %s] ...", m.Snapshot.Metadata.Index, types.ID(m.From))
  239. }
  240. // save incoming database snapshot.
  241. n, err := h.snapshotter.SaveDBFrom(r.Body, m.Snapshot.Metadata.Index)
  242. if err != nil {
  243. msg := fmt.Sprintf("failed to save KV snapshot (%v)", err)
  244. if h.lg != nil {
  245. h.lg.Warn(
  246. "failed to save incoming database snapshot",
  247. zap.String("local-member-id", h.localID.String()),
  248. zap.String("remote-snapshot-sender-id", from),
  249. zap.Uint64("incoming-snapshot-index", m.Snapshot.Metadata.Index),
  250. zap.Error(err),
  251. )
  252. } else {
  253. plog.Error(msg)
  254. }
  255. http.Error(w, msg, http.StatusInternalServerError)
  256. snapshotReceiveFailures.WithLabelValues(from).Inc()
  257. return
  258. }
  259. receivedBytes.WithLabelValues(from).Add(float64(n))
  260. if h.lg != nil {
  261. h.lg.Info(
  262. "received and saved database snapshot",
  263. zap.String("local-member-id", h.localID.String()),
  264. zap.String("remote-snapshot-sender-id", from),
  265. zap.Uint64("incoming-snapshot-index", m.Snapshot.Metadata.Index),
  266. zap.Int64("incoming-snapshot-size-bytes", n),
  267. zap.String("incoming-snapshot-size", humanize.Bytes(uint64(n))),
  268. )
  269. } else {
  270. plog.Infof("received and saved database snapshot [index: %d, from: %s] successfully", m.Snapshot.Metadata.Index, types.ID(m.From))
  271. }
  272. if err := h.r.Process(context.TODO(), m); err != nil {
  273. switch v := err.(type) {
  274. // Process may return writerToResponse error when doing some
  275. // additional checks before calling raft.Node.Step.
  276. case writerToResponse:
  277. v.WriteTo(w)
  278. default:
  279. msg := fmt.Sprintf("failed to process raft message (%v)", err)
  280. if h.lg != nil {
  281. h.lg.Warn(
  282. "failed to process Raft message",
  283. zap.String("local-member-id", h.localID.String()),
  284. zap.String("remote-snapshot-sender-id", from),
  285. zap.Error(err),
  286. )
  287. } else {
  288. plog.Error(msg)
  289. }
  290. http.Error(w, msg, http.StatusInternalServerError)
  291. snapshotReceiveFailures.WithLabelValues(from).Inc()
  292. }
  293. return
  294. }
  295. // Write StatusNoContent header after the message has been processed by
  296. // raft, which facilitates the client to report MsgSnap status.
  297. w.WriteHeader(http.StatusNoContent)
  298. snapshotReceive.WithLabelValues(from).Inc()
  299. snapshotReceiveSeconds.WithLabelValues(from).Observe(time.Since(start).Seconds())
  300. }
  301. type streamHandler struct {
  302. lg *zap.Logger
  303. tr *Transport
  304. peerGetter peerGetter
  305. r Raft
  306. id types.ID
  307. cid types.ID
  308. }
  309. func newStreamHandler(t *Transport, pg peerGetter, r Raft, id, cid types.ID) http.Handler {
  310. return &streamHandler{
  311. lg: t.Logger,
  312. tr: t,
  313. peerGetter: pg,
  314. r: r,
  315. id: id,
  316. cid: cid,
  317. }
  318. }
  319. func (h *streamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  320. if r.Method != "GET" {
  321. w.Header().Set("Allow", "GET")
  322. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  323. return
  324. }
  325. w.Header().Set("X-Server-Version", version.Version)
  326. w.Header().Set("X-Etcd-Cluster-ID", h.cid.String())
  327. if err := checkClusterCompatibilityFromHeader(h.lg, h.tr.ID, r.Header, h.cid); err != nil {
  328. http.Error(w, err.Error(), http.StatusPreconditionFailed)
  329. return
  330. }
  331. var t streamType
  332. switch path.Dir(r.URL.Path) {
  333. case streamTypeMsgAppV2.endpoint():
  334. t = streamTypeMsgAppV2
  335. case streamTypeMessage.endpoint():
  336. t = streamTypeMessage
  337. default:
  338. if h.lg != nil {
  339. h.lg.Debug(
  340. "ignored unexpected streaming request path",
  341. zap.String("local-member-id", h.tr.ID.String()),
  342. zap.String("remote-peer-id-stream-handler", h.id.String()),
  343. zap.String("path", r.URL.Path),
  344. )
  345. } else {
  346. plog.Debugf("ignored unexpected streaming request path %s", r.URL.Path)
  347. }
  348. http.Error(w, "invalid path", http.StatusNotFound)
  349. return
  350. }
  351. fromStr := path.Base(r.URL.Path)
  352. from, err := types.IDFromString(fromStr)
  353. if err != nil {
  354. if h.lg != nil {
  355. h.lg.Warn(
  356. "failed to parse path into ID",
  357. zap.String("local-member-id", h.tr.ID.String()),
  358. zap.String("remote-peer-id-stream-handler", h.id.String()),
  359. zap.String("path", fromStr),
  360. zap.Error(err),
  361. )
  362. } else {
  363. plog.Errorf("failed to parse from %s into ID (%v)", fromStr, err)
  364. }
  365. http.Error(w, "invalid from", http.StatusNotFound)
  366. return
  367. }
  368. if h.r.IsIDRemoved(uint64(from)) {
  369. if h.lg != nil {
  370. h.lg.Warn(
  371. "rejected stream from remote peer because it was removed",
  372. zap.String("local-member-id", h.tr.ID.String()),
  373. zap.String("remote-peer-id-stream-handler", h.id.String()),
  374. zap.String("remote-peer-id-from", from.String()),
  375. )
  376. } else {
  377. plog.Warningf("rejected the stream from peer %s since it was removed", from)
  378. }
  379. http.Error(w, "removed member", http.StatusGone)
  380. return
  381. }
  382. p := h.peerGetter.Get(from)
  383. if p == nil {
  384. // This may happen in following cases:
  385. // 1. user starts a remote peer that belongs to a different cluster
  386. // with the same cluster ID.
  387. // 2. local etcd falls behind of the cluster, and cannot recognize
  388. // the members that joined after its current progress.
  389. if urls := r.Header.Get("X-PeerURLs"); urls != "" {
  390. h.tr.AddRemote(from, strings.Split(urls, ","))
  391. }
  392. if h.lg != nil {
  393. h.lg.Warn(
  394. "failed to find remote peer in cluster",
  395. zap.String("local-member-id", h.tr.ID.String()),
  396. zap.String("remote-peer-id-stream-handler", h.id.String()),
  397. zap.String("remote-peer-id-from", from.String()),
  398. zap.String("cluster-id", h.cid.String()),
  399. )
  400. } else {
  401. plog.Errorf("failed to find member %s in cluster %s", from, h.cid)
  402. }
  403. http.Error(w, "error sender not found", http.StatusNotFound)
  404. return
  405. }
  406. wto := h.id.String()
  407. if gto := r.Header.Get("X-Raft-To"); gto != wto {
  408. if h.lg != nil {
  409. h.lg.Warn(
  410. "ignored streaming request; ID mismatch",
  411. zap.String("local-member-id", h.tr.ID.String()),
  412. zap.String("remote-peer-id-stream-handler", h.id.String()),
  413. zap.String("remote-peer-id-header", gto),
  414. zap.String("remote-peer-id-from", from.String()),
  415. zap.String("cluster-id", h.cid.String()),
  416. )
  417. } else {
  418. plog.Errorf("streaming request ignored (ID mismatch got %s want %s)", gto, wto)
  419. }
  420. http.Error(w, "to field mismatch", http.StatusPreconditionFailed)
  421. return
  422. }
  423. w.WriteHeader(http.StatusOK)
  424. w.(http.Flusher).Flush()
  425. c := newCloseNotifier()
  426. conn := &outgoingConn{
  427. t: t,
  428. Writer: w,
  429. Flusher: w.(http.Flusher),
  430. Closer: c,
  431. localID: h.tr.ID,
  432. peerID: h.id,
  433. }
  434. p.attachOutgoingConn(conn)
  435. <-c.closeNotify()
  436. }
  437. // checkClusterCompatibilityFromHeader checks the cluster compatibility of
  438. // the local member from the given header.
  439. // It checks whether the version of local member is compatible with
  440. // the versions in the header, and whether the cluster ID of local member
  441. // matches the one in the header.
  442. func checkClusterCompatibilityFromHeader(lg *zap.Logger, localID types.ID, header http.Header, cid types.ID) error {
  443. remoteName := header.Get("X-Server-From")
  444. remoteServer := serverVersion(header)
  445. remoteVs := ""
  446. if remoteServer != nil {
  447. remoteVs = remoteServer.String()
  448. }
  449. remoteMinClusterVer := minClusterVersion(header)
  450. remoteMinClusterVs := ""
  451. if remoteMinClusterVer != nil {
  452. remoteMinClusterVs = remoteMinClusterVer.String()
  453. }
  454. localServer, localMinCluster, err := checkVersionCompatibility(remoteName, remoteServer, remoteMinClusterVer)
  455. localVs := ""
  456. if localServer != nil {
  457. localVs = localServer.String()
  458. }
  459. localMinClusterVs := ""
  460. if localMinCluster != nil {
  461. localMinClusterVs = localMinCluster.String()
  462. }
  463. if err != nil {
  464. if lg != nil {
  465. lg.Warn(
  466. "failed to check version compatibility",
  467. zap.String("local-member-id", localID.String()),
  468. zap.String("local-member-cluster-id", cid.String()),
  469. zap.String("local-member-server-version", localVs),
  470. zap.String("local-member-server-minimum-cluster-version", localMinClusterVs),
  471. zap.String("remote-peer-server-name", remoteName),
  472. zap.String("remote-peer-server-version", remoteVs),
  473. zap.String("remote-peer-server-minimum-cluster-version", remoteMinClusterVs),
  474. zap.Error(err),
  475. )
  476. } else {
  477. plog.Errorf("request version incompatibility (%v)", err)
  478. }
  479. return errIncompatibleVersion
  480. }
  481. if gcid := header.Get("X-Etcd-Cluster-ID"); gcid != cid.String() {
  482. if lg != nil {
  483. lg.Warn(
  484. "request cluster ID mismatch",
  485. zap.String("local-member-id", localID.String()),
  486. zap.String("local-member-cluster-id", cid.String()),
  487. zap.String("local-member-server-version", localVs),
  488. zap.String("local-member-server-minimum-cluster-version", localMinClusterVs),
  489. zap.String("remote-peer-server-name", remoteName),
  490. zap.String("remote-peer-server-version", remoteVs),
  491. zap.String("remote-peer-server-minimum-cluster-version", remoteMinClusterVs),
  492. zap.String("remote-peer-cluster-id", gcid),
  493. )
  494. } else {
  495. plog.Errorf("request cluster ID mismatch (got %s want %s)", gcid, cid)
  496. }
  497. return errClusterIDMismatch
  498. }
  499. return nil
  500. }
  501. type closeNotifier struct {
  502. done chan struct{}
  503. }
  504. func newCloseNotifier() *closeNotifier {
  505. return &closeNotifier{
  506. done: make(chan struct{}),
  507. }
  508. }
  509. func (n *closeNotifier) Close() error {
  510. close(n.done)
  511. return nil
  512. }
  513. func (n *closeNotifier) closeNotify() <-chan struct{} { return n.done }