client.go 9.6 KB

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