reverse.go 4.6 KB

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