client.go 5.7 KB

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