http.go 5.2 KB

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