http.go 9.8 KB

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