client.go 5.4 KB

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