client.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // Copyright 2015 flannel authors
  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. body, err := ioutil.ReadAll(resp.Body)
  90. if err != nil {
  91. return nil, err
  92. }
  93. config, err := subnet.ParseConfig(string(body))
  94. if err != nil {
  95. return nil, err
  96. }
  97. return config, nil
  98. }
  99. func (m *RemoteManager) AcquireLease(ctx context.Context, network string, attrs *subnet.LeaseAttrs) (*subnet.Lease, error) {
  100. url := m.mkurl(network, "leases/")
  101. body, err := json.Marshal(attrs)
  102. if err != nil {
  103. return nil, err
  104. }
  105. resp, err := m.httpPutPost(ctx, "POST", url, "application/json", body)
  106. if err != nil {
  107. return nil, err
  108. }
  109. defer resp.Body.Close()
  110. if resp.StatusCode != http.StatusOK {
  111. return nil, httpError(resp)
  112. }
  113. newLease := &subnet.Lease{}
  114. if err := json.NewDecoder(resp.Body).Decode(newLease); err != nil {
  115. return nil, err
  116. }
  117. return newLease, nil
  118. }
  119. func (m *RemoteManager) RenewLease(ctx context.Context, network string, lease *subnet.Lease) error {
  120. url := m.mkurl(network, "leases", lease.Key())
  121. body, err := json.Marshal(lease)
  122. if err != nil {
  123. return err
  124. }
  125. resp, err := m.httpPutPost(ctx, "PUT", url, "application/json", body)
  126. if err != nil {
  127. return err
  128. }
  129. defer resp.Body.Close()
  130. if resp.StatusCode != http.StatusOK {
  131. return httpError(resp)
  132. }
  133. newLease := &subnet.Lease{}
  134. if err := json.NewDecoder(resp.Body).Decode(newLease); err != nil {
  135. return err
  136. }
  137. *lease = *newLease
  138. return nil
  139. }
  140. func (m *RemoteManager) watch(ctx context.Context, url string, cursor interface{}, wr interface{}) error {
  141. if cursor != nil {
  142. c, ok := cursor.(string)
  143. if !ok {
  144. return fmt.Errorf("internal error: RemoteManager.watch received non-string cursor")
  145. }
  146. url = fmt.Sprintf("%v?next=%v", url, c)
  147. }
  148. resp, err := m.httpGet(ctx, url)
  149. if err != nil {
  150. return err
  151. }
  152. if resp.StatusCode != http.StatusOK {
  153. return httpError(resp)
  154. }
  155. if err := json.NewDecoder(resp.Body).Decode(wr); err != nil {
  156. return err
  157. }
  158. return nil
  159. }
  160. func (m *RemoteManager) WatchLeases(ctx context.Context, network string, cursor interface{}) (subnet.LeaseWatchResult, error) {
  161. url := m.mkurl(network, "leases")
  162. wr := subnet.LeaseWatchResult{}
  163. err := m.watch(ctx, url, cursor, &wr)
  164. if err != nil {
  165. return subnet.LeaseWatchResult{}, err
  166. }
  167. if _, ok := wr.Cursor.(string); !ok {
  168. return subnet.LeaseWatchResult{}, fmt.Errorf("watch returned non-string cursor")
  169. }
  170. return wr, nil
  171. }
  172. func (m *RemoteManager) WatchNetworks(ctx context.Context, cursor interface{}) (subnet.NetworkWatchResult, error) {
  173. wr := subnet.NetworkWatchResult{}
  174. err := m.watch(ctx, m.base+"/", cursor, &wr)
  175. if err != nil {
  176. return subnet.NetworkWatchResult{}, err
  177. }
  178. if _, ok := wr.Cursor.(string); !ok {
  179. return subnet.NetworkWatchResult{}, fmt.Errorf("watch returned non-string cursor")
  180. }
  181. return wr, nil
  182. }
  183. func httpError(resp *http.Response) error {
  184. b, err := ioutil.ReadAll(resp.Body)
  185. if err != nil {
  186. return err
  187. }
  188. return fmt.Errorf("%v: %v", resp.Status, string(b))
  189. }
  190. type httpRespErr struct {
  191. resp *http.Response
  192. err error
  193. }
  194. func (m *RemoteManager) httpDo(ctx context.Context, req *http.Request) (*http.Response, error) {
  195. // Run the HTTP request in a goroutine (so it can be canceled) and pass
  196. // the result via the channel c
  197. client := &http.Client{Transport: m.transport}
  198. c := make(chan httpRespErr, 1)
  199. go func() {
  200. resp, err := client.Do(req)
  201. c <- httpRespErr{resp, err}
  202. }()
  203. select {
  204. case <-ctx.Done():
  205. m.transport.CancelRequest(req)
  206. <-c // Wait for f to return.
  207. return nil, ctx.Err()
  208. case r := <-c:
  209. return r.resp, r.err
  210. }
  211. }
  212. func (m *RemoteManager) httpGet(ctx context.Context, url string) (*http.Response, error) {
  213. req, err := http.NewRequest("GET", url, nil)
  214. if err != nil {
  215. return nil, err
  216. }
  217. return m.httpDo(ctx, req)
  218. }
  219. func (m *RemoteManager) httpPutPost(ctx context.Context, method, url, contentType string, body []byte) (*http.Response, error) {
  220. req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
  221. if err != nil {
  222. return nil, err
  223. }
  224. req.Header.Set("Content-Type", contentType)
  225. return m.httpDo(ctx, req)
  226. }