http.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. plog.Infof("receiving database snapshot [index:%d, from %s] ...", m.Snapshot.Metadata.Index, types.ID(m.From))
  176. // save incoming database snapshot.
  177. n, err := h.snapshotter.SaveDBFrom(r.Body, m.Snapshot.Metadata.Index)
  178. if err != nil {
  179. msg := fmt.Sprintf("failed to save KV snapshot (%v)", err)
  180. plog.Error(msg)
  181. http.Error(w, msg, http.StatusInternalServerError)
  182. snapshotReceiveFailures.WithLabelValues(from).Inc()
  183. return
  184. }
  185. receivedBytes.WithLabelValues(from).Add(float64(n))
  186. plog.Infof("received and saved database snapshot [index: %d, from: %s] successfully", m.Snapshot.Metadata.Index, types.ID(m.From))
  187. if err := h.r.Process(context.TODO(), m); err != nil {
  188. switch v := err.(type) {
  189. // Process may return writerToResponse error when doing some
  190. // additional checks before calling raft.Node.Step.
  191. case writerToResponse:
  192. v.WriteTo(w)
  193. default:
  194. msg := fmt.Sprintf("failed to process raft message (%v)", err)
  195. plog.Warningf(msg)
  196. http.Error(w, msg, http.StatusInternalServerError)
  197. snapshotReceiveFailures.WithLabelValues(from).Inc()
  198. }
  199. return
  200. }
  201. // Write StatusNoContent header after the message has been processed by
  202. // raft, which facilitates the client to report MsgSnap status.
  203. w.WriteHeader(http.StatusNoContent)
  204. snapshotReceive.WithLabelValues(from).Inc()
  205. snapshotReceiveSeconds.WithLabelValues(from).Observe(time.Since(start).Seconds())
  206. }
  207. type streamHandler struct {
  208. tr *Transport
  209. peerGetter peerGetter
  210. r Raft
  211. id types.ID
  212. cid types.ID
  213. }
  214. func newStreamHandler(tr *Transport, pg peerGetter, r Raft, id, cid types.ID) http.Handler {
  215. return &streamHandler{
  216. tr: tr,
  217. peerGetter: pg,
  218. r: r,
  219. id: id,
  220. cid: cid,
  221. }
  222. }
  223. func (h *streamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  224. if r.Method != "GET" {
  225. w.Header().Set("Allow", "GET")
  226. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  227. return
  228. }
  229. w.Header().Set("X-Server-Version", version.Version)
  230. w.Header().Set("X-Etcd-Cluster-ID", h.cid.String())
  231. if err := checkClusterCompatibilityFromHeader(r.Header, h.cid); err != nil {
  232. http.Error(w, err.Error(), http.StatusPreconditionFailed)
  233. return
  234. }
  235. var t streamType
  236. switch path.Dir(r.URL.Path) {
  237. case streamTypeMsgAppV2.endpoint():
  238. t = streamTypeMsgAppV2
  239. case streamTypeMessage.endpoint():
  240. t = streamTypeMessage
  241. default:
  242. plog.Debugf("ignored unexpected streaming request path %s", r.URL.Path)
  243. http.Error(w, "invalid path", http.StatusNotFound)
  244. return
  245. }
  246. fromStr := path.Base(r.URL.Path)
  247. from, err := types.IDFromString(fromStr)
  248. if err != nil {
  249. plog.Errorf("failed to parse from %s into ID (%v)", fromStr, err)
  250. http.Error(w, "invalid from", http.StatusNotFound)
  251. return
  252. }
  253. if h.r.IsIDRemoved(uint64(from)) {
  254. plog.Warningf("rejected the stream from peer %s since it was removed", from)
  255. http.Error(w, "removed member", http.StatusGone)
  256. return
  257. }
  258. p := h.peerGetter.Get(from)
  259. if p == nil {
  260. // This may happen in following cases:
  261. // 1. user starts a remote peer that belongs to a different cluster
  262. // with the same cluster ID.
  263. // 2. local etcd falls behind of the cluster, and cannot recognize
  264. // the members that joined after its current progress.
  265. if urls := r.Header.Get("X-PeerURLs"); urls != "" {
  266. h.tr.AddRemote(from, strings.Split(urls, ","))
  267. }
  268. plog.Errorf("failed to find member %s in cluster %s", from, h.cid)
  269. http.Error(w, "error sender not found", http.StatusNotFound)
  270. return
  271. }
  272. wto := h.id.String()
  273. if gto := r.Header.Get("X-Raft-To"); gto != wto {
  274. plog.Errorf("streaming request ignored (ID mismatch got %s want %s)", gto, wto)
  275. http.Error(w, "to field mismatch", http.StatusPreconditionFailed)
  276. return
  277. }
  278. w.WriteHeader(http.StatusOK)
  279. w.(http.Flusher).Flush()
  280. c := newCloseNotifier()
  281. conn := &outgoingConn{
  282. t: t,
  283. Writer: w,
  284. Flusher: w.(http.Flusher),
  285. Closer: c,
  286. }
  287. p.attachOutgoingConn(conn)
  288. <-c.closeNotify()
  289. }
  290. // checkClusterCompatibilityFromHeader checks the cluster compatibility of
  291. // the local member from the given header.
  292. // It checks whether the version of local member is compatible with
  293. // the versions in the header, and whether the cluster ID of local member
  294. // matches the one in the header.
  295. func checkClusterCompatibilityFromHeader(header http.Header, cid types.ID) error {
  296. if err := checkVersionCompability(header.Get("X-Server-From"), serverVersion(header), minClusterVersion(header)); err != nil {
  297. plog.Errorf("request version incompatibility (%v)", err)
  298. return errIncompatibleVersion
  299. }
  300. if gcid := header.Get("X-Etcd-Cluster-ID"); gcid != cid.String() {
  301. plog.Errorf("request cluster ID mismatch (got %s want %s)", gcid, cid)
  302. return errClusterIDMismatch
  303. }
  304. return nil
  305. }
  306. type closeNotifier struct {
  307. done chan struct{}
  308. }
  309. func newCloseNotifier() *closeNotifier {
  310. return &closeNotifier{
  311. done: make(chan struct{}),
  312. }
  313. }
  314. func (n *closeNotifier) Close() error {
  315. close(n.done)
  316. return nil
  317. }
  318. func (n *closeNotifier) closeNotify() <-chan struct{} { return n.done }