http.go 11 KB

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