http.go 5.7 KB

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