client.go 11 KB

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