http.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. func NewHandler(r Raft, cid types.ID) http.Handler {
  34. return &handler{
  35. r: r,
  36. cid: cid,
  37. }
  38. }
  39. // NewStreamHandler returns a handler which initiates streamer when receiving
  40. // stream request from follower.
  41. func NewStreamHandler(tr *transport, id, cid types.ID) http.Handler {
  42. return &streamHandler{
  43. tr: tr,
  44. id: id,
  45. cid: cid,
  46. }
  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 := ioutils.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. fromStr := strings.TrimPrefix(r.URL.Path, RaftStreamPrefix+"/")
  105. from, err := types.IDFromString(fromStr)
  106. if err != nil {
  107. log.Printf("rafthttp: path %s cannot be parsed", fromStr)
  108. http.Error(w, "invalid path", http.StatusNotFound)
  109. return
  110. }
  111. p := h.tr.Peer(from)
  112. if p == nil {
  113. log.Printf("rafthttp: fail to find sender %s", from)
  114. http.Error(w, "error sender not found", http.StatusNotFound)
  115. return
  116. }
  117. wcid := h.cid.String()
  118. if gcid := r.Header.Get("X-Etcd-Cluster-ID"); gcid != wcid {
  119. log.Printf("rafthttp: streaming request ignored due to cluster ID mismatch got %s want %s", gcid, wcid)
  120. http.Error(w, "clusterID mismatch", http.StatusPreconditionFailed)
  121. return
  122. }
  123. wto := h.id.String()
  124. if gto := r.Header.Get("X-Raft-To"); gto != wto {
  125. log.Printf("rafthttp: streaming request ignored due to ID mismatch got %s want %s", gto, wto)
  126. http.Error(w, "to field mismatch", http.StatusPreconditionFailed)
  127. return
  128. }
  129. termStr := r.Header.Get("X-Raft-Term")
  130. term, err := strconv.ParseUint(termStr, 10, 64)
  131. if err != nil {
  132. log.Printf("rafthttp: streaming request ignored due to parse term %s error: %v", termStr, err)
  133. http.Error(w, "invalid term field", http.StatusBadRequest)
  134. return
  135. }
  136. sw := newStreamWriter(from, term)
  137. err = p.attachStream(sw)
  138. if err != nil {
  139. log.Printf("rafthttp: %v", err)
  140. http.Error(w, err.Error(), http.StatusBadRequest)
  141. return
  142. }
  143. w.WriteHeader(http.StatusOK)
  144. w.(http.Flusher).Flush()
  145. go sw.handle(w.(WriteFlusher))
  146. <-sw.stopNotify()
  147. }
  148. type writerToResponse interface {
  149. WriteTo(w http.ResponseWriter)
  150. }