http.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. pioutil "github.com/coreos/etcd/pkg/ioutil"
  25. "github.com/coreos/etcd/pkg/types"
  26. "github.com/coreos/etcd/raft/raftpb"
  27. "github.com/coreos/etcd/snap"
  28. "github.com/coreos/etcd/version"
  29. )
  30. const (
  31. // connReadLimitByte limits the number of bytes
  32. // a single read can read out.
  33. //
  34. // 64KB should be large enough for not causing
  35. // throughput bottleneck as well as small enough
  36. // for not causing a read timeout.
  37. connReadLimitByte = 64 * 1024
  38. )
  39. var (
  40. RaftPrefix = "/raft"
  41. ProbingPrefix = path.Join(RaftPrefix, "probing")
  42. RaftStreamPrefix = path.Join(RaftPrefix, "stream")
  43. RaftSnapshotPrefix = path.Join(RaftPrefix, "snapshot")
  44. errIncompatibleVersion = errors.New("incompatible version")
  45. errClusterIDMismatch = errors.New("cluster ID mismatch")
  46. )
  47. type peerGetter interface {
  48. Get(id types.ID) Peer
  49. }
  50. type writerToResponse interface {
  51. WriteTo(w http.ResponseWriter)
  52. }
  53. type pipelineHandler struct {
  54. tr Transporter
  55. r Raft
  56. cid types.ID
  57. }
  58. // newPipelineHandler returns a handler for handling raft messages
  59. // from pipeline for RaftPrefix.
  60. //
  61. // The handler reads out the raft message from request body,
  62. // and forwards it to the given raft state machine for processing.
  63. func newPipelineHandler(tr Transporter, r Raft, cid types.ID) http.Handler {
  64. return &pipelineHandler{
  65. tr: tr,
  66. r: r,
  67. cid: cid,
  68. }
  69. }
  70. func (h *pipelineHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  71. if r.Method != "POST" {
  72. w.Header().Set("Allow", "POST")
  73. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  74. return
  75. }
  76. w.Header().Set("X-Etcd-Cluster-ID", h.cid.String())
  77. if err := checkClusterCompatibilityFromHeader(r.Header, h.cid); err != nil {
  78. http.Error(w, err.Error(), http.StatusPreconditionFailed)
  79. return
  80. }
  81. addRemoteFromRequest(h.tr, r)
  82. // Limit the data size that could be read from the request body, which ensures that read from
  83. // connection will not time out accidentally due to possible blocking in underlying implementation.
  84. limitedr := pioutil.NewLimitedBufferReader(r.Body, connReadLimitByte)
  85. b, err := ioutil.ReadAll(limitedr)
  86. if err != nil {
  87. plog.Errorf("failed to read raft message (%v)", err)
  88. http.Error(w, "error reading raft message", http.StatusBadRequest)
  89. recvFailures.WithLabelValues(r.RemoteAddr).Inc()
  90. return
  91. }
  92. var m raftpb.Message
  93. if err := m.Unmarshal(b); err != nil {
  94. plog.Errorf("failed to unmarshal raft message (%v)", err)
  95. http.Error(w, "error unmarshaling raft message", http.StatusBadRequest)
  96. recvFailures.WithLabelValues(r.RemoteAddr).Inc()
  97. return
  98. }
  99. receivedBytes.WithLabelValues(types.ID(m.From).String()).Add(float64(len(b)))
  100. if err := h.r.Process(context.TODO(), m); err != nil {
  101. switch v := err.(type) {
  102. case writerToResponse:
  103. v.WriteTo(w)
  104. default:
  105. plog.Warningf("failed to process raft message (%v)", err)
  106. http.Error(w, "error processing raft message", http.StatusInternalServerError)
  107. w.(http.Flusher).Flush()
  108. // disconnect the http stream
  109. panic(err)
  110. }
  111. return
  112. }
  113. // Write StatusNoContent header after the message has been processed by
  114. // raft, which facilitates the client to report MsgSnap status.
  115. w.WriteHeader(http.StatusNoContent)
  116. }
  117. type snapshotHandler struct {
  118. tr Transporter
  119. r Raft
  120. snapshotter *snap.Snapshotter
  121. cid types.ID
  122. }
  123. func newSnapshotHandler(tr Transporter, r Raft, snapshotter *snap.Snapshotter, cid types.ID) http.Handler {
  124. return &snapshotHandler{
  125. tr: tr,
  126. r: r,
  127. snapshotter: snapshotter,
  128. cid: cid,
  129. }
  130. }
  131. const unknownSnapshotSender = "UNKNOWN_SNAPSHOT_SENDER"
  132. // ServeHTTP serves HTTP request to receive and process snapshot message.
  133. //
  134. // If request sender dies without closing underlying TCP connection,
  135. // the handler will keep waiting for the request body until TCP keepalive
  136. // finds out that the connection is broken after several minutes.
  137. // This is acceptable because
  138. // 1. snapshot messages sent through other TCP connections could still be
  139. // received and processed.
  140. // 2. this case should happen rarely, so no further optimization is done.
  141. func (h *snapshotHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  142. start := time.Now()
  143. if r.Method != "POST" {
  144. w.Header().Set("Allow", "POST")
  145. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  146. snapshotReceiveFailures.WithLabelValues(unknownSnapshotSender).Inc()
  147. return
  148. }
  149. w.Header().Set("X-Etcd-Cluster-ID", h.cid.String())
  150. if err := checkClusterCompatibilityFromHeader(r.Header, h.cid); err != nil {
  151. http.Error(w, err.Error(), http.StatusPreconditionFailed)
  152. snapshotReceiveFailures.WithLabelValues(unknownSnapshotSender).Inc()
  153. return
  154. }
  155. addRemoteFromRequest(h.tr, r)
  156. dec := &messageDecoder{r: r.Body}
  157. // let snapshots be very large since they can exceed 512MB for large installations
  158. m, err := dec.decodeLimit(uint64(1 << 63))
  159. from := types.ID(m.From).String()
  160. if err != nil {
  161. msg := fmt.Sprintf("failed to decode raft message (%v)", err)
  162. plog.Errorf(msg)
  163. http.Error(w, msg, http.StatusBadRequest)
  164. recvFailures.WithLabelValues(r.RemoteAddr).Inc()
  165. snapshotReceiveFailures.WithLabelValues(from).Inc()
  166. return
  167. }
  168. receivedBytes.WithLabelValues(from).Add(float64(m.Size()))
  169. if m.Type != raftpb.MsgSnap {
  170. plog.Errorf("unexpected raft message type %s on snapshot path", m.Type)
  171. http.Error(w, "wrong raft message type", http.StatusBadRequest)
  172. snapshotReceiveFailures.WithLabelValues(from).Inc()
  173. return
  174. }
  175. snapshotReceiveInflights.WithLabelValues(from).Inc()
  176. defer func() {
  177. snapshotReceiveInflights.WithLabelValues(from).Dec()
  178. }()
  179. plog.Infof("receiving database snapshot [index:%d, from %s] ...", m.Snapshot.Metadata.Index, types.ID(m.From))
  180. // save incoming database snapshot.
  181. n, err := h.snapshotter.SaveDBFrom(r.Body, m.Snapshot.Metadata.Index)
  182. if err != nil {
  183. msg := fmt.Sprintf("failed to save KV snapshot (%v)", err)
  184. plog.Error(msg)
  185. http.Error(w, msg, http.StatusInternalServerError)
  186. snapshotReceiveFailures.WithLabelValues(from).Inc()
  187. return
  188. }
  189. receivedBytes.WithLabelValues(from).Add(float64(n))
  190. plog.Infof("received and saved database snapshot [index: %d, from: %s] successfully", m.Snapshot.Metadata.Index, types.ID(m.From))
  191. if err := h.r.Process(context.TODO(), m); err != nil {
  192. switch v := err.(type) {
  193. // Process may return writerToResponse error when doing some
  194. // additional checks before calling raft.Node.Step.
  195. case writerToResponse:
  196. v.WriteTo(w)
  197. default:
  198. msg := fmt.Sprintf("failed to process raft message (%v)", err)
  199. plog.Warningf(msg)
  200. http.Error(w, msg, http.StatusInternalServerError)
  201. snapshotReceiveFailures.WithLabelValues(from).Inc()
  202. }
  203. return
  204. }
  205. // Write StatusNoContent header after the message has been processed by
  206. // raft, which facilitates the client to report MsgSnap status.
  207. w.WriteHeader(http.StatusNoContent)
  208. snapshotReceive.WithLabelValues(from).Inc()
  209. snapshotReceiveSeconds.WithLabelValues(from).Observe(time.Since(start).Seconds())
  210. }
  211. type streamHandler struct {
  212. tr *Transport
  213. peerGetter peerGetter
  214. r Raft
  215. id types.ID
  216. cid types.ID
  217. }
  218. func newStreamHandler(tr *Transport, pg peerGetter, r Raft, id, cid types.ID) http.Handler {
  219. return &streamHandler{
  220. tr: tr,
  221. peerGetter: pg,
  222. r: r,
  223. id: id,
  224. cid: cid,
  225. }
  226. }
  227. func (h *streamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  228. if r.Method != "GET" {
  229. w.Header().Set("Allow", "GET")
  230. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  231. return
  232. }
  233. w.Header().Set("X-Server-Version", version.Version)
  234. w.Header().Set("X-Etcd-Cluster-ID", h.cid.String())
  235. if err := checkClusterCompatibilityFromHeader(r.Header, h.cid); err != nil {
  236. http.Error(w, err.Error(), http.StatusPreconditionFailed)
  237. return
  238. }
  239. var t streamType
  240. switch path.Dir(r.URL.Path) {
  241. case streamTypeMsgAppV2.endpoint():
  242. t = streamTypeMsgAppV2
  243. case streamTypeMessage.endpoint():
  244. t = streamTypeMessage
  245. default:
  246. plog.Debugf("ignored unexpected streaming request path %s", r.URL.Path)
  247. http.Error(w, "invalid path", http.StatusNotFound)
  248. return
  249. }
  250. fromStr := path.Base(r.URL.Path)
  251. from, err := types.IDFromString(fromStr)
  252. if err != nil {
  253. plog.Errorf("failed to parse from %s into ID (%v)", fromStr, err)
  254. http.Error(w, "invalid from", http.StatusNotFound)
  255. return
  256. }
  257. if h.r.IsIDRemoved(uint64(from)) {
  258. plog.Warningf("rejected the stream from peer %s since it was removed", from)
  259. http.Error(w, "removed member", http.StatusGone)
  260. return
  261. }
  262. p := h.peerGetter.Get(from)
  263. if p == nil {
  264. // This may happen in following cases:
  265. // 1. user starts a remote peer that belongs to a different cluster
  266. // with the same cluster ID.
  267. // 2. local etcd falls behind of the cluster, and cannot recognize
  268. // the members that joined after its current progress.
  269. if urls := r.Header.Get("X-PeerURLs"); urls != "" {
  270. h.tr.AddRemote(from, strings.Split(urls, ","))
  271. }
  272. plog.Errorf("failed to find member %s in cluster %s", from, h.cid)
  273. http.Error(w, "error sender not found", http.StatusNotFound)
  274. return
  275. }
  276. wto := h.id.String()
  277. if gto := r.Header.Get("X-Raft-To"); gto != wto {
  278. plog.Errorf("streaming request ignored (ID mismatch got %s want %s)", gto, wto)
  279. http.Error(w, "to field mismatch", http.StatusPreconditionFailed)
  280. return
  281. }
  282. w.WriteHeader(http.StatusOK)
  283. w.(http.Flusher).Flush()
  284. c := newCloseNotifier()
  285. conn := &outgoingConn{
  286. t: t,
  287. Writer: w,
  288. Flusher: w.(http.Flusher),
  289. Closer: c,
  290. }
  291. p.attachOutgoingConn(conn)
  292. <-c.closeNotify()
  293. }
  294. // checkClusterCompatibilityFromHeader checks the cluster compatibility of
  295. // the local member from the given header.
  296. // It checks whether the version of local member is compatible with
  297. // the versions in the header, and whether the cluster ID of local member
  298. // matches the one in the header.
  299. func checkClusterCompatibilityFromHeader(header http.Header, cid types.ID) error {
  300. if err := checkVersionCompability(header.Get("X-Server-From"), serverVersion(header), minClusterVersion(header)); err != nil {
  301. plog.Errorf("request version incompatibility (%v)", err)
  302. return errIncompatibleVersion
  303. }
  304. if gcid := header.Get("X-Etcd-Cluster-ID"); gcid != cid.String() {
  305. plog.Errorf("request cluster ID mismatch (got %s want %s)", gcid, cid)
  306. return errClusterIDMismatch
  307. }
  308. return nil
  309. }
  310. type closeNotifier struct {
  311. done chan struct{}
  312. }
  313. func newCloseNotifier() *closeNotifier {
  314. return &closeNotifier{
  315. done: make(chan struct{}),
  316. }
  317. }
  318. func (n *closeNotifier) Close() error {
  319. close(n.done)
  320. return nil
  321. }
  322. func (n *closeNotifier) closeNotify() <-chan struct{} { return n.done }