client.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. package plugins
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. "net/url"
  10. "time"
  11. "github.com/docker/docker/pkg/ioutils"
  12. "github.com/docker/docker/pkg/plugins/transport"
  13. "github.com/docker/go-connections/sockets"
  14. "github.com/docker/go-connections/tlsconfig"
  15. "github.com/sirupsen/logrus"
  16. )
  17. const (
  18. defaultTimeOut = 30
  19. )
  20. func newTransport(addr string, tlsConfig *tlsconfig.Options) (transport.Transport, error) {
  21. tr := &http.Transport{}
  22. if tlsConfig != nil {
  23. c, err := tlsconfig.Client(*tlsConfig)
  24. if err != nil {
  25. return nil, err
  26. }
  27. tr.TLSClientConfig = c
  28. }
  29. u, err := url.Parse(addr)
  30. if err != nil {
  31. return nil, err
  32. }
  33. socket := u.Host
  34. if socket == "" {
  35. // valid local socket addresses have the host empty.
  36. socket = u.Path
  37. }
  38. if err := sockets.ConfigureTransport(tr, u.Scheme, socket); err != nil {
  39. return nil, err
  40. }
  41. scheme := httpScheme(u)
  42. return transport.NewHTTPTransport(tr, scheme, socket), nil
  43. }
  44. // NewClient creates a new plugin client (http).
  45. func NewClient(addr string, tlsConfig *tlsconfig.Options) (*Client, error) {
  46. clientTransport, err := newTransport(addr, tlsConfig)
  47. if err != nil {
  48. return nil, err
  49. }
  50. return newClientWithTransport(clientTransport, 0), nil
  51. }
  52. // NewClientWithTimeout creates a new plugin client (http).
  53. func NewClientWithTimeout(addr string, tlsConfig *tlsconfig.Options, timeout time.Duration) (*Client, error) {
  54. clientTransport, err := newTransport(addr, tlsConfig)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return newClientWithTransport(clientTransport, timeout), nil
  59. }
  60. // newClientWithTransport creates a new plugin client with a given transport.
  61. func newClientWithTransport(tr transport.Transport, timeout time.Duration) *Client {
  62. return &Client{
  63. http: &http.Client{
  64. Transport: tr,
  65. Timeout: timeout,
  66. },
  67. requestFactory: tr,
  68. }
  69. }
  70. // Client represents a plugin client.
  71. type Client struct {
  72. http *http.Client // http client to use
  73. requestFactory transport.RequestFactory
  74. }
  75. // RequestOpts is the set of options that can be passed into a request
  76. type RequestOpts struct {
  77. Timeout time.Duration
  78. }
  79. // WithRequestTimeout sets a timeout duration for plugin requests
  80. func WithRequestTimeout(t time.Duration) func(*RequestOpts) {
  81. return func(o *RequestOpts) {
  82. o.Timeout = t
  83. }
  84. }
  85. // Call calls the specified method with the specified arguments for the plugin.
  86. // It will retry for 30 seconds if a failure occurs when calling.
  87. func (c *Client) Call(serviceMethod string, args, ret interface{}) error {
  88. return c.CallWithOptions(serviceMethod, args, ret)
  89. }
  90. // CallWithOptions is just like call except it takes options
  91. func (c *Client) CallWithOptions(serviceMethod string, args interface{}, ret interface{}, opts ...func(*RequestOpts)) error {
  92. var buf bytes.Buffer
  93. if args != nil {
  94. if err := json.NewEncoder(&buf).Encode(args); err != nil {
  95. return err
  96. }
  97. }
  98. body, err := c.callWithRetry(serviceMethod, &buf, true, opts...)
  99. if err != nil {
  100. return err
  101. }
  102. defer body.Close()
  103. if ret != nil {
  104. if err := json.NewDecoder(body).Decode(&ret); err != nil {
  105. logrus.Errorf("%s: error reading plugin resp: %v", serviceMethod, err)
  106. return err
  107. }
  108. }
  109. return nil
  110. }
  111. // Stream calls the specified method with the specified arguments for the plugin and returns the response body
  112. func (c *Client) Stream(serviceMethod string, args interface{}) (io.ReadCloser, error) {
  113. var buf bytes.Buffer
  114. if err := json.NewEncoder(&buf).Encode(args); err != nil {
  115. return nil, err
  116. }
  117. return c.callWithRetry(serviceMethod, &buf, true)
  118. }
  119. // SendFile calls the specified method, and passes through the IO stream
  120. func (c *Client) SendFile(serviceMethod string, data io.Reader, ret interface{}) error {
  121. body, err := c.callWithRetry(serviceMethod, data, true)
  122. if err != nil {
  123. return err
  124. }
  125. defer body.Close()
  126. if err := json.NewDecoder(body).Decode(&ret); err != nil {
  127. logrus.Errorf("%s: error reading plugin resp: %v", serviceMethod, err)
  128. return err
  129. }
  130. return nil
  131. }
  132. func (c *Client) callWithRetry(serviceMethod string, data io.Reader, retry bool, reqOpts ...func(*RequestOpts)) (io.ReadCloser, error) {
  133. var retries int
  134. start := time.Now()
  135. var opts RequestOpts
  136. for _, o := range reqOpts {
  137. o(&opts)
  138. }
  139. for {
  140. req, err := c.requestFactory.NewRequest(serviceMethod, data)
  141. if err != nil {
  142. return nil, err
  143. }
  144. cancelRequest := func() {}
  145. if opts.Timeout > 0 {
  146. var ctx context.Context
  147. ctx, cancelRequest = context.WithTimeout(req.Context(), opts.Timeout)
  148. req = req.WithContext(ctx)
  149. }
  150. resp, err := c.http.Do(req)
  151. if err != nil {
  152. cancelRequest()
  153. if !retry {
  154. return nil, err
  155. }
  156. timeOff := backoff(retries)
  157. if abort(start, timeOff) {
  158. return nil, err
  159. }
  160. retries++
  161. logrus.Warnf("Unable to connect to plugin: %s%s: %v, retrying in %v", req.URL.Host, req.URL.Path, err, timeOff)
  162. time.Sleep(timeOff)
  163. continue
  164. }
  165. if resp.StatusCode != http.StatusOK {
  166. b, err := ioutil.ReadAll(resp.Body)
  167. resp.Body.Close()
  168. cancelRequest()
  169. if err != nil {
  170. return nil, &statusError{resp.StatusCode, serviceMethod, err.Error()}
  171. }
  172. // Plugins' Response(s) should have an Err field indicating what went
  173. // wrong. Try to unmarshal into ResponseErr. Otherwise fallback to just
  174. // return the string(body)
  175. type responseErr struct {
  176. Err string
  177. }
  178. remoteErr := responseErr{}
  179. if err := json.Unmarshal(b, &remoteErr); err == nil {
  180. if remoteErr.Err != "" {
  181. return nil, &statusError{resp.StatusCode, serviceMethod, remoteErr.Err}
  182. }
  183. }
  184. // old way...
  185. return nil, &statusError{resp.StatusCode, serviceMethod, string(b)}
  186. }
  187. return ioutils.NewReadCloserWrapper(resp.Body, func() error {
  188. err := resp.Body.Close()
  189. cancelRequest()
  190. return err
  191. }), nil
  192. }
  193. }
  194. func backoff(retries int) time.Duration {
  195. b, max := 1, defaultTimeOut
  196. for b < max && retries > 0 {
  197. b *= 2
  198. retries--
  199. }
  200. if b > max {
  201. b = max
  202. }
  203. return time.Duration(b) * time.Second
  204. }
  205. func abort(start time.Time, timeOff time.Duration) bool {
  206. return timeOff+time.Since(start) >= time.Duration(defaultTimeOut)*time.Second
  207. }
  208. func httpScheme(u *url.URL) string {
  209. scheme := u.Scheme
  210. if scheme != "https" {
  211. scheme = "http"
  212. }
  213. return scheme
  214. }