peer.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 v2http
  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. leasesPrefix = "/leases"
  26. )
  27. // NewPeerHandler generates an http.Handler to handle etcd peer requests.
  28. func NewPeerHandler(s *etcdserver.EtcdServer) http.Handler {
  29. var lh http.Handler
  30. if l := s.Lessor(); l != nil {
  31. lh = leasehttp.NewHandler(l)
  32. }
  33. return newPeerHandler(s.Cluster(), s.RaftHandler(), lh)
  34. }
  35. func newPeerHandler(cluster api.Cluster, raftHandler http.Handler, leaseHandler http.Handler) http.Handler {
  36. mh := &peerMembersHandler{
  37. cluster: cluster,
  38. }
  39. mux := http.NewServeMux()
  40. mux.HandleFunc("/", http.NotFound)
  41. mux.Handle(rafthttp.RaftPrefix, raftHandler)
  42. mux.Handle(rafthttp.RaftPrefix+"/", raftHandler)
  43. mux.Handle(peerMembersPrefix, mh)
  44. if leaseHandler != nil {
  45. mux.Handle(leasesPrefix, leaseHandler)
  46. }
  47. mux.HandleFunc(versionPath, versionHandler(cluster, serveVersion))
  48. return mux
  49. }
  50. type peerMembersHandler struct {
  51. cluster api.Cluster
  52. }
  53. func (h *peerMembersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  54. if !allowMethod(w, r.Method, "GET") {
  55. return
  56. }
  57. w.Header().Set("X-Etcd-Cluster-ID", h.cluster.ID().String())
  58. if r.URL.Path != peerMembersPrefix {
  59. http.Error(w, "bad path", http.StatusBadRequest)
  60. return
  61. }
  62. ms := h.cluster.Members()
  63. w.Header().Set("Content-Type", "application/json")
  64. if err := json.NewEncoder(w).Encode(ms); err != nil {
  65. plog.Warningf("failed to encode members response (%v)", err)
  66. }
  67. }