options.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. package client
  2. import (
  3. "context"
  4. "net"
  5. "net/http"
  6. "os"
  7. "path/filepath"
  8. "time"
  9. "github.com/docker/go-connections/sockets"
  10. "github.com/docker/go-connections/tlsconfig"
  11. "github.com/pkg/errors"
  12. )
  13. // Opt is a configuration option to initialize a [Client].
  14. type Opt func(*Client) error
  15. // FromEnv configures the client with values from environment variables. It
  16. // is the equivalent of using the [WithTLSClientConfigFromEnv], [WithHostFromEnv],
  17. // and [WithVersionFromEnv] options.
  18. //
  19. // FromEnv uses the following environment variables:
  20. //
  21. // - DOCKER_HOST ([EnvOverrideHost]) to set the URL to the docker server.
  22. // - DOCKER_API_VERSION ([EnvOverrideAPIVersion]) to set the version of the
  23. // API to use, leave empty for latest.
  24. // - DOCKER_CERT_PATH ([EnvOverrideCertPath]) to specify the directory from
  25. // which to load the TLS certificates ("ca.pem", "cert.pem", "key.pem').
  26. // - DOCKER_TLS_VERIFY ([EnvTLSVerify]) to enable or disable TLS verification
  27. // (off by default).
  28. func FromEnv(c *Client) error {
  29. ops := []Opt{
  30. WithTLSClientConfigFromEnv(),
  31. WithHostFromEnv(),
  32. WithVersionFromEnv(),
  33. }
  34. for _, op := range ops {
  35. if err := op(c); err != nil {
  36. return err
  37. }
  38. }
  39. return nil
  40. }
  41. // WithDialContext applies the dialer to the client transport. This can be
  42. // used to set the Timeout and KeepAlive settings of the client. It returns
  43. // an error if the client does not have a [http.Transport] configured.
  44. func WithDialContext(dialContext func(ctx context.Context, network, addr string) (net.Conn, error)) Opt {
  45. return func(c *Client) error {
  46. if transport, ok := c.client.Transport.(*http.Transport); ok {
  47. transport.DialContext = dialContext
  48. return nil
  49. }
  50. return errors.Errorf("cannot apply dialer to transport: %T", c.client.Transport)
  51. }
  52. }
  53. // WithHost overrides the client host with the specified one.
  54. func WithHost(host string) Opt {
  55. return func(c *Client) error {
  56. hostURL, err := ParseHostURL(host)
  57. if err != nil {
  58. return err
  59. }
  60. c.host = host
  61. c.proto = hostURL.Scheme
  62. c.addr = hostURL.Host
  63. c.basePath = hostURL.Path
  64. if transport, ok := c.client.Transport.(*http.Transport); ok {
  65. return sockets.ConfigureTransport(transport, c.proto, c.addr)
  66. }
  67. return errors.Errorf("cannot apply host to transport: %T", c.client.Transport)
  68. }
  69. }
  70. // WithHostFromEnv overrides the client host with the host specified in the
  71. // DOCKER_HOST ([EnvOverrideHost]) environment variable. If DOCKER_HOST is not set,
  72. // or set to an empty value, the host is not modified.
  73. func WithHostFromEnv() Opt {
  74. return func(c *Client) error {
  75. if host := os.Getenv(EnvOverrideHost); host != "" {
  76. return WithHost(host)(c)
  77. }
  78. return nil
  79. }
  80. }
  81. // WithHTTPClient overrides the client's HTTP client with the specified one.
  82. func WithHTTPClient(client *http.Client) Opt {
  83. return func(c *Client) error {
  84. if client != nil {
  85. c.client = client
  86. }
  87. return nil
  88. }
  89. }
  90. // WithTimeout configures the time limit for requests made by the HTTP client.
  91. func WithTimeout(timeout time.Duration) Opt {
  92. return func(c *Client) error {
  93. c.client.Timeout = timeout
  94. return nil
  95. }
  96. }
  97. // WithUserAgent configures the User-Agent header to use for HTTP requests.
  98. // It overrides any User-Agent set in headers. When set to an empty string,
  99. // the User-Agent header is removed, and no header is sent.
  100. func WithUserAgent(ua string) Opt {
  101. return func(c *Client) error {
  102. c.userAgent = &ua
  103. return nil
  104. }
  105. }
  106. // WithHTTPHeaders appends custom HTTP headers to the client's default headers.
  107. // It does not allow for built-in headers (such as "User-Agent", if set) to
  108. // be overridden. Also see [WithUserAgent].
  109. func WithHTTPHeaders(headers map[string]string) Opt {
  110. return func(c *Client) error {
  111. c.customHTTPHeaders = headers
  112. return nil
  113. }
  114. }
  115. // WithScheme overrides the client scheme with the specified one.
  116. func WithScheme(scheme string) Opt {
  117. return func(c *Client) error {
  118. c.scheme = scheme
  119. return nil
  120. }
  121. }
  122. // WithTLSClientConfig applies a TLS config to the client transport.
  123. func WithTLSClientConfig(cacertPath, certPath, keyPath string) Opt {
  124. return func(c *Client) error {
  125. transport, ok := c.client.Transport.(*http.Transport)
  126. if !ok {
  127. return errors.Errorf("cannot apply tls config to transport: %T", c.client.Transport)
  128. }
  129. config, err := tlsconfig.Client(tlsconfig.Options{
  130. CAFile: cacertPath,
  131. CertFile: certPath,
  132. KeyFile: keyPath,
  133. ExclusiveRootPools: true,
  134. })
  135. if err != nil {
  136. return errors.Wrap(err, "failed to create tls config")
  137. }
  138. transport.TLSClientConfig = config
  139. return nil
  140. }
  141. }
  142. // WithTLSClientConfigFromEnv configures the client's TLS settings with the
  143. // settings in the DOCKER_CERT_PATH ([EnvOverrideCertPath]) and DOCKER_TLS_VERIFY
  144. // ([EnvTLSVerify]) environment variables. If DOCKER_CERT_PATH is not set or empty,
  145. // TLS configuration is not modified.
  146. //
  147. // WithTLSClientConfigFromEnv uses the following environment variables:
  148. //
  149. // - DOCKER_CERT_PATH ([EnvOverrideCertPath]) to specify the directory from
  150. // which to load the TLS certificates ("ca.pem", "cert.pem", "key.pem").
  151. // - DOCKER_TLS_VERIFY ([EnvTLSVerify]) to enable or disable TLS verification
  152. // (off by default).
  153. func WithTLSClientConfigFromEnv() Opt {
  154. return func(c *Client) error {
  155. dockerCertPath := os.Getenv(EnvOverrideCertPath)
  156. if dockerCertPath == "" {
  157. return nil
  158. }
  159. tlsc, err := tlsconfig.Client(tlsconfig.Options{
  160. CAFile: filepath.Join(dockerCertPath, "ca.pem"),
  161. CertFile: filepath.Join(dockerCertPath, "cert.pem"),
  162. KeyFile: filepath.Join(dockerCertPath, "key.pem"),
  163. InsecureSkipVerify: os.Getenv(EnvTLSVerify) == "",
  164. })
  165. if err != nil {
  166. return err
  167. }
  168. c.client = &http.Client{
  169. Transport: &http.Transport{TLSClientConfig: tlsc},
  170. CheckRedirect: CheckRedirect,
  171. }
  172. return nil
  173. }
  174. }
  175. // WithVersion overrides the client version with the specified one. If an empty
  176. // version is provided, the value is ignored to allow version negotiation
  177. // (see [WithAPIVersionNegotiation]).
  178. func WithVersion(version string) Opt {
  179. return func(c *Client) error {
  180. if version != "" {
  181. c.version = version
  182. c.manualOverride = true
  183. }
  184. return nil
  185. }
  186. }
  187. // WithVersionFromEnv overrides the client version with the version specified in
  188. // the DOCKER_API_VERSION ([EnvOverrideAPIVersion]) environment variable.
  189. // If DOCKER_API_VERSION is not set, or set to an empty value, the version
  190. // is not modified.
  191. func WithVersionFromEnv() Opt {
  192. return func(c *Client) error {
  193. return WithVersion(os.Getenv(EnvOverrideAPIVersion))(c)
  194. }
  195. }
  196. // WithAPIVersionNegotiation enables automatic API version negotiation for the client.
  197. // With this option enabled, the client automatically negotiates the API version
  198. // to use when making requests. API version negotiation is performed on the first
  199. // request; subsequent requests do not re-negotiate.
  200. func WithAPIVersionNegotiation() Opt {
  201. return func(c *Client) error {
  202. c.negotiateVersion = true
  203. return nil
  204. }
  205. }