reverse.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  28. "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
  29. "github.com/coreos/etcd/pkg/httputil"
  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. closeCh := closeNotifier.CloseNotify()
  99. go func() {
  100. select {
  101. case <-closeCh:
  102. atomic.StoreInt32(&requestClosed, 1)
  103. log.Printf("proxy: client %v closed request prematurely", clientreq.RemoteAddr)
  104. cancel()
  105. case <-completeCh:
  106. }
  107. }()
  108. defer func() {
  109. completeCh <- true
  110. }()
  111. }
  112. var res *http.Response
  113. for _, ep := range endpoints {
  114. if proxybody != nil {
  115. proxyreq.Body = ioutil.NopCloser(bytes.NewBuffer(proxybody))
  116. }
  117. redirectRequest(proxyreq, ep.URL)
  118. res, err = p.transport.RoundTrip(proxyreq)
  119. if atomic.LoadInt32(&requestClosed) == 1 {
  120. return
  121. }
  122. if err != nil {
  123. reportRequestDropped(clientreq, failedSendingRequest)
  124. log.Printf("proxy: failed to direct request to %s: %v", ep.URL.String(), err)
  125. ep.Failed()
  126. continue
  127. }
  128. break
  129. }
  130. if res == nil {
  131. // TODO: limit the rate of the error logging.
  132. msg := fmt.Sprintf("proxy: unable to get response from %d endpoint(s)", len(endpoints))
  133. reportRequestDropped(clientreq, failedGettingResponse)
  134. log.Printf(msg)
  135. e := httptypes.NewHTTPError(http.StatusBadGateway, msg)
  136. if we := e.WriteTo(rw); we != nil {
  137. plog.Debugf("error writing HTTPError (%v) to %s", we, clientreq.RemoteAddr)
  138. }
  139. return
  140. }
  141. defer res.Body.Close()
  142. reportRequestHandled(clientreq, res, startTime)
  143. removeSingleHopHeaders(&res.Header)
  144. copyHeader(rw.Header(), res.Header)
  145. rw.WriteHeader(res.StatusCode)
  146. io.Copy(rw, res.Body)
  147. }
  148. func copyHeader(dst, src http.Header) {
  149. for k, vv := range src {
  150. for _, v := range vv {
  151. dst.Add(k, v)
  152. }
  153. }
  154. }
  155. func redirectRequest(req *http.Request, loc url.URL) {
  156. req.URL.Scheme = loc.Scheme
  157. req.URL.Host = loc.Host
  158. }
  159. func normalizeRequest(req *http.Request) {
  160. req.Proto = "HTTP/1.1"
  161. req.ProtoMajor = 1
  162. req.ProtoMinor = 1
  163. req.Close = false
  164. }
  165. func maybeSetForwardedFor(req *http.Request) {
  166. clientIP, _, err := net.SplitHostPort(req.RemoteAddr)
  167. if err != nil {
  168. return
  169. }
  170. // If we aren't the first proxy retain prior
  171. // X-Forwarded-For information as a comma+space
  172. // separated list and fold multiple headers into one.
  173. if prior, ok := req.Header["X-Forwarded-For"]; ok {
  174. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  175. }
  176. req.Header.Set("X-Forwarded-For", clientIP)
  177. }