client.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 remote
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "io/ioutil"
  20. "net/http"
  21. "path"
  22. "github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
  23. "github.com/coreos/flannel/subnet"
  24. )
  25. // implements subnet.Manager by sending requests to the server
  26. type RemoteManager struct {
  27. base string // includes scheme, host, and port, and version
  28. }
  29. func NewRemoteManager(listenAddr string) subnet.Manager {
  30. return &RemoteManager{base: "http://" + listenAddr + "/v1"}
  31. }
  32. func (m *RemoteManager) mkurl(network string, parts ...string) string {
  33. if network == "" {
  34. network = "/_"
  35. }
  36. if network[0] != '/' {
  37. network = "/" + network
  38. }
  39. return m.base + path.Join(append([]string{network}, parts...)...)
  40. }
  41. func (m *RemoteManager) GetNetworkConfig(ctx context.Context, network string) (*subnet.Config, error) {
  42. url := m.mkurl(network, "config")
  43. resp, err := httpGet(ctx, url)
  44. if err != nil {
  45. return nil, err
  46. }
  47. defer resp.Body.Close()
  48. if resp.StatusCode != http.StatusOK {
  49. return nil, httpError(resp)
  50. }
  51. config := &subnet.Config{}
  52. if err := json.NewDecoder(resp.Body).Decode(config); err != nil {
  53. return nil, err
  54. }
  55. return config, nil
  56. }
  57. func (m *RemoteManager) AcquireLease(ctx context.Context, network string, attrs *subnet.LeaseAttrs) (*subnet.Lease, error) {
  58. url := m.mkurl(network, "leases/")
  59. body, err := json.Marshal(attrs)
  60. if err != nil {
  61. return nil, err
  62. }
  63. resp, err := httpPutPost(ctx, "POST", url, "application/json", body)
  64. if err != nil {
  65. return nil, err
  66. }
  67. defer resp.Body.Close()
  68. if resp.StatusCode != http.StatusOK {
  69. return nil, httpError(resp)
  70. }
  71. newLease := &subnet.Lease{}
  72. if err := json.NewDecoder(resp.Body).Decode(newLease); err != nil {
  73. return nil, err
  74. }
  75. return newLease, nil
  76. }
  77. func (m *RemoteManager) RenewLease(ctx context.Context, network string, lease *subnet.Lease) error {
  78. url := m.mkurl(network, "leases", lease.Key())
  79. body, err := json.Marshal(lease)
  80. if err != nil {
  81. return err
  82. }
  83. resp, err := httpPutPost(ctx, "PUT", url, "application/json", body)
  84. if err != nil {
  85. return err
  86. }
  87. defer resp.Body.Close()
  88. if resp.StatusCode != http.StatusOK {
  89. return httpError(resp)
  90. }
  91. newLease := &subnet.Lease{}
  92. if err := json.NewDecoder(resp.Body).Decode(newLease); err != nil {
  93. return err
  94. }
  95. *lease = *newLease
  96. return nil
  97. }
  98. func (m *RemoteManager) WatchLeases(ctx context.Context, network string, cursor interface{}) (subnet.WatchResult, error) {
  99. url := m.mkurl(network, "leases")
  100. if cursor != nil {
  101. c, ok := cursor.(string)
  102. if !ok {
  103. return subnet.WatchResult{}, fmt.Errorf("internal error: RemoteManager.WatchLeases received non-string cursor")
  104. }
  105. url = fmt.Sprintf("%v?next=%v", url, c)
  106. }
  107. resp, err := httpGet(ctx, url)
  108. if err != nil {
  109. return subnet.WatchResult{}, err
  110. }
  111. if resp.StatusCode != http.StatusOK {
  112. return subnet.WatchResult{}, httpError(resp)
  113. }
  114. wr := subnet.WatchResult{}
  115. if err := json.NewDecoder(resp.Body).Decode(&wr); err != nil {
  116. return subnet.WatchResult{}, err
  117. }
  118. if _, ok := wr.Cursor.(string); !ok {
  119. return subnet.WatchResult{}, fmt.Errorf("lease watch returned non-string cursor")
  120. }
  121. return wr, nil
  122. }
  123. func httpError(resp *http.Response) error {
  124. b, err := ioutil.ReadAll(resp.Body)
  125. if err != nil {
  126. return err
  127. }
  128. return fmt.Errorf("%v: %v", resp.Status, string(b))
  129. }
  130. type httpRespErr struct {
  131. resp *http.Response
  132. err error
  133. }
  134. func httpDo(ctx context.Context, req *http.Request) (*http.Response, error) {
  135. // Run the HTTP request in a goroutine (so it can be canceled) and pass
  136. // the result via the channel c
  137. tr := &http.Transport{}
  138. client := &http.Client{Transport: tr}
  139. c := make(chan httpRespErr, 1)
  140. go func() {
  141. resp, err := client.Do(req)
  142. c <- httpRespErr{resp, err}
  143. }()
  144. select {
  145. case <-ctx.Done():
  146. tr.CancelRequest(req)
  147. <-c // Wait for f to return.
  148. return nil, ctx.Err()
  149. case r := <-c:
  150. return r.resp, r.err
  151. }
  152. }
  153. func httpGet(ctx context.Context, url string) (*http.Response, error) {
  154. req, err := http.NewRequest("GET", url, nil)
  155. if err != nil {
  156. return nil, err
  157. }
  158. return httpDo(ctx, req)
  159. }
  160. func httpPutPost(ctx context.Context, method, url, contentType string, body []byte) (*http.Response, error) {
  161. req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
  162. if err != nil {
  163. return nil, err
  164. }
  165. req.Header.Set("Content-Type", contentType)
  166. return httpDo(ctx, req)
  167. }