http.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package client
  14. import (
  15. "io/ioutil"
  16. "net/http"
  17. "net/url"
  18. "time"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/code.google.com/p/go.net/context"
  20. )
  21. var (
  22. ErrTimeout = context.DeadlineExceeded
  23. DefaultRequestTimeout = 5 * time.Second
  24. )
  25. type SyncableHTTPClient interface {
  26. HTTPClient
  27. Sync(context.Context) error
  28. }
  29. type HTTPClient interface {
  30. Do(context.Context, HTTPAction) (*http.Response, []byte, error)
  31. }
  32. type HTTPAction interface {
  33. HTTPRequest(url.URL) *http.Request
  34. }
  35. // CancelableTransport mimics http.Transport to provide an interface which can be
  36. // substituted for testing (since the RoundTripper interface alone does not
  37. // require the CancelRequest method)
  38. type CancelableTransport interface {
  39. http.RoundTripper
  40. CancelRequest(req *http.Request)
  41. }
  42. func NewHTTPClient(tr CancelableTransport, eps []string) (SyncableHTTPClient, error) {
  43. return newHTTPClusterClient(tr, eps)
  44. }
  45. func newHTTPClusterClient(tr CancelableTransport, eps []string) (*httpClusterClient, error) {
  46. c := httpClusterClient{
  47. transport: tr,
  48. endpoints: make([]HTTPClient, len(eps)),
  49. }
  50. for i, ep := range eps {
  51. u, err := url.Parse(ep)
  52. if err != nil {
  53. return nil, err
  54. }
  55. c.endpoints[i] = &httpClient{
  56. transport: tr,
  57. endpoint: *u,
  58. }
  59. }
  60. return &c, nil
  61. }
  62. type httpClusterClient struct {
  63. transport CancelableTransport
  64. endpoints []HTTPClient
  65. }
  66. func (c *httpClusterClient) Do(ctx context.Context, act HTTPAction) (*http.Response, []byte, error) {
  67. //TODO(bcwaldon): introduce retry logic so all endpoints are attempted
  68. return c.endpoints[0].Do(ctx, act)
  69. }
  70. func (c *httpClusterClient) Sync(ctx context.Context) error {
  71. mAPI := NewMembersAPI(c)
  72. ms, err := mAPI.List(ctx)
  73. if err != nil {
  74. return err
  75. }
  76. eps := make([]string, 0)
  77. for _, m := range ms {
  78. eps = append(eps, m.ClientURLs...)
  79. }
  80. nc, err := newHTTPClusterClient(c.transport, eps)
  81. if err != nil {
  82. return err
  83. }
  84. *c = *nc
  85. return nil
  86. }
  87. type roundTripResponse struct {
  88. resp *http.Response
  89. err error
  90. }
  91. type httpClient struct {
  92. transport CancelableTransport
  93. endpoint url.URL
  94. }
  95. func (c *httpClient) Do(ctx context.Context, act HTTPAction) (*http.Response, []byte, error) {
  96. req := act.HTTPRequest(c.endpoint)
  97. rtchan := make(chan roundTripResponse, 1)
  98. go func() {
  99. resp, err := c.transport.RoundTrip(req)
  100. rtchan <- roundTripResponse{resp: resp, err: err}
  101. close(rtchan)
  102. }()
  103. var resp *http.Response
  104. var err error
  105. select {
  106. case rtresp := <-rtchan:
  107. resp, err = rtresp.resp, rtresp.err
  108. case <-ctx.Done():
  109. c.transport.CancelRequest(req)
  110. // wait for request to actually exit before continuing
  111. <-rtchan
  112. err = ctx.Err()
  113. }
  114. // always check for resp nil-ness to deal with possible
  115. // race conditions between channels above
  116. defer func() {
  117. if resp != nil {
  118. resp.Body.Close()
  119. }
  120. }()
  121. if err != nil {
  122. return nil, nil, err
  123. }
  124. body, err := ioutil.ReadAll(resp.Body)
  125. return resp, body, err
  126. }