client.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. // Copyright 2015 The etcd Authors
  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. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "io/ioutil"
  20. "math/rand"
  21. "net"
  22. "net/http"
  23. "net/url"
  24. "sort"
  25. "strconv"
  26. "sync"
  27. "time"
  28. "github.com/coreos/etcd/version"
  29. "golang.org/x/net/context"
  30. )
  31. var (
  32. ErrNoEndpoints = errors.New("client: no endpoints available")
  33. ErrTooManyRedirects = errors.New("client: too many redirects")
  34. ErrClusterUnavailable = errors.New("client: etcd cluster is unavailable or misconfigured")
  35. ErrNoLeaderEndpoint = errors.New("client: no leader endpoint available")
  36. errTooManyRedirectChecks = errors.New("client: too many redirect checks")
  37. // oneShotCtxValue is set on a context using WithValue(&oneShotValue) so
  38. // that Do() will not retry a request
  39. oneShotCtxValue interface{}
  40. )
  41. var DefaultRequestTimeout = 5 * time.Second
  42. var DefaultTransport CancelableTransport = &http.Transport{
  43. Proxy: http.ProxyFromEnvironment,
  44. Dial: (&net.Dialer{
  45. Timeout: 30 * time.Second,
  46. KeepAlive: 30 * time.Second,
  47. }).Dial,
  48. TLSHandshakeTimeout: 10 * time.Second,
  49. }
  50. type EndpointSelectionMode int
  51. const (
  52. // EndpointSelectionRandom is the default value of the 'SelectionMode'.
  53. // As the name implies, the client object will pick a node from the members
  54. // of the cluster in a random fashion. If the cluster has three members, A, B,
  55. // and C, the client picks any node from its three members as its request
  56. // destination.
  57. EndpointSelectionRandom EndpointSelectionMode = iota
  58. // If 'SelectionMode' is set to 'EndpointSelectionPrioritizeLeader',
  59. // requests are sent directly to the cluster leader. This reduces
  60. // forwarding roundtrips compared to making requests to etcd followers
  61. // who then forward them to the cluster leader. In the event of a leader
  62. // failure, however, clients configured this way cannot prioritize among
  63. // the remaining etcd followers. Therefore, when a client sets 'SelectionMode'
  64. // to 'EndpointSelectionPrioritizeLeader', it must use 'client.AutoSync()' to
  65. // maintain its knowledge of current cluster state.
  66. //
  67. // This mode should be used with Client.AutoSync().
  68. EndpointSelectionPrioritizeLeader
  69. )
  70. type Config struct {
  71. // Endpoints defines a set of URLs (schemes, hosts and ports only)
  72. // that can be used to communicate with a logical etcd cluster. For
  73. // example, a three-node cluster could be provided like so:
  74. //
  75. // Endpoints: []string{
  76. // "http://node1.example.com:2379",
  77. // "http://node2.example.com:2379",
  78. // "http://node3.example.com:2379",
  79. // }
  80. //
  81. // If multiple endpoints are provided, the Client will attempt to
  82. // use them all in the event that one or more of them are unusable.
  83. //
  84. // If Client.Sync is ever called, the Client may cache an alternate
  85. // set of endpoints to continue operation.
  86. Endpoints []string
  87. // Transport is used by the Client to drive HTTP requests. If not
  88. // provided, DefaultTransport will be used.
  89. Transport CancelableTransport
  90. // CheckRedirect specifies the policy for handling HTTP redirects.
  91. // If CheckRedirect is not nil, the Client calls it before
  92. // following an HTTP redirect. The sole argument is the number of
  93. // requests that have already been made. If CheckRedirect returns
  94. // an error, Client.Do will not make any further requests and return
  95. // the error back it to the caller.
  96. //
  97. // If CheckRedirect is nil, the Client uses its default policy,
  98. // which is to stop after 10 consecutive requests.
  99. CheckRedirect CheckRedirectFunc
  100. // Username specifies the user credential to add as an authorization header
  101. Username string
  102. // Password is the password for the specified user to add as an authorization header
  103. // to the request.
  104. Password string
  105. // HeaderTimeoutPerRequest specifies the time limit to wait for response
  106. // header in a single request made by the Client. The timeout includes
  107. // connection time, any redirects, and header wait time.
  108. //
  109. // For non-watch GET request, server returns the response body immediately.
  110. // For PUT/POST/DELETE request, server will attempt to commit request
  111. // before responding, which is expected to take `100ms + 2 * RTT`.
  112. // For watch request, server returns the header immediately to notify Client
  113. // watch start. But if server is behind some kind of proxy, the response
  114. // header may be cached at proxy, and Client cannot rely on this behavior.
  115. //
  116. // Especially, wait request will ignore this timeout.
  117. //
  118. // One API call may send multiple requests to different etcd servers until it
  119. // succeeds. Use context of the API to specify the overall timeout.
  120. //
  121. // A HeaderTimeoutPerRequest of zero means no timeout.
  122. HeaderTimeoutPerRequest time.Duration
  123. // SelectionMode is an EndpointSelectionMode enum that specifies the
  124. // policy for choosing the etcd cluster node to which requests are sent.
  125. SelectionMode EndpointSelectionMode
  126. }
  127. func (cfg *Config) transport() CancelableTransport {
  128. if cfg.Transport == nil {
  129. return DefaultTransport
  130. }
  131. return cfg.Transport
  132. }
  133. func (cfg *Config) checkRedirect() CheckRedirectFunc {
  134. if cfg.CheckRedirect == nil {
  135. return DefaultCheckRedirect
  136. }
  137. return cfg.CheckRedirect
  138. }
  139. // CancelableTransport mimics net/http.Transport, but requires that
  140. // the object also support request cancellation.
  141. type CancelableTransport interface {
  142. http.RoundTripper
  143. CancelRequest(req *http.Request)
  144. }
  145. type CheckRedirectFunc func(via int) error
  146. // DefaultCheckRedirect follows up to 10 redirects, but no more.
  147. var DefaultCheckRedirect CheckRedirectFunc = func(via int) error {
  148. if via > 10 {
  149. return ErrTooManyRedirects
  150. }
  151. return nil
  152. }
  153. type Client interface {
  154. // Sync updates the internal cache of the etcd cluster's membership.
  155. Sync(context.Context) error
  156. // AutoSync periodically calls Sync() every given interval.
  157. // The recommended sync interval is 10 seconds to 1 minute, which does
  158. // not bring too much overhead to server and makes client catch up the
  159. // cluster change in time.
  160. //
  161. // The example to use it:
  162. //
  163. // for {
  164. // err := client.AutoSync(ctx, 10*time.Second)
  165. // if err == context.DeadlineExceeded || err == context.Canceled {
  166. // break
  167. // }
  168. // log.Print(err)
  169. // }
  170. AutoSync(context.Context, time.Duration) error
  171. // Endpoints returns a copy of the current set of API endpoints used
  172. // by Client to resolve HTTP requests. If Sync has ever been called,
  173. // this may differ from the initial Endpoints provided in the Config.
  174. Endpoints() []string
  175. // SetEndpoints sets the set of API endpoints used by Client to resolve
  176. // HTTP requests. If the given endpoints are not valid, an error will be
  177. // returned
  178. SetEndpoints(eps []string) error
  179. // GetVersion retrieves the current etcd server and cluster version
  180. GetVersion(ctx context.Context) (*version.Versions, error)
  181. httpClient
  182. }
  183. func New(cfg Config) (Client, error) {
  184. c := &httpClusterClient{
  185. clientFactory: newHTTPClientFactory(cfg.transport(), cfg.checkRedirect(), cfg.HeaderTimeoutPerRequest),
  186. rand: rand.New(rand.NewSource(int64(time.Now().Nanosecond()))),
  187. selectionMode: cfg.SelectionMode,
  188. }
  189. if cfg.Username != "" {
  190. c.credentials = &credentials{
  191. username: cfg.Username,
  192. password: cfg.Password,
  193. }
  194. }
  195. if err := c.SetEndpoints(cfg.Endpoints); err != nil {
  196. return nil, err
  197. }
  198. return c, nil
  199. }
  200. type httpClient interface {
  201. Do(context.Context, httpAction) (*http.Response, []byte, error)
  202. }
  203. func newHTTPClientFactory(tr CancelableTransport, cr CheckRedirectFunc, headerTimeout time.Duration) httpClientFactory {
  204. return func(ep url.URL) httpClient {
  205. return &redirectFollowingHTTPClient{
  206. checkRedirect: cr,
  207. client: &simpleHTTPClient{
  208. transport: tr,
  209. endpoint: ep,
  210. headerTimeout: headerTimeout,
  211. },
  212. }
  213. }
  214. }
  215. type credentials struct {
  216. username string
  217. password string
  218. }
  219. type httpClientFactory func(url.URL) httpClient
  220. type httpAction interface {
  221. HTTPRequest(url.URL) *http.Request
  222. }
  223. type httpClusterClient struct {
  224. clientFactory httpClientFactory
  225. endpoints []url.URL
  226. pinned int
  227. credentials *credentials
  228. sync.RWMutex
  229. rand *rand.Rand
  230. selectionMode EndpointSelectionMode
  231. }
  232. func (c *httpClusterClient) getLeaderEndpoint(ctx context.Context, eps []url.URL) (string, error) {
  233. ceps := make([]url.URL, len(eps))
  234. copy(ceps, eps)
  235. // To perform a lookup on the new endpoint list without using the current
  236. // client, we'll copy it
  237. clientCopy := &httpClusterClient{
  238. clientFactory: c.clientFactory,
  239. credentials: c.credentials,
  240. rand: c.rand,
  241. pinned: 0,
  242. endpoints: ceps,
  243. }
  244. mAPI := NewMembersAPI(clientCopy)
  245. leader, err := mAPI.Leader(ctx)
  246. if err != nil {
  247. return "", err
  248. }
  249. if len(leader.ClientURLs) == 0 {
  250. return "", ErrNoLeaderEndpoint
  251. }
  252. return leader.ClientURLs[0], nil // TODO: how to handle multiple client URLs?
  253. }
  254. func (c *httpClusterClient) parseEndpoints(eps []string) ([]url.URL, error) {
  255. if len(eps) == 0 {
  256. return []url.URL{}, ErrNoEndpoints
  257. }
  258. neps := make([]url.URL, len(eps))
  259. for i, ep := range eps {
  260. u, err := url.Parse(ep)
  261. if err != nil {
  262. return []url.URL{}, err
  263. }
  264. neps[i] = *u
  265. }
  266. return neps, nil
  267. }
  268. func (c *httpClusterClient) SetEndpoints(eps []string) error {
  269. neps, err := c.parseEndpoints(eps)
  270. if err != nil {
  271. return err
  272. }
  273. c.Lock()
  274. defer c.Unlock()
  275. c.endpoints = shuffleEndpoints(c.rand, neps)
  276. // We're not doing anything for PrioritizeLeader here. This is
  277. // due to not having a context meaning we can't call getLeaderEndpoint
  278. // However, if you're using PrioritizeLeader, you've already been told
  279. // to regularly call sync, where we do have a ctx, and can figure the
  280. // leader. PrioritizeLeader is also quite a loose guarantee, so deal
  281. // with it
  282. c.pinned = 0
  283. return nil
  284. }
  285. func (c *httpClusterClient) Do(ctx context.Context, act httpAction) (*http.Response, []byte, error) {
  286. action := act
  287. c.RLock()
  288. leps := len(c.endpoints)
  289. eps := make([]url.URL, leps)
  290. n := copy(eps, c.endpoints)
  291. pinned := c.pinned
  292. if c.credentials != nil {
  293. action = &authedAction{
  294. act: act,
  295. credentials: *c.credentials,
  296. }
  297. }
  298. c.RUnlock()
  299. if leps == 0 {
  300. return nil, nil, ErrNoEndpoints
  301. }
  302. if leps != n {
  303. return nil, nil, errors.New("unable to pick endpoint: copy failed")
  304. }
  305. var resp *http.Response
  306. var body []byte
  307. var err error
  308. cerr := &ClusterError{}
  309. isOneShot := ctx.Value(&oneShotCtxValue) != nil
  310. for i := pinned; i < leps+pinned; i++ {
  311. k := i % leps
  312. hc := c.clientFactory(eps[k])
  313. resp, body, err = hc.Do(ctx, action)
  314. if err != nil {
  315. cerr.Errors = append(cerr.Errors, err)
  316. if err == ctx.Err() {
  317. return nil, nil, ctx.Err()
  318. }
  319. if err == context.Canceled || err == context.DeadlineExceeded {
  320. return nil, nil, err
  321. }
  322. if isOneShot {
  323. return nil, nil, err
  324. }
  325. continue
  326. }
  327. if resp.StatusCode/100 == 5 {
  328. switch resp.StatusCode {
  329. case http.StatusInternalServerError, http.StatusServiceUnavailable:
  330. // TODO: make sure this is a no leader response
  331. cerr.Errors = append(cerr.Errors, fmt.Errorf("client: etcd member %s has no leader", eps[k].String()))
  332. default:
  333. cerr.Errors = append(cerr.Errors, fmt.Errorf("client: etcd member %s returns server error [%s]", eps[k].String(), http.StatusText(resp.StatusCode)))
  334. }
  335. if isOneShot {
  336. return nil, nil, cerr.Errors[0]
  337. }
  338. continue
  339. }
  340. if k != pinned {
  341. c.Lock()
  342. c.pinned = k
  343. c.Unlock()
  344. }
  345. return resp, body, nil
  346. }
  347. return nil, nil, cerr
  348. }
  349. func (c *httpClusterClient) Endpoints() []string {
  350. c.RLock()
  351. defer c.RUnlock()
  352. eps := make([]string, len(c.endpoints))
  353. for i, ep := range c.endpoints {
  354. eps[i] = ep.String()
  355. }
  356. return eps
  357. }
  358. func (c *httpClusterClient) Sync(ctx context.Context) error {
  359. mAPI := NewMembersAPI(c)
  360. ms, err := mAPI.List(ctx)
  361. if err != nil {
  362. return err
  363. }
  364. var eps []string
  365. for _, m := range ms {
  366. eps = append(eps, m.ClientURLs...)
  367. }
  368. neps, err := c.parseEndpoints(eps)
  369. if err != nil {
  370. return err
  371. }
  372. npin := 0
  373. switch c.selectionMode {
  374. case EndpointSelectionRandom:
  375. c.RLock()
  376. eq := endpointsEqual(c.endpoints, neps)
  377. c.RUnlock()
  378. if eq {
  379. return nil
  380. }
  381. // When items in the endpoint list changes, we choose a new pin
  382. neps = shuffleEndpoints(c.rand, neps)
  383. case EndpointSelectionPrioritizeLeader:
  384. nle, err := c.getLeaderEndpoint(ctx, neps)
  385. if err != nil {
  386. return ErrNoLeaderEndpoint
  387. }
  388. for i, n := range neps {
  389. if n.String() == nle {
  390. npin = i
  391. break
  392. }
  393. }
  394. default:
  395. return fmt.Errorf("invalid endpoint selection mode: %d", c.selectionMode)
  396. }
  397. c.Lock()
  398. defer c.Unlock()
  399. c.endpoints = neps
  400. c.pinned = npin
  401. return nil
  402. }
  403. func (c *httpClusterClient) AutoSync(ctx context.Context, interval time.Duration) error {
  404. ticker := time.NewTicker(interval)
  405. defer ticker.Stop()
  406. for {
  407. err := c.Sync(ctx)
  408. if err != nil {
  409. return err
  410. }
  411. select {
  412. case <-ctx.Done():
  413. return ctx.Err()
  414. case <-ticker.C:
  415. }
  416. }
  417. }
  418. func (c *httpClusterClient) GetVersion(ctx context.Context) (*version.Versions, error) {
  419. act := &getAction{Prefix: "/version"}
  420. resp, body, err := c.Do(ctx, act)
  421. if err != nil {
  422. return nil, err
  423. }
  424. switch resp.StatusCode {
  425. case http.StatusOK:
  426. if len(body) == 0 {
  427. return nil, ErrEmptyBody
  428. }
  429. var vresp version.Versions
  430. if err := json.Unmarshal(body, &vresp); err != nil {
  431. return nil, ErrInvalidJSON
  432. }
  433. return &vresp, nil
  434. default:
  435. var etcdErr Error
  436. if err := json.Unmarshal(body, &etcdErr); err != nil {
  437. return nil, ErrInvalidJSON
  438. }
  439. return nil, etcdErr
  440. }
  441. }
  442. type roundTripResponse struct {
  443. resp *http.Response
  444. err error
  445. }
  446. type simpleHTTPClient struct {
  447. transport CancelableTransport
  448. endpoint url.URL
  449. headerTimeout time.Duration
  450. }
  451. func (c *simpleHTTPClient) Do(ctx context.Context, act httpAction) (*http.Response, []byte, error) {
  452. req := act.HTTPRequest(c.endpoint)
  453. if err := printcURL(req); err != nil {
  454. return nil, nil, err
  455. }
  456. isWait := false
  457. if req != nil && req.URL != nil {
  458. ws := req.URL.Query().Get("wait")
  459. if len(ws) != 0 {
  460. var err error
  461. isWait, err = strconv.ParseBool(ws)
  462. if err != nil {
  463. return nil, nil, fmt.Errorf("wrong wait value %s (%v for %+v)", ws, err, req)
  464. }
  465. }
  466. }
  467. var hctx context.Context
  468. var hcancel context.CancelFunc
  469. if !isWait && c.headerTimeout > 0 {
  470. hctx, hcancel = context.WithTimeout(ctx, c.headerTimeout)
  471. } else {
  472. hctx, hcancel = context.WithCancel(ctx)
  473. }
  474. defer hcancel()
  475. reqcancel := requestCanceler(c.transport, req)
  476. rtchan := make(chan roundTripResponse, 1)
  477. go func() {
  478. resp, err := c.transport.RoundTrip(req)
  479. rtchan <- roundTripResponse{resp: resp, err: err}
  480. close(rtchan)
  481. }()
  482. var resp *http.Response
  483. var err error
  484. select {
  485. case rtresp := <-rtchan:
  486. resp, err = rtresp.resp, rtresp.err
  487. case <-hctx.Done():
  488. // cancel and wait for request to actually exit before continuing
  489. reqcancel()
  490. rtresp := <-rtchan
  491. resp = rtresp.resp
  492. switch {
  493. case ctx.Err() != nil:
  494. err = ctx.Err()
  495. case hctx.Err() != nil:
  496. err = fmt.Errorf("client: endpoint %s exceeded header timeout", c.endpoint.String())
  497. default:
  498. panic("failed to get error from context")
  499. }
  500. }
  501. // always check for resp nil-ness to deal with possible
  502. // race conditions between channels above
  503. defer func() {
  504. if resp != nil {
  505. resp.Body.Close()
  506. }
  507. }()
  508. if err != nil {
  509. return nil, nil, err
  510. }
  511. var body []byte
  512. done := make(chan struct{})
  513. go func() {
  514. body, err = ioutil.ReadAll(resp.Body)
  515. done <- struct{}{}
  516. }()
  517. select {
  518. case <-ctx.Done():
  519. resp.Body.Close()
  520. <-done
  521. return nil, nil, ctx.Err()
  522. case <-done:
  523. }
  524. return resp, body, err
  525. }
  526. type authedAction struct {
  527. act httpAction
  528. credentials credentials
  529. }
  530. func (a *authedAction) HTTPRequest(url url.URL) *http.Request {
  531. r := a.act.HTTPRequest(url)
  532. r.SetBasicAuth(a.credentials.username, a.credentials.password)
  533. return r
  534. }
  535. type redirectFollowingHTTPClient struct {
  536. client httpClient
  537. checkRedirect CheckRedirectFunc
  538. }
  539. func (r *redirectFollowingHTTPClient) Do(ctx context.Context, act httpAction) (*http.Response, []byte, error) {
  540. next := act
  541. for i := 0; i < 100; i++ {
  542. if i > 0 {
  543. if err := r.checkRedirect(i); err != nil {
  544. return nil, nil, err
  545. }
  546. }
  547. resp, body, err := r.client.Do(ctx, next)
  548. if err != nil {
  549. return nil, nil, err
  550. }
  551. if resp.StatusCode/100 == 3 {
  552. hdr := resp.Header.Get("Location")
  553. if hdr == "" {
  554. return nil, nil, fmt.Errorf("Location header not set")
  555. }
  556. loc, err := url.Parse(hdr)
  557. if err != nil {
  558. return nil, nil, fmt.Errorf("Location header not valid URL: %s", hdr)
  559. }
  560. next = &redirectedHTTPAction{
  561. action: act,
  562. location: *loc,
  563. }
  564. continue
  565. }
  566. return resp, body, nil
  567. }
  568. return nil, nil, errTooManyRedirectChecks
  569. }
  570. type redirectedHTTPAction struct {
  571. action httpAction
  572. location url.URL
  573. }
  574. func (r *redirectedHTTPAction) HTTPRequest(ep url.URL) *http.Request {
  575. orig := r.action.HTTPRequest(ep)
  576. orig.URL = &r.location
  577. return orig
  578. }
  579. func shuffleEndpoints(r *rand.Rand, eps []url.URL) []url.URL {
  580. p := r.Perm(len(eps))
  581. neps := make([]url.URL, len(eps))
  582. for i, k := range p {
  583. neps[i] = eps[k]
  584. }
  585. return neps
  586. }
  587. func endpointsEqual(left, right []url.URL) bool {
  588. if len(left) != len(right) {
  589. return false
  590. }
  591. sLeft := make([]string, len(left))
  592. sRight := make([]string, len(right))
  593. for i, l := range left {
  594. sLeft[i] = l.String()
  595. }
  596. for i, r := range right {
  597. sRight[i] = r.String()
  598. }
  599. sort.Strings(sLeft)
  600. sort.Strings(sRight)
  601. for i := range sLeft {
  602. if sLeft[i] != sRight[i] {
  603. return false
  604. }
  605. }
  606. return true
  607. }