client.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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) watch(ctx context.Context, url string, cursor interface{}, wr interface{}) error {
  137. if cursor != nil {
  138. c, ok := cursor.(string)
  139. if !ok {
  140. return fmt.Errorf("internal error: RemoteManager.watch received non-string cursor")
  141. }
  142. url = fmt.Sprintf("%v?next=%v", url, c)
  143. }
  144. resp, err := m.httpGet(ctx, url)
  145. if err != nil {
  146. return err
  147. }
  148. if resp.StatusCode != http.StatusOK {
  149. return httpError(resp)
  150. }
  151. if err := json.NewDecoder(resp.Body).Decode(wr); err != nil {
  152. return err
  153. }
  154. return nil
  155. }
  156. func (m *RemoteManager) WatchLeases(ctx context.Context, network string, cursor interface{}) (subnet.LeaseWatchResult, error) {
  157. url := m.mkurl(network, "leases")
  158. wr := subnet.LeaseWatchResult{}
  159. err := m.watch(ctx, url, cursor, &wr)
  160. if err != nil {
  161. return subnet.LeaseWatchResult{}, err
  162. }
  163. if _, ok := wr.Cursor.(string); !ok {
  164. return subnet.LeaseWatchResult{}, fmt.Errorf("watch returned non-string cursor")
  165. }
  166. return wr, nil
  167. }
  168. func (m *RemoteManager) WatchNetworks(ctx context.Context, cursor interface{}) (subnet.NetworkWatchResult, error) {
  169. wr := subnet.NetworkWatchResult{}
  170. err := m.watch(ctx, m.base+"/", cursor, &wr)
  171. if err != nil {
  172. return subnet.NetworkWatchResult{}, err
  173. }
  174. if _, ok := wr.Cursor.(string); !ok {
  175. return subnet.NetworkWatchResult{}, fmt.Errorf("watch returned non-string cursor")
  176. }
  177. return wr, nil
  178. }
  179. func httpError(resp *http.Response) error {
  180. b, err := ioutil.ReadAll(resp.Body)
  181. if err != nil {
  182. return err
  183. }
  184. return fmt.Errorf("%v: %v", resp.Status, string(b))
  185. }
  186. type httpRespErr struct {
  187. resp *http.Response
  188. err error
  189. }
  190. func (m *RemoteManager) httpDo(ctx context.Context, req *http.Request) (*http.Response, error) {
  191. // Run the HTTP request in a goroutine (so it can be canceled) and pass
  192. // the result via the channel c
  193. client := &http.Client{Transport: m.transport}
  194. c := make(chan httpRespErr, 1)
  195. go func() {
  196. resp, err := client.Do(req)
  197. c <- httpRespErr{resp, err}
  198. }()
  199. select {
  200. case <-ctx.Done():
  201. m.transport.CancelRequest(req)
  202. <-c // Wait for f to return.
  203. return nil, ctx.Err()
  204. case r := <-c:
  205. return r.resp, r.err
  206. }
  207. }
  208. func (m *RemoteManager) httpGet(ctx context.Context, url string) (*http.Response, error) {
  209. req, err := http.NewRequest("GET", url, nil)
  210. if err != nil {
  211. return nil, err
  212. }
  213. return m.httpDo(ctx, req)
  214. }
  215. func (m *RemoteManager) httpPutPost(ctx context.Context, method, url, contentType string, body []byte) (*http.Response, error) {
  216. req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
  217. if err != nil {
  218. return nil, err
  219. }
  220. req.Header.Set("Content-Type", contentType)
  221. return m.httpDo(ctx, req)
  222. }