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