client.go 6.5 KB

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