http.go 9.4 KB

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