http.go 10 KB

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