http.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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 client
  15. import (
  16. "errors"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "net/url"
  21. "sync"
  22. "time"
  23. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  24. )
  25. var (
  26. ErrTimeout = context.DeadlineExceeded
  27. ErrCanceled = context.Canceled
  28. ErrNoEndpoints = errors.New("no endpoints available")
  29. ErrTooManyRedirects = errors.New("too many redirects")
  30. DefaultRequestTimeout = 5 * time.Second
  31. DefaultMaxRedirects = 10
  32. )
  33. func newHTTPClientFactory(tr CancelableTransport) httpClientFactory {
  34. return func(ep url.URL) HTTPClient {
  35. return &redirectFollowingHTTPClient{
  36. max: DefaultMaxRedirects,
  37. client: &simpleHTTPClient{
  38. transport: tr,
  39. endpoint: ep,
  40. },
  41. }
  42. }
  43. }
  44. type Config struct {
  45. Endpoints []string
  46. Transport CancelableTransport
  47. }
  48. func New(cfg Config) (SyncableHTTPClient, error) {
  49. c := &httpClusterClient{clientFactory: newHTTPClientFactory(cfg.Transport)}
  50. if err := c.reset(cfg.Endpoints); err != nil {
  51. return nil, err
  52. }
  53. return c, nil
  54. }
  55. type SyncableHTTPClient interface {
  56. HTTPClient
  57. Sync(context.Context) error
  58. Endpoints() []string
  59. }
  60. type HTTPClient interface {
  61. Do(context.Context, httpAction) (*http.Response, []byte, error)
  62. }
  63. type httpClientFactory func(url.URL) HTTPClient
  64. type httpAction interface {
  65. HTTPRequest(url.URL) *http.Request
  66. }
  67. // CancelableTransport mimics http.Transport to provide an interface which can be
  68. // substituted for testing (since the RoundTripper interface alone does not
  69. // require the CancelRequest method)
  70. type CancelableTransport interface {
  71. http.RoundTripper
  72. CancelRequest(req *http.Request)
  73. }
  74. type httpClusterClient struct {
  75. clientFactory httpClientFactory
  76. endpoints []url.URL
  77. sync.RWMutex
  78. }
  79. func (c *httpClusterClient) reset(eps []string) error {
  80. if len(eps) == 0 {
  81. return ErrNoEndpoints
  82. }
  83. neps := make([]url.URL, len(eps))
  84. for i, ep := range eps {
  85. u, err := url.Parse(ep)
  86. if err != nil {
  87. return err
  88. }
  89. neps[i] = *u
  90. }
  91. c.endpoints = neps
  92. return nil
  93. }
  94. func (c *httpClusterClient) Do(ctx context.Context, act httpAction) (resp *http.Response, body []byte, err error) {
  95. c.RLock()
  96. leps := len(c.endpoints)
  97. eps := make([]url.URL, leps)
  98. n := copy(eps, c.endpoints)
  99. c.RUnlock()
  100. if leps == 0 {
  101. err = ErrNoEndpoints
  102. return
  103. }
  104. if leps != n {
  105. err = errors.New("unable to pick endpoint: copy failed")
  106. return
  107. }
  108. for _, ep := range eps {
  109. hc := c.clientFactory(ep)
  110. resp, body, err = hc.Do(ctx, act)
  111. if err != nil {
  112. if err == ErrTimeout || err == ErrCanceled {
  113. return nil, nil, err
  114. }
  115. continue
  116. }
  117. if resp.StatusCode/100 == 5 {
  118. continue
  119. }
  120. break
  121. }
  122. return
  123. }
  124. func (c *httpClusterClient) Endpoints() []string {
  125. c.RLock()
  126. defer c.RUnlock()
  127. eps := make([]string, len(c.endpoints))
  128. for i, ep := range c.endpoints {
  129. eps[i] = ep.String()
  130. }
  131. return eps
  132. }
  133. func (c *httpClusterClient) Sync(ctx context.Context) error {
  134. c.Lock()
  135. defer c.Unlock()
  136. mAPI := NewMembersAPI(c)
  137. ms, err := mAPI.List(ctx)
  138. if err != nil {
  139. return err
  140. }
  141. eps := make([]string, 0)
  142. for _, m := range ms {
  143. eps = append(eps, m.ClientURLs...)
  144. }
  145. return c.reset(eps)
  146. }
  147. type roundTripResponse struct {
  148. resp *http.Response
  149. err error
  150. }
  151. type simpleHTTPClient struct {
  152. transport CancelableTransport
  153. endpoint url.URL
  154. }
  155. func (c *simpleHTTPClient) Do(ctx context.Context, act httpAction) (*http.Response, []byte, error) {
  156. req := act.HTTPRequest(c.endpoint)
  157. rtchan := make(chan roundTripResponse, 1)
  158. go func() {
  159. resp, err := c.transport.RoundTrip(req)
  160. rtchan <- roundTripResponse{resp: resp, err: err}
  161. close(rtchan)
  162. }()
  163. var resp *http.Response
  164. var err error
  165. select {
  166. case rtresp := <-rtchan:
  167. resp, err = rtresp.resp, rtresp.err
  168. case <-ctx.Done():
  169. c.transport.CancelRequest(req)
  170. // wait for request to actually exit before continuing
  171. <-rtchan
  172. err = ctx.Err()
  173. }
  174. // always check for resp nil-ness to deal with possible
  175. // race conditions between channels above
  176. defer func() {
  177. if resp != nil {
  178. resp.Body.Close()
  179. }
  180. }()
  181. if err != nil {
  182. return nil, nil, err
  183. }
  184. body, err := ioutil.ReadAll(resp.Body)
  185. return resp, body, err
  186. }
  187. type redirectFollowingHTTPClient struct {
  188. client HTTPClient
  189. max int
  190. }
  191. func (r *redirectFollowingHTTPClient) Do(ctx context.Context, act httpAction) (*http.Response, []byte, error) {
  192. for i := 0; i <= r.max; i++ {
  193. resp, body, err := r.client.Do(ctx, act)
  194. if err != nil {
  195. return nil, nil, err
  196. }
  197. if resp.StatusCode/100 == 3 {
  198. hdr := resp.Header.Get("Location")
  199. if hdr == "" {
  200. return nil, nil, fmt.Errorf("Location header not set")
  201. }
  202. loc, err := url.Parse(hdr)
  203. if err != nil {
  204. return nil, nil, fmt.Errorf("Location header not valid URL: %s", hdr)
  205. }
  206. act = &redirectedHTTPAction{
  207. action: act,
  208. location: *loc,
  209. }
  210. continue
  211. }
  212. return resp, body, nil
  213. }
  214. return nil, nil, ErrTooManyRedirects
  215. }
  216. type redirectedHTTPAction struct {
  217. action httpAction
  218. location url.URL
  219. }
  220. func (r *redirectedHTTPAction) HTTPRequest(ep url.URL) *http.Request {
  221. orig := r.action.HTTPRequest(ep)
  222. orig.URL = &r.location
  223. return orig
  224. }