client.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. /*
  2. Package client is a Go client for the Docker Engine API.
  3. For more information about the Engine API, see the documentation:
  4. https://docs.docker.com/engine/api/
  5. # Usage
  6. You use the library by constructing a client object using [NewClientWithOpts]
  7. and calling methods on it. The client can be configured from environment
  8. variables by passing the [FromEnv] option, or configured manually by passing any
  9. of the other available [Opts].
  10. For example, to list running containers (the equivalent of "docker ps"):
  11. package main
  12. import (
  13. "context"
  14. "fmt"
  15. "github.com/docker/docker/api/types/container"
  16. "github.com/docker/docker/client"
  17. )
  18. func main() {
  19. cli, err := client.NewClientWithOpts(client.FromEnv)
  20. if err != nil {
  21. panic(err)
  22. }
  23. containers, err := cli.ContainerList(context.Background(), container.ListOptions{})
  24. if err != nil {
  25. panic(err)
  26. }
  27. for _, ctr := range containers {
  28. fmt.Printf("%s %s\n", ctr.ID, ctr.Image)
  29. }
  30. }
  31. */
  32. package client // import "github.com/docker/docker/client"
  33. import (
  34. "context"
  35. "crypto/tls"
  36. "net"
  37. "net/http"
  38. "net/url"
  39. "path"
  40. "strings"
  41. "time"
  42. "github.com/docker/docker/api"
  43. "github.com/docker/docker/api/types"
  44. "github.com/docker/docker/api/types/versions"
  45. "github.com/docker/go-connections/sockets"
  46. "github.com/pkg/errors"
  47. "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
  48. "go.opentelemetry.io/otel/trace"
  49. )
  50. // DummyHost is a hostname used for local communication.
  51. //
  52. // It acts as a valid formatted hostname for local connections (such as "unix://"
  53. // or "npipe://") which do not require a hostname. It should never be resolved,
  54. // but uses the special-purpose ".localhost" TLD (as defined in [RFC 2606, Section 2]
  55. // and [RFC 6761, Section 6.3]).
  56. //
  57. // [RFC 7230, Section 5.4] defines that an empty header must be used for such
  58. // cases:
  59. //
  60. // If the authority component is missing or undefined for the target URI,
  61. // then a client MUST send a Host header field with an empty field-value.
  62. //
  63. // However, [Go stdlib] enforces the semantics of HTTP(S) over TCP, does not
  64. // allow an empty header to be used, and requires req.URL.Scheme to be either
  65. // "http" or "https".
  66. //
  67. // For further details, refer to:
  68. //
  69. // - https://github.com/docker/engine-api/issues/189
  70. // - https://github.com/golang/go/issues/13624
  71. // - https://github.com/golang/go/issues/61076
  72. // - https://github.com/moby/moby/issues/45935
  73. //
  74. // [RFC 2606, Section 2]: https://www.rfc-editor.org/rfc/rfc2606.html#section-2
  75. // [RFC 6761, Section 6.3]: https://www.rfc-editor.org/rfc/rfc6761#section-6.3
  76. // [RFC 7230, Section 5.4]: https://datatracker.ietf.org/doc/html/rfc7230#section-5.4
  77. // [Go stdlib]: https://github.com/golang/go/blob/6244b1946bc2101b01955468f1be502dbadd6807/src/net/http/transport.go#L558-L569
  78. const DummyHost = "api.moby.localhost"
  79. // fallbackAPIVersion is the version to fallback to if API-version negotiation
  80. // fails. This version is the highest version of the API before API-version
  81. // negotiation was introduced. If negotiation fails (or no API version was
  82. // included in the API response), we assume the API server uses the most
  83. // recent version before negotiation was introduced.
  84. const fallbackAPIVersion = "1.24"
  85. // Client is the API client that performs all operations
  86. // against a docker server.
  87. type Client struct {
  88. // scheme sets the scheme for the client
  89. scheme string
  90. // host holds the server address to connect to
  91. host string
  92. // proto holds the client protocol i.e. unix.
  93. proto string
  94. // addr holds the client address.
  95. addr string
  96. // basePath holds the path to prepend to the requests.
  97. basePath string
  98. // client used to send and receive http requests.
  99. client *http.Client
  100. // version of the server to talk to.
  101. version string
  102. // userAgent is the User-Agent header to use for HTTP requests. It takes
  103. // precedence over User-Agent headers set in customHTTPHeaders, and other
  104. // header variables. When set to an empty string, the User-Agent header
  105. // is removed, and no header is sent.
  106. userAgent *string
  107. // custom HTTP headers configured by users.
  108. customHTTPHeaders map[string]string
  109. // manualOverride is set to true when the version was set by users.
  110. manualOverride bool
  111. // negotiateVersion indicates if the client should automatically negotiate
  112. // the API version to use when making requests. API version negotiation is
  113. // performed on the first request, after which negotiated is set to "true"
  114. // so that subsequent requests do not re-negotiate.
  115. negotiateVersion bool
  116. // negotiated indicates that API version negotiation took place
  117. negotiated bool
  118. tp trace.TracerProvider
  119. // When the client transport is an *http.Transport (default) we need to do some extra things (like closing idle connections).
  120. // Store the original transport as the http.Client transport will be wrapped with tracing libs.
  121. baseTransport *http.Transport
  122. }
  123. // ErrRedirect is the error returned by checkRedirect when the request is non-GET.
  124. var ErrRedirect = errors.New("unexpected redirect in response")
  125. // CheckRedirect specifies the policy for dealing with redirect responses. It
  126. // can be set on [http.Client.CheckRedirect] to prevent HTTP redirects for
  127. // non-GET requests. It returns an [ErrRedirect] for non-GET request, otherwise
  128. // returns a [http.ErrUseLastResponse], which is special-cased by http.Client
  129. // to use the last response.
  130. //
  131. // Go 1.8 changed behavior for HTTP redirects (specifically 301, 307, and 308)
  132. // in the client. The client (and by extension API client) can be made to send
  133. // a request like "POST /containers//start" where what would normally be in the
  134. // name section of the URL is empty. This triggers an HTTP 301 from the daemon.
  135. //
  136. // In go 1.8 this 301 is converted to a GET request, and ends up getting
  137. // a 404 from the daemon. This behavior change manifests in the client in that
  138. // before, the 301 was not followed and the client did not generate an error,
  139. // but now results in a message like "Error response from daemon: page not found".
  140. func CheckRedirect(_ *http.Request, via []*http.Request) error {
  141. if via[0].Method == http.MethodGet {
  142. return http.ErrUseLastResponse
  143. }
  144. return ErrRedirect
  145. }
  146. // NewClientWithOpts initializes a new API client with a default HTTPClient, and
  147. // default API host and version. It also initializes the custom HTTP headers to
  148. // add to each request.
  149. //
  150. // It takes an optional list of [Opt] functional arguments, which are applied in
  151. // the order they're provided, which allows modifying the defaults when creating
  152. // the client. For example, the following initializes a client that configures
  153. // itself with values from environment variables ([FromEnv]), and has automatic
  154. // API version negotiation enabled ([WithAPIVersionNegotiation]).
  155. //
  156. // cli, err := client.NewClientWithOpts(
  157. // client.FromEnv,
  158. // client.WithAPIVersionNegotiation(),
  159. // )
  160. func NewClientWithOpts(ops ...Opt) (*Client, error) {
  161. hostURL, err := ParseHostURL(DefaultDockerHost)
  162. if err != nil {
  163. return nil, err
  164. }
  165. client, err := defaultHTTPClient(hostURL)
  166. if err != nil {
  167. return nil, err
  168. }
  169. c := &Client{
  170. host: DefaultDockerHost,
  171. version: api.DefaultVersion,
  172. client: client,
  173. proto: hostURL.Scheme,
  174. addr: hostURL.Host,
  175. }
  176. for _, op := range ops {
  177. if err := op(c); err != nil {
  178. return nil, err
  179. }
  180. }
  181. if tr, ok := c.client.Transport.(*http.Transport); ok {
  182. // Store the base transport before we wrap it in tracing libs below
  183. // This is used, as an example, to close idle connections when the client is closed
  184. c.baseTransport = tr
  185. }
  186. if c.scheme == "" {
  187. // TODO(stevvooe): This isn't really the right way to write clients in Go.
  188. // `NewClient` should probably only take an `*http.Client` and work from there.
  189. // Unfortunately, the model of having a host-ish/url-thingy as the connection
  190. // string has us confusing protocol and transport layers. We continue doing
  191. // this to avoid breaking existing clients but this should be addressed.
  192. if c.tlsConfig() != nil {
  193. c.scheme = "https"
  194. } else {
  195. c.scheme = "http"
  196. }
  197. }
  198. c.client.Transport = otelhttp.NewTransport(
  199. c.client.Transport,
  200. otelhttp.WithTracerProvider(c.tp),
  201. otelhttp.WithSpanNameFormatter(func(_ string, req *http.Request) string {
  202. return req.Method + " " + req.URL.Path
  203. }),
  204. )
  205. return c, nil
  206. }
  207. func (cli *Client) tlsConfig() *tls.Config {
  208. if cli.baseTransport == nil {
  209. return nil
  210. }
  211. return cli.baseTransport.TLSClientConfig
  212. }
  213. func defaultHTTPClient(hostURL *url.URL) (*http.Client, error) {
  214. transport := &http.Transport{}
  215. err := sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host)
  216. if err != nil {
  217. return nil, err
  218. }
  219. return &http.Client{
  220. Transport: transport,
  221. CheckRedirect: CheckRedirect,
  222. }, nil
  223. }
  224. // Close the transport used by the client
  225. func (cli *Client) Close() error {
  226. if cli.baseTransport != nil {
  227. cli.baseTransport.CloseIdleConnections()
  228. return nil
  229. }
  230. return nil
  231. }
  232. // checkVersion manually triggers API version negotiation (if configured).
  233. // This allows for version-dependent code to use the same version as will
  234. // be negotiated when making the actual requests, and for which cases
  235. // we cannot do the negotiation lazily.
  236. func (cli *Client) checkVersion(ctx context.Context) {
  237. if cli.negotiateVersion && !cli.negotiated {
  238. cli.NegotiateAPIVersion(ctx)
  239. }
  240. }
  241. // getAPIPath returns the versioned request path to call the API.
  242. // It appends the query parameters to the path if they are not empty.
  243. func (cli *Client) getAPIPath(ctx context.Context, p string, query url.Values) string {
  244. var apiPath string
  245. cli.checkVersion(ctx)
  246. if cli.version != "" {
  247. v := strings.TrimPrefix(cli.version, "v")
  248. apiPath = path.Join(cli.basePath, "/v"+v, p)
  249. } else {
  250. apiPath = path.Join(cli.basePath, p)
  251. }
  252. return (&url.URL{Path: apiPath, RawQuery: query.Encode()}).String()
  253. }
  254. // ClientVersion returns the API version used by this client.
  255. func (cli *Client) ClientVersion() string {
  256. return cli.version
  257. }
  258. // NegotiateAPIVersion queries the API and updates the version to match the API
  259. // version. NegotiateAPIVersion downgrades the client's API version to match the
  260. // APIVersion if the ping version is lower than the default version. If the API
  261. // version reported by the server is higher than the maximum version supported
  262. // by the client, it uses the client's maximum version.
  263. //
  264. // If a manual override is in place, either through the "DOCKER_API_VERSION"
  265. // ([EnvOverrideAPIVersion]) environment variable, or if the client is initialized
  266. // with a fixed version ([WithVersion]), no negotiation is performed.
  267. //
  268. // If the API server's ping response does not contain an API version, or if the
  269. // client did not get a successful ping response, it assumes it is connected with
  270. // an old daemon that does not support API version negotiation, in which case it
  271. // downgrades to the latest version of the API before version negotiation was
  272. // added (1.24).
  273. func (cli *Client) NegotiateAPIVersion(ctx context.Context) {
  274. if !cli.manualOverride {
  275. ping, _ := cli.Ping(ctx)
  276. cli.negotiateAPIVersionPing(ping)
  277. }
  278. }
  279. // NegotiateAPIVersionPing downgrades the client's API version to match the
  280. // APIVersion in the ping response. If the API version in pingResponse is higher
  281. // than the maximum version supported by the client, it uses the client's maximum
  282. // version.
  283. //
  284. // If a manual override is in place, either through the "DOCKER_API_VERSION"
  285. // ([EnvOverrideAPIVersion]) environment variable, or if the client is initialized
  286. // with a fixed version ([WithVersion]), no negotiation is performed.
  287. //
  288. // If the API server's ping response does not contain an API version, we assume
  289. // we are connected with an old daemon without API version negotiation support,
  290. // and downgrade to the latest version of the API before version negotiation was
  291. // added (1.24).
  292. func (cli *Client) NegotiateAPIVersionPing(pingResponse types.Ping) {
  293. if !cli.manualOverride {
  294. cli.negotiateAPIVersionPing(pingResponse)
  295. }
  296. }
  297. // negotiateAPIVersionPing queries the API and updates the version to match the
  298. // API version from the ping response.
  299. func (cli *Client) negotiateAPIVersionPing(pingResponse types.Ping) {
  300. // default to the latest version before versioning headers existed
  301. if pingResponse.APIVersion == "" {
  302. pingResponse.APIVersion = fallbackAPIVersion
  303. }
  304. // if the client is not initialized with a version, start with the latest supported version
  305. if cli.version == "" {
  306. cli.version = api.DefaultVersion
  307. }
  308. // if server version is lower than the client version, downgrade
  309. if versions.LessThan(pingResponse.APIVersion, cli.version) {
  310. cli.version = pingResponse.APIVersion
  311. }
  312. // Store the results, so that automatic API version negotiation (if enabled)
  313. // won't be performed on the next request.
  314. if cli.negotiateVersion {
  315. cli.negotiated = true
  316. }
  317. }
  318. // DaemonHost returns the host address used by the client
  319. func (cli *Client) DaemonHost() string {
  320. return cli.host
  321. }
  322. // HTTPClient returns a copy of the HTTP client bound to the server
  323. func (cli *Client) HTTPClient() *http.Client {
  324. c := *cli.client
  325. return &c
  326. }
  327. // ParseHostURL parses a url string, validates the string is a host url, and
  328. // returns the parsed URL
  329. func ParseHostURL(host string) (*url.URL, error) {
  330. proto, addr, ok := strings.Cut(host, "://")
  331. if !ok || addr == "" {
  332. return nil, errors.Errorf("unable to parse docker host `%s`", host)
  333. }
  334. var basePath string
  335. if proto == "tcp" {
  336. parsed, err := url.Parse("tcp://" + addr)
  337. if err != nil {
  338. return nil, err
  339. }
  340. addr = parsed.Host
  341. basePath = parsed.Path
  342. }
  343. return &url.URL{
  344. Scheme: proto,
  345. Host: addr,
  346. Path: basePath,
  347. }, nil
  348. }
  349. func (cli *Client) dialerFromTransport() func(context.Context, string, string) (net.Conn, error) {
  350. if cli.baseTransport == nil || cli.baseTransport.DialContext == nil {
  351. return nil
  352. }
  353. if cli.baseTransport.TLSClientConfig != nil {
  354. // When using a tls config we don't use the configured dialer but instead a fallback dialer...
  355. // Note: It seems like this should use the normal dialer and wrap the returned net.Conn in a tls.Conn
  356. // I honestly don't know why it doesn't do that, but it doesn't and such a change is entirely unrelated to the change in this commit.
  357. return nil
  358. }
  359. return cli.baseTransport.DialContext
  360. }
  361. // Dialer returns a dialer for a raw stream connection, with an HTTP/1.1 header,
  362. // that can be used for proxying the daemon connection. It is used by
  363. // ["docker dial-stdio"].
  364. //
  365. // ["docker dial-stdio"]: https://github.com/docker/cli/pull/1014
  366. func (cli *Client) Dialer() func(context.Context) (net.Conn, error) {
  367. return func(ctx context.Context) (net.Conn, error) {
  368. if dialFn := cli.dialerFromTransport(); dialFn != nil {
  369. return dialFn(ctx, cli.proto, cli.addr)
  370. }
  371. switch cli.proto {
  372. case "unix":
  373. return net.Dial(cli.proto, cli.addr)
  374. case "npipe":
  375. return sockets.DialPipe(cli.addr, 32*time.Second)
  376. default:
  377. if tlsConfig := cli.tlsConfig(); tlsConfig != nil {
  378. return tls.Dial(cli.proto, cli.addr, tlsConfig)
  379. }
  380. return net.Dial(cli.proto, cli.addr)
  381. }
  382. }
  383. }