client.go 11 KB

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