Debian Codegraph @

vendor/github.com/coreos/etcd/rafthttp/http.go

raw
1 // Copyright 2015 The etcd Authors
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
15 package rafthttp
16
17 import (
18 "context"
19 "errors"
20 "fmt"
21 "io/ioutil"
22 "net/http"
23 "path"
24 "strings"
25
26 pioutil "github.com/coreos/etcd/pkg/ioutil"
27 "github.com/coreos/etcd/pkg/types"
28 "github.com/coreos/etcd/raft/raftpb"
29 "github.com/coreos/etcd/snap"
30 "github.com/coreos/etcd/version"
31 )
32
33 const (
34 // connReadLimitByte limits the number of bytes
35 // a single read can read out.
36 //
37 // 64KB should be large enough for not causing
38 // throughput bottleneck as well as small enough
39 // for not causing a read timeout.
40 connReadLimitByte = 64 * 1024
41 )
42
43 var (
44 RaftPrefix = "/raft"
45 ProbingPrefix = path.Join(RaftPrefix, "probing")
46 RaftStreamPrefix = path.Join(RaftPrefix, "stream")
47 RaftSnapshotPrefix = path.Join(RaftPrefix, "snapshot")
48
49 errIncompatibleVersion = errors.New("incompatible version")
50 errClusterIDMismatch = errors.New("cluster ID mismatch")
51 )
52
53 type peerGetter interface {
54 Get(id types.ID) Peer
55 }
56
57 type writerToResponse interface {
58 WriteTo(w http.ResponseWriter)
59 }
60
61 type pipelineHandler struct {
62 tr Transporter
63 r Raft
64 cid types.ID
65 }
66
67 // newPipelineHandler returns a handler for handling raft messages
68 // from pipeline for RaftPrefix.
69 //
70 // The handler reads out the raft message from request body,
71 // and forwards it to the given raft state machine for processing.
72 func newPipelineHandler(tr Transporter, r Raft, cid types.ID) http.Handler {
73 return &pipelineHandler{
74 tr: tr,
75 r: r,
76 cid: cid,
77 }
78 }
79
80 func (h *pipelineHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
81 if r.Method != "POST" {
82 w.Header().Set("Allow", "POST")
83 http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
84 return
85 }
86
87 w.Header().Set("X-Etcd-Cluster-ID", h.cid.String())
88
89 if err := checkClusterCompatibilityFromHeader(r.Header, h.cid); err != nil {
90 http.Error(w, err.Error(), http.StatusPreconditionFailed)
91 return
92 }
93
94 addRemoteFromRequest(h.tr, r)
95
96 // Limit the data size that could be read from the request body, which ensures that read from
97 // connection will not time out accidentally due to possible blocking in underlying implementation.
98 limitedr := pioutil.NewLimitedBufferReader(r.Body, connReadLimitByte)
99 b, err := ioutil.ReadAll(limitedr)
100 if err != nil {
101 plog.Errorf("failed to read raft message (%v)", err)
102 http.Error(w, "error reading raft message", http.StatusBadRequest)
103 recvFailures.WithLabelValues(r.RemoteAddr).Inc()
104 return
105 }
106
107 var m raftpb.Message
108 if err := m.Unmarshal(b); err != nil {
109 plog.Errorf("failed to unmarshal raft message (%v)", err)
110 http.Error(w, "error unmarshaling raft message", http.StatusBadRequest)
111 recvFailures.WithLabelValues(r.RemoteAddr).Inc()
112 return
113 }
114
115 receivedBytes.WithLabelValues(types.ID(m.From).String()).Add(float64(len(b)))
116
117 if err := h.r.Process(context.TODO(), m); err != nil {
118 switch v := err.(type) {
119 case writerToResponse:
120 v.WriteTo(w)
121 default:
122 plog.Warningf("failed to process raft message (%v)", err)
123 http.Error(w, "error processing raft message", http.StatusInternalServerError)
124 w.(http.Flusher).Flush()
125 // disconnect the http stream
126 panic(err)
127 }
128 return
129 }
130
131 // Write StatusNoContent header after the message has been processed by
132 // raft, which facilitates the client to report MsgSnap status.
133 w.WriteHeader(http.StatusNoContent)
134 }
135
136 type snapshotHandler struct {
137 tr Transporter
138 r Raft
139 snapshotter *snap.Snapshotter
140 cid types.ID
141 }
142
143 func newSnapshotHandler(tr Transporter, r Raft, snapshotter *snap.Snapshotter, cid types.ID) http.Handler {
144 return &snapshotHandler{
145 tr: tr,
146 r: r,
147 snapshotter: snapshotter,
148 cid: cid,
149 }
150 }
151
152 // ServeHTTP serves HTTP request to receive and process snapshot message.
153 //
154 // If request sender dies without closing underlying TCP connection,
155 // the handler will keep waiting for the request body until TCP keepalive
156 // finds out that the connection is broken after several minutes.
157 // This is acceptable because
158 // 1. snapshot messages sent through other TCP connections could still be
159 // received and processed.
160 // 2. this case should happen rarely, so no further optimization is done.
161 func (h *snapshotHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
162 if r.Method != "POST" {
163 w.Header().Set("Allow", "POST")
164 http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
165 return
166 }
167
168 w.Header().Set("X-Etcd-Cluster-ID", h.cid.String())
169
170 if err := checkClusterCompatibilityFromHeader(r.Header, h.cid); err != nil {
171 http.Error(w, err.Error(), http.StatusPreconditionFailed)
172 return
173 }
174
175 addRemoteFromRequest(h.tr, r)
176
177 dec := &messageDecoder{r: r.Body}
178 // let snapshots be very large since they can exceed 512MB for large installations
179 m, err := dec.decodeLimit(uint64(1 << 63))
180 if err != nil {
181 msg := fmt.Sprintf("failed to decode raft message (%v)", err)
182 plog.Errorf(msg)
183 http.Error(w, msg, http.StatusBadRequest)
184 recvFailures.WithLabelValues(r.RemoteAddr).Inc()
185 return
186 }
187
188 receivedBytes.WithLabelValues(types.ID(m.From).String()).Add(float64(m.Size()))
189
190 if m.Type != raftpb.MsgSnap {
191 plog.Errorf("unexpected raft message type %s on snapshot path", m.Type)
192 http.Error(w, "wrong raft message type", http.StatusBadRequest)
193 return
194 }
195
196 plog.Infof("receiving database snapshot [index:%d, from %s] ...", m.Snapshot.Metadata.Index, types.ID(m.From))
197 // save incoming database snapshot.
198 n, err := h.snapshotter.SaveDBFrom(r.Body, m.Snapshot.Metadata.Index)
199 if err != nil {
200 msg := fmt.Sprintf("failed to save KV snapshot (%v)", err)
201 plog.Error(msg)
202 http.Error(w, msg, http.StatusInternalServerError)
203 return
204 }
205 receivedBytes.WithLabelValues(types.ID(m.From).String()).Add(float64(n))
206 plog.Infof("received and saved database snapshot [index: %d, from: %s] successfully", m.Snapshot.Metadata.Index, types.ID(m.From))
207
208 if err := h.r.Process(context.TODO(), m); err != nil {
209 switch v := err.(type) {
210 // Process may return writerToResponse error when doing some
211 // additional checks before calling raft.Node.Step.
212 case writerToResponse:
213 v.WriteTo(w)
214 default:
215 msg := fmt.Sprintf("failed to process raft message (%v)", err)
216 plog.Warningf(msg)
217 http.Error(w, msg, http.StatusInternalServerError)
218 }
219 return
220 }
221 // Write StatusNoContent header after the message has been processed by
222 // raft, which facilitates the client to report MsgSnap status.
223 w.WriteHeader(http.StatusNoContent)
224 }
225
226 type streamHandler struct {
227 tr *Transport
228 peerGetter peerGetter
229 r Raft
230 id types.ID
231 cid types.ID
232 }
233
234 func newStreamHandler(tr *Transport, pg peerGetter, r Raft, id, cid types.ID) http.Handler {
235 return &streamHandler{
236 tr: tr,
237 peerGetter: pg,
238 r: r,
239 id: id,
240 cid: cid,
241 }
242 }
243
244 func (h *streamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
245 if r.Method != "GET" {
246 w.Header().Set("Allow", "GET")
247 http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
248 return
249 }
250
251 w.Header().Set("X-Server-Version", version.Version)
252 w.Header().Set("X-Etcd-Cluster-ID", h.cid.String())
253
254 if err := checkClusterCompatibilityFromHeader(r.Header, h.cid); err != nil {
255 http.Error(w, err.Error(), http.StatusPreconditionFailed)
256 return
257 }
258
259 var t streamType
260 switch path.Dir(r.URL.Path) {
261 case streamTypeMsgAppV2.endpoint():
262 t = streamTypeMsgAppV2
263 case streamTypeMessage.endpoint():
264 t = streamTypeMessage
265 default:
266 plog.Debugf("ignored unexpected streaming request path %s", r.URL.Path)
267 http.Error(w, "invalid path", http.StatusNotFound)
268 return
269 }
270
271 fromStr := path.Base(r.URL.Path)
272 from, err := types.IDFromString(fromStr)
273 if err != nil {
274 plog.Errorf("failed to parse from %s into ID (%v)", fromStr, err)
275 http.Error(w, "invalid from", http.StatusNotFound)
276 return
277 }
278 if h.r.IsIDRemoved(uint64(from)) {
279 plog.Warningf("rejected the stream from peer %s since it was removed", from)
280 http.Error(w, "removed member", http.StatusGone)
281 return
282 }
283 p := h.peerGetter.Get(from)
284 if p == nil {
285 // This may happen in following cases:
286 // 1. user starts a remote peer that belongs to a different cluster
287 // with the same cluster ID.
288 // 2. local etcd falls behind of the cluster, and cannot recognize
289 // the members that joined after its current progress.
290 if urls := r.Header.Get("X-PeerURLs"); urls != "" {
291 h.tr.AddRemote(from, strings.Split(urls, ","))
292 }
293 plog.Errorf("failed to find member %s in cluster %s", from, h.cid)
294 http.Error(w, "error sender not found", http.StatusNotFound)
295 return
296 }
297
298 wto := h.id.String()
299 if gto := r.Header.Get("X-Raft-To"); gto != wto {
300 plog.Errorf("streaming request ignored (ID mismatch got %s want %s)", gto, wto)
301 http.Error(w, "to field mismatch", http.StatusPreconditionFailed)
302 return
303 }
304
305 w.WriteHeader(http.StatusOK)
306 w.(http.Flusher).Flush()
307
308 c := newCloseNotifier()
309 conn := &outgoingConn{
310 t: t,
311 Writer: w,
312 Flusher: w.(http.Flusher),
313 Closer: c,
314 }
315 p.attachOutgoingConn(conn)
316 <-c.closeNotify()
317 }
318
319 // checkClusterCompatibilityFromHeader checks the cluster compatibility of
320 // the local member from the given header.
321 // It checks whether the version of local member is compatible with
322 // the versions in the header, and whether the cluster ID of local member
323 // matches the one in the header.
324 func checkClusterCompatibilityFromHeader(header http.Header, cid types.ID) error {
325 if err := checkVersionCompability(header.Get("X-Server-From"), serverVersion(header), minClusterVersion(header)); err != nil {
326 plog.Errorf("request version incompatibility (%v)", err)
327 return errIncompatibleVersion
328 }
329 if gcid := header.Get("X-Etcd-Cluster-ID"); gcid != cid.String() {
330 plog.Errorf("request cluster ID mismatch (got %s want %s)", gcid, cid)
331 return errClusterIDMismatch
332 }
333 return nil
334 }
335
336 type closeNotifier struct {
337 done chan struct{}
338 }
339
340 func newCloseNotifier() *closeNotifier {
341 return &closeNotifier{
342 done: make(chan struct{}),
343 }
344 }
345
346 func (n *closeNotifier) Close() error {
347 close(n.done)
348 return nil
349 }
350
351 func (n *closeNotifier) closeNotify() <-chan struct{} { return n.done }