proxy.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // Copyright 2015 CoreOS, Inc.
  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 proxy
  15. import (
  16. "encoding/json"
  17. "net/http"
  18. "strings"
  19. "time"
  20. )
  21. const (
  22. // DefaultMaxIdleConnsPerHost indicates the default maximum idle connection
  23. // count maintained between proxy and each member. We set it to 128 to
  24. // let proxy handle 128 concurrent requests in long term smoothly.
  25. // If the number of concurrent requests is bigger than this value,
  26. // proxy needs to create one new connection when handling each request in
  27. // the delta, which is bad because the creation consumes resource and
  28. // may eat up ephemeral ports.
  29. DefaultMaxIdleConnsPerHost = 128
  30. )
  31. // GetProxyURLs is a function which should return the current set of URLs to
  32. // which client requests should be proxied. This function will be queried
  33. // periodically by the proxy Handler to refresh the set of available
  34. // backends.
  35. type GetProxyURLs func() []string
  36. // NewHandler creates a new HTTP handler, listening on the given transport,
  37. // which will proxy requests to an etcd cluster.
  38. // The handler will periodically update its view of the cluster.
  39. func NewHandler(t *http.Transport, urlsFunc GetProxyURLs, failureWait time.Duration, refreshInterval time.Duration) http.Handler {
  40. p := &reverseProxy{
  41. director: newDirector(urlsFunc, failureWait, refreshInterval),
  42. transport: t,
  43. }
  44. mux := http.NewServeMux()
  45. mux.Handle("/", p)
  46. mux.HandleFunc("/v2/config/local/proxy", p.configHandler)
  47. return mux
  48. }
  49. // NewReadonlyHandler wraps the given HTTP handler to allow only GET requests
  50. func NewReadonlyHandler(hdlr http.Handler) http.Handler {
  51. readonly := readonlyHandlerFunc(hdlr)
  52. return http.HandlerFunc(readonly)
  53. }
  54. func readonlyHandlerFunc(next http.Handler) func(http.ResponseWriter, *http.Request) {
  55. return func(w http.ResponseWriter, req *http.Request) {
  56. if req.Method != "GET" {
  57. w.WriteHeader(http.StatusNotImplemented)
  58. return
  59. }
  60. next.ServeHTTP(w, req)
  61. }
  62. }
  63. func (p *reverseProxy) configHandler(w http.ResponseWriter, r *http.Request) {
  64. if !allowMethod(w, r.Method, "GET") {
  65. return
  66. }
  67. eps := p.director.endpoints()
  68. epstr := make([]string, len(eps))
  69. for i, e := range eps {
  70. epstr[i] = e.URL.String()
  71. }
  72. proxyConfig := struct {
  73. Endpoints []string `json:"endpoints"`
  74. }{
  75. Endpoints: epstr,
  76. }
  77. json.NewEncoder(w).Encode(proxyConfig)
  78. }
  79. // allowMethod verifies that the given method is one of the allowed methods,
  80. // and if not, it writes an error to w. A boolean is returned indicating
  81. // whether or not the method is allowed.
  82. func allowMethod(w http.ResponseWriter, m string, ms ...string) bool {
  83. for _, meth := range ms {
  84. if m == meth {
  85. return true
  86. }
  87. }
  88. w.Header().Set("Allow", strings.Join(ms, ","))
  89. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  90. return false
  91. }