client.go 7.0 KB

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