peer.go 2.1 KB

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