peer.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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.EtcdServer) http.Handler {
  28. var lh http.Handler
  29. l := s.Lessor()
  30. if l != nil {
  31. lh = leasehttp.NewHandler(l, func() <-chan struct{} { return s.ApplyWait() })
  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(leasehttp.LeasePrefix, leaseHandler)
  46. mux.Handle(leasehttp.LeaseInternalPrefix, leaseHandler)
  47. }
  48. mux.HandleFunc(versionPath, versionHandler(cluster, serveVersion))
  49. return mux
  50. }
  51. type peerMembersHandler struct {
  52. cluster api.Cluster
  53. }
  54. func (h *peerMembersHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  55. if !allowMethod(w, r, "GET") {
  56. return
  57. }
  58. w.Header().Set("X-Etcd-Cluster-ID", h.cluster.ID().String())
  59. if r.URL.Path != peerMembersPrefix {
  60. http.Error(w, "bad path", http.StatusBadRequest)
  61. return
  62. }
  63. ms := h.cluster.Members()
  64. w.Header().Set("Content-Type", "application/json")
  65. if err := json.NewEncoder(w).Encode(ms); err != nil {
  66. plog.Warningf("failed to encode members response (%v)", err)
  67. }
  68. }