http.go 5.0 KB

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