client.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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/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. }
  95. // WithRequestTimeout sets a timeout duration for plugin requests
  96. func WithRequestTimeout(t time.Duration) func(*RequestOpts) {
  97. return func(o *RequestOpts) {
  98. o.Timeout = t
  99. }
  100. }
  101. // Call calls the specified method with the specified arguments for the plugin.
  102. // It will retry for 30 seconds if a failure occurs when calling.
  103. func (c *Client) Call(serviceMethod string, args, ret interface{}) error {
  104. return c.CallWithOptions(serviceMethod, args, ret)
  105. }
  106. // CallWithOptions is just like call except it takes options
  107. func (c *Client) CallWithOptions(serviceMethod string, args interface{}, ret interface{}, opts ...func(*RequestOpts)) error {
  108. var buf bytes.Buffer
  109. if args != nil {
  110. if err := json.NewEncoder(&buf).Encode(args); err != nil {
  111. return err
  112. }
  113. }
  114. body, err := c.callWithRetry(serviceMethod, &buf, true, opts...)
  115. if err != nil {
  116. return err
  117. }
  118. defer body.Close()
  119. if ret != nil {
  120. if err := json.NewDecoder(body).Decode(&ret); err != nil {
  121. log.G(context.TODO()).Errorf("%s: error reading plugin resp: %v", serviceMethod, err)
  122. return err
  123. }
  124. }
  125. return nil
  126. }
  127. // Stream calls the specified method with the specified arguments for the plugin and returns the response body
  128. func (c *Client) Stream(serviceMethod string, args interface{}) (io.ReadCloser, error) {
  129. var buf bytes.Buffer
  130. if err := json.NewEncoder(&buf).Encode(args); err != nil {
  131. return nil, err
  132. }
  133. return c.callWithRetry(serviceMethod, &buf, true)
  134. }
  135. // SendFile calls the specified method, and passes through the IO stream
  136. func (c *Client) SendFile(serviceMethod string, data io.Reader, ret interface{}) error {
  137. body, err := c.callWithRetry(serviceMethod, data, true)
  138. if err != nil {
  139. return err
  140. }
  141. defer body.Close()
  142. if err := json.NewDecoder(body).Decode(&ret); err != nil {
  143. log.G(context.TODO()).Errorf("%s: error reading plugin resp: %v", serviceMethod, err)
  144. return err
  145. }
  146. return nil
  147. }
  148. func (c *Client) callWithRetry(serviceMethod string, data io.Reader, retry bool, reqOpts ...func(*RequestOpts)) (io.ReadCloser, error) {
  149. var retries int
  150. start := time.Now()
  151. var opts RequestOpts
  152. for _, o := range reqOpts {
  153. o(&opts)
  154. }
  155. for {
  156. req, err := c.requestFactory.NewRequest(serviceMethod, data)
  157. if err != nil {
  158. return nil, err
  159. }
  160. cancelRequest := func() {}
  161. if opts.Timeout > 0 {
  162. var ctx context.Context
  163. ctx, cancelRequest = context.WithTimeout(req.Context(), opts.Timeout)
  164. req = req.WithContext(ctx)
  165. }
  166. resp, err := c.http.Do(req)
  167. if err != nil {
  168. cancelRequest()
  169. if !retry {
  170. return nil, err
  171. }
  172. timeOff := backoff(retries)
  173. if abort(start, timeOff) {
  174. return nil, err
  175. }
  176. retries++
  177. log.G(context.TODO()).Warnf("Unable to connect to plugin: %s%s: %v, retrying in %v", req.URL.Host, req.URL.Path, err, timeOff)
  178. time.Sleep(timeOff)
  179. continue
  180. }
  181. if resp.StatusCode != http.StatusOK {
  182. b, err := io.ReadAll(resp.Body)
  183. resp.Body.Close()
  184. cancelRequest()
  185. if err != nil {
  186. return nil, &statusError{resp.StatusCode, serviceMethod, err.Error()}
  187. }
  188. // Plugins' Response(s) should have an Err field indicating what went
  189. // wrong. Try to unmarshal into ResponseErr. Otherwise fallback to just
  190. // return the string(body)
  191. type responseErr struct {
  192. Err string
  193. }
  194. remoteErr := responseErr{}
  195. if err := json.Unmarshal(b, &remoteErr); err == nil {
  196. if remoteErr.Err != "" {
  197. return nil, &statusError{resp.StatusCode, serviceMethod, remoteErr.Err}
  198. }
  199. }
  200. // old way...
  201. return nil, &statusError{resp.StatusCode, serviceMethod, string(b)}
  202. }
  203. return ioutils.NewReadCloserWrapper(resp.Body, func() error {
  204. err := resp.Body.Close()
  205. cancelRequest()
  206. return err
  207. }), nil
  208. }
  209. }
  210. func backoff(retries int) time.Duration {
  211. b, max := 1, defaultTimeOut
  212. for b < max && retries > 0 {
  213. b *= 2
  214. retries--
  215. }
  216. if b > max {
  217. b = max
  218. }
  219. return time.Duration(b) * time.Second
  220. }
  221. func abort(start time.Time, timeOff time.Duration) bool {
  222. return timeOff+time.Since(start) >= time.Duration(defaultTimeOut)*time.Second
  223. }
  224. func httpScheme(u *url.URL) string {
  225. scheme := u.Scheme
  226. if scheme != "https" {
  227. scheme = "http"
  228. }
  229. return scheme
  230. }