reverse.go 5.1 KB

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