reverse.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. "bytes"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "log"
  21. "net"
  22. "net/http"
  23. "net/url"
  24. "strings"
  25. "sync/atomic"
  26. "time"
  27. "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
  28. "github.com/coreos/etcd/pkg/httputil"
  29. "github.com/coreos/pkg/capnslog"
  30. )
  31. var (
  32. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "proxy")
  33. // Hop-by-hop headers. These are removed when sent to the backend.
  34. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  35. // This list of headers borrowed from stdlib httputil.ReverseProxy
  36. singleHopHeaders = []string{
  37. "Connection",
  38. "Keep-Alive",
  39. "Proxy-Authenticate",
  40. "Proxy-Authorization",
  41. "Te", // canonicalized version of "TE"
  42. "Trailers",
  43. "Transfer-Encoding",
  44. "Upgrade",
  45. }
  46. )
  47. func removeSingleHopHeaders(hdrs *http.Header) {
  48. for _, h := range singleHopHeaders {
  49. hdrs.Del(h)
  50. }
  51. }
  52. type reverseProxy struct {
  53. director *director
  54. transport http.RoundTripper
  55. }
  56. func (p *reverseProxy) ServeHTTP(rw http.ResponseWriter, clientreq *http.Request) {
  57. proxyreq := new(http.Request)
  58. *proxyreq = *clientreq
  59. startTime := time.Now()
  60. var (
  61. proxybody []byte
  62. err error
  63. )
  64. if clientreq.Body != nil {
  65. proxybody, err = ioutil.ReadAll(clientreq.Body)
  66. if err != nil {
  67. msg := fmt.Sprintf("proxy: failed to read request body: %v", err)
  68. e := httptypes.NewHTTPError(http.StatusInternalServerError, msg)
  69. if we := e.WriteTo(rw); we != nil {
  70. plog.Debugf("error writing HTTPError (%v) to %s", we, clientreq.RemoteAddr)
  71. }
  72. return
  73. }
  74. }
  75. // deep-copy the headers, as these will be modified below
  76. proxyreq.Header = make(http.Header)
  77. copyHeader(proxyreq.Header, clientreq.Header)
  78. normalizeRequest(proxyreq)
  79. removeSingleHopHeaders(&proxyreq.Header)
  80. maybeSetForwardedFor(proxyreq)
  81. endpoints := p.director.endpoints()
  82. if len(endpoints) == 0 {
  83. msg := "proxy: zero endpoints currently available"
  84. reportRequestDropped(clientreq, zeroEndpoints)
  85. // TODO: limit the rate of the error logging.
  86. log.Printf(msg)
  87. e := httptypes.NewHTTPError(http.StatusServiceUnavailable, msg)
  88. if we := e.WriteTo(rw); we != nil {
  89. plog.Debugf("error writing HTTPError (%v) to %s", we, clientreq.RemoteAddr)
  90. }
  91. return
  92. }
  93. var requestClosed int32
  94. completeCh := make(chan bool, 1)
  95. closeNotifier, ok := rw.(http.CloseNotifier)
  96. cancel := httputil.RequestCanceler(p.transport, proxyreq)
  97. if ok {
  98. go func() {
  99. select {
  100. case <-closeNotifier.CloseNotify():
  101. atomic.StoreInt32(&requestClosed, 1)
  102. log.Printf("proxy: client %v closed request prematurely", clientreq.RemoteAddr)
  103. cancel()
  104. case <-completeCh:
  105. }
  106. }()
  107. defer func() {
  108. completeCh <- true
  109. }()
  110. }
  111. var res *http.Response
  112. for _, ep := range endpoints {
  113. if proxybody != nil {
  114. proxyreq.Body = ioutil.NopCloser(bytes.NewBuffer(proxybody))
  115. }
  116. redirectRequest(proxyreq, ep.URL)
  117. res, err = p.transport.RoundTrip(proxyreq)
  118. if atomic.LoadInt32(&requestClosed) == 1 {
  119. return
  120. }
  121. if err != nil {
  122. reportRequestDropped(clientreq, failedSendingRequest)
  123. log.Printf("proxy: failed to direct request to %s: %v", ep.URL.String(), err)
  124. ep.Failed()
  125. continue
  126. }
  127. break
  128. }
  129. if res == nil {
  130. // TODO: limit the rate of the error logging.
  131. msg := fmt.Sprintf("proxy: unable to get response from %d endpoint(s)", len(endpoints))
  132. reportRequestDropped(clientreq, failedGettingResponse)
  133. log.Printf(msg)
  134. e := httptypes.NewHTTPError(http.StatusBadGateway, msg)
  135. if we := e.WriteTo(rw); we != nil {
  136. plog.Debugf("error writing HTTPError (%v) to %s", we, clientreq.RemoteAddr)
  137. }
  138. return
  139. }
  140. defer res.Body.Close()
  141. reportRequestHandled(clientreq, res, startTime)
  142. removeSingleHopHeaders(&res.Header)
  143. copyHeader(rw.Header(), res.Header)
  144. rw.WriteHeader(res.StatusCode)
  145. io.Copy(rw, res.Body)
  146. }
  147. func copyHeader(dst, src http.Header) {
  148. for k, vv := range src {
  149. for _, v := range vv {
  150. dst.Add(k, v)
  151. }
  152. }
  153. }
  154. func redirectRequest(req *http.Request, loc url.URL) {
  155. req.URL.Scheme = loc.Scheme
  156. req.URL.Host = loc.Host
  157. }
  158. func normalizeRequest(req *http.Request) {
  159. req.Proto = "HTTP/1.1"
  160. req.ProtoMajor = 1
  161. req.ProtoMinor = 1
  162. req.Close = false
  163. }
  164. func maybeSetForwardedFor(req *http.Request) {
  165. clientIP, _, err := net.SplitHostPort(req.RemoteAddr)
  166. if err != nil {
  167. return
  168. }
  169. // If we aren't the first proxy retain prior
  170. // X-Forwarded-For information as a comma+space
  171. // separated list and fold multiple headers into one.
  172. if prior, ok := req.Header["X-Forwarded-For"]; ok {
  173. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  174. }
  175. req.Header.Set("X-Forwarded-For", clientIP)
  176. }