reverse.go 4.6 KB

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