client.go 9.6 KB

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