client.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. host string // includes scheme, host, and port
  28. }
  29. func NewRemoteManager(listenAddr string) subnet.Manager {
  30. return &RemoteManager{host: "http://" + listenAddr}
  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.host + 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. url = fmt.Sprintf("%v?next=%v", url, cursor)
  102. }
  103. resp, err := httpGet(ctx, url)
  104. if err != nil {
  105. return subnet.WatchResult{}, err
  106. }
  107. if resp.StatusCode != http.StatusOK {
  108. return subnet.WatchResult{}, httpError(resp)
  109. }
  110. wr := subnet.WatchResult{}
  111. if err := json.NewDecoder(resp.Body).Decode(&wr); err != nil {
  112. return subnet.WatchResult{}, err
  113. }
  114. return wr, nil
  115. }
  116. func httpError(resp *http.Response) error {
  117. b, err := ioutil.ReadAll(resp.Body)
  118. if err != nil {
  119. return err
  120. }
  121. return fmt.Errorf("%v: %v", resp.Status, string(b))
  122. }
  123. type httpRespErr struct {
  124. resp *http.Response
  125. err error
  126. }
  127. func httpDo(ctx context.Context, req *http.Request) (*http.Response, error) {
  128. // Run the HTTP request in a goroutine (so it can be canceled) and pass
  129. // the result via the channel c
  130. tr := &http.Transport{}
  131. client := &http.Client{Transport: tr}
  132. c := make(chan httpRespErr, 1)
  133. go func() {
  134. resp, err := client.Do(req)
  135. c <- httpRespErr{resp, err}
  136. }()
  137. select {
  138. case <-ctx.Done():
  139. tr.CancelRequest(req)
  140. <-c // Wait for f to return.
  141. return nil, ctx.Err()
  142. case r := <-c:
  143. return r.resp, r.err
  144. }
  145. }
  146. func httpGet(ctx context.Context, url string) (*http.Response, error) {
  147. req, err := http.NewRequest("GET", url, nil)
  148. if err != nil {
  149. return nil, err
  150. }
  151. return httpDo(ctx, req)
  152. }
  153. func httpPutPost(ctx context.Context, method, url, contentType string, body []byte) (*http.Response, error) {
  154. req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
  155. if err != nil {
  156. return nil, err
  157. }
  158. req.Header.Set("Content-Type", contentType)
  159. return httpDo(ctx, req)
  160. }