client.go 15 KB

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