http.go 10 KB

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