http.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package rafthttp
  14. import (
  15. "io/ioutil"
  16. "log"
  17. "net/http"
  18. "path"
  19. "strconv"
  20. "strings"
  21. "github.com/coreos/etcd/pkg/ioutils"
  22. "github.com/coreos/etcd/pkg/types"
  23. "github.com/coreos/etcd/raft/raftpb"
  24. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  25. )
  26. const (
  27. ConnReadLimitByte = 64 * 1024
  28. )
  29. var (
  30. RaftPrefix = "/raft"
  31. RaftStreamPrefix = path.Join(RaftPrefix, "stream")
  32. )
  33. type SenderFinder interface {
  34. // Sender returns the sender of the given id.
  35. Sender(id types.ID) Sender
  36. }
  37. func NewHandler(p Processor, cid types.ID) http.Handler {
  38. return &handler{
  39. p: p,
  40. cid: cid,
  41. }
  42. }
  43. // NewStreamHandler returns a handler which initiates streamer when receiving
  44. // stream request from follower.
  45. func NewStreamHandler(finder SenderFinder, id, cid types.ID) http.Handler {
  46. return &streamHandler{
  47. finder: finder,
  48. id: id,
  49. cid: cid,
  50. }
  51. }
  52. type handler struct {
  53. p Processor
  54. cid types.ID
  55. }
  56. func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  57. if r.Method != "POST" {
  58. w.Header().Set("Allow", "POST")
  59. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  60. return
  61. }
  62. wcid := h.cid.String()
  63. w.Header().Set("X-Etcd-Cluster-ID", wcid)
  64. gcid := r.Header.Get("X-Etcd-Cluster-ID")
  65. if gcid != wcid {
  66. log.Printf("rafthttp: request ignored due to cluster ID mismatch got %s want %s", gcid, wcid)
  67. http.Error(w, "clusterID mismatch", http.StatusPreconditionFailed)
  68. return
  69. }
  70. // Limit the data size that could be read from the request body, which ensures that read from
  71. // connection will not time out accidentally due to possible block in underlying implementation.
  72. limitedr := ioutils.NewLimitedBufferReader(r.Body, ConnReadLimitByte)
  73. b, err := ioutil.ReadAll(limitedr)
  74. if err != nil {
  75. log.Println("rafthttp: error reading raft message:", err)
  76. http.Error(w, "error reading raft message", http.StatusBadRequest)
  77. return
  78. }
  79. var m raftpb.Message
  80. if err := m.Unmarshal(b); err != nil {
  81. log.Println("rafthttp: error unmarshaling raft message:", err)
  82. http.Error(w, "error unmarshaling raft message", http.StatusBadRequest)
  83. return
  84. }
  85. if err := h.p.Process(context.TODO(), m); err != nil {
  86. switch v := err.(type) {
  87. case writerToResponse:
  88. v.WriteTo(w)
  89. default:
  90. log.Printf("rafthttp: error processing raft message: %v", err)
  91. http.Error(w, "error processing raft message", http.StatusInternalServerError)
  92. }
  93. return
  94. }
  95. w.WriteHeader(http.StatusNoContent)
  96. }
  97. type streamHandler struct {
  98. finder SenderFinder
  99. id types.ID
  100. cid types.ID
  101. }
  102. func (h *streamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  103. if r.Method != "GET" {
  104. w.Header().Set("Allow", "GET")
  105. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  106. return
  107. }
  108. fromStr := strings.TrimPrefix(r.URL.Path, RaftStreamPrefix+"/")
  109. from, err := types.IDFromString(fromStr)
  110. if err != nil {
  111. log.Printf("rafthttp: path %s cannot be parsed", fromStr)
  112. http.Error(w, "invalid path", http.StatusNotFound)
  113. return
  114. }
  115. s := h.finder.Sender(from)
  116. if s == nil {
  117. log.Printf("rafthttp: fail to find sender %s", from)
  118. http.Error(w, "error sender not found", http.StatusNotFound)
  119. return
  120. }
  121. wcid := h.cid.String()
  122. if gcid := r.Header.Get("X-Etcd-Cluster-ID"); gcid != wcid {
  123. log.Printf("rafthttp: streaming request ignored due to cluster ID mismatch got %s want %s", gcid, wcid)
  124. http.Error(w, "clusterID mismatch", http.StatusPreconditionFailed)
  125. return
  126. }
  127. wto := h.id.String()
  128. if gto := r.Header.Get("X-Raft-To"); gto != wto {
  129. log.Printf("rafthttp: streaming request ignored due to ID mismatch got %s want %s", gto, wto)
  130. http.Error(w, "to field mismatch", http.StatusPreconditionFailed)
  131. return
  132. }
  133. termStr := r.Header.Get("X-Raft-Term")
  134. term, err := strconv.ParseUint(termStr, 10, 64)
  135. if err != nil {
  136. log.Printf("rafthttp: streaming request ignored due to parse term %s error: %v", termStr, err)
  137. http.Error(w, "invalid term field", http.StatusBadRequest)
  138. return
  139. }
  140. w.WriteHeader(http.StatusOK)
  141. w.(http.Flusher).Flush()
  142. done, err := s.StartStreaming(w.(WriteFlusher), from, term)
  143. if err != nil {
  144. log.Printf("rafthttp: streaming request ignored due to start streaming error: %v", err)
  145. // TODO: consider http status and info here
  146. http.Error(w, "error enable streaming", http.StatusInternalServerError)
  147. return
  148. }
  149. <-done
  150. }
  151. type writerToResponse interface {
  152. WriteTo(w http.ResponseWriter)
  153. }