http.go 10 KB

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