client.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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"
  20. "net/http"
  21. "net/url"
  22. "sync"
  23. "time"
  24. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  25. )
  26. var (
  27. ErrNoEndpoints = errors.New("client: no endpoints available")
  28. ErrTooManyRedirects = errors.New("client: too many redirects")
  29. errTooManyRedirectChecks = errors.New("client: too many redirect checks")
  30. )
  31. var DefaultRequestTimeout = 5 * time.Second
  32. var DefaultTransport CancelableTransport = &http.Transport{
  33. Proxy: http.ProxyFromEnvironment,
  34. Dial: (&net.Dialer{
  35. Timeout: 30 * time.Second,
  36. KeepAlive: 30 * time.Second,
  37. }).Dial,
  38. TLSHandshakeTimeout: 10 * time.Second,
  39. }
  40. type Config struct {
  41. // Endpoints defines a set of URLs (schemes, hosts and ports only)
  42. // that can be used to communicate with a logical etcd cluster. For
  43. // example, a three-node cluster could be provided like so:
  44. //
  45. // Endpoints: []string{
  46. // "http://node1.example.com:2379",
  47. // "http://node2.example.com:2379",
  48. // "http://node3.example.com:2379",
  49. // }
  50. //
  51. // If multiple endpoints are provided, the Client will attempt to
  52. // use them all in the event that one or more of them are unusable.
  53. //
  54. // If Client.Sync is ever called, the Client may cache an alternate
  55. // set of endpoints to continue operation.
  56. Endpoints []string
  57. // Transport is used by the Client to drive HTTP requests. If not
  58. // provided, DefaultTransport will be used.
  59. Transport CancelableTransport
  60. // CheckRedirect specifies the policy for handling HTTP redirects.
  61. // If CheckRedirect is not nil, the Client calls it before
  62. // following an HTTP redirect. The sole argument is the number of
  63. // requests that have alrady been made. If CheckRedirect returns
  64. // an error, Client.Do will not make any further requests and return
  65. // the error back it to the caller.
  66. //
  67. // If CheckRedirect is nil, the Client uses its default policy,
  68. // which is to stop after 10 consecutive requests.
  69. CheckRedirect CheckRedirectFunc
  70. }
  71. func (cfg *Config) transport() CancelableTransport {
  72. if cfg.Transport == nil {
  73. return DefaultTransport
  74. }
  75. return cfg.Transport
  76. }
  77. func (cfg *Config) checkRedirect() CheckRedirectFunc {
  78. if cfg.CheckRedirect == nil {
  79. return DefaultCheckRedirect
  80. }
  81. return cfg.CheckRedirect
  82. }
  83. // CancelableTransport mimics net/http.Transport, but requires that
  84. // the object also support request cancellation.
  85. type CancelableTransport interface {
  86. http.RoundTripper
  87. CancelRequest(req *http.Request)
  88. }
  89. type CheckRedirectFunc func(via int) error
  90. // DefaultCheckRedirect follows up to 10 redirects, but no more.
  91. var DefaultCheckRedirect CheckRedirectFunc = func(via int) error {
  92. if via > 10 {
  93. return ErrTooManyRedirects
  94. }
  95. return nil
  96. }
  97. type Client interface {
  98. // Sync updates the internal cache of the etcd cluster's membership.
  99. Sync(context.Context) error
  100. // Endpoints returns a copy of the current set of API endpoints used
  101. // by Client to resolve HTTP requests. If Sync has ever been called,
  102. // this may differ from the initial Endpoints provided in the Config.
  103. Endpoints() []string
  104. httpClient
  105. }
  106. func New(cfg Config) (Client, error) {
  107. c := &httpClusterClient{clientFactory: newHTTPClientFactory(cfg.transport(), cfg.checkRedirect())}
  108. if err := c.reset(cfg.Endpoints); err != nil {
  109. return nil, err
  110. }
  111. return c, nil
  112. }
  113. type httpClient interface {
  114. Do(context.Context, httpAction) (*http.Response, []byte, error)
  115. }
  116. func newHTTPClientFactory(tr CancelableTransport, cr CheckRedirectFunc) httpClientFactory {
  117. return func(ep url.URL) httpClient {
  118. return &redirectFollowingHTTPClient{
  119. checkRedirect: cr,
  120. client: &simpleHTTPClient{
  121. transport: tr,
  122. endpoint: ep,
  123. },
  124. }
  125. }
  126. }
  127. type httpClientFactory func(url.URL) httpClient
  128. type httpAction interface {
  129. HTTPRequest(url.URL) *http.Request
  130. }
  131. type httpClusterClient struct {
  132. clientFactory httpClientFactory
  133. endpoints []url.URL
  134. sync.RWMutex
  135. }
  136. func (c *httpClusterClient) reset(eps []string) error {
  137. if len(eps) == 0 {
  138. return ErrNoEndpoints
  139. }
  140. neps := make([]url.URL, len(eps))
  141. for i, ep := range eps {
  142. u, err := url.Parse(ep)
  143. if err != nil {
  144. return err
  145. }
  146. neps[i] = *u
  147. }
  148. c.endpoints = neps
  149. return nil
  150. }
  151. func (c *httpClusterClient) Do(ctx context.Context, act httpAction) (*http.Response, []byte, error) {
  152. c.RLock()
  153. leps := len(c.endpoints)
  154. eps := make([]url.URL, leps)
  155. n := copy(eps, c.endpoints)
  156. c.RUnlock()
  157. if leps == 0 {
  158. return nil, nil, ErrNoEndpoints
  159. }
  160. if leps != n {
  161. return nil, nil, errors.New("unable to pick endpoint: copy failed")
  162. }
  163. var resp *http.Response
  164. var body []byte
  165. var err error
  166. for _, ep := range eps {
  167. hc := c.clientFactory(ep)
  168. resp, body, err = hc.Do(ctx, act)
  169. if err != nil {
  170. if err == context.DeadlineExceeded || err == context.Canceled {
  171. return nil, nil, err
  172. }
  173. continue
  174. }
  175. if resp.StatusCode/100 == 5 {
  176. continue
  177. }
  178. break
  179. }
  180. return resp, body, err
  181. }
  182. func (c *httpClusterClient) Endpoints() []string {
  183. c.RLock()
  184. defer c.RUnlock()
  185. eps := make([]string, len(c.endpoints))
  186. for i, ep := range c.endpoints {
  187. eps[i] = ep.String()
  188. }
  189. return eps
  190. }
  191. func (c *httpClusterClient) Sync(ctx context.Context) error {
  192. mAPI := NewMembersAPI(c)
  193. ms, err := mAPI.List(ctx)
  194. if err != nil {
  195. return err
  196. }
  197. c.Lock()
  198. defer c.Unlock()
  199. eps := make([]string, 0)
  200. for _, m := range ms {
  201. eps = append(eps, m.ClientURLs...)
  202. }
  203. return c.reset(eps)
  204. }
  205. type roundTripResponse struct {
  206. resp *http.Response
  207. err error
  208. }
  209. type simpleHTTPClient struct {
  210. transport CancelableTransport
  211. endpoint url.URL
  212. }
  213. func (c *simpleHTTPClient) Do(ctx context.Context, act httpAction) (*http.Response, []byte, error) {
  214. req := act.HTTPRequest(c.endpoint)
  215. rtchan := make(chan roundTripResponse, 1)
  216. go func() {
  217. resp, err := c.transport.RoundTrip(req)
  218. rtchan <- roundTripResponse{resp: resp, err: err}
  219. close(rtchan)
  220. }()
  221. var resp *http.Response
  222. var err error
  223. select {
  224. case rtresp := <-rtchan:
  225. resp, err = rtresp.resp, rtresp.err
  226. case <-ctx.Done():
  227. // cancel and wait for request to actually exit before continuing
  228. c.transport.CancelRequest(req)
  229. rtresp := <-rtchan
  230. resp = rtresp.resp
  231. err = ctx.Err()
  232. }
  233. // always check for resp nil-ness to deal with possible
  234. // race conditions between channels above
  235. defer func() {
  236. if resp != nil {
  237. resp.Body.Close()
  238. }
  239. }()
  240. if err != nil {
  241. return nil, nil, err
  242. }
  243. body, err := ioutil.ReadAll(resp.Body)
  244. return resp, body, err
  245. }
  246. type redirectFollowingHTTPClient struct {
  247. client httpClient
  248. checkRedirect CheckRedirectFunc
  249. }
  250. func (r *redirectFollowingHTTPClient) Do(ctx context.Context, act httpAction) (*http.Response, []byte, error) {
  251. next := act
  252. for i := 0; i < 100; i++ {
  253. if i > 0 {
  254. if err := r.checkRedirect(i); err != nil {
  255. return nil, nil, err
  256. }
  257. }
  258. resp, body, err := r.client.Do(ctx, next)
  259. if err != nil {
  260. return nil, nil, err
  261. }
  262. if resp.StatusCode/100 == 3 {
  263. hdr := resp.Header.Get("Location")
  264. if hdr == "" {
  265. return nil, nil, fmt.Errorf("Location header not set")
  266. }
  267. loc, err := url.Parse(hdr)
  268. if err != nil {
  269. return nil, nil, fmt.Errorf("Location header not valid URL: %s", hdr)
  270. }
  271. next = &redirectedHTTPAction{
  272. action: act,
  273. location: *loc,
  274. }
  275. continue
  276. }
  277. return resp, body, nil
  278. }
  279. return nil, nil, errTooManyRedirectChecks
  280. }
  281. type redirectedHTTPAction struct {
  282. action httpAction
  283. location url.URL
  284. }
  285. func (r *redirectedHTTPAction) HTTPRequest(ep url.URL) *http.Request {
  286. orig := r.action.HTTPRequest(ep)
  287. orig.URL = &r.location
  288. return orig
  289. }