client.go 15 KB

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