proxy.go 3.5 KB

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