http.go 11 KB

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