client.go 7.2 KB

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