khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 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 etcdhttp |
| 16 | |
| 17 | import ( |
| 18 | "encoding/json" |
| 19 | "net/http" |
| 20 | |
| 21 | "github.com/coreos/etcd/etcdserver" |
| 22 | "github.com/coreos/etcd/etcdserver/api" |
| 23 | "github.com/coreos/etcd/lease/leasehttp" |
| 24 | "github.com/coreos/etcd/rafthttp" |
| 25 | ) |
| 26 | |
| 27 | const ( |
| 28 | peerMembersPrefix = "/members" |
| 29 | ) |
| 30 | |
| 31 | // NewPeerHandler generates an http.Handler to handle etcd peer requests. |
| 32 | func NewPeerHandler(s etcdserver.ServerPeer) http.Handler { |
| 33 | return newPeerHandler(s.Cluster(), s.RaftHandler(), s.LeaseHandler()) |
| 34 | } |
| 35 | |
| 36 | func newPeerHandler(cluster api.Cluster, raftHandler http.Handler, leaseHandler http.Handler) http.Handler { |
| 37 | mh := &peerMembersHandler{ |
| 38 | cluster: cluster, |
| 39 | } |
| 40 | |
| 41 | mux := http.NewServeMux() |
| 42 | mux.HandleFunc("/", http.NotFound) |
| 43 | mux.Handle(rafthttp.RaftPrefix, raftHandler) |
| 44 | mux.Handle(rafthttp.RaftPrefix+"/", raftHandler) |
| 45 | mux.Handle(peerMembersPrefix, mh) |
| 46 | if leaseHandler != nil { |
| 47 | mux.Handle(leasehttp.LeasePrefix, leaseHandler) |
| 48 | mux.Handle(leasehttp.LeaseInternalPrefix, leaseHandler) |
| 49 | } |
| 50 | mux.HandleFunc(versionPath, versionHandler(cluster, serveVersion)) |
| 51 | return mux |
| 52 | } |
| 53 | |
| 54 | type peerMembersHandler struct { |
| 55 | cluster api.Cluster |
| 56 | } |
| 57 | |
| 58 | func (h *peerMembersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 59 | if !allowMethod(w, r, "GET") { |
| 60 | return |
| 61 | } |
| 62 | w.Header().Set("X-Etcd-Cluster-ID", h.cluster.ID().String()) |
| 63 | |
| 64 | if r.URL.Path != peerMembersPrefix { |
| 65 | http.Error(w, "bad path", http.StatusBadRequest) |
| 66 | return |
| 67 | } |
| 68 | ms := h.cluster.Members() |
| 69 | w.Header().Set("Content-Type", "application/json") |
| 70 | if err := json.NewEncoder(w).Encode(ms); err != nil { |
| 71 | plog.Warningf("failed to encode members response (%v)", err) |
| 72 | } |
| 73 | } |