http.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. "io/ioutil"
  17. "log"
  18. "net/http"
  19. "path"
  20. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  21. pioutil "github.com/coreos/etcd/pkg/ioutil"
  22. "github.com/coreos/etcd/pkg/types"
  23. "github.com/coreos/etcd/raft/raftpb"
  24. )
  25. const (
  26. ConnReadLimitByte = 64 * 1024
  27. )
  28. var (
  29. RaftPrefix = "/raft"
  30. RaftStreamPrefix = path.Join(RaftPrefix, "stream")
  31. )
  32. func NewHandler(r Raft, cid types.ID) http.Handler {
  33. return &handler{
  34. r: r,
  35. cid: cid,
  36. }
  37. }
  38. type peerGetter interface {
  39. Get(id types.ID) Peer
  40. }
  41. func newStreamHandler(peerGetter peerGetter, id, cid types.ID) http.Handler {
  42. return &streamHandler{
  43. peerGetter: peerGetter,
  44. id: id,
  45. cid: cid,
  46. }
  47. }
  48. type writerToResponse interface {
  49. WriteTo(w http.ResponseWriter)
  50. }
  51. type handler struct {
  52. r Raft
  53. cid types.ID
  54. }
  55. func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  56. if r.Method != "POST" {
  57. w.Header().Set("Allow", "POST")
  58. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  59. return
  60. }
  61. wcid := h.cid.String()
  62. w.Header().Set("X-Etcd-Cluster-ID", wcid)
  63. gcid := r.Header.Get("X-Etcd-Cluster-ID")
  64. if gcid != wcid {
  65. log.Printf("rafthttp: request ignored due to cluster ID mismatch got %s want %s", gcid, wcid)
  66. http.Error(w, "clusterID mismatch", http.StatusPreconditionFailed)
  67. return
  68. }
  69. // Limit the data size that could be read from the request body, which ensures that read from
  70. // connection will not time out accidentally due to possible block in underlying implementation.
  71. limitedr := pioutil.NewLimitedBufferReader(r.Body, ConnReadLimitByte)
  72. b, err := ioutil.ReadAll(limitedr)
  73. if err != nil {
  74. log.Println("rafthttp: error reading raft message:", err)
  75. http.Error(w, "error reading raft message", http.StatusBadRequest)
  76. return
  77. }
  78. var m raftpb.Message
  79. if err := m.Unmarshal(b); err != nil {
  80. log.Println("rafthttp: error unmarshaling raft message:", err)
  81. http.Error(w, "error unmarshaling raft message", http.StatusBadRequest)
  82. return
  83. }
  84. if err := h.r.Process(context.TODO(), m); err != nil {
  85. switch v := err.(type) {
  86. case writerToResponse:
  87. v.WriteTo(w)
  88. default:
  89. log.Printf("rafthttp: error processing raft message: %v", err)
  90. http.Error(w, "error processing raft message", http.StatusInternalServerError)
  91. }
  92. return
  93. }
  94. // Write StatusNoContet header after the message has been processed by
  95. // raft, which faciliates the client to report MsgSnap status.
  96. w.WriteHeader(http.StatusNoContent)
  97. }
  98. type streamHandler struct {
  99. peerGetter peerGetter
  100. id types.ID
  101. cid types.ID
  102. }
  103. func (h *streamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  104. if r.Method != "GET" {
  105. w.Header().Set("Allow", "GET")
  106. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  107. return
  108. }
  109. var t streamType
  110. switch path.Dir(r.URL.Path) {
  111. case path.Join(RaftStreamPrefix, string(streamTypeMsgApp)):
  112. t = streamTypeMsgApp
  113. case path.Join(RaftStreamPrefix, string(streamTypeMessage)):
  114. t = streamTypeMessage
  115. // backward compatibility
  116. case RaftStreamPrefix:
  117. t = streamTypeMsgApp
  118. default:
  119. log.Printf("rafthttp: ignored unexpected streaming request path %s", r.URL.Path)
  120. http.Error(w, "invalid path", http.StatusNotFound)
  121. return
  122. }
  123. fromStr := path.Base(r.URL.Path)
  124. from, err := types.IDFromString(fromStr)
  125. if err != nil {
  126. log.Printf("rafthttp: failed to parse from %s into ID", fromStr)
  127. http.Error(w, "invalid from", http.StatusNotFound)
  128. return
  129. }
  130. p := h.peerGetter.Get(from)
  131. if p == nil {
  132. log.Printf("rafthttp: fail to find sender %s", from)
  133. http.Error(w, "error sender not found", http.StatusNotFound)
  134. return
  135. }
  136. wcid := h.cid.String()
  137. if gcid := r.Header.Get("X-Etcd-Cluster-ID"); gcid != wcid {
  138. log.Printf("rafthttp: streaming request ignored due to cluster ID mismatch got %s want %s", gcid, wcid)
  139. http.Error(w, "clusterID mismatch", http.StatusPreconditionFailed)
  140. return
  141. }
  142. wto := h.id.String()
  143. if gto := r.Header.Get("X-Raft-To"); gto != wto {
  144. log.Printf("rafthttp: streaming request ignored due to ID mismatch got %s want %s", gto, wto)
  145. http.Error(w, "to field mismatch", http.StatusPreconditionFailed)
  146. return
  147. }
  148. w.WriteHeader(http.StatusOK)
  149. w.(http.Flusher).Flush()
  150. c := newCloseNotifier()
  151. conn := &outgoingConn{
  152. t: t,
  153. termStr: r.Header.Get("X-Raft-Term"),
  154. Writer: w,
  155. Flusher: w.(http.Flusher),
  156. Closer: c,
  157. }
  158. p.attachOutgoingConn(conn)
  159. <-c.closeNotify()
  160. }
  161. type closeNotifier struct {
  162. done chan struct{}
  163. }
  164. func newCloseNotifier() *closeNotifier {
  165. return &closeNotifier{
  166. done: make(chan struct{}),
  167. }
  168. }
  169. func (n *closeNotifier) Close() error {
  170. close(n.done)
  171. return nil
  172. }
  173. func (n *closeNotifier) closeNotify() <-chan struct{} { return n.done }