http.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. "strconv"
  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. )
  27. const (
  28. ConnReadLimitByte = 64 * 1024
  29. )
  30. var (
  31. RaftPrefix = "/raft"
  32. RaftStreamPrefix = path.Join(RaftPrefix, "stream")
  33. )
  34. func NewHandler(r Raft, cid types.ID) http.Handler {
  35. return &handler{
  36. r: r,
  37. cid: cid,
  38. }
  39. }
  40. // NewStreamHandler returns a handler which initiates streamer when receiving
  41. // stream request from follower.
  42. func NewStreamHandler(tr *transport, id, cid types.ID) http.Handler {
  43. return &streamHandler{
  44. tr: tr,
  45. id: id,
  46. cid: cid,
  47. }
  48. }
  49. type handler struct {
  50. r Raft
  51. cid types.ID
  52. }
  53. func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  54. if r.Method != "POST" {
  55. w.Header().Set("Allow", "POST")
  56. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  57. return
  58. }
  59. wcid := h.cid.String()
  60. w.Header().Set("X-Etcd-Cluster-ID", wcid)
  61. gcid := r.Header.Get("X-Etcd-Cluster-ID")
  62. if gcid != wcid {
  63. log.Printf("rafthttp: request ignored due to cluster ID mismatch got %s want %s", gcid, wcid)
  64. http.Error(w, "clusterID mismatch", http.StatusPreconditionFailed)
  65. return
  66. }
  67. // Limit the data size that could be read from the request body, which ensures that read from
  68. // connection will not time out accidentally due to possible block in underlying implementation.
  69. limitedr := pioutil.NewLimitedBufferReader(r.Body, ConnReadLimitByte)
  70. b, err := ioutil.ReadAll(limitedr)
  71. if err != nil {
  72. log.Println("rafthttp: error reading raft message:", err)
  73. http.Error(w, "error reading raft message", http.StatusBadRequest)
  74. return
  75. }
  76. var m raftpb.Message
  77. if err := m.Unmarshal(b); err != nil {
  78. log.Println("rafthttp: error unmarshaling raft message:", err)
  79. http.Error(w, "error unmarshaling raft message", http.StatusBadRequest)
  80. return
  81. }
  82. if err := h.r.Process(context.TODO(), m); err != nil {
  83. switch v := err.(type) {
  84. case writerToResponse:
  85. v.WriteTo(w)
  86. default:
  87. log.Printf("rafthttp: error processing raft message: %v", err)
  88. http.Error(w, "error processing raft message", http.StatusInternalServerError)
  89. }
  90. return
  91. }
  92. w.WriteHeader(http.StatusNoContent)
  93. }
  94. type streamHandler struct {
  95. tr *transport
  96. id types.ID
  97. cid types.ID
  98. }
  99. func (h *streamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  100. if r.Method != "GET" {
  101. w.Header().Set("Allow", "GET")
  102. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  103. return
  104. }
  105. fromStr := strings.TrimPrefix(r.URL.Path, RaftStreamPrefix+"/")
  106. from, err := types.IDFromString(fromStr)
  107. if err != nil {
  108. log.Printf("rafthttp: path %s cannot be parsed", fromStr)
  109. http.Error(w, "invalid path", http.StatusNotFound)
  110. return
  111. }
  112. p := h.tr.Peer(from)
  113. if p == nil {
  114. log.Printf("rafthttp: fail to find sender %s", from)
  115. http.Error(w, "error sender not found", http.StatusNotFound)
  116. return
  117. }
  118. wcid := h.cid.String()
  119. if gcid := r.Header.Get("X-Etcd-Cluster-ID"); gcid != wcid {
  120. log.Printf("rafthttp: streaming request ignored due to cluster ID mismatch got %s want %s", gcid, wcid)
  121. http.Error(w, "clusterID mismatch", http.StatusPreconditionFailed)
  122. return
  123. }
  124. wto := h.id.String()
  125. if gto := r.Header.Get("X-Raft-To"); gto != wto {
  126. log.Printf("rafthttp: streaming request ignored due to ID mismatch got %s want %s", gto, wto)
  127. http.Error(w, "to field mismatch", http.StatusPreconditionFailed)
  128. return
  129. }
  130. termStr := r.Header.Get("X-Raft-Term")
  131. term, err := strconv.ParseUint(termStr, 10, 64)
  132. if err != nil {
  133. log.Printf("rafthttp: streaming request ignored due to parse term %s error: %v", termStr, err)
  134. http.Error(w, "invalid term field", http.StatusBadRequest)
  135. return
  136. }
  137. sw := newStreamWriter(from, term)
  138. err = p.attachStream(sw)
  139. if err != nil {
  140. log.Printf("rafthttp: %v", err)
  141. http.Error(w, err.Error(), http.StatusBadRequest)
  142. return
  143. }
  144. w.WriteHeader(http.StatusOK)
  145. w.(http.Flusher).Flush()
  146. go sw.handle(w.(WriteFlusher))
  147. <-sw.stopNotify()
  148. }
  149. type writerToResponse interface {
  150. WriteTo(w http.ResponseWriter)
  151. }