client.go 6.4 KB

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