client.go 14 KB

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