http.go 4.6 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/types"
  22. "github.com/coreos/etcd/raft/raftpb"
  23. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  24. )
  25. var (
  26. RaftPrefix = "/raft"
  27. RaftStreamPrefix = path.Join(RaftPrefix, "stream")
  28. )
  29. type Processor interface {
  30. Process(ctx context.Context, m raftpb.Message) error
  31. }
  32. type SenderFinder interface {
  33. // Sender returns the sender of the given id.
  34. Sender(id types.ID) Sender
  35. }
  36. func NewHandler(p Processor, cid types.ID) http.Handler {
  37. return &handler{
  38. p: p,
  39. cid: cid,
  40. }
  41. }
  42. // NewStreamHandler returns a handler which initiates streamer when receiving
  43. // stream request from follower.
  44. func NewStreamHandler(finder SenderFinder, id, cid types.ID) http.Handler {
  45. return &streamHandler{
  46. finder: finder,
  47. id: id,
  48. cid: cid,
  49. }
  50. }
  51. type handler struct {
  52. p Processor
  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. b, err := ioutil.ReadAll(r.Body)
  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.p.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. finder SenderFinder
  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. s := h.finder.Sender(from)
  112. if s == 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. w.WriteHeader(http.StatusOK)
  137. w.(http.Flusher).Flush()
  138. done, err := s.StartStreaming(w.(WriteFlusher), from, term)
  139. if err != nil {
  140. log.Printf("rafthttp: streaming request ignored due to start streaming error: %v", err)
  141. // TODO: consider http status and info here
  142. http.Error(w, "error enable streaming", http.StatusInternalServerError)
  143. return
  144. }
  145. <-done
  146. }
  147. type writerToResponse interface {
  148. WriteTo(w http.ResponseWriter)
  149. }