Merge pull request #1458 from crazy-max/dependabot/go_modules/github.com/docker/docker-28.3.3incompatible

chore(deps): bump github.com/docker/docker from 27.3.1+incompatible to 28.3.3+incompatible
This commit is contained in:
CrazyMax
2025-08-03 17:13:49 +02:00
committed by GitHub
205 changed files with 5397 additions and 2910 deletions

5
go.mod
View File

@@ -14,7 +14,7 @@ require (
github.com/crazy-max/gohealthchecks v0.5.0 github.com/crazy-max/gohealthchecks v0.5.0
github.com/crazy-max/gonfig v0.7.1 github.com/crazy-max/gonfig v0.7.1
github.com/distribution/reference v0.6.0 github.com/distribution/reference v0.6.0
github.com/docker/docker v27.3.1+incompatible github.com/docker/docker v28.3.3+incompatible
github.com/docker/go-connections v0.5.0 github.com/docker/go-connections v0.5.0
github.com/docker/go-units v0.5.0 github.com/docker/go-units v0.5.0
github.com/dromara/carbon/v2 v2.6.11 github.com/dromara/carbon/v2 v2.6.11
@@ -63,6 +63,8 @@ require (
github.com/andybalholm/cascadia v1.3.2 // indirect github.com/andybalholm/cascadia v1.3.2 // indirect
github.com/aokoli/goutils v1.0.1 // indirect github.com/aokoli/goutils v1.0.1 // indirect
github.com/aymerick/douceur v0.2.0 // indirect github.com/aymerick/douceur v0.2.0 // indirect
github.com/containerd/errdefs v0.3.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect github.com/containerd/log v0.1.0 // indirect
github.com/containerd/typeurl/v2 v2.2.0 // indirect github.com/containerd/typeurl/v2 v2.2.0 // indirect
github.com/containers/libtrust v0.0.0-20230121012942-c1716e8a8d01 // indirect github.com/containers/libtrust v0.0.0-20230121012942-c1716e8a8d01 // indirect
@@ -113,6 +115,7 @@ require (
github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/sys/atomicwriter v0.1.0 // indirect
github.com/moby/sys/capability v0.3.0 // indirect github.com/moby/sys/capability v0.3.0 // indirect
github.com/moby/sys/mountinfo v0.7.2 // indirect github.com/moby/sys/mountinfo v0.7.2 // indirect
github.com/moby/sys/user v0.3.0 // indirect github.com/moby/sys/user v0.3.0 // indirect

12
go.sum
View File

@@ -53,6 +53,10 @@ github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5P
github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8=
github.com/containerd/errdefs v0.3.0 h1:FSZgGOeK4yuT/+DnF07/Olde/q4KBoMsaamhXxIMDp4=
github.com/containerd/errdefs v0.3.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I=
github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo=
github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A=
@@ -86,8 +90,8 @@ github.com/docker/cli v27.3.1+incompatible h1:qEGdFBF3Xu6SCvCYhc7CzaQTlBmqDuzxPD
github.com/docker/cli v27.3.1+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/cli v27.3.1+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk= github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk=
github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/docker/docker v27.3.1+incompatible h1:KttF0XoteNTicmUtBO0L2tP+J7FGRFTjaEF4k6WdhfI= github.com/docker/docker v28.3.3+incompatible h1:Dypm25kh4rmk49v1eiVbsAtpAsYURjYkaKubwuBdxEI=
github.com/docker/docker v27.3.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/docker v28.3.3+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/docker/docker-credential-helpers v0.8.2 h1:bX3YxiGzFP5sOXWc3bTPEXdEaZSeVMrFgOr3T+zrFAo= github.com/docker/docker-credential-helpers v0.8.2 h1:bX3YxiGzFP5sOXWc3bTPEXdEaZSeVMrFgOr3T+zrFAo=
github.com/docker/docker-credential-helpers v0.8.2/go.mod h1:P3ci7E3lwkZg6XiHdRKft1KckHiO9a2rNtyFbZ/ry9M= github.com/docker/docker-credential-helpers v0.8.2/go.mod h1:P3ci7E3lwkZg6XiHdRKft1KckHiO9a2rNtyFbZ/ry9M=
github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c= github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=
@@ -248,10 +252,14 @@ github.com/moby/buildkit v0.17.3 h1:XN8ddC5gO1kGJJfi86kzvDlPOyLyPk66hTvswqhj6NQ=
github.com/moby/buildkit v0.17.3/go.mod h1:vr5vltV8wt4F2jThbNOChfbAklJ0DOW11w36v210hOg= github.com/moby/buildkit v0.17.3/go.mod h1:vr5vltV8wt4F2jThbNOChfbAklJ0DOW11w36v210hOg=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
github.com/moby/sys/atomicwriter v0.1.0 h1:kw5D/EqkBwsBFi0ss9v1VG3wIkVhzGvLklJ+w3A14Sw=
github.com/moby/sys/atomicwriter v0.1.0/go.mod h1:Ul8oqv2ZMNHOceF643P6FKPXeCmYtlQMvpizfsSoaWs=
github.com/moby/sys/capability v0.3.0 h1:kEP+y6te0gEXIaeQhIi0s7vKs/w0RPoH1qPa6jROcVg= github.com/moby/sys/capability v0.3.0 h1:kEP+y6te0gEXIaeQhIi0s7vKs/w0RPoH1qPa6jROcVg=
github.com/moby/sys/capability v0.3.0/go.mod h1:4g9IK291rVkms3LKCDOoYlnV8xKwoDTpIrNEE35Wq0I= github.com/moby/sys/capability v0.3.0/go.mod h1:4g9IK291rVkms3LKCDOoYlnV8xKwoDTpIrNEE35Wq0I=
github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9KouLrg= github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9KouLrg=
github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4= github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4=
github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU=
github.com/moby/sys/sequential v0.6.0/go.mod h1:uyv8EUTrca5PnDsdMGXhZe6CCe8U/UiTWd+lL+7b/Ko=
github.com/moby/sys/user v0.3.0 h1:9ni5DlcW5an3SvRSx4MouotOygvzaXbaSrc/wGDFWPo= github.com/moby/sys/user v0.3.0 h1:9ni5DlcW5an3SvRSx4MouotOygvzaXbaSrc/wGDFWPo=
github.com/moby/sys/user v0.3.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs= github.com/moby/sys/user v0.3.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs=
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=

View File

@@ -9,7 +9,7 @@ import (
"github.com/crazy-max/diun/v4/internal/model" "github.com/crazy-max/diun/v4/internal/model"
"github.com/crazy-max/diun/v4/internal/provider" "github.com/crazy-max/diun/v4/internal/provider"
"github.com/crazy-max/diun/v4/pkg/docker" "github.com/crazy-max/diun/v4/pkg/docker"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/docker/go-units" "github.com/docker/go-units"
) )
@@ -43,7 +43,7 @@ func (c *Client) listContainerImage() []model.Image {
var list []model.Image var list []model.Image
for _, ctn := range ctns { for _, ctn := range ctns {
imageName := ctn.Image imageName := ctn.Image
imageRaw, err := cli.ImageInspectWithRaw(imageName) imageInfo, err := cli.ImageInspect(imageName)
if err != nil { if err != nil {
c.logger.Error().Err(err). c.logger.Error().Err(err).
Str("ctn_id", ctn.ID). Str("ctn_id", ctn.ID).
@@ -52,7 +52,7 @@ func (c *Client) listContainerImage() []model.Image {
continue continue
} }
if local := cli.IsLocalImage(imageRaw); local { if local := cli.IsLocalImage(imageInfo); local {
c.logger.Debug(). c.logger.Debug().
Str("ctn_id", ctn.ID). Str("ctn_id", ctn.ID).
Str("ctn_image", imageName). Str("ctn_image", imageName).
@@ -60,7 +60,7 @@ func (c *Client) listContainerImage() []model.Image {
continue continue
} }
if dangling := cli.IsDanglingImage(imageRaw); dangling { if dangling := cli.IsDanglingImage(imageInfo); dangling {
c.logger.Debug(). c.logger.Debug().
Str("ctn_id", ctn.ID). Str("ctn_id", ctn.ID).
Str("ctn_image", imageName). Str("ctn_image", imageName).
@@ -69,18 +69,18 @@ func (c *Client) listContainerImage() []model.Image {
} }
if cli.IsDigest(imageName) { if cli.IsDigest(imageName) {
if len(imageRaw.RepoDigests) > 0 { if len(imageInfo.RepoDigests) > 0 {
c.logger.Debug(). c.logger.Debug().
Str("ctn_id", ctn.ID). Str("ctn_id", ctn.ID).
Str("ctn_image", imageName). Str("ctn_image", imageName).
Strs("img_repodigests", imageRaw.RepoDigests). Strs("img_repodigests", imageInfo.RepoDigests).
Msg("Using first image repo digest available as image name") Msg("Using first image repo digest available as image name")
imageName = imageRaw.RepoDigests[0] imageName = imageInfo.RepoDigests[0]
} else { } else {
c.logger.Debug(). c.logger.Debug().
Str("ctn_id", ctn.ID). Str("ctn_id", ctn.ID).
Str("ctn_image", imageName). Str("ctn_image", imageName).
Strs("img_repodigests", imageRaw.RepoDigests). Strs("img_repodigests", imageInfo.RepoDigests).
Msg("Skip unknown image digest ref") Msg("Skip unknown image digest ref")
continue continue
} }
@@ -115,7 +115,7 @@ func (c *Client) listContainerImage() []model.Image {
return list return list
} }
func metadata(ctn types.Container) map[string]string { func metadata(ctn container.Summary) map[string]string {
return map[string]string{ return map[string]string{
"ctn_id": ctn.ID, "ctn_id": ctn.ID,
"ctn_names": formatNames(ctn.Names), "ctn_names": formatNames(ctn.Names),

View File

@@ -3,13 +3,12 @@ package docker
import ( import (
"sort" "sort"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
) )
// ContainerList returns Docker containers // ContainerList returns Docker containers
func (c *Client) ContainerList(filterArgs filters.Args) ([]types.Container, error) { func (c *Client) ContainerList(filterArgs filters.Args) ([]container.Summary, error) {
containers, err := c.API.ContainerList(c.ctx, container.ListOptions{ containers, err := c.API.ContainerList(c.ctx, container.ListOptions{
Filters: filterArgs, Filters: filterArgs,
}) })

View File

@@ -3,11 +3,12 @@ package docker
import ( import (
"regexp" "regexp"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
) )
// ContainerInspect returns the container information. // ContainerInspect returns the container information.
func (c *Client) ContainerInspect(containerID string) (types.ContainerJSON, error) { func (c *Client) ContainerInspect(containerID string) (container.InspectResponse, error) {
return c.API.ContainerInspect(c.ctx, containerID) return c.API.ContainerInspect(c.ctx, containerID)
} }
@@ -16,20 +17,19 @@ func (c *Client) IsDigest(imageID string) bool {
return regexp.MustCompile(`^(@|sha256:|@sha256:)([0-9a-f]{64})$`).MatchString(imageID) return regexp.MustCompile(`^(@|sha256:|@sha256:)([0-9a-f]{64})$`).MatchString(imageID)
} }
// ImageInspectWithRaw returns the image information and its raw representation. // ImageInspect returns the image information.
func (c *Client) ImageInspectWithRaw(imageID string) (types.ImageInspect, error) { func (c *Client) ImageInspect(imageID string) (image.InspectResponse, error) {
imageRaw, _, err := c.API.ImageInspectWithRaw(c.ctx, imageID) return c.API.ImageInspect(c.ctx, imageID)
return imageRaw, err
} }
// IsLocalImage checks if the image has been built locally // IsLocalImage checks if the image has been built locally
func (c *Client) IsLocalImage(image types.ImageInspect) bool { func (c *Client) IsLocalImage(image image.InspectResponse) bool {
return len(image.RepoDigests) == 0 return len(image.RepoDigests) == 0
} }
// IsDanglingImage returns whether the given image is "dangling" which means // IsDanglingImage returns whether the given image is "dangling" which means
// that there are no repository references to the given image and it has no // that there are no repository references to the given image and it has no
// child images // child images
func (c *Client) IsDanglingImage(image types.ImageInspect) bool { func (c *Client) IsDanglingImage(image image.InspectResponse) bool {
return len(image.RepoTags) == 1 && image.RepoTags[0] == "<none>:<none>" && len(image.RepoDigests) == 1 && image.RepoDigests[0] == "<none>@<none>" return len(image.RepoTags) == 1 && image.RepoTags[0] == "<none>:<none>" && len(image.RepoDigests) == 1 && image.RepoDigests[0] == "<none>@<none>"
} }

View File

@@ -3,14 +3,13 @@ package docker
import ( import (
"sort" "sort"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
) )
// ServiceList returns Swarm services // ServiceList returns Swarm services
func (c *Client) ServiceList(filterArgs filters.Args) ([]swarm.Service, error) { func (c *Client) ServiceList(filterArgs filters.Args) ([]swarm.Service, error) {
services, err := c.API.ServiceList(c.ctx, types.ServiceListOptions{ services, err := c.API.ServiceList(c.ctx, swarm.ServiceListOptions{
Filters: filterArgs, Filters: filterArgs,
}) })
if err != nil { if err != nil {

191
vendor/github.com/containerd/errdefs/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright The containerd Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

13
vendor/github.com/containerd/errdefs/README.md generated vendored Normal file
View File

@@ -0,0 +1,13 @@
# errdefs
A Go package for defining and checking common containerd errors.
## Project details
**errdefs** is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE).
As a containerd sub-project, you will find the:
* [Project governance](https://github.com/containerd/project/blob/main/GOVERNANCE.md),
* [Maintainers](https://github.com/containerd/project/blob/main/MAINTAINERS),
* and [Contributing guidelines](https://github.com/containerd/project/blob/main/CONTRIBUTING.md)
information in our [`containerd/project`](https://github.com/containerd/project) repository.

443
vendor/github.com/containerd/errdefs/errors.go generated vendored Normal file
View File

@@ -0,0 +1,443 @@
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package errdefs defines the common errors used throughout containerd
// packages.
//
// Use with fmt.Errorf to add context to an error.
//
// To detect an error class, use the IsXXX functions to tell whether an error
// is of a certain type.
package errdefs
import (
"context"
"errors"
)
// Definitions of common error types used throughout containerd. All containerd
// errors returned by most packages will map into one of these errors classes.
// Packages should return errors of these types when they want to instruct a
// client to take a particular action.
//
// These errors map closely to grpc errors.
var (
ErrUnknown = errUnknown{}
ErrInvalidArgument = errInvalidArgument{}
ErrNotFound = errNotFound{}
ErrAlreadyExists = errAlreadyExists{}
ErrPermissionDenied = errPermissionDenied{}
ErrResourceExhausted = errResourceExhausted{}
ErrFailedPrecondition = errFailedPrecondition{}
ErrConflict = errConflict{}
ErrNotModified = errNotModified{}
ErrAborted = errAborted{}
ErrOutOfRange = errOutOfRange{}
ErrNotImplemented = errNotImplemented{}
ErrInternal = errInternal{}
ErrUnavailable = errUnavailable{}
ErrDataLoss = errDataLoss{}
ErrUnauthenticated = errUnauthorized{}
)
// cancelled maps to Moby's "ErrCancelled"
type cancelled interface {
Cancelled()
}
// IsCanceled returns true if the error is due to `context.Canceled`.
func IsCanceled(err error) bool {
return errors.Is(err, context.Canceled) || isInterface[cancelled](err)
}
type errUnknown struct{}
func (errUnknown) Error() string { return "unknown" }
func (errUnknown) Unknown() {}
func (e errUnknown) WithMessage(msg string) error {
return customMessage{e, msg}
}
// unknown maps to Moby's "ErrUnknown"
type unknown interface {
Unknown()
}
// IsUnknown returns true if the error is due to an unknown error,
// unhandled condition or unexpected response.
func IsUnknown(err error) bool {
return errors.Is(err, errUnknown{}) || isInterface[unknown](err)
}
type errInvalidArgument struct{}
func (errInvalidArgument) Error() string { return "invalid argument" }
func (errInvalidArgument) InvalidParameter() {}
func (e errInvalidArgument) WithMessage(msg string) error {
return customMessage{e, msg}
}
// invalidParameter maps to Moby's "ErrInvalidParameter"
type invalidParameter interface {
InvalidParameter()
}
// IsInvalidArgument returns true if the error is due to an invalid argument
func IsInvalidArgument(err error) bool {
return errors.Is(err, ErrInvalidArgument) || isInterface[invalidParameter](err)
}
// deadlineExceed maps to Moby's "ErrDeadline"
type deadlineExceeded interface {
DeadlineExceeded()
}
// IsDeadlineExceeded returns true if the error is due to
// `context.DeadlineExceeded`.
func IsDeadlineExceeded(err error) bool {
return errors.Is(err, context.DeadlineExceeded) || isInterface[deadlineExceeded](err)
}
type errNotFound struct{}
func (errNotFound) Error() string { return "not found" }
func (errNotFound) NotFound() {}
func (e errNotFound) WithMessage(msg string) error {
return customMessage{e, msg}
}
// notFound maps to Moby's "ErrNotFound"
type notFound interface {
NotFound()
}
// IsNotFound returns true if the error is due to a missing object
func IsNotFound(err error) bool {
return errors.Is(err, ErrNotFound) || isInterface[notFound](err)
}
type errAlreadyExists struct{}
func (errAlreadyExists) Error() string { return "already exists" }
func (errAlreadyExists) AlreadyExists() {}
func (e errAlreadyExists) WithMessage(msg string) error {
return customMessage{e, msg}
}
type alreadyExists interface {
AlreadyExists()
}
// IsAlreadyExists returns true if the error is due to an already existing
// metadata item
func IsAlreadyExists(err error) bool {
return errors.Is(err, ErrAlreadyExists) || isInterface[alreadyExists](err)
}
type errPermissionDenied struct{}
func (errPermissionDenied) Error() string { return "permission denied" }
func (errPermissionDenied) Forbidden() {}
func (e errPermissionDenied) WithMessage(msg string) error {
return customMessage{e, msg}
}
// forbidden maps to Moby's "ErrForbidden"
type forbidden interface {
Forbidden()
}
// IsPermissionDenied returns true if the error is due to permission denied
// or forbidden (403) response
func IsPermissionDenied(err error) bool {
return errors.Is(err, ErrPermissionDenied) || isInterface[forbidden](err)
}
type errResourceExhausted struct{}
func (errResourceExhausted) Error() string { return "resource exhausted" }
func (errResourceExhausted) ResourceExhausted() {}
func (e errResourceExhausted) WithMessage(msg string) error {
return customMessage{e, msg}
}
type resourceExhausted interface {
ResourceExhausted()
}
// IsResourceExhausted returns true if the error is due to
// a lack of resources or too many attempts.
func IsResourceExhausted(err error) bool {
return errors.Is(err, errResourceExhausted{}) || isInterface[resourceExhausted](err)
}
type errFailedPrecondition struct{}
func (e errFailedPrecondition) Error() string { return "failed precondition" }
func (errFailedPrecondition) FailedPrecondition() {}
func (e errFailedPrecondition) WithMessage(msg string) error {
return customMessage{e, msg}
}
type failedPrecondition interface {
FailedPrecondition()
}
// IsFailedPrecondition returns true if an operation could not proceed due to
// the lack of a particular condition
func IsFailedPrecondition(err error) bool {
return errors.Is(err, errFailedPrecondition{}) || isInterface[failedPrecondition](err)
}
type errConflict struct{}
func (errConflict) Error() string { return "conflict" }
func (errConflict) Conflict() {}
func (e errConflict) WithMessage(msg string) error {
return customMessage{e, msg}
}
// conflict maps to Moby's "ErrConflict"
type conflict interface {
Conflict()
}
// IsConflict returns true if an operation could not proceed due to
// a conflict.
func IsConflict(err error) bool {
return errors.Is(err, errConflict{}) || isInterface[conflict](err)
}
type errNotModified struct{}
func (errNotModified) Error() string { return "not modified" }
func (errNotModified) NotModified() {}
func (e errNotModified) WithMessage(msg string) error {
return customMessage{e, msg}
}
// notModified maps to Moby's "ErrNotModified"
type notModified interface {
NotModified()
}
// IsNotModified returns true if an operation could not proceed due
// to an object not modified from a previous state.
func IsNotModified(err error) bool {
return errors.Is(err, errNotModified{}) || isInterface[notModified](err)
}
type errAborted struct{}
func (errAborted) Error() string { return "aborted" }
func (errAborted) Aborted() {}
func (e errAborted) WithMessage(msg string) error {
return customMessage{e, msg}
}
type aborted interface {
Aborted()
}
// IsAborted returns true if an operation was aborted.
func IsAborted(err error) bool {
return errors.Is(err, errAborted{}) || isInterface[aborted](err)
}
type errOutOfRange struct{}
func (errOutOfRange) Error() string { return "out of range" }
func (errOutOfRange) OutOfRange() {}
func (e errOutOfRange) WithMessage(msg string) error {
return customMessage{e, msg}
}
type outOfRange interface {
OutOfRange()
}
// IsOutOfRange returns true if an operation could not proceed due
// to data being out of the expected range.
func IsOutOfRange(err error) bool {
return errors.Is(err, errOutOfRange{}) || isInterface[outOfRange](err)
}
type errNotImplemented struct{}
func (errNotImplemented) Error() string { return "not implemented" }
func (errNotImplemented) NotImplemented() {}
func (e errNotImplemented) WithMessage(msg string) error {
return customMessage{e, msg}
}
// notImplemented maps to Moby's "ErrNotImplemented"
type notImplemented interface {
NotImplemented()
}
// IsNotImplemented returns true if the error is due to not being implemented
func IsNotImplemented(err error) bool {
return errors.Is(err, errNotImplemented{}) || isInterface[notImplemented](err)
}
type errInternal struct{}
func (errInternal) Error() string { return "internal" }
func (errInternal) System() {}
func (e errInternal) WithMessage(msg string) error {
return customMessage{e, msg}
}
// system maps to Moby's "ErrSystem"
type system interface {
System()
}
// IsInternal returns true if the error returns to an internal or system error
func IsInternal(err error) bool {
return errors.Is(err, errInternal{}) || isInterface[system](err)
}
type errUnavailable struct{}
func (errUnavailable) Error() string { return "unavailable" }
func (errUnavailable) Unavailable() {}
func (e errUnavailable) WithMessage(msg string) error {
return customMessage{e, msg}
}
// unavailable maps to Moby's "ErrUnavailable"
type unavailable interface {
Unavailable()
}
// IsUnavailable returns true if the error is due to a resource being unavailable
func IsUnavailable(err error) bool {
return errors.Is(err, errUnavailable{}) || isInterface[unavailable](err)
}
type errDataLoss struct{}
func (errDataLoss) Error() string { return "data loss" }
func (errDataLoss) DataLoss() {}
func (e errDataLoss) WithMessage(msg string) error {
return customMessage{e, msg}
}
// dataLoss maps to Moby's "ErrDataLoss"
type dataLoss interface {
DataLoss()
}
// IsDataLoss returns true if data during an operation was lost or corrupted
func IsDataLoss(err error) bool {
return errors.Is(err, errDataLoss{}) || isInterface[dataLoss](err)
}
type errUnauthorized struct{}
func (errUnauthorized) Error() string { return "unauthorized" }
func (errUnauthorized) Unauthorized() {}
func (e errUnauthorized) WithMessage(msg string) error {
return customMessage{e, msg}
}
// unauthorized maps to Moby's "ErrUnauthorized"
type unauthorized interface {
Unauthorized()
}
// IsUnauthorized returns true if the error indicates that the user was
// unauthenticated or unauthorized.
func IsUnauthorized(err error) bool {
return errors.Is(err, errUnauthorized{}) || isInterface[unauthorized](err)
}
func isInterface[T any](err error) bool {
for {
switch x := err.(type) {
case T:
return true
case customMessage:
err = x.err
case interface{ Unwrap() error }:
err = x.Unwrap()
if err == nil {
return false
}
case interface{ Unwrap() []error }:
for _, err := range x.Unwrap() {
if isInterface[T](err) {
return true
}
}
return false
default:
return false
}
}
}
// customMessage is used to provide a defined error with a custom message.
// The message is not wrapped but can be compared by the `Is(error) bool` interface.
type customMessage struct {
err error
msg string
}
func (c customMessage) Is(err error) bool {
return c.err == err
}
func (c customMessage) As(target any) bool {
return errors.As(c.err, target)
}
func (c customMessage) Error() string {
return c.msg
}

191
vendor/github.com/containerd/errdefs/pkg/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright The containerd Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,96 @@
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package errhttp provides utility functions for translating errors to
// and from a HTTP context.
//
// The functions ToHTTP and ToNative can be used to map server-side and
// client-side errors to the correct types.
package errhttp
import (
"errors"
"net/http"
"github.com/containerd/errdefs"
"github.com/containerd/errdefs/pkg/internal/cause"
)
// ToHTTP returns the best status code for the given error
func ToHTTP(err error) int {
switch {
case errdefs.IsNotFound(err):
return http.StatusNotFound
case errdefs.IsInvalidArgument(err):
return http.StatusBadRequest
case errdefs.IsConflict(err):
return http.StatusConflict
case errdefs.IsNotModified(err):
return http.StatusNotModified
case errdefs.IsFailedPrecondition(err):
return http.StatusPreconditionFailed
case errdefs.IsUnauthorized(err):
return http.StatusUnauthorized
case errdefs.IsPermissionDenied(err):
return http.StatusForbidden
case errdefs.IsResourceExhausted(err):
return http.StatusTooManyRequests
case errdefs.IsInternal(err):
return http.StatusInternalServerError
case errdefs.IsNotImplemented(err):
return http.StatusNotImplemented
case errdefs.IsUnavailable(err):
return http.StatusServiceUnavailable
case errdefs.IsUnknown(err):
var unexpected cause.ErrUnexpectedStatus
if errors.As(err, &unexpected) && unexpected.Status >= 200 && unexpected.Status < 600 {
return unexpected.Status
}
return http.StatusInternalServerError
default:
return http.StatusInternalServerError
}
}
// ToNative returns the error best matching the HTTP status code
func ToNative(statusCode int) error {
switch statusCode {
case http.StatusNotFound:
return errdefs.ErrNotFound
case http.StatusBadRequest:
return errdefs.ErrInvalidArgument
case http.StatusConflict:
return errdefs.ErrConflict
case http.StatusPreconditionFailed:
return errdefs.ErrFailedPrecondition
case http.StatusUnauthorized:
return errdefs.ErrUnauthenticated
case http.StatusForbidden:
return errdefs.ErrPermissionDenied
case http.StatusNotModified:
return errdefs.ErrNotModified
case http.StatusTooManyRequests:
return errdefs.ErrResourceExhausted
case http.StatusInternalServerError:
return errdefs.ErrInternal
case http.StatusNotImplemented:
return errdefs.ErrNotImplemented
case http.StatusServiceUnavailable:
return errdefs.ErrUnavailable
default:
return cause.ErrUnexpectedStatus{Status: statusCode}
}
}

View File

@@ -0,0 +1,33 @@
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package cause is used to define root causes for errors
// common to errors packages like grpc and http.
package cause
import "fmt"
type ErrUnexpectedStatus struct {
Status int
}
const UnexpectedStatusPrefix = "unexpected status "
func (e ErrUnexpectedStatus) Error() string {
return fmt.Sprintf("%s%d", UnexpectedStatusPrefix, e.Status)
}
func (ErrUnexpectedStatus) Unknown() {}

147
vendor/github.com/containerd/errdefs/resolve.go generated vendored Normal file
View File

@@ -0,0 +1,147 @@
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package errdefs
import "context"
// Resolve returns the first error found in the error chain which matches an
// error defined in this package or context error. A raw, unwrapped error is
// returned or ErrUnknown if no matching error is found.
//
// This is useful for determining a response code based on the outermost wrapped
// error rather than the original cause. For example, a not found error deep
// in the code may be wrapped as an invalid argument. When determining status
// code from Is* functions, the depth or ordering of the error is not
// considered.
//
// The search order is depth first, a wrapped error returned from any part of
// the chain from `Unwrap() error` will be returned before any joined errors
// as returned by `Unwrap() []error`.
func Resolve(err error) error {
if err == nil {
return nil
}
err = firstError(err)
if err == nil {
err = ErrUnknown
}
return err
}
func firstError(err error) error {
for {
switch err {
case ErrUnknown,
ErrInvalidArgument,
ErrNotFound,
ErrAlreadyExists,
ErrPermissionDenied,
ErrResourceExhausted,
ErrFailedPrecondition,
ErrConflict,
ErrNotModified,
ErrAborted,
ErrOutOfRange,
ErrNotImplemented,
ErrInternal,
ErrUnavailable,
ErrDataLoss,
ErrUnauthenticated,
context.DeadlineExceeded,
context.Canceled:
return err
}
switch e := err.(type) {
case customMessage:
err = e.err
case unknown:
return ErrUnknown
case invalidParameter:
return ErrInvalidArgument
case notFound:
return ErrNotFound
case alreadyExists:
return ErrAlreadyExists
case forbidden:
return ErrPermissionDenied
case resourceExhausted:
return ErrResourceExhausted
case failedPrecondition:
return ErrFailedPrecondition
case conflict:
return ErrConflict
case notModified:
return ErrNotModified
case aborted:
return ErrAborted
case errOutOfRange:
return ErrOutOfRange
case notImplemented:
return ErrNotImplemented
case system:
return ErrInternal
case unavailable:
return ErrUnavailable
case dataLoss:
return ErrDataLoss
case unauthorized:
return ErrUnauthenticated
case deadlineExceeded:
return context.DeadlineExceeded
case cancelled:
return context.Canceled
case interface{ Unwrap() error }:
err = e.Unwrap()
if err == nil {
return nil
}
case interface{ Unwrap() []error }:
for _, ue := range e.Unwrap() {
if fe := firstError(ue); fe != nil {
return fe
}
}
return nil
case interface{ Is(error) bool }:
for _, target := range []error{ErrUnknown,
ErrInvalidArgument,
ErrNotFound,
ErrAlreadyExists,
ErrPermissionDenied,
ErrResourceExhausted,
ErrFailedPrecondition,
ErrConflict,
ErrNotModified,
ErrAborted,
ErrOutOfRange,
ErrNotImplemented,
ErrInternal,
ErrUnavailable,
ErrDataLoss,
ErrUnauthenticated,
context.DeadlineExceeded,
context.Canceled} {
if e.Is(target) {
return target
}
}
return nil
default:
return nil
}
}
}

View File

@@ -2,7 +2,10 @@
# This file lists all contributors to the repository. # This file lists all contributors to the repository.
# See hack/generate-authors.sh to make modifications. # See hack/generate-authors.sh to make modifications.
17neverends <ionianrise@gmail.com>
7sunarni <710720732@qq.com>
Aanand Prasad <aanand.prasad@gmail.com> Aanand Prasad <aanand.prasad@gmail.com>
Aarni Koskela <akx@iki.fi>
Aaron Davidson <aaron@databricks.com> Aaron Davidson <aaron@databricks.com>
Aaron Feng <aaron.feng@gmail.com> Aaron Feng <aaron.feng@gmail.com>
Aaron Hnatiw <aaron@griddio.com> Aaron Hnatiw <aaron@griddio.com>
@@ -11,6 +14,7 @@ Aaron L. Xu <liker.xu@foxmail.com>
Aaron Lehmann <alehmann@netflix.com> Aaron Lehmann <alehmann@netflix.com>
Aaron Welch <welch@packet.net> Aaron Welch <welch@packet.net>
Aaron Yoshitake <airandfingers@gmail.com> Aaron Yoshitake <airandfingers@gmail.com>
Abdur Rehman <abdur_rehman@mentor.com>
Abel Muiño <amuino@gmail.com> Abel Muiño <amuino@gmail.com>
Abhijeet Kasurde <akasurde@redhat.com> Abhijeet Kasurde <akasurde@redhat.com>
Abhinandan Prativadi <aprativadi@gmail.com> Abhinandan Prativadi <aprativadi@gmail.com>
@@ -24,9 +28,11 @@ Adam Avilla <aavilla@yp.com>
Adam Dobrawy <naczelnik@jawnosc.tk> Adam Dobrawy <naczelnik@jawnosc.tk>
Adam Eijdenberg <adam.eijdenberg@gmail.com> Adam Eijdenberg <adam.eijdenberg@gmail.com>
Adam Kunk <adam.kunk@tiaa-cref.org> Adam Kunk <adam.kunk@tiaa-cref.org>
Adam Lamers <adam.lamers@wmsdev.pl>
Adam Miller <admiller@redhat.com> Adam Miller <admiller@redhat.com>
Adam Mills <adam@armills.info> Adam Mills <adam@armills.info>
Adam Pointer <adam.pointer@skybettingandgaming.com> Adam Pointer <adam.pointer@skybettingandgaming.com>
Adam Simon <adamsimon85100@gmail.com>
Adam Singer <financeCoding@gmail.com> Adam Singer <financeCoding@gmail.com>
Adam Thornton <adam.thornton@maryville.com> Adam Thornton <adam.thornton@maryville.com>
Adam Walz <adam@adamwalz.net> Adam Walz <adam@adamwalz.net>
@@ -119,6 +125,7 @@ amangoel <amangoel@gmail.com>
Amen Belayneh <amenbelayneh@gmail.com> Amen Belayneh <amenbelayneh@gmail.com>
Ameya Gawde <agawde@mirantis.com> Ameya Gawde <agawde@mirantis.com>
Amir Goldstein <amir73il@aquasec.com> Amir Goldstein <amir73il@aquasec.com>
AmirBuddy <badinlu.amirhossein@gmail.com>
Amit Bakshi <ambakshi@gmail.com> Amit Bakshi <ambakshi@gmail.com>
Amit Krishnan <amit.krishnan@oracle.com> Amit Krishnan <amit.krishnan@oracle.com>
Amit Shukla <amit.shukla@docker.com> Amit Shukla <amit.shukla@docker.com>
@@ -168,6 +175,7 @@ Andrey Kolomentsev <andrey.kolomentsev@docker.com>
Andrey Petrov <andrey.petrov@shazow.net> Andrey Petrov <andrey.petrov@shazow.net>
Andrey Stolbovsky <andrey.stolbovsky@gmail.com> Andrey Stolbovsky <andrey.stolbovsky@gmail.com>
André Martins <aanm90@gmail.com> André Martins <aanm90@gmail.com>
Andrés Maldonado <maldonado@codelutin.com>
Andy Chambers <anchambers@paypal.com> Andy Chambers <anchambers@paypal.com>
andy diller <dillera@gmail.com> andy diller <dillera@gmail.com>
Andy Goldstein <agoldste@redhat.com> Andy Goldstein <agoldste@redhat.com>
@@ -182,6 +190,7 @@ Anes Hasicic <anes.hasicic@gmail.com>
Angel Velazquez <angelcar@amazon.com> Angel Velazquez <angelcar@amazon.com>
Anil Belur <askb23@gmail.com> Anil Belur <askb23@gmail.com>
Anil Madhavapeddy <anil@recoil.org> Anil Madhavapeddy <anil@recoil.org>
Anirudh Aithal <aithal@amazon.com>
Ankit Jain <ajatkj@yahoo.co.in> Ankit Jain <ajatkj@yahoo.co.in>
Ankush Agarwal <ankushagarwal11@gmail.com> Ankush Agarwal <ankushagarwal11@gmail.com>
Anonmily <michelle@michelleliu.io> Anonmily <michelle@michelleliu.io>
@@ -219,7 +228,8 @@ Artur Meyster <arthurfbi@yahoo.com>
Arun Gupta <arun.gupta@gmail.com> Arun Gupta <arun.gupta@gmail.com>
Asad Saeeduddin <masaeedu@gmail.com> Asad Saeeduddin <masaeedu@gmail.com>
Asbjørn Enge <asbjorn@hanafjedle.net> Asbjørn Enge <asbjorn@hanafjedle.net>
Austin Vazquez <macedonv@amazon.com> Ashly Mathew <ashly.mathew@sap.com>
Austin Vazquez <austin.vazquez.dev@gmail.com>
averagehuman <averagehuman@users.noreply.github.com> averagehuman <averagehuman@users.noreply.github.com>
Avi Das <andas222@gmail.com> Avi Das <andas222@gmail.com>
Avi Kivity <avi@scylladb.com> Avi Kivity <avi@scylladb.com>
@@ -285,6 +295,7 @@ Brandon Liu <bdon@bdon.org>
Brandon Philips <brandon.philips@coreos.com> Brandon Philips <brandon.philips@coreos.com>
Brandon Rhodes <brandon@rhodesmill.org> Brandon Rhodes <brandon@rhodesmill.org>
Brendan Dixon <brendand@microsoft.com> Brendan Dixon <brendand@microsoft.com>
Brendon Smith <bws@bws.bio>
Brennan Kinney <5098581+polarathene@users.noreply.github.com> Brennan Kinney <5098581+polarathene@users.noreply.github.com>
Brent Salisbury <brent.salisbury@docker.com> Brent Salisbury <brent.salisbury@docker.com>
Brett Higgins <brhiggins@arbor.net> Brett Higgins <brhiggins@arbor.net>
@@ -339,12 +350,14 @@ Casey Bisson <casey.bisson@joyent.com>
Catalin Pirvu <pirvu.catalin94@gmail.com> Catalin Pirvu <pirvu.catalin94@gmail.com>
Ce Gao <ce.gao@outlook.com> Ce Gao <ce.gao@outlook.com>
Cedric Davies <cedricda@microsoft.com> Cedric Davies <cedricda@microsoft.com>
Cesar Talledo <cesar.talledo@docker.com>
Cezar Sa Espinola <cezarsa@gmail.com> Cezar Sa Espinola <cezarsa@gmail.com>
Chad Swenson <chadswen@gmail.com> Chad Swenson <chadswen@gmail.com>
Chance Zibolski <chance.zibolski@gmail.com> Chance Zibolski <chance.zibolski@gmail.com>
Chander Govindarajan <chandergovind@gmail.com> Chander Govindarajan <chandergovind@gmail.com>
Chanhun Jeong <keyolk@gmail.com> Chanhun Jeong <keyolk@gmail.com>
Chao Wang <wangchao.fnst@cn.fujitsu.com> Chao Wang <wangchao.fnst@cn.fujitsu.com>
Charity Kathure <ckathure@microsoft.com>
Charles Chan <charleswhchan@users.noreply.github.com> Charles Chan <charleswhchan@users.noreply.github.com>
Charles Hooper <charles.hooper@dotcloud.com> Charles Hooper <charles.hooper@dotcloud.com>
Charles Law <claw@conduce.com> Charles Law <claw@conduce.com>
@@ -366,6 +379,7 @@ Chen Qiu <cheney-90@hotmail.com>
Cheng-mean Liu <soccerl@microsoft.com> Cheng-mean Liu <soccerl@microsoft.com>
Chengfei Shang <cfshang@alauda.io> Chengfei Shang <cfshang@alauda.io>
Chengguang Xu <cgxu519@gmx.com> Chengguang Xu <cgxu519@gmx.com>
Chengyu Zhu <hudson@cyzhu.com>
Chentianze <cmoman@126.com> Chentianze <cmoman@126.com>
Chenyang Yan <memory.yancy@gmail.com> Chenyang Yan <memory.yancy@gmail.com>
chenyuzhu <chenyuzhi@oschina.cn> chenyuzhu <chenyuzhi@oschina.cn>
@@ -480,6 +494,7 @@ Daniel Farrell <dfarrell@redhat.com>
Daniel Garcia <daniel@danielgarcia.info> Daniel Garcia <daniel@danielgarcia.info>
Daniel Gasienica <daniel@gasienica.ch> Daniel Gasienica <daniel@gasienica.ch>
Daniel Grunwell <mwgrunny@gmail.com> Daniel Grunwell <mwgrunny@gmail.com>
Daniel Guns <danbguns@gmail.com>
Daniel Helfand <helfand.4@gmail.com> Daniel Helfand <helfand.4@gmail.com>
Daniel Hiltgen <daniel.hiltgen@docker.com> Daniel Hiltgen <daniel.hiltgen@docker.com>
Daniel J Walsh <dwalsh@redhat.com> Daniel J Walsh <dwalsh@redhat.com>
@@ -763,6 +778,7 @@ Frank Macreery <frank@macreery.com>
Frank Rosquin <frank.rosquin+github@gmail.com> Frank Rosquin <frank.rosquin+github@gmail.com>
Frank Villaro-Dixon <frank.villarodixon@merkle.com> Frank Villaro-Dixon <frank.villarodixon@merkle.com>
Frank Yang <yyb196@gmail.com> Frank Yang <yyb196@gmail.com>
François Scala <github@arcenik.net>
Fred Lifton <fred.lifton@docker.com> Fred Lifton <fred.lifton@docker.com>
Frederick F. Kautz IV <fkautz@redhat.com> Frederick F. Kautz IV <fkautz@redhat.com>
Frederico F. de Oliveira <FreddieOliveira@users.noreply.github.com> Frederico F. de Oliveira <FreddieOliveira@users.noreply.github.com>
@@ -798,6 +814,7 @@ GennadySpb <lipenkov@gmail.com>
Geoff Levand <geoff@infradead.org> Geoff Levand <geoff@infradead.org>
Geoffrey Bachelet <grosfrais@gmail.com> Geoffrey Bachelet <grosfrais@gmail.com>
Geon Kim <geon0250@gmail.com> Geon Kim <geon0250@gmail.com>
George Adams <georgeadams1995@gmail.com>
George Kontridze <george@bugsnag.com> George Kontridze <george@bugsnag.com>
George Ma <mayangang@outlook.com> George Ma <mayangang@outlook.com>
George MacRorie <gmacr31@gmail.com> George MacRorie <gmacr31@gmail.com>
@@ -826,6 +843,7 @@ Gopikannan Venugopalsamy <gopikannan.venugopalsamy@gmail.com>
Gosuke Miyashita <gosukenator@gmail.com> Gosuke Miyashita <gosukenator@gmail.com>
Gou Rao <gou@portworx.com> Gou Rao <gou@portworx.com>
Govinda Fichtner <govinda.fichtner@googlemail.com> Govinda Fichtner <govinda.fichtner@googlemail.com>
Grace Choi <grace.54109@gmail.com>
Grant Millar <rid@cylo.io> Grant Millar <rid@cylo.io>
Grant Reaber <grant.reaber@gmail.com> Grant Reaber <grant.reaber@gmail.com>
Graydon Hoare <graydon@pobox.com> Graydon Hoare <graydon@pobox.com>
@@ -966,6 +984,7 @@ James Nugent <james@jen20.com>
James Sanders <james3sanders@gmail.com> James Sanders <james3sanders@gmail.com>
James Turnbull <james@lovedthanlost.net> James Turnbull <james@lovedthanlost.net>
James Watkins-Harvey <jwatkins@progi-media.com> James Watkins-Harvey <jwatkins@progi-media.com>
Jameson Hyde <jameson.hyde@docker.com>
Jamie Hannaford <jamie@limetree.org> Jamie Hannaford <jamie@limetree.org>
Jamshid Afshar <jafshar@yahoo.com> Jamshid Afshar <jafshar@yahoo.com>
Jan Breig <git@pygos.space> Jan Breig <git@pygos.space>
@@ -1064,13 +1083,16 @@ Jim Perrin <jperrin@centos.org>
Jimmy Cuadra <jimmy@jimmycuadra.com> Jimmy Cuadra <jimmy@jimmycuadra.com>
Jimmy Puckett <jimmy.puckett@spinen.com> Jimmy Puckett <jimmy.puckett@spinen.com>
Jimmy Song <rootsongjc@gmail.com> Jimmy Song <rootsongjc@gmail.com>
jinjiadu <jinjiadu@aliyun.com>
Jinsoo Park <cellpjs@gmail.com> Jinsoo Park <cellpjs@gmail.com>
Jintao Zhang <zhangjintao9020@gmail.com> Jintao Zhang <zhangjintao9020@gmail.com>
Jiri Appl <jiria@microsoft.com> Jiri Appl <jiria@microsoft.com>
Jiri Popelka <jpopelka@redhat.com> Jiri Popelka <jpopelka@redhat.com>
Jiuyue Ma <majiuyue@huawei.com> Jiuyue Ma <majiuyue@huawei.com>
Jiří Župka <jzupka@redhat.com> Jiří Župka <jzupka@redhat.com>
jjimbo137 <115816493+jjimbo137@users.noreply.github.com>
Joakim Roubert <joakim.roubert@axis.com> Joakim Roubert <joakim.roubert@axis.com>
Joan Grau <grautxo.dev@proton.me>
Joao Fernandes <joao.fernandes@docker.com> Joao Fernandes <joao.fernandes@docker.com>
Joao Trindade <trindade.joao@gmail.com> Joao Trindade <trindade.joao@gmail.com>
Joe Beda <joe.github@bedafamily.com> Joe Beda <joe.github@bedafamily.com>
@@ -1155,6 +1177,7 @@ Josiah Kiehl <jkiehl@riotgames.com>
José Tomás Albornoz <jojo@eljojo.net> José Tomás Albornoz <jojo@eljojo.net>
Joyce Jang <mail@joycejang.com> Joyce Jang <mail@joycejang.com>
JP <jpellerin@leapfrogonline.com> JP <jpellerin@leapfrogonline.com>
JSchltggr <jschltggr@gmail.com>
Julian Taylor <jtaylor.debian@googlemail.com> Julian Taylor <jtaylor.debian@googlemail.com>
Julien Barbier <write0@gmail.com> Julien Barbier <write0@gmail.com>
Julien Bisconti <veggiemonk@users.noreply.github.com> Julien Bisconti <veggiemonk@users.noreply.github.com>
@@ -1189,6 +1212,7 @@ K. Heller <pestophagous@gmail.com>
Kai Blin <kai@samba.org> Kai Blin <kai@samba.org>
Kai Qiang Wu (Kennan) <wkq5325@gmail.com> Kai Qiang Wu (Kennan) <wkq5325@gmail.com>
Kaijie Chen <chen@kaijie.org> Kaijie Chen <chen@kaijie.org>
Kaita Nakamura <kaita.nakamura0830@gmail.com>
Kamil Domański <kamil@domanski.co> Kamil Domański <kamil@domanski.co>
Kamjar Gerami <kami.gerami@gmail.com> Kamjar Gerami <kami.gerami@gmail.com>
Kanstantsin Shautsou <kanstantsin.sha@gmail.com> Kanstantsin Shautsou <kanstantsin.sha@gmail.com>
@@ -1263,6 +1287,7 @@ Krasi Georgiev <krasi@vip-consult.solutions>
Krasimir Georgiev <support@vip-consult.co.uk> Krasimir Georgiev <support@vip-consult.co.uk>
Kris-Mikael Krister <krismikael@protonmail.com> Kris-Mikael Krister <krismikael@protonmail.com>
Kristian Haugene <kristian.haugene@capgemini.com> Kristian Haugene <kristian.haugene@capgemini.com>
Kristian Heljas <kristian@kristian.ee>
Kristina Zabunova <triara.xiii@gmail.com> Kristina Zabunova <triara.xiii@gmail.com>
Krystian Wojcicki <kwojcicki@sympatico.ca> Krystian Wojcicki <kwojcicki@sympatico.ca>
Kunal Kushwaha <kushwaha_kunal_v7@lab.ntt.co.jp> Kunal Kushwaha <kushwaha_kunal_v7@lab.ntt.co.jp>
@@ -1289,6 +1314,7 @@ Laura Brehm <laurabrehm@hey.com>
Laura Frank <ljfrank@gmail.com> Laura Frank <ljfrank@gmail.com>
Laurent Bernaille <laurent.bernaille@datadoghq.com> Laurent Bernaille <laurent.bernaille@datadoghq.com>
Laurent Erignoux <lerignoux@gmail.com> Laurent Erignoux <lerignoux@gmail.com>
Laurent Goderre <laurent.goderre@docker.com>
Laurie Voss <github@seldo.com> Laurie Voss <github@seldo.com>
Leandro Motta Barros <lmb@stackedboxes.org> Leandro Motta Barros <lmb@stackedboxes.org>
Leandro Siqueira <leandro.siqueira@gmail.com> Leandro Siqueira <leandro.siqueira@gmail.com>
@@ -1369,6 +1395,7 @@ Madhan Raj Mookkandy <MadhanRaj.Mookkandy@microsoft.com>
Madhav Puri <madhav.puri@gmail.com> Madhav Puri <madhav.puri@gmail.com>
Madhu Venugopal <mavenugo@gmail.com> Madhu Venugopal <mavenugo@gmail.com>
Mageee <fangpuyi@foxmail.com> Mageee <fangpuyi@foxmail.com>
maggie44 <64841595+maggie44@users.noreply.github.com>
Mahesh Tiyyagura <tmahesh@gmail.com> Mahesh Tiyyagura <tmahesh@gmail.com>
malnick <malnick@gmail..com> malnick <malnick@gmail..com>
Malte Janduda <mail@janduda.net> Malte Janduda <mail@janduda.net>
@@ -1462,6 +1489,7 @@ Matthias Kühnle <git.nivoc@neverbox.com>
Matthias Rampke <mr@soundcloud.com> Matthias Rampke <mr@soundcloud.com>
Matthieu Fronton <m@tthieu.fr> Matthieu Fronton <m@tthieu.fr>
Matthieu Hauglustaine <matt.hauglustaine@gmail.com> Matthieu Hauglustaine <matt.hauglustaine@gmail.com>
Matthieu MOREL <matthieu.morel35@gmail.com>
Mattias Jernberg <nostrad@gmail.com> Mattias Jernberg <nostrad@gmail.com>
Mauricio Garavaglia <mauricio@medallia.com> Mauricio Garavaglia <mauricio@medallia.com>
mauriyouth <mauriyouth@gmail.com> mauriyouth <mauriyouth@gmail.com>
@@ -1579,6 +1607,7 @@ Muayyad Alsadi <alsadi@gmail.com>
Muhammad Zohaib Aslam <zohaibse011@gmail.com> Muhammad Zohaib Aslam <zohaibse011@gmail.com>
Mustafa Akın <mustafa91@gmail.com> Mustafa Akın <mustafa91@gmail.com>
Muthukumar R <muthur@gmail.com> Muthukumar R <muthur@gmail.com>
Myeongjoon Kim <kimmj8409@gmail.com>
Máximo Cuadros <mcuadros@gmail.com> Máximo Cuadros <mcuadros@gmail.com>
Médi-Rémi Hashim <medimatrix@users.noreply.github.com> Médi-Rémi Hashim <medimatrix@users.noreply.github.com>
Nace Oroz <orkica@gmail.com> Nace Oroz <orkica@gmail.com>
@@ -1593,6 +1622,7 @@ Natasha Jarus <linuxmercedes@gmail.com>
Nate Brennand <nate.brennand@clever.com> Nate Brennand <nate.brennand@clever.com>
Nate Eagleson <nate@nateeag.com> Nate Eagleson <nate@nateeag.com>
Nate Jones <nate@endot.org> Nate Jones <nate@endot.org>
Nathan Baulch <nathan.baulch@gmail.com>
Nathan Carlson <carl4403@umn.edu> Nathan Carlson <carl4403@umn.edu>
Nathan Herald <me@nathanherald.com> Nathan Herald <me@nathanherald.com>
Nathan Hsieh <hsieh.nathan@gmail.com> Nathan Hsieh <hsieh.nathan@gmail.com>
@@ -1655,6 +1685,7 @@ Nuutti Kotivuori <naked@iki.fi>
nzwsch <hi@nzwsch.com> nzwsch <hi@nzwsch.com>
O.S. Tezer <ostezer@gmail.com> O.S. Tezer <ostezer@gmail.com>
objectified <objectified@gmail.com> objectified <objectified@gmail.com>
Octol1ttle <l1ttleofficial@outlook.com>
Odin Ugedal <odin@ugedal.com> Odin Ugedal <odin@ugedal.com>
Oguz Bilgic <fisyonet@gmail.com> Oguz Bilgic <fisyonet@gmail.com>
Oh Jinkyun <tintypemolly@gmail.com> Oh Jinkyun <tintypemolly@gmail.com>
@@ -1689,6 +1720,7 @@ Patrick Hemmer <patrick.hemmer@gmail.com>
Patrick St. laurent <patrick@saint-laurent.us> Patrick St. laurent <patrick@saint-laurent.us>
Patrick Stapleton <github@gdi2290.com> Patrick Stapleton <github@gdi2290.com>
Patrik Cyvoct <patrik@ptrk.io> Patrik Cyvoct <patrik@ptrk.io>
Patrik Leifert <patrikleifert@hotmail.com>
pattichen <craftsbear@gmail.com> pattichen <craftsbear@gmail.com>
Paul "TBBle" Hampson <Paul.Hampson@Pobox.com> Paul "TBBle" Hampson <Paul.Hampson@Pobox.com>
Paul <paul9869@gmail.com> Paul <paul9869@gmail.com>
@@ -1763,6 +1795,7 @@ Pierre Carrier <pierre@meteor.com>
Pierre Dal-Pra <dalpra.pierre@gmail.com> Pierre Dal-Pra <dalpra.pierre@gmail.com>
Pierre Wacrenier <pierre.wacrenier@gmail.com> Pierre Wacrenier <pierre.wacrenier@gmail.com>
Pierre-Alain RIVIERE <pariviere@ippon.fr> Pierre-Alain RIVIERE <pariviere@ippon.fr>
pinglanlu <pinglanlu@outlook.com>
Piotr Bogdan <ppbogdan@gmail.com> Piotr Bogdan <ppbogdan@gmail.com>
Piotr Karbowski <piotr.karbowski@protonmail.ch> Piotr Karbowski <piotr.karbowski@protonmail.ch>
Porjo <porjo38@yahoo.com.au> Porjo <porjo38@yahoo.com.au>
@@ -1790,6 +1823,7 @@ Quentin Tayssier <qtayssier@gmail.com>
r0n22 <cameron.regan@gmail.com> r0n22 <cameron.regan@gmail.com>
Rachit Sharma <rachitsharma613@gmail.com> Rachit Sharma <rachitsharma613@gmail.com>
Radostin Stoyanov <rstoyanov1@gmail.com> Radostin Stoyanov <rstoyanov1@gmail.com>
Rafael Fernández López <ereslibre@ereslibre.es>
Rafal Jeczalik <rjeczalik@gmail.com> Rafal Jeczalik <rjeczalik@gmail.com>
Rafe Colton <rafael.colton@gmail.com> Rafe Colton <rafael.colton@gmail.com>
Raghavendra K T <raghavendra.kt@linux.vnet.ibm.com> Raghavendra K T <raghavendra.kt@linux.vnet.ibm.com>
@@ -1845,6 +1879,7 @@ Robert Obryk <robryk@gmail.com>
Robert Schneider <mail@shakeme.info> Robert Schneider <mail@shakeme.info>
Robert Shade <robert.shade@gmail.com> Robert Shade <robert.shade@gmail.com>
Robert Stern <lexandro2000@gmail.com> Robert Stern <lexandro2000@gmail.com>
Robert Sturla <robertsturla@outlook.com>
Robert Terhaar <rterhaar@atlanticdynamic.com> Robert Terhaar <rterhaar@atlanticdynamic.com>
Robert Wallis <smilingrob@gmail.com> Robert Wallis <smilingrob@gmail.com>
Robert Wang <robert@arctic.tw> Robert Wang <robert@arctic.tw>
@@ -1856,7 +1891,7 @@ Robin Speekenbrink <robin@kingsquare.nl>
Robin Thoni <robin@rthoni.com> Robin Thoni <robin@rthoni.com>
robpc <rpcann@gmail.com> robpc <rpcann@gmail.com>
Rodolfo Carvalho <rhcarvalho@gmail.com> Rodolfo Carvalho <rhcarvalho@gmail.com>
Rodrigo Campos <rodrigo@kinvolk.io> Rodrigo Campos <rodrigoca@microsoft.com>
Rodrigo Vaz <rodrigo.vaz@gmail.com> Rodrigo Vaz <rodrigo.vaz@gmail.com>
Roel Van Nyen <roel.vannyen@gmail.com> Roel Van Nyen <roel.vannyen@gmail.com>
Roger Peppe <rogpeppe@gmail.com> Roger Peppe <rogpeppe@gmail.com>
@@ -1995,6 +2030,7 @@ Sevki Hasirci <s@sevki.org>
Shane Canon <scanon@lbl.gov> Shane Canon <scanon@lbl.gov>
Shane da Silva <shane@dasilva.io> Shane da Silva <shane@dasilva.io>
Shaun Kaasten <shaunk@gmail.com> Shaun Kaasten <shaunk@gmail.com>
Shaun Thompson <shaun.thompson@docker.com>
shaunol <shaunol@gmail.com> shaunol <shaunol@gmail.com>
Shawn Landden <shawn@churchofgit.com> Shawn Landden <shawn@churchofgit.com>
Shawn Siefkas <shawn.siefkas@meredith.com> Shawn Siefkas <shawn.siefkas@meredith.com>
@@ -2013,6 +2049,7 @@ Shijun Qin <qinshijun16@mails.ucas.ac.cn>
Shishir Mahajan <shishir.mahajan@redhat.com> Shishir Mahajan <shishir.mahajan@redhat.com>
Shoubhik Bose <sbose78@gmail.com> Shoubhik Bose <sbose78@gmail.com>
Shourya Sarcar <shourya.sarcar@gmail.com> Shourya Sarcar <shourya.sarcar@gmail.com>
Shreenidhi Shedi <shreenidhi.shedi@broadcom.com>
Shu-Wai Chow <shu-wai.chow@seattlechildrens.org> Shu-Wai Chow <shu-wai.chow@seattlechildrens.org>
shuai-z <zs.broccoli@gmail.com> shuai-z <zs.broccoli@gmail.com>
Shukui Yang <yangshukui@huawei.com> Shukui Yang <yangshukui@huawei.com>
@@ -2100,6 +2137,7 @@ Sébastien Stormacq <sebsto@users.noreply.github.com>
Sören Tempel <soeren+git@soeren-tempel.net> Sören Tempel <soeren+git@soeren-tempel.net>
Tabakhase <mail@tabakhase.com> Tabakhase <mail@tabakhase.com>
Tadej Janež <tadej.j@nez.si> Tadej Janež <tadej.j@nez.si>
Tadeusz Dudkiewicz <tadeusz.dudkiewicz@rtbhouse.com>
Takuto Sato <tockn.jp@gmail.com> Takuto Sato <tockn.jp@gmail.com>
tang0th <tang0th@gmx.com> tang0th <tang0th@gmx.com>
Tangi Colin <tangicolin@gmail.com> Tangi Colin <tangicolin@gmail.com>
@@ -2107,6 +2145,7 @@ Tatsuki Sugiura <sugi@nemui.org>
Tatsushi Inagaki <e29253@jp.ibm.com> Tatsushi Inagaki <e29253@jp.ibm.com>
Taylan Isikdemir <taylani@google.com> Taylan Isikdemir <taylani@google.com>
Taylor Jones <monitorjbl@gmail.com> Taylor Jones <monitorjbl@gmail.com>
tcpdumppy <847462026@qq.com>
Ted M. Young <tedyoung@gmail.com> Ted M. Young <tedyoung@gmail.com>
Tehmasp Chaudhri <tehmasp@gmail.com> Tehmasp Chaudhri <tehmasp@gmail.com>
Tejaswini Duggaraju <naduggar@microsoft.com> Tejaswini Duggaraju <naduggar@microsoft.com>
@@ -2391,6 +2430,7 @@ You-Sheng Yang (楊有勝) <vicamo@gmail.com>
youcai <omegacoleman@gmail.com> youcai <omegacoleman@gmail.com>
Youcef YEKHLEF <yyekhlef@gmail.com> Youcef YEKHLEF <yyekhlef@gmail.com>
Youfu Zhang <zhangyoufu@gmail.com> Youfu Zhang <zhangyoufu@gmail.com>
YR Chen <stevapple@icloud.com>
Yu Changchun <yuchangchun1@huawei.com> Yu Changchun <yuchangchun1@huawei.com>
Yu Chengxia <yuchengxia@huawei.com> Yu Chengxia <yuchengxia@huawei.com>
Yu Peng <yu.peng36@zte.com.cn> Yu Peng <yu.peng36@zte.com.cn>

View File

@@ -1,9 +1,9 @@
package api // import "github.com/docker/docker/api" package api
// Common constants for daemon and client. // Common constants for daemon and client.
const ( const (
// DefaultVersion of the current REST API. // DefaultVersion of the current REST API.
DefaultVersion = "1.47" DefaultVersion = "1.51"
// MinSupportedAPIVersion is the minimum API version that can be supported // MinSupportedAPIVersion is the minimum API version that can be supported
// by the API server, specified as "major.minor". Note that the daemon // by the API server, specified as "major.minor". Note that the daemon

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,4 @@
package blkiodev // import "github.com/docker/docker/api/types/blkiodev" package blkiodev
import "fmt" import "fmt"

View File

@@ -0,0 +1,91 @@
package build
import (
"io"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/registry"
)
// BuilderVersion sets the version of underlying builder to use
type BuilderVersion string
const (
// BuilderV1 is the first generation builder in docker daemon
BuilderV1 BuilderVersion = "1"
// BuilderBuildKit is builder based on moby/buildkit project
BuilderBuildKit BuilderVersion = "2"
)
// Result contains the image id of a successful build.
type Result struct {
ID string
}
// ImageBuildOptions holds the information
// necessary to build images.
type ImageBuildOptions struct {
Tags []string
SuppressOutput bool
RemoteContext string
NoCache bool
Remove bool
ForceRemove bool
PullParent bool
Isolation container.Isolation
CPUSetCPUs string
CPUSetMems string
CPUShares int64
CPUQuota int64
CPUPeriod int64
Memory int64
MemorySwap int64
CgroupParent string
NetworkMode string
ShmSize int64
Dockerfile string
Ulimits []*container.Ulimit
// BuildArgs needs to be a *string instead of just a string so that
// we can tell the difference between "" (empty string) and no value
// at all (nil). See the parsing of buildArgs in
// api/server/router/build/build_routes.go for even more info.
BuildArgs map[string]*string
AuthConfigs map[string]registry.AuthConfig
Context io.Reader
Labels map[string]string
// squash the resulting image's layers to the parent
// preserves the original image and creates a new one from the parent with all
// the changes applied to a single layer
Squash bool
// CacheFrom specifies images that are used for matching cache. Images
// specified here do not need to have a valid parent chain to match cache.
CacheFrom []string
SecurityOpt []string
ExtraHosts []string // List of extra hosts
Target string
SessionID string
Platform string
// Version specifies the version of the underlying builder to use
Version BuilderVersion
// BuildID is an optional identifier that can be passed together with the
// build request. The same identifier can be used to gracefully cancel the
// build with the cancel request.
BuildID string
// Outputs defines configurations for exporting build results. Only supported
// in BuildKit mode
Outputs []ImageBuildOutput
}
// ImageBuildOutput defines configuration for exporting a build result
type ImageBuildOutput struct {
Type string
Attrs map[string]string
}
// ImageBuildResponse holds information
// returned by a server after building
// an image.
type ImageBuildResponse struct {
Body io.ReadCloser
OSType string
}

View File

@@ -0,0 +1,52 @@
package build
import (
"time"
"github.com/docker/docker/api/types/filters"
)
// CacheRecord contains information about a build cache record.
type CacheRecord struct {
// ID is the unique ID of the build cache record.
ID string
// Parent is the ID of the parent build cache record.
//
// Deprecated: deprecated in API v1.42 and up, as it was deprecated in BuildKit; use Parents instead.
Parent string `json:"Parent,omitempty"`
// Parents is the list of parent build cache record IDs.
Parents []string `json:" Parents,omitempty"`
// Type is the cache record type.
Type string
// Description is a description of the build-step that produced the build cache.
Description string
// InUse indicates if the build cache is in use.
InUse bool
// Shared indicates if the build cache is shared.
Shared bool
// Size is the amount of disk space used by the build cache (in bytes).
Size int64
// CreatedAt is the date and time at which the build cache was created.
CreatedAt time.Time
// LastUsedAt is the date and time at which the build cache was last used.
LastUsedAt *time.Time
UsageCount int
}
// CachePruneOptions hold parameters to prune the build cache.
type CachePruneOptions struct {
All bool
ReservedSpace int64
MaxUsedSpace int64
MinFreeSpace int64
Filters filters.Args
KeepStorage int64 // Deprecated: deprecated in API 1.48.
}
// CachePruneReport contains the response for Engine API:
// POST "/build/prune"
type CachePruneReport struct {
CachesDeleted []string
SpaceReclaimed uint64
}

View File

@@ -0,0 +1,8 @@
package build
// CacheDiskUsage contains disk usage for the build cache.
type CacheDiskUsage struct {
TotalSize int64
Reclaimable int64
Items []*CacheRecord
}

View File

@@ -1,17 +1,12 @@
package types // import "github.com/docker/docker/api/types" package types
import ( import (
"bufio" "bufio"
"context" "context"
"io"
"net" "net"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/registry"
) )
// NewHijackedResponse intializes a HijackedResponse type // NewHijackedResponse initializes a [HijackedResponse] type.
func NewHijackedResponse(conn net.Conn, mediaType string) HijackedResponse { func NewHijackedResponse(conn net.Conn, mediaType string) HijackedResponse {
return HijackedResponse{Conn: conn, Reader: bufio.NewReader(conn), mediaType: mediaType} return HijackedResponse{Conn: conn, Reader: bufio.NewReader(conn), mediaType: mediaType}
} }
@@ -51,173 +46,6 @@ func (h *HijackedResponse) CloseWrite() error {
return nil return nil
} }
// ImageBuildOptions holds the information
// necessary to build images.
type ImageBuildOptions struct {
Tags []string
SuppressOutput bool
RemoteContext string
NoCache bool
Remove bool
ForceRemove bool
PullParent bool
Isolation container.Isolation
CPUSetCPUs string
CPUSetMems string
CPUShares int64
CPUQuota int64
CPUPeriod int64
Memory int64
MemorySwap int64
CgroupParent string
NetworkMode string
ShmSize int64
Dockerfile string
Ulimits []*container.Ulimit
// BuildArgs needs to be a *string instead of just a string so that
// we can tell the difference between "" (empty string) and no value
// at all (nil). See the parsing of buildArgs in
// api/server/router/build/build_routes.go for even more info.
BuildArgs map[string]*string
AuthConfigs map[string]registry.AuthConfig
Context io.Reader
Labels map[string]string
// squash the resulting image's layers to the parent
// preserves the original image and creates a new one from the parent with all
// the changes applied to a single layer
Squash bool
// CacheFrom specifies images that are used for matching cache. Images
// specified here do not need to have a valid parent chain to match cache.
CacheFrom []string
SecurityOpt []string
ExtraHosts []string // List of extra hosts
Target string
SessionID string
Platform string
// Version specifies the version of the underlying builder to use
Version BuilderVersion
// BuildID is an optional identifier that can be passed together with the
// build request. The same identifier can be used to gracefully cancel the
// build with the cancel request.
BuildID string
// Outputs defines configurations for exporting build results. Only supported
// in BuildKit mode
Outputs []ImageBuildOutput
}
// ImageBuildOutput defines configuration for exporting a build result
type ImageBuildOutput struct {
Type string
Attrs map[string]string
}
// BuilderVersion sets the version of underlying builder to use
type BuilderVersion string
const (
// BuilderV1 is the first generation builder in docker daemon
BuilderV1 BuilderVersion = "1"
// BuilderBuildKit is builder based on moby/buildkit project
BuilderBuildKit BuilderVersion = "2"
)
// ImageBuildResponse holds information
// returned by a server after building
// an image.
type ImageBuildResponse struct {
Body io.ReadCloser
OSType string
}
// RequestPrivilegeFunc is a function interface that
// clients can supply to retry operations after
// getting an authorization error.
// This function returns the registry authentication
// header value in base 64 format, or an error
// if the privilege request fails.
type RequestPrivilegeFunc func(context.Context) (string, error)
// NodeListOptions holds parameters to list nodes with.
type NodeListOptions struct {
Filters filters.Args
}
// NodeRemoveOptions holds parameters to remove nodes with.
type NodeRemoveOptions struct {
Force bool
}
// ServiceCreateOptions contains the options to use when creating a service.
type ServiceCreateOptions struct {
// EncodedRegistryAuth is the encoded registry authorization credentials to
// use when updating the service.
//
// This field follows the format of the X-Registry-Auth header.
EncodedRegistryAuth string
// QueryRegistry indicates whether the service update requires
// contacting a registry. A registry may be contacted to retrieve
// the image digest and manifest, which in turn can be used to update
// platform or other information about the service.
QueryRegistry bool
}
// Values for RegistryAuthFrom in ServiceUpdateOptions
const (
RegistryAuthFromSpec = "spec"
RegistryAuthFromPreviousSpec = "previous-spec"
)
// ServiceUpdateOptions contains the options to be used for updating services.
type ServiceUpdateOptions struct {
// EncodedRegistryAuth is the encoded registry authorization credentials to
// use when updating the service.
//
// This field follows the format of the X-Registry-Auth header.
EncodedRegistryAuth string
// TODO(stevvooe): Consider moving the version parameter of ServiceUpdate
// into this field. While it does open API users up to racy writes, most
// users may not need that level of consistency in practice.
// RegistryAuthFrom specifies where to find the registry authorization
// credentials if they are not given in EncodedRegistryAuth. Valid
// values are "spec" and "previous-spec".
RegistryAuthFrom string
// Rollback indicates whether a server-side rollback should be
// performed. When this is set, the provided spec will be ignored.
// The valid values are "previous" and "none". An empty value is the
// same as "none".
Rollback string
// QueryRegistry indicates whether the service update requires
// contacting a registry. A registry may be contacted to retrieve
// the image digest and manifest, which in turn can be used to update
// platform or other information about the service.
QueryRegistry bool
}
// ServiceListOptions holds parameters to list services with.
type ServiceListOptions struct {
Filters filters.Args
// Status indicates whether the server should include the service task
// count of running and desired tasks.
Status bool
}
// ServiceInspectOptions holds parameters related to the "service inspect"
// operation.
type ServiceInspectOptions struct {
InsertDefaults bool
}
// TaskListOptions holds parameters to list tasks with.
type TaskListOptions struct {
Filters filters.Args
}
// PluginRemoveOptions holds parameters to remove plugins. // PluginRemoveOptions holds parameters to remove plugins.
type PluginRemoveOptions struct { type PluginRemoveOptions struct {
Force bool Force bool
@@ -239,18 +67,18 @@ type PluginInstallOptions struct {
AcceptAllPermissions bool AcceptAllPermissions bool
RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry
RemoteRef string // RemoteRef is the plugin name on the registry RemoteRef string // RemoteRef is the plugin name on the registry
PrivilegeFunc RequestPrivilegeFunc
// PrivilegeFunc is a function that clients can supply to retry operations
// after getting an authorization error. This function returns the registry
// authentication header value in base64 encoded format, or an error if the
// privilege request fails.
//
// For details, refer to [github.com/docker/docker/api/types/registry.RequestAuthConfig].
PrivilegeFunc func(context.Context) (string, error)
AcceptPermissionsFunc func(context.Context, PluginPrivileges) (bool, error) AcceptPermissionsFunc func(context.Context, PluginPrivileges) (bool, error)
Args []string Args []string
} }
// SwarmUnlockKeyResponse contains the response for Engine API:
// GET /swarm/unlockkey
type SwarmUnlockKeyResponse struct {
// UnlockKey is the unlock key in ASCII-armored format.
UnlockKey string
}
// PluginCreateOptions hold all options to plugin create. // PluginCreateOptions hold all options to plugin create.
type PluginCreateOptions struct { type PluginCreateOptions struct {
RepoName string RepoName string

View File

@@ -1,10 +1,10 @@
package types package common
// This file was generated by the swagger tool. // This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command // Editing this file might prove futile when you re-run the swagger generate command
// IDResponse Response to an API call that returns just an Id // IDResponse Response to an API call that returns just an Id
// swagger:model IdResponse // swagger:model IDResponse
type IDResponse struct { type IDResponse struct {
// The id of the newly created object. // The id of the newly created object.

View File

@@ -0,0 +1,7 @@
package container
import "github.com/docker/docker/api/types/common"
// CommitResponse response for the commit API call, containing the ID of the
// image that was produced.
type CommitResponse = common.IDResponse

View File

@@ -1,4 +1,4 @@
package container // import "github.com/docker/docker/api/types/container" package container
import ( import (
"time" "time"

View File

@@ -4,8 +4,22 @@ import (
"io" "io"
"os" "os"
"time" "time"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/storage"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
) )
// ContainerUpdateOKBody OK response to ContainerUpdate operation
//
// Deprecated: use [UpdateResponse]. This alias will be removed in the next release.
type ContainerUpdateOKBody = UpdateResponse
// ContainerTopOKBody OK response to ContainerTop operation
//
// Deprecated: use [TopResponse]. This alias will be removed in the next release.
type ContainerTopOKBody = TopResponse
// PruneReport contains the response for Engine API: // PruneReport contains the response for Engine API:
// POST "/containers/prune" // POST "/containers/prune"
type PruneReport struct { type PruneReport struct {
@@ -42,3 +56,133 @@ type StatsResponseReader struct {
Body io.ReadCloser `json:"body"` Body io.ReadCloser `json:"body"`
OSType string `json:"ostype"` OSType string `json:"ostype"`
} }
// MountPoint represents a mount point configuration inside the container.
// This is used for reporting the mountpoints in use by a container.
type MountPoint struct {
// Type is the type of mount, see `Type<foo>` definitions in
// github.com/docker/docker/api/types/mount.Type
Type mount.Type `json:",omitempty"`
// Name is the name reference to the underlying data defined by `Source`
// e.g., the volume name.
Name string `json:",omitempty"`
// Source is the source location of the mount.
//
// For volumes, this contains the storage location of the volume (within
// `/var/lib/docker/volumes/`). For bind-mounts, and `npipe`, this contains
// the source (host) part of the bind-mount. For `tmpfs` mount points, this
// field is empty.
Source string
// Destination is the path relative to the container root (`/`) where the
// Source is mounted inside the container.
Destination string
// Driver is the volume driver used to create the volume (if it is a volume).
Driver string `json:",omitempty"`
// Mode is a comma separated list of options supplied by the user when
// creating the bind/volume mount.
//
// The default is platform-specific (`"z"` on Linux, empty on Windows).
Mode string
// RW indicates whether the mount is mounted writable (read-write).
RW bool
// Propagation describes how mounts are propagated from the host into the
// mount point, and vice-versa. Refer to the Linux kernel documentation
// for details:
// https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt
//
// This field is not used on Windows.
Propagation mount.Propagation
}
// State stores container's running state
// it's part of ContainerJSONBase and returned by "inspect" command
type State struct {
Status ContainerState // String representation of the container state. Can be one of "created", "running", "paused", "restarting", "removing", "exited", or "dead"
Running bool
Paused bool
Restarting bool
OOMKilled bool
Dead bool
Pid int
ExitCode int
Error string
StartedAt string
FinishedAt string
Health *Health `json:",omitempty"`
}
// Summary contains response of Engine API:
// GET "/containers/json"
type Summary struct {
ID string `json:"Id"`
Names []string
Image string
ImageID string
ImageManifestDescriptor *ocispec.Descriptor `json:"ImageManifestDescriptor,omitempty"`
Command string
Created int64
Ports []Port
SizeRw int64 `json:",omitempty"`
SizeRootFs int64 `json:",omitempty"`
Labels map[string]string
State ContainerState
Status string
HostConfig struct {
NetworkMode string `json:",omitempty"`
Annotations map[string]string `json:",omitempty"`
}
NetworkSettings *NetworkSettingsSummary
Mounts []MountPoint
}
// ContainerJSONBase contains response of Engine API GET "/containers/{name:.*}/json"
// for API version 1.18 and older.
//
// TODO(thaJeztah): combine ContainerJSONBase and InspectResponse into a single struct.
// The split between ContainerJSONBase (ContainerJSONBase) and InspectResponse (InspectResponse)
// was done in commit 6deaa58ba5f051039643cedceee97c8695e2af74 (https://github.com/moby/moby/pull/13675).
// ContainerJSONBase contained all fields for API < 1.19, and InspectResponse
// held fields that were added in API 1.19 and up. Given that the minimum
// supported API version is now 1.24, we no longer use the separate type.
type ContainerJSONBase struct {
ID string `json:"Id"`
Created string
Path string
Args []string
State *State
Image string
ResolvConfPath string
HostnamePath string
HostsPath string
LogPath string
Name string
RestartCount int
Driver string
Platform string
MountLabel string
ProcessLabel string
AppArmorProfile string
ExecIDs []string
HostConfig *HostConfig
GraphDriver storage.DriverData
SizeRw *int64 `json:",omitempty"`
SizeRootFs *int64 `json:",omitempty"`
}
// InspectResponse is the response for the GET "/containers/{name:.*}/json"
// endpoint.
type InspectResponse struct {
*ContainerJSONBase
Mounts []MountPoint
Config *Config
NetworkSettings *NetworkSettings
// ImageManifestDescriptor is the descriptor of a platform-specific manifest of the image used to create the container.
ImageManifestDescriptor *ocispec.Descriptor `json:"ImageManifestDescriptor,omitempty"`
}

View File

@@ -1,22 +0,0 @@
package container // import "github.com/docker/docker/api/types/container"
// ----------------------------------------------------------------------------
// Code generated by `swagger generate operation`. DO NOT EDIT.
//
// See hack/generate-swagger-api.sh
// ----------------------------------------------------------------------------
// ContainerTopOKBody OK response to ContainerTop operation
// swagger:model ContainerTopOKBody
type ContainerTopOKBody struct {
// Each process running in the container, where each is process
// is an array of values corresponding to the titles.
//
// Required: true
Processes [][]string `json:"Processes"`
// The ps column titles
// Required: true
Titles []string `json:"Titles"`
}

View File

@@ -1,16 +0,0 @@
package container // import "github.com/docker/docker/api/types/container"
// ----------------------------------------------------------------------------
// Code generated by `swagger generate operation`. DO NOT EDIT.
//
// See hack/generate-swagger-api.sh
// ----------------------------------------------------------------------------
// ContainerUpdateOKBody OK response to ContainerUpdate operation
// swagger:model ContainerUpdateOKBody
type ContainerUpdateOKBody struct {
// warnings
// Required: true
Warnings []string `json:"Warnings"`
}

View File

@@ -0,0 +1,8 @@
package container
// DiskUsage contains disk usage for containers.
type DiskUsage struct {
TotalSize int64
Reclaimable int64
Items []*Summary
}

View File

@@ -1,5 +1,13 @@
package container package container
import "github.com/docker/docker/api/types/common"
// ExecCreateResponse is the response for a successful exec-create request.
// It holds the ID of the exec that was created.
//
// TODO(thaJeztah): make this a distinct type.
type ExecCreateResponse = common.IDResponse
// ExecOptions is a small subset of the Config struct that holds the configuration // ExecOptions is a small subset of the Config struct that holds the configuration
// for the exec feature of docker. // for the exec feature of docker.
type ExecOptions struct { type ExecOptions struct {
@@ -10,11 +18,13 @@ type ExecOptions struct {
AttachStdin bool // Attach the standard input, makes possible user interaction AttachStdin bool // Attach the standard input, makes possible user interaction
AttachStderr bool // Attach the standard error AttachStderr bool // Attach the standard error
AttachStdout bool // Attach the standard output AttachStdout bool // Attach the standard output
Detach bool // Execute in detach mode
DetachKeys string // Escape keys for detach DetachKeys string // Escape keys for detach
Env []string // Environment variables Env []string // Environment variables
WorkingDir string // Working directory WorkingDir string // Working directory
Cmd []string // Execution commands and args Cmd []string // Execution commands and args
// Deprecated: the Detach field is not used, and will be removed in a future release.
Detach bool
} }
// ExecStartOptions is a temp struct used by execStart // ExecStartOptions is a temp struct used by execStart

View File

@@ -0,0 +1,50 @@
package container
import (
"fmt"
"strings"
"time"
)
// HealthStatus is a string representation of the container's health.
//
// It currently is an alias for string, but may become a distinct type in future.
type HealthStatus = string
// Health states
const (
NoHealthcheck HealthStatus = "none" // Indicates there is no healthcheck
Starting HealthStatus = "starting" // Starting indicates that the container is not yet ready
Healthy HealthStatus = "healthy" // Healthy indicates that the container is running correctly
Unhealthy HealthStatus = "unhealthy" // Unhealthy indicates that the container has a problem
)
// Health stores information about the container's healthcheck results
type Health struct {
Status HealthStatus // Status is one of [Starting], [Healthy] or [Unhealthy].
FailingStreak int // FailingStreak is the number of consecutive failures
Log []*HealthcheckResult // Log contains the last few results (oldest first)
}
// HealthcheckResult stores information about a single run of a healthcheck probe
type HealthcheckResult struct {
Start time.Time // Start is the time this check started
End time.Time // End is the time this check ended
ExitCode int // ExitCode meanings: 0=healthy, 1=unhealthy, 2=reserved (considered unhealthy), else=error running probe
Output string // Output from last check
}
var validHealths = []string{
NoHealthcheck, Starting, Healthy, Unhealthy,
}
// ValidateHealthStatus checks if the provided string is a valid
// container [HealthStatus].
func ValidateHealthStatus(s HealthStatus) error {
switch s {
case NoHealthcheck, Starting, Healthy, Unhealthy:
return nil
default:
return errInvalidParameter{error: fmt.Errorf("invalid value for health (%s): must be one of %s", s, strings.Join(validHealths, ", "))}
}
}

View File

@@ -1,4 +1,4 @@
package container // import "github.com/docker/docker/api/types/container" package container
import ( import (
"errors" "errors"
@@ -10,7 +10,7 @@ import (
"github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/strslice" "github.com/docker/docker/api/types/strslice"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
units "github.com/docker/go-units" "github.com/docker/go-units"
) )
// CgroupnsMode represents the cgroup namespace mode of the container // CgroupnsMode represents the cgroup namespace mode of the container
@@ -145,7 +145,7 @@ func (n NetworkMode) IsDefault() bool {
// IsPrivate indicates whether container uses its private network stack. // IsPrivate indicates whether container uses its private network stack.
func (n NetworkMode) IsPrivate() bool { func (n NetworkMode) IsPrivate() bool {
return !(n.IsHost() || n.IsContainer()) return !n.IsHost() && !n.IsContainer()
} }
// IsContainer indicates whether container uses a container network stack. // IsContainer indicates whether container uses a container network stack.
@@ -230,7 +230,7 @@ type PidMode string
// IsPrivate indicates whether the container uses its own new pid namespace. // IsPrivate indicates whether the container uses its own new pid namespace.
func (n PidMode) IsPrivate() bool { func (n PidMode) IsPrivate() bool {
return !(n.IsHost() || n.IsContainer()) return !n.IsHost() && !n.IsContainer()
} }
// IsHost indicates whether the container uses the host's pid namespace. // IsHost indicates whether the container uses the host's pid namespace.

View File

@@ -1,6 +1,6 @@
//go:build !windows //go:build !windows
package container // import "github.com/docker/docker/api/types/container" package container
import "github.com/docker/docker/api/types/network" import "github.com/docker/docker/api/types/network"

View File

@@ -1,4 +1,4 @@
package container // import "github.com/docker/docker/api/types/container" package container
import "github.com/docker/docker/api/types/network" import "github.com/docker/docker/api/types/network"

View File

@@ -0,0 +1,56 @@
package container
import (
"github.com/docker/docker/api/types/network"
"github.com/docker/go-connections/nat"
)
// NetworkSettings exposes the network settings in the api
type NetworkSettings struct {
NetworkSettingsBase
DefaultNetworkSettings
Networks map[string]*network.EndpointSettings
}
// NetworkSettingsBase holds networking state for a container when inspecting it.
type NetworkSettingsBase struct {
Bridge string // Bridge contains the name of the default bridge interface iff it was set through the daemon --bridge flag.
SandboxID string // SandboxID uniquely represents a container's network stack
SandboxKey string // SandboxKey identifies the sandbox
Ports nat.PortMap // Ports is a collection of PortBinding indexed by Port
// HairpinMode specifies if hairpin NAT should be enabled on the virtual interface
//
// Deprecated: This field is never set and will be removed in a future release.
HairpinMode bool
// LinkLocalIPv6Address is an IPv6 unicast address using the link-local prefix
//
// Deprecated: This field is never set and will be removed in a future release.
LinkLocalIPv6Address string
// LinkLocalIPv6PrefixLen is the prefix length of an IPv6 unicast address
//
// Deprecated: This field is never set and will be removed in a future release.
LinkLocalIPv6PrefixLen int
SecondaryIPAddresses []network.Address // Deprecated: This field is never set and will be removed in a future release.
SecondaryIPv6Addresses []network.Address // Deprecated: This field is never set and will be removed in a future release.
}
// DefaultNetworkSettings holds network information
// during the 2 release deprecation period.
// It will be removed in Docker 1.11.
type DefaultNetworkSettings struct {
EndpointID string // EndpointID uniquely represents a service endpoint in a Sandbox
Gateway string // Gateway holds the gateway address for the network
GlobalIPv6Address string // GlobalIPv6Address holds network's global IPv6 address
GlobalIPv6PrefixLen int // GlobalIPv6PrefixLen represents mask length of network's global IPv6 address
IPAddress string // IPAddress holds the IPv4 address for the network
IPPrefixLen int // IPPrefixLen represents mask length of network's IPv4 address
IPv6Gateway string // IPv6Gateway holds gateway address specific for IPv6
MacAddress string // MacAddress holds the MAC address for the network
}
// NetworkSettingsSummary provides a summary of container's networks
// in /containers/json
type NetworkSettingsSummary struct {
Networks map[string]*network.EndpointSettings
}

View File

@@ -1,4 +1,4 @@
package types package container
// This file was generated by the swagger tool. // This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command // Editing this file might prove futile when you re-run the swagger generate command

View File

@@ -0,0 +1,64 @@
package container
import (
"fmt"
"strings"
)
// ContainerState is a string representation of the container's current state.
//
// It currently is an alias for string, but may become a distinct type in the future.
type ContainerState = string
const (
StateCreated ContainerState = "created" // StateCreated indicates the container is created, but not (yet) started.
StateRunning ContainerState = "running" // StateRunning indicates that the container is running.
StatePaused ContainerState = "paused" // StatePaused indicates that the container's current state is paused.
StateRestarting ContainerState = "restarting" // StateRestarting indicates that the container is currently restarting.
StateRemoving ContainerState = "removing" // StateRemoving indicates that the container is being removed.
StateExited ContainerState = "exited" // StateExited indicates that the container exited.
StateDead ContainerState = "dead" // StateDead indicates that the container failed to be deleted. Containers in this state are attempted to be cleaned up when the daemon restarts.
)
var validStates = []ContainerState{
StateCreated, StateRunning, StatePaused, StateRestarting, StateRemoving, StateExited, StateDead,
}
// ValidateContainerState checks if the provided string is a valid
// container [ContainerState].
func ValidateContainerState(s ContainerState) error {
switch s {
case StateCreated, StateRunning, StatePaused, StateRestarting, StateRemoving, StateExited, StateDead:
return nil
default:
return errInvalidParameter{error: fmt.Errorf("invalid value for state (%s): must be one of %s", s, strings.Join(validStates, ", "))}
}
}
// StateStatus is used to return container wait results.
// Implements exec.ExitCode interface.
// This type is needed as State include a sync.Mutex field which make
// copying it unsafe.
type StateStatus struct {
exitCode int
err error
}
// ExitCode returns current exitcode for the state.
func (s StateStatus) ExitCode() int {
return s.exitCode
}
// Err returns current error for the state. Returns nil if the container had
// exited on its own.
func (s StateStatus) Err() error {
return s.err
}
// NewStateStatus returns a new StateStatus with the given exit code and error.
func NewStateStatus(exitCode int, err error) StateStatus {
return StateStatus{
exitCode: exitCode,
err: err,
}
}

View File

@@ -148,7 +148,15 @@ type PidsStats struct {
} }
// Stats is Ultimate struct aggregating all types of stats of one container // Stats is Ultimate struct aggregating all types of stats of one container
type Stats struct { //
// Deprecated: use [StatsResponse] instead. This type will be removed in the next release.
type Stats = StatsResponse
// StatsResponse aggregates all types of stats of one container.
type StatsResponse struct {
Name string `json:"name,omitempty"`
ID string `json:"id,omitempty"`
// Common stats // Common stats
Read time.Time `json:"read"` Read time.Time `json:"read"`
PreRead time.Time `json:"preread"` PreRead time.Time `json:"preread"`
@@ -165,17 +173,5 @@ type Stats struct {
CPUStats CPUStats `json:"cpu_stats,omitempty"` CPUStats CPUStats `json:"cpu_stats,omitempty"`
PreCPUStats CPUStats `json:"precpu_stats,omitempty"` // "Pre"="Previous" PreCPUStats CPUStats `json:"precpu_stats,omitempty"` // "Pre"="Previous"
MemoryStats MemoryStats `json:"memory_stats,omitempty"` MemoryStats MemoryStats `json:"memory_stats,omitempty"`
}
// StatsResponse is newly used Networks.
//
// TODO(thaJeztah): unify with [Stats]. This wrapper was to account for pre-api v1.21 changes, see https://github.com/moby/moby/commit/d3379946ec96fb6163cb8c4517d7d5a067045801
type StatsResponse struct {
Stats
Name string `json:"name,omitempty"`
ID string `json:"id,omitempty"`
// Networks request version >=1.21
Networks map[string]NetworkStats `json:"networks,omitempty"` Networks map[string]NetworkStats `json:"networks,omitempty"`
} }

View File

@@ -0,0 +1,18 @@
package container
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
// TopResponse ContainerTopResponse
//
// Container "top" response.
// swagger:model TopResponse
type TopResponse struct {
// Each process running in the container, where each process
// is an array of values corresponding to the titles.
Processes [][]string `json:"Processes"`
// The ps column titles
Titles []string `json:"Titles"`
}

View File

@@ -0,0 +1,14 @@
package container
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
// UpdateResponse ContainerUpdateResponse
//
// Response for a successful container-update.
// swagger:model UpdateResponse
type UpdateResponse struct {
// Warnings encountered when updating the container.
Warnings []string `json:"Warnings"`
}

View File

@@ -1,4 +1,4 @@
package container // import "github.com/docker/docker/api/types/container" package container
// WaitCondition is a type used to specify a container state for which // WaitCondition is a type used to specify a container state for which
// to wait. // to wait.

View File

@@ -1,4 +1,5 @@
package events // import "github.com/docker/docker/api/types/events" package events
import "github.com/docker/docker/api/types/filters" import "github.com/docker/docker/api/types/filters"
// Type is used for event-types. // Type is used for event-types.
@@ -111,11 +112,14 @@ type Actor struct {
// Message represents the information an event contains // Message represents the information an event contains
type Message struct { type Message struct {
// Deprecated information from JSONMessage. // Deprecated: use Action instead.
// Information from JSONMessage.
// With data only in container events. // With data only in container events.
Status string `json:"status,omitempty"` // Deprecated: use Action instead. Status string `json:"status,omitempty"`
ID string `json:"id,omitempty"` // Deprecated: use Actor.ID instead. // Deprecated: use Actor.ID instead.
From string `json:"from,omitempty"` // Deprecated: use Actor.Attributes["image"] instead. ID string `json:"id,omitempty"`
// Deprecated: use Actor.Attributes["image"] instead.
From string `json:"from,omitempty"`
Type Type Type Type
Action Action Action Action

View File

@@ -22,16 +22,3 @@ func (e invalidFilter) Error() string {
// InvalidParameter marks this error as ErrInvalidParameter // InvalidParameter marks this error as ErrInvalidParameter
func (e invalidFilter) InvalidParameter() {} func (e invalidFilter) InvalidParameter() {}
// unreachableCode is an error indicating that the code path was not expected to be reached.
type unreachableCode struct {
Filter string
Value []string
}
// System marks this error as ErrSystem
func (e unreachableCode) System() {}
func (e unreachableCode) Error() string {
return fmt.Sprintf("unreachable code reached for filter: %q with values: %s", e.Filter, e.Value)
}

View File

@@ -2,7 +2,7 @@
Package filters provides tools for encoding a mapping of keys to a set of Package filters provides tools for encoding a mapping of keys to a set of
multiple values. multiple values.
*/ */
package filters // import "github.com/docker/docker/api/types/filters" package filters
import ( import (
"encoding/json" "encoding/json"
@@ -200,7 +200,6 @@ func (args Args) Match(field, source string) bool {
// Error is not nil only if the filter values are not valid boolean or are conflicting. // Error is not nil only if the filter values are not valid boolean or are conflicting.
func (args Args) GetBoolOrDefault(key string, defaultValue bool) (bool, error) { func (args Args) GetBoolOrDefault(key string, defaultValue bool) (bool, error) {
fieldValues, ok := args.fields[key] fieldValues, ok := args.fields[key]
if !ok { if !ok {
return defaultValue, nil return defaultValue, nil
} }
@@ -211,20 +210,11 @@ func (args Args) GetBoolOrDefault(key string, defaultValue bool) (bool, error) {
isFalse := fieldValues["0"] || fieldValues["false"] isFalse := fieldValues["0"] || fieldValues["false"]
isTrue := fieldValues["1"] || fieldValues["true"] isTrue := fieldValues["1"] || fieldValues["true"]
if isFalse == isTrue {
conflicting := isFalse && isTrue // Either no or conflicting truthy/falsy value were provided
invalid := !isFalse && !isTrue
if conflicting || invalid {
return defaultValue, &invalidFilter{key, args.Get(key)} return defaultValue, &invalidFilter{key, args.Get(key)}
} else if isFalse {
return false, nil
} else if isTrue {
return true, nil
} }
return isTrue, nil
// This code shouldn't be reached.
return defaultValue, &unreachableCode{Filter: key, Value: args.Get(key)}
} }
// ExactMatch returns true if the source matches exactly one of the values. // ExactMatch returns true if the source matches exactly one of the values.

View File

@@ -0,0 +1,8 @@
package image
// DiskUsage contains disk usage for images.
type DiskUsage struct {
TotalSize int64
Reclaimable int64
Items []*Summary
}

View File

@@ -1,4 +1,4 @@
package image // import "github.com/docker/docker/api/types/image" package image
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Code generated by `swagger generate operation`. DO NOT EDIT. // Code generated by `swagger generate operation`. DO NOT EDIT.

View File

@@ -0,0 +1,142 @@
package image
import (
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/storage"
dockerspec "github.com/moby/docker-image-spec/specs-go/v1"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)
// RootFS returns Image's RootFS description including the layer IDs.
type RootFS struct {
Type string `json:",omitempty"`
Layers []string `json:",omitempty"`
}
// InspectResponse contains response of Engine API:
// GET "/images/{name:.*}/json"
type InspectResponse struct {
// ID is the content-addressable ID of an image.
//
// This identifier is a content-addressable digest calculated from the
// image's configuration (which includes the digests of layers used by
// the image).
//
// Note that this digest differs from the `RepoDigests` below, which
// holds digests of image manifests that reference the image.
ID string `json:"Id"`
// RepoTags is a list of image names/tags in the local image cache that
// reference this image.
//
// Multiple image tags can refer to the same image, and this list may be
// empty if no tags reference the image, in which case the image is
// "untagged", in which case it can still be referenced by its ID.
RepoTags []string
// RepoDigests is a list of content-addressable digests of locally available
// image manifests that the image is referenced from. Multiple manifests can
// refer to the same image.
//
// These digests are usually only available if the image was either pulled
// from a registry, or if the image was pushed to a registry, which is when
// the manifest is generated and its digest calculated.
RepoDigests []string
// Parent is the ID of the parent image.
//
// Depending on how the image was created, this field may be empty and
// is only set for images that were built/created locally. This field
// is empty if the image was pulled from an image registry.
Parent string
// Comment is an optional message that can be set when committing or
// importing the image.
Comment string
// Created is the date and time at which the image was created, formatted in
// RFC 3339 nano-seconds (time.RFC3339Nano).
//
// This information is only available if present in the image,
// and omitted otherwise.
Created string `json:",omitempty"`
// Container is the ID of the container that was used to create the image.
//
// Depending on how the image was created, this field may be empty.
//
// Deprecated: this field is omitted in API v1.45, but kept for backward compatibility.
Container string `json:",omitempty"`
// ContainerConfig is an optional field containing the configuration of the
// container that was last committed when creating the image.
//
// Previous versions of Docker builder used this field to store build cache,
// and it is not in active use anymore.
//
// Deprecated: this field is omitted in API v1.45, but kept for backward compatibility.
ContainerConfig *container.Config `json:",omitempty"`
// DockerVersion is the version of Docker that was used to build the image.
//
// Depending on how the image was created, this field may be empty.
DockerVersion string
// Author is the name of the author that was specified when committing the
// image, or as specified through MAINTAINER (deprecated) in the Dockerfile.
Author string
Config *dockerspec.DockerOCIImageConfig
// Architecture is the hardware CPU architecture that the image runs on.
Architecture string
// Variant is the CPU architecture variant (presently ARM-only).
Variant string `json:",omitempty"`
// OS is the Operating System the image is built to run on.
Os string
// OsVersion is the version of the Operating System the image is built to
// run on (especially for Windows).
OsVersion string `json:",omitempty"`
// Size is the total size of the image including all layers it is composed of.
Size int64
// VirtualSize is the total size of the image including all layers it is
// composed of.
//
// Deprecated: this field is omitted in API v1.44, but kept for backward compatibility. Use Size instead.
VirtualSize int64 `json:"VirtualSize,omitempty"`
// GraphDriver holds information about the storage driver used to store the
// container's and image's filesystem.
GraphDriver storage.DriverData
// RootFS contains information about the image's RootFS, including the
// layer IDs.
RootFS RootFS
// Metadata of the image in the local cache.
//
// This information is local to the daemon, and not part of the image itself.
Metadata Metadata
// Descriptor is the OCI descriptor of the image target.
// It's only set if the daemon provides a multi-platform image store.
//
// WARNING: This is experimental and may change at any time without any backward
// compatibility.
Descriptor *ocispec.Descriptor `json:"Descriptor,omitempty"`
// Manifests is a list of image manifests available in this image. It
// provides a more detailed view of the platform-specific image manifests or
// other image-attached data like build attestations.
//
// Only available if the daemon provides a multi-platform image store, the client
// requests manifests AND does not request a specific platform.
//
// WARNING: This is experimental and may change at any time without any backward
// compatibility.
Manifests []ManifestSummary `json:"Manifests,omitempty"`
}

View File

@@ -38,7 +38,7 @@ type PullOptions struct {
// authentication header value in base64 encoded format, or an error if the // authentication header value in base64 encoded format, or an error if the
// privilege request fails. // privilege request fails.
// //
// Also see [github.com/docker/docker/api/types.RequestPrivilegeFunc]. // For details, refer to [github.com/docker/docker/api/types/registry.RequestAuthConfig].
PrivilegeFunc func(context.Context) (string, error) PrivilegeFunc func(context.Context) (string, error)
Platform string Platform string
} }
@@ -53,7 +53,7 @@ type PushOptions struct {
// authentication header value in base64 encoded format, or an error if the // authentication header value in base64 encoded format, or an error if the
// privilege request fails. // privilege request fails.
// //
// Also see [github.com/docker/docker/api/types.RequestPrivilegeFunc]. // For details, refer to [github.com/docker/docker/api/types/registry.RequestAuthConfig].
PrivilegeFunc func(context.Context) (string, error) PrivilegeFunc func(context.Context) (string, error)
// Platform is an optional field that selects a specific platform to push // Platform is an optional field that selects a specific platform to push
@@ -75,6 +75,8 @@ type ListOptions struct {
SharedSize bool SharedSize bool
// ContainerCount indicates whether container count should be computed. // ContainerCount indicates whether container count should be computed.
//
// Deprecated: This field has been unused and is no longer required and will be removed in a future version.
ContainerCount bool ContainerCount bool
// Manifests indicates whether the image manifests should be returned. // Manifests indicates whether the image manifests should be returned.
@@ -83,6 +85,40 @@ type ListOptions struct {
// RemoveOptions holds parameters to remove images. // RemoveOptions holds parameters to remove images.
type RemoveOptions struct { type RemoveOptions struct {
Platforms []ocispec.Platform
Force bool Force bool
PruneChildren bool PruneChildren bool
} }
// HistoryOptions holds parameters to get image history.
type HistoryOptions struct {
// Platform from the manifest list to use for history.
Platform *ocispec.Platform
}
// LoadOptions holds parameters to load images.
type LoadOptions struct {
// Quiet suppresses progress output
Quiet bool
// Platforms selects the platforms to load if the image is a
// multi-platform image and has multiple variants.
Platforms []ocispec.Platform
}
type InspectOptions struct {
// Manifests returns the image manifests.
Manifests bool
// Platform selects the specific platform of a multi-platform image to inspect.
//
// This option is only available for API version 1.49 and up.
Platform *ocispec.Platform
}
// SaveOptions holds parameters to save images.
type SaveOptions struct {
// Platforms selects the platforms to save if the image is a
// multi-platform image and has multiple variants.
Platforms []ocispec.Platform
}

View File

@@ -1,5 +1,7 @@
package image package image
import ocispec "github.com/opencontainers/image-spec/specs-go/v1"
type Summary struct { type Summary struct {
// Number of containers using this image. Includes both stopped and running // Number of containers using this image. Includes both stopped and running
@@ -42,6 +44,13 @@ type Summary struct {
// Required: true // Required: true
ParentID string `json:"ParentId"` ParentID string `json:"ParentId"`
// Descriptor is the OCI descriptor of the image target.
// It's only set if the daemon provides a multi-platform image store.
//
// WARNING: This is experimental and may change at any time without any backward
// compatibility.
Descriptor *ocispec.Descriptor `json:"Descriptor,omitempty"`
// Manifests is a list of image manifests available in this image. It // Manifests is a list of image manifests available in this image. It
// provides a more detailed view of the platform-specific image manifests or // provides a more detailed view of the platform-specific image manifests or
// other image-attached data like build attestations. // other image-attached data like build attestations.

View File

@@ -1,4 +1,4 @@
package mount // import "github.com/docker/docker/api/types/mount" package mount
import ( import (
"os" "os"
@@ -19,6 +19,8 @@ const (
TypeNamedPipe Type = "npipe" TypeNamedPipe Type = "npipe"
// TypeCluster is the type for Swarm Cluster Volumes. // TypeCluster is the type for Swarm Cluster Volumes.
TypeCluster Type = "cluster" TypeCluster Type = "cluster"
// TypeImage is the type for mounting another image's filesystem
TypeImage Type = "image"
) )
// Mount represents a mount (volume). // Mount represents a mount (volume).
@@ -34,6 +36,7 @@ type Mount struct {
BindOptions *BindOptions `json:",omitempty"` BindOptions *BindOptions `json:",omitempty"`
VolumeOptions *VolumeOptions `json:",omitempty"` VolumeOptions *VolumeOptions `json:",omitempty"`
ImageOptions *ImageOptions `json:",omitempty"`
TmpfsOptions *TmpfsOptions `json:",omitempty"` TmpfsOptions *TmpfsOptions `json:",omitempty"`
ClusterOptions *ClusterOptions `json:",omitempty"` ClusterOptions *ClusterOptions `json:",omitempty"`
} }
@@ -100,6 +103,10 @@ type VolumeOptions struct {
DriverConfig *Driver `json:",omitempty"` DriverConfig *Driver `json:",omitempty"`
} }
type ImageOptions struct {
Subpath string `json:",omitempty"`
}
// Driver represents a volume driver. // Driver represents a volume driver.
type Driver struct { type Driver struct {
Name string `json:",omitempty"` Name string `json:",omitempty"`

View File

@@ -19,6 +19,12 @@ type EndpointSettings struct {
// generated address). // generated address).
MacAddress string MacAddress string
DriverOpts map[string]string DriverOpts map[string]string
// GwPriority determines which endpoint will provide the default gateway
// for the container. The endpoint with the highest priority will be used.
// If multiple endpoints have the same priority, they are lexicographically
// sorted based on their network name, and the one that sorts first is picked.
GwPriority int
// Operational data // Operational data
NetworkID string NetworkID string
EndpointID string EndpointID string

View File

@@ -1,4 +1,4 @@
package network // import "github.com/docker/docker/api/types/network" package network
import ( import (
"time" "time"
@@ -33,6 +33,7 @@ type CreateRequest struct {
type CreateOptions struct { type CreateOptions struct {
Driver string // Driver is the driver-name used to create the network (e.g. `bridge`, `overlay`) Driver string // Driver is the driver-name used to create the network (e.g. `bridge`, `overlay`)
Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level). Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level).
EnableIPv4 *bool `json:",omitempty"` // EnableIPv4 represents whether to enable IPv4.
EnableIPv6 *bool `json:",omitempty"` // EnableIPv6 represents whether to enable IPv6. EnableIPv6 *bool `json:",omitempty"` // EnableIPv6 represents whether to enable IPv6.
IPAM *IPAM // IPAM is the network's IP Address Management. IPAM *IPAM // IPAM is the network's IP Address Management.
Internal bool // Internal represents if the network is used internal only. Internal bool // Internal represents if the network is used internal only.
@@ -76,7 +77,8 @@ type Inspect struct {
Created time.Time // Created is the time the network created Created time.Time // Created is the time the network created
Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level) Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level)
Driver string // Driver is the Driver name used to create the network (e.g. `bridge`, `overlay`) Driver string // Driver is the Driver name used to create the network (e.g. `bridge`, `overlay`)
EnableIPv6 bool // EnableIPv6 represents whether to enable IPv6 EnableIPv4 bool // EnableIPv4 represents whether IPv4 is enabled
EnableIPv6 bool // EnableIPv6 represents whether IPv6 is enabled
IPAM IPAM // IPAM is the network's IP Address Management IPAM IPAM // IPAM is the network's IP Address Management
Internal bool // Internal represents if the network is used internal only Internal bool // Internal represents if the network is used internal only
Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode.

View File

@@ -1,4 +1,4 @@
package types // import "github.com/docker/docker/api/types" package types
import ( import (
"encoding/json" "encoding/json"

View File

@@ -1,17 +1,30 @@
package registry // import "github.com/docker/docker/api/types/registry" package registry
import ( import (
"context"
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"strings" "strings"
"github.com/pkg/errors"
) )
// AuthHeader is the name of the header used to send encoded registry // AuthHeader is the name of the header used to send encoded registry
// authorization credentials for registry operations (push/pull). // authorization credentials for registry operations (push/pull).
const AuthHeader = "X-Registry-Auth" const AuthHeader = "X-Registry-Auth"
// RequestAuthConfig is a function interface that clients can supply
// to retry operations after getting an authorization error.
//
// The function must return the [AuthHeader] value ([AuthConfig]), encoded
// in base64url format ([RFC4648, section 5]), which can be decoded by
// [DecodeAuthConfig].
//
// It must return an error if the privilege request fails.
//
// [RFC4648, section 5]: https://tools.ietf.org/html/rfc4648#section-5
type RequestAuthConfig func(context.Context) (string, error)
// AuthConfig contains authorization information for connecting to a Registry. // AuthConfig contains authorization information for connecting to a Registry.
type AuthConfig struct { type AuthConfig struct {
Username string `json:"username,omitempty"` Username string `json:"username,omitempty"`
@@ -70,6 +83,8 @@ func DecodeAuthConfig(authEncoded string) (*AuthConfig, error) {
// Like [DecodeAuthConfig], this function always returns an [AuthConfig], even if an // Like [DecodeAuthConfig], this function always returns an [AuthConfig], even if an
// error occurs. It is up to the caller to decide if authentication is required, // error occurs. It is up to the caller to decide if authentication is required,
// and if the error can be ignored. // and if the error can be ignored.
//
// Deprecated: this function is no longer used and will be removed in the next release.
func DecodeAuthConfigBody(rdr io.ReadCloser) (*AuthConfig, error) { func DecodeAuthConfigBody(rdr io.ReadCloser) (*AuthConfig, error) {
return decodeAuthConfigFromReader(rdr) return decodeAuthConfigFromReader(rdr)
} }
@@ -85,7 +100,7 @@ func decodeAuthConfigFromReader(rdr io.Reader) (*AuthConfig, error) {
} }
func invalid(err error) error { func invalid(err error) error {
return errInvalidParameter{errors.Wrap(err, "invalid X-Registry-Auth header")} return errInvalidParameter{fmt.Errorf("invalid X-Registry-Auth header: %w", err)}
} }
type errInvalidParameter struct{ error } type errInvalidParameter struct{ error }

View File

@@ -1,4 +1,4 @@
package registry // import "github.com/docker/docker/api/types/registry" package registry
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// DO NOT EDIT THIS FILE // DO NOT EDIT THIS FILE

View File

@@ -1,4 +1,7 @@
package registry // import "github.com/docker/docker/api/types/registry" // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
//go:build go1.23
package registry
import ( import (
"encoding/json" "encoding/json"
@@ -9,11 +12,32 @@ import (
// ServiceConfig stores daemon registry services configuration. // ServiceConfig stores daemon registry services configuration.
type ServiceConfig struct { type ServiceConfig struct {
AllowNondistributableArtifactsCIDRs []*NetIPNet AllowNondistributableArtifactsCIDRs []*NetIPNet `json:"AllowNondistributableArtifactsCIDRs,omitempty"` // Deprecated: non-distributable artifacts are deprecated and enabled by default. This field will be removed in the next release.
AllowNondistributableArtifactsHostnames []string AllowNondistributableArtifactsHostnames []string `json:"AllowNondistributableArtifactsHostnames,omitempty"` // Deprecated: non-distributable artifacts are deprecated and enabled by default. This field will be removed in the next release.
InsecureRegistryCIDRs []*NetIPNet `json:"InsecureRegistryCIDRs"` InsecureRegistryCIDRs []*NetIPNet `json:"InsecureRegistryCIDRs"`
IndexConfigs map[string]*IndexInfo `json:"IndexConfigs"` IndexConfigs map[string]*IndexInfo `json:"IndexConfigs"`
Mirrors []string Mirrors []string
// ExtraFields is for internal use to include deprecated fields on older API versions.
ExtraFields map[string]any `json:"-"`
}
// MarshalJSON implements a custom marshaler to include legacy fields
// in API responses.
func (sc *ServiceConfig) MarshalJSON() ([]byte, error) {
type tmp ServiceConfig
base, err := json.Marshal((*tmp)(sc))
if err != nil {
return nil, err
}
var merged map[string]any
_ = json.Unmarshal(base, &merged)
for k, v := range sc.ExtraFields {
merged[k] = v
}
return json.Marshal(merged)
} }
// NetIPNet is the net.IPNet type, which can be marshalled and // NetIPNet is the net.IPNet type, which can be marshalled and
@@ -31,15 +55,17 @@ func (ipnet *NetIPNet) MarshalJSON() ([]byte, error) {
} }
// UnmarshalJSON sets the IPNet from a byte array of JSON // UnmarshalJSON sets the IPNet from a byte array of JSON
func (ipnet *NetIPNet) UnmarshalJSON(b []byte) (err error) { func (ipnet *NetIPNet) UnmarshalJSON(b []byte) error {
var ipnetStr string var ipnetStr string
if err = json.Unmarshal(b, &ipnetStr); err == nil { if err := json.Unmarshal(b, &ipnetStr); err != nil {
var cidr *net.IPNet return err
if _, cidr, err = net.ParseCIDR(ipnetStr); err == nil { }
_, cidr, err := net.ParseCIDR(ipnetStr)
if err != nil {
return err
}
*ipnet = NetIPNet(*cidr) *ipnet = NetIPNet(*cidr)
} return nil
}
return
} }
// IndexInfo contains information about a registry // IndexInfo contains information about a registry

View File

@@ -10,11 +10,12 @@ import (
type SearchOptions struct { type SearchOptions struct {
RegistryAuth string RegistryAuth string
// PrivilegeFunc is a [types.RequestPrivilegeFunc] the client can // PrivilegeFunc is a function that clients can supply to retry operations
// supply to retry operations after getting an authorization error. // after getting an authorization error. This function returns the registry
// authentication header value in base64 encoded format, or an error if the
// privilege request fails.
// //
// It must return the registry authentication header value in base64 // For details, refer to [github.com/docker/docker/api/types/registry.RequestAuthConfig].
// format, or an error if the privilege request fails.
PrivilegeFunc func(context.Context) (string, error) PrivilegeFunc func(context.Context) (string, error)
Filters filters.Args Filters filters.Args
Limit int Limit int

View File

@@ -1,13 +1,13 @@
package types package storage
// This file was generated by the swagger tool. // This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command // Editing this file might prove futile when you re-run the swagger generate command
// GraphDriverData Information about the storage driver used to store the container's and // DriverData Information about the storage driver used to store the container's and
// image's filesystem. // image's filesystem.
// //
// swagger:model GraphDriverData // swagger:model DriverData
type GraphDriverData struct { type DriverData struct {
// Low-level storage metadata, provided as key/value pairs. // Low-level storage metadata, provided as key/value pairs.
// //

View File

@@ -1,4 +1,4 @@
package strslice // import "github.com/docker/docker/api/types/strslice" package strslice
import "encoding/json" import "encoding/json"

View File

@@ -1,4 +1,4 @@
package swarm // import "github.com/docker/docker/api/types/swarm" package swarm
import ( import (
"strconv" "strconv"

View File

@@ -1,6 +1,10 @@
package swarm // import "github.com/docker/docker/api/types/swarm" package swarm
import "os" import (
"os"
"github.com/docker/docker/api/types/filters"
)
// Config represents a config. // Config represents a config.
type Config struct { type Config struct {
@@ -12,6 +16,12 @@ type Config struct {
// ConfigSpec represents a config specification from a config in swarm // ConfigSpec represents a config specification from a config in swarm
type ConfigSpec struct { type ConfigSpec struct {
Annotations Annotations
// Data is the data to store as a config.
//
// The maximum allowed size is 1000KB, as defined in [MaxConfigSize].
//
// [MaxConfigSize]: https://pkg.go.dev/github.com/moby/swarmkit/v2@v2.0.0-20250103191802-8c1959736554/manager/controlapi#MaxConfigSize
Data []byte `json:",omitempty"` Data []byte `json:",omitempty"`
// Templating controls whether and how to evaluate the config payload as // Templating controls whether and how to evaluate the config payload as
@@ -38,3 +48,15 @@ type ConfigReference struct {
ConfigID string ConfigID string
ConfigName string ConfigName string
} }
// ConfigCreateResponse contains the information returned to a client
// on the creation of a new config.
type ConfigCreateResponse struct {
// ID is the id of the created config.
ID string
}
// ConfigListOptions holds parameters to list configs
type ConfigListOptions struct {
Filters filters.Args
}

View File

@@ -1,4 +1,4 @@
package swarm // import "github.com/docker/docker/api/types/swarm" package swarm
import ( import (
"time" "time"

View File

@@ -1,4 +1,4 @@
package swarm // import "github.com/docker/docker/api/types/swarm" package swarm
import ( import (
"github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/network"

View File

@@ -1,4 +1,6 @@
package swarm // import "github.com/docker/docker/api/types/swarm" package swarm
import "github.com/docker/docker/api/types/filters"
// Node represents a node. // Node represents a node.
type Node struct { type Node struct {
@@ -137,3 +139,13 @@ const (
type Topology struct { type Topology struct {
Segments map[string]string `json:",omitempty"` Segments map[string]string `json:",omitempty"`
} }
// NodeListOptions holds parameters to list nodes with.
type NodeListOptions struct {
Filters filters.Args
}
// NodeRemoveOptions holds parameters to remove nodes with.
type NodeRemoveOptions struct {
Force bool
}

View File

@@ -1,4 +1,4 @@
package swarm // import "github.com/docker/docker/api/types/swarm" package swarm
// RuntimeType is the type of runtime used for the TaskSpec // RuntimeType is the type of runtime used for the TaskSpec
type RuntimeType string type RuntimeType string

View File

@@ -1,3 +1,3 @@
//go:generate protoc --gogofaster_out=import_path=github.com/docker/docker/api/types/swarm/runtime:. plugin.proto //go:generate protoc --gogofaster_out=import_path=github.com/docker/docker/api/types/swarm/runtime:. plugin.proto
package runtime // import "github.com/docker/docker/api/types/swarm/runtime" package runtime

View File

@@ -1,6 +1,10 @@
package swarm // import "github.com/docker/docker/api/types/swarm" package swarm
import "os" import (
"os"
"github.com/docker/docker/api/types/filters"
)
// Secret represents a secret. // Secret represents a secret.
type Secret struct { type Secret struct {
@@ -12,8 +16,22 @@ type Secret struct {
// SecretSpec represents a secret specification from a secret in swarm // SecretSpec represents a secret specification from a secret in swarm
type SecretSpec struct { type SecretSpec struct {
Annotations Annotations
// Data is the data to store as a secret. It must be empty if a
// [Driver] is used, in which case the data is loaded from an external
// secret store. The maximum allowed size is 500KB, as defined in
// [MaxSecretSize].
//
// This field is only used to create the secret, and is not returned
// by other endpoints.
//
// [MaxSecretSize]: https://pkg.go.dev/github.com/moby/swarmkit/v2@v2.0.0-20250103191802-8c1959736554/api/validation#MaxSecretSize
Data []byte `json:",omitempty"` Data []byte `json:",omitempty"`
Driver *Driver `json:",omitempty"` // name of the secrets driver used to fetch the secret's value from an external secret store
// Driver is the name of the secrets driver used to fetch the secret's
// value from an external secret store. If not set, the default built-in
// store is used.
Driver *Driver `json:",omitempty"`
// Templating controls whether and how to evaluate the secret payload as // Templating controls whether and how to evaluate the secret payload as
// a template. If it is not set, no templating is used. // a template. If it is not set, no templating is used.
@@ -34,3 +52,15 @@ type SecretReference struct {
SecretID string SecretID string
SecretName string SecretName string
} }
// SecretCreateResponse contains the information returned to a client
// on the creation of a new secret.
type SecretCreateResponse struct {
// ID is the id of the created secret.
ID string
}
// SecretListOptions holds parameters to list secrets
type SecretListOptions struct {
Filters filters.Args
}

View File

@@ -1,6 +1,10 @@
package swarm // import "github.com/docker/docker/api/types/swarm" package swarm
import "time" import (
"time"
"github.com/docker/docker/api/types/filters"
)
// Service represents a service. // Service represents a service.
type Service struct { type Service struct {
@@ -200,3 +204,69 @@ type JobStatus struct {
// Swarm manager. // Swarm manager.
LastExecution time.Time `json:",omitempty"` LastExecution time.Time `json:",omitempty"`
} }
// ServiceCreateOptions contains the options to use when creating a service.
type ServiceCreateOptions struct {
// EncodedRegistryAuth is the encoded registry authorization credentials to
// use when updating the service.
//
// This field follows the format of the X-Registry-Auth header.
EncodedRegistryAuth string
// QueryRegistry indicates whether the service update requires
// contacting a registry. A registry may be contacted to retrieve
// the image digest and manifest, which in turn can be used to update
// platform or other information about the service.
QueryRegistry bool
}
// Values for RegistryAuthFrom in ServiceUpdateOptions
const (
RegistryAuthFromSpec = "spec"
RegistryAuthFromPreviousSpec = "previous-spec"
)
// ServiceUpdateOptions contains the options to be used for updating services.
type ServiceUpdateOptions struct {
// EncodedRegistryAuth is the encoded registry authorization credentials to
// use when updating the service.
//
// This field follows the format of the X-Registry-Auth header.
EncodedRegistryAuth string
// TODO(stevvooe): Consider moving the version parameter of ServiceUpdate
// into this field. While it does open API users up to racy writes, most
// users may not need that level of consistency in practice.
// RegistryAuthFrom specifies where to find the registry authorization
// credentials if they are not given in EncodedRegistryAuth. Valid
// values are "spec" and "previous-spec".
RegistryAuthFrom string
// Rollback indicates whether a server-side rollback should be
// performed. When this is set, the provided spec will be ignored.
// The valid values are "previous" and "none". An empty value is the
// same as "none".
Rollback string
// QueryRegistry indicates whether the service update requires
// contacting a registry. A registry may be contacted to retrieve
// the image digest and manifest, which in turn can be used to update
// platform or other information about the service.
QueryRegistry bool
}
// ServiceListOptions holds parameters to list services with.
type ServiceListOptions struct {
Filters filters.Args
// Status indicates whether the server should include the service task
// count of running and desired tasks.
Status bool
}
// ServiceInspectOptions holds parameters related to the "service inspect"
// operation.
type ServiceInspectOptions struct {
InsertDefaults bool
}

View File

@@ -1,4 +1,4 @@
package swarm // import "github.com/docker/docker/api/types/swarm" package swarm
import ( import (
"time" "time"
@@ -235,3 +235,10 @@ type UpdateFlags struct {
RotateManagerToken bool RotateManagerToken bool
RotateManagerUnlockKey bool RotateManagerUnlockKey bool
} }
// UnlockKeyResponse contains the response for Engine API:
// GET /swarm/unlockkey
type UnlockKeyResponse struct {
// UnlockKey is the unlock key in ASCII-armored format.
UnlockKey string
}

View File

@@ -1,8 +1,9 @@
package swarm // import "github.com/docker/docker/api/types/swarm" package swarm
import ( import (
"time" "time"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm/runtime" "github.com/docker/docker/api/types/swarm/runtime"
) )
@@ -223,3 +224,8 @@ type VolumeAttachment struct {
// in the ContainerSpec, that this volume fulfills. // in the ContainerSpec, that this volume fulfills.
Target string `json:",omitempty"` Target string `json:",omitempty"`
} }
// TaskListOptions holds parameters to list tasks with.
type TaskListOptions struct {
Filters filters.Args
}

View File

@@ -0,0 +1,17 @@
package system
import (
"github.com/docker/docker/api/types/build"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/volume"
)
// DiskUsage contains response of Engine API for API 1.49 and greater:
// GET "/system/df"
type DiskUsage struct {
Images *image.DiskUsage
Containers *container.DiskUsage
Volumes *volume.DiskUsage
BuildCache *build.CacheDiskUsage
}

View File

@@ -29,8 +29,6 @@ type Info struct {
CPUSet bool CPUSet bool
PidsLimit bool PidsLimit bool
IPv4Forwarding bool IPv4Forwarding bool
BridgeNfIptables bool
BridgeNfIP6tables bool `json:"BridgeNfIp6tables"`
Debug bool Debug bool
NFd int NFd int
OomKillDisable bool OomKillDisable bool
@@ -73,7 +71,9 @@ type Info struct {
SecurityOptions []string SecurityOptions []string
ProductLicense string `json:",omitempty"` ProductLicense string `json:",omitempty"`
DefaultAddressPools []NetworkAddressPool `json:",omitempty"` DefaultAddressPools []NetworkAddressPool `json:",omitempty"`
FirewallBackend *FirewallInfo `json:"FirewallBackend,omitempty"`
CDISpecDirs []string CDISpecDirs []string
DiscoveredDevices []DeviceInfo `json:",omitempty"`
Containerd *ContainerdInfo `json:",omitempty"` Containerd *ContainerdInfo `json:",omitempty"`
@@ -137,8 +137,13 @@ type PluginsInfo struct {
// Commit holds the Git-commit (SHA1) that a binary was built from, as reported // Commit holds the Git-commit (SHA1) that a binary was built from, as reported
// in the version-string of external tools, such as containerd, or runC. // in the version-string of external tools, such as containerd, or runC.
type Commit struct { type Commit struct {
ID string // ID is the actual commit ID of external tool. // ID is the actual commit ID or version of external tool.
Expected string // Expected is the commit ID of external tool expected by dockerd as set at build time. ID string
// Expected is the commit ID of external tool expected by dockerd as set at build time.
//
// Deprecated: this field is no longer used in API v1.49, but kept for backward-compatibility with older API versions.
Expected string `json:",omitempty"`
} }
// NetworkAddressPool is a temp struct used by [Info] struct. // NetworkAddressPool is a temp struct used by [Info] struct.
@@ -146,3 +151,20 @@ type NetworkAddressPool struct {
Base string Base string
Size int Size int
} }
// FirewallInfo describes the firewall backend.
type FirewallInfo struct {
// Driver is the name of the firewall backend driver.
Driver string `json:"Driver"`
// Info is a list of label/value pairs, containing information related to the firewall.
Info [][2]string `json:"Info,omitempty"`
}
// DeviceInfo represents a discoverable device from a device driver.
type DeviceInfo struct {
// Source indicates the origin device driver.
Source string `json:"Source"`
// ID is the unique identifier for the device.
// Example: CDI FQDN like "vendor.com/gpu=0", or other driver-specific device ID
ID string `json:"ID"`
}

View File

@@ -1,4 +1,4 @@
package time // import "github.com/docker/docker/api/types/time" package time
import ( import (
"fmt" "fmt"
@@ -30,7 +30,7 @@ func GetTimestamp(value string, reference time.Time) (string, error) {
var format string var format string
// if the string has a Z or a + or three dashes use parse otherwise use parseinlocation // if the string has a Z or a + or three dashes use parse otherwise use parseinlocation
parseInLocation := !(strings.ContainsAny(value, "zZ+") || strings.Count(value, "-") == 3) parseInLocation := !strings.ContainsAny(value, "zZ+") && strings.Count(value, "-") != 3
if strings.Contains(value, ".") { if strings.Contains(value, ".") {
if parseInLocation { if parseInLocation {
@@ -105,23 +105,23 @@ func GetTimestamp(value string, reference time.Time) (string, error) {
// since := time.Unix(seconds, nanoseconds) // since := time.Unix(seconds, nanoseconds)
// //
// returns seconds as defaultSeconds if value == "" // returns seconds as defaultSeconds if value == ""
func ParseTimestamps(value string, defaultSeconds int64) (seconds int64, nanoseconds int64, err error) { func ParseTimestamps(value string, defaultSeconds int64) (seconds int64, nanoseconds int64, _ error) {
if value == "" { if value == "" {
return defaultSeconds, 0, nil return defaultSeconds, 0, nil
} }
return parseTimestamp(value) return parseTimestamp(value)
} }
func parseTimestamp(value string) (sec int64, nsec int64, err error) { func parseTimestamp(value string) (seconds int64, nanoseconds int64, _ error) {
s, n, ok := strings.Cut(value, ".") s, n, ok := strings.Cut(value, ".")
sec, err = strconv.ParseInt(s, 10, 64) sec, err := strconv.ParseInt(s, 10, 64)
if err != nil { if err != nil {
return sec, 0, err return sec, 0, err
} }
if !ok { if !ok {
return sec, 0, nil return sec, 0, nil
} }
nsec, err = strconv.ParseInt(n, 10, 64) nsec, err := strconv.ParseInt(n, 10, 64)
if err != nil { if err != nil {
return sec, nsec, err return sec, nsec, err
} }

View File

@@ -1,16 +1,11 @@
package types // import "github.com/docker/docker/api/types" package types
import ( import (
"time" "github.com/docker/docker/api/types/build"
"github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/api/types/volume" "github.com/docker/docker/api/types/volume"
"github.com/docker/go-connections/nat"
) )
const ( const (
@@ -21,152 +16,13 @@ const (
MediaTypeMultiplexedStream = "application/vnd.docker.multiplexed-stream" MediaTypeMultiplexedStream = "application/vnd.docker.multiplexed-stream"
) )
// RootFS returns Image's RootFS description including the layer IDs.
type RootFS struct {
Type string `json:",omitempty"`
Layers []string `json:",omitempty"`
}
// ImageInspect contains response of Engine API:
// GET "/images/{name:.*}/json"
type ImageInspect struct {
// ID is the content-addressable ID of an image.
//
// This identifier is a content-addressable digest calculated from the
// image's configuration (which includes the digests of layers used by
// the image).
//
// Note that this digest differs from the `RepoDigests` below, which
// holds digests of image manifests that reference the image.
ID string `json:"Id"`
// RepoTags is a list of image names/tags in the local image cache that
// reference this image.
//
// Multiple image tags can refer to the same image, and this list may be
// empty if no tags reference the image, in which case the image is
// "untagged", in which case it can still be referenced by its ID.
RepoTags []string
// RepoDigests is a list of content-addressable digests of locally available
// image manifests that the image is referenced from. Multiple manifests can
// refer to the same image.
//
// These digests are usually only available if the image was either pulled
// from a registry, or if the image was pushed to a registry, which is when
// the manifest is generated and its digest calculated.
RepoDigests []string
// Parent is the ID of the parent image.
//
// Depending on how the image was created, this field may be empty and
// is only set for images that were built/created locally. This field
// is empty if the image was pulled from an image registry.
Parent string
// Comment is an optional message that can be set when committing or
// importing the image.
Comment string
// Created is the date and time at which the image was created, formatted in
// RFC 3339 nano-seconds (time.RFC3339Nano).
//
// This information is only available if present in the image,
// and omitted otherwise.
Created string `json:",omitempty"`
// Container is the ID of the container that was used to create the image.
//
// Depending on how the image was created, this field may be empty.
//
// Deprecated: this field is omitted in API v1.45, but kept for backward compatibility.
Container string `json:",omitempty"`
// ContainerConfig is an optional field containing the configuration of the
// container that was last committed when creating the image.
//
// Previous versions of Docker builder used this field to store build cache,
// and it is not in active use anymore.
//
// Deprecated: this field is omitted in API v1.45, but kept for backward compatibility.
ContainerConfig *container.Config `json:",omitempty"`
// DockerVersion is the version of Docker that was used to build the image.
//
// Depending on how the image was created, this field may be empty.
DockerVersion string
// Author is the name of the author that was specified when committing the
// image, or as specified through MAINTAINER (deprecated) in the Dockerfile.
Author string
Config *container.Config
// Architecture is the hardware CPU architecture that the image runs on.
Architecture string
// Variant is the CPU architecture variant (presently ARM-only).
Variant string `json:",omitempty"`
// OS is the Operating System the image is built to run on.
Os string
// OsVersion is the version of the Operating System the image is built to
// run on (especially for Windows).
OsVersion string `json:",omitempty"`
// Size is the total size of the image including all layers it is composed of.
Size int64
// VirtualSize is the total size of the image including all layers it is
// composed of.
//
// Deprecated: this field is omitted in API v1.44, but kept for backward compatibility. Use Size instead.
VirtualSize int64 `json:"VirtualSize,omitempty"`
// GraphDriver holds information about the storage driver used to store the
// container's and image's filesystem.
GraphDriver GraphDriverData
// RootFS contains information about the image's RootFS, including the
// layer IDs.
RootFS RootFS
// Metadata of the image in the local cache.
//
// This information is local to the daemon, and not part of the image itself.
Metadata image.Metadata
}
// Container contains response of Engine API:
// GET "/containers/json"
type Container struct {
ID string `json:"Id"`
Names []string
Image string
ImageID string
Command string
Created int64
Ports []Port
SizeRw int64 `json:",omitempty"`
SizeRootFs int64 `json:",omitempty"`
Labels map[string]string
State string
Status string
HostConfig struct {
NetworkMode string `json:",omitempty"`
Annotations map[string]string `json:",omitempty"`
}
NetworkSettings *SummaryNetworkSettings
Mounts []MountPoint
}
// Ping contains response of Engine API: // Ping contains response of Engine API:
// GET "/_ping" // GET "/_ping"
type Ping struct { type Ping struct {
APIVersion string APIVersion string
OSType string OSType string
Experimental bool Experimental bool
BuilderVersion BuilderVersion BuilderVersion build.BuilderVersion
// SwarmStatus provides information about the current swarm status of the // SwarmStatus provides information about the current swarm status of the
// engine, obtained from the "Swarm" header in the API response. // engine, obtained from the "Swarm" header in the API response.
@@ -205,176 +61,6 @@ type Version struct {
BuildTime string `json:",omitempty"` BuildTime string `json:",omitempty"`
} }
// HealthcheckResult stores information about a single run of a healthcheck probe
type HealthcheckResult struct {
Start time.Time // Start is the time this check started
End time.Time // End is the time this check ended
ExitCode int // ExitCode meanings: 0=healthy, 1=unhealthy, 2=reserved (considered unhealthy), else=error running probe
Output string // Output from last check
}
// Health states
const (
NoHealthcheck = "none" // Indicates there is no healthcheck
Starting = "starting" // Starting indicates that the container is not yet ready
Healthy = "healthy" // Healthy indicates that the container is running correctly
Unhealthy = "unhealthy" // Unhealthy indicates that the container has a problem
)
// Health stores information about the container's healthcheck results
type Health struct {
Status string // Status is one of Starting, Healthy or Unhealthy
FailingStreak int // FailingStreak is the number of consecutive failures
Log []*HealthcheckResult // Log contains the last few results (oldest first)
}
// ContainerState stores container's running state
// it's part of ContainerJSONBase and will return by "inspect" command
type ContainerState struct {
Status string // String representation of the container state. Can be one of "created", "running", "paused", "restarting", "removing", "exited", or "dead"
Running bool
Paused bool
Restarting bool
OOMKilled bool
Dead bool
Pid int
ExitCode int
Error string
StartedAt string
FinishedAt string
Health *Health `json:",omitempty"`
}
// ContainerJSONBase contains response of Engine API:
// GET "/containers/{name:.*}/json"
type ContainerJSONBase struct {
ID string `json:"Id"`
Created string
Path string
Args []string
State *ContainerState
Image string
ResolvConfPath string
HostnamePath string
HostsPath string
LogPath string
Node *ContainerNode `json:",omitempty"` // Deprecated: Node was only propagated by Docker Swarm standalone API. It sill be removed in the next release.
Name string
RestartCount int
Driver string
Platform string
MountLabel string
ProcessLabel string
AppArmorProfile string
ExecIDs []string
HostConfig *container.HostConfig
GraphDriver GraphDriverData
SizeRw *int64 `json:",omitempty"`
SizeRootFs *int64 `json:",omitempty"`
}
// ContainerJSON is newly used struct along with MountPoint
type ContainerJSON struct {
*ContainerJSONBase
Mounts []MountPoint
Config *container.Config
NetworkSettings *NetworkSettings
}
// NetworkSettings exposes the network settings in the api
type NetworkSettings struct {
NetworkSettingsBase
DefaultNetworkSettings
Networks map[string]*network.EndpointSettings
}
// SummaryNetworkSettings provides a summary of container's networks
// in /containers/json
type SummaryNetworkSettings struct {
Networks map[string]*network.EndpointSettings
}
// NetworkSettingsBase holds networking state for a container when inspecting it.
type NetworkSettingsBase struct {
Bridge string // Bridge contains the name of the default bridge interface iff it was set through the daemon --bridge flag.
SandboxID string // SandboxID uniquely represents a container's network stack
SandboxKey string // SandboxKey identifies the sandbox
Ports nat.PortMap // Ports is a collection of PortBinding indexed by Port
// HairpinMode specifies if hairpin NAT should be enabled on the virtual interface
//
// Deprecated: This field is never set and will be removed in a future release.
HairpinMode bool
// LinkLocalIPv6Address is an IPv6 unicast address using the link-local prefix
//
// Deprecated: This field is never set and will be removed in a future release.
LinkLocalIPv6Address string
// LinkLocalIPv6PrefixLen is the prefix length of an IPv6 unicast address
//
// Deprecated: This field is never set and will be removed in a future release.
LinkLocalIPv6PrefixLen int
SecondaryIPAddresses []network.Address // Deprecated: This field is never set and will be removed in a future release.
SecondaryIPv6Addresses []network.Address // Deprecated: This field is never set and will be removed in a future release.
}
// DefaultNetworkSettings holds network information
// during the 2 release deprecation period.
// It will be removed in Docker 1.11.
type DefaultNetworkSettings struct {
EndpointID string // EndpointID uniquely represents a service endpoint in a Sandbox
Gateway string // Gateway holds the gateway address for the network
GlobalIPv6Address string // GlobalIPv6Address holds network's global IPv6 address
GlobalIPv6PrefixLen int // GlobalIPv6PrefixLen represents mask length of network's global IPv6 address
IPAddress string // IPAddress holds the IPv4 address for the network
IPPrefixLen int // IPPrefixLen represents mask length of network's IPv4 address
IPv6Gateway string // IPv6Gateway holds gateway address specific for IPv6
MacAddress string // MacAddress holds the MAC address for the network
}
// MountPoint represents a mount point configuration inside the container.
// This is used for reporting the mountpoints in use by a container.
type MountPoint struct {
// Type is the type of mount, see `Type<foo>` definitions in
// github.com/docker/docker/api/types/mount.Type
Type mount.Type `json:",omitempty"`
// Name is the name reference to the underlying data defined by `Source`
// e.g., the volume name.
Name string `json:",omitempty"`
// Source is the source location of the mount.
//
// For volumes, this contains the storage location of the volume (within
// `/var/lib/docker/volumes/`). For bind-mounts, and `npipe`, this contains
// the source (host) part of the bind-mount. For `tmpfs` mount points, this
// field is empty.
Source string
// Destination is the path relative to the container root (`/`) where the
// Source is mounted inside the container.
Destination string
// Driver is the volume driver used to create the volume (if it is a volume).
Driver string `json:",omitempty"`
// Mode is a comma separated list of options supplied by the user when
// creating the bind/volume mount.
//
// The default is platform-specific (`"z"` on Linux, empty on Windows).
Mode string
// RW indicates whether the mount is mounted writable (read-write).
RW bool
// Propagation describes how mounts are propagated from the host into the
// mount point, and vice-versa. Refer to the Linux kernel documentation
// for details:
// https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt
//
// This field is not used on Windows.
Propagation mount.Propagation
}
// DiskUsageObject represents an object type used for disk usage query filtering. // DiskUsageObject represents an object type used for disk usage query filtering.
type DiskUsageObject string type DiskUsageObject string
@@ -401,43 +87,12 @@ type DiskUsageOptions struct {
type DiskUsage struct { type DiskUsage struct {
LayersSize int64 LayersSize int64
Images []*image.Summary Images []*image.Summary
Containers []*Container Containers []*container.Summary
Volumes []*volume.Volume Volumes []*volume.Volume
BuildCache []*BuildCache BuildCache []*build.CacheRecord
BuilderSize int64 `json:",omitempty"` // Deprecated: deprecated in API 1.38, and no longer used since API 1.40. BuilderSize int64 `json:",omitempty"` // Deprecated: deprecated in API 1.38, and no longer used since API 1.40.
} }
// BuildCachePruneReport contains the response for Engine API:
// POST "/build/prune"
type BuildCachePruneReport struct {
CachesDeleted []string
SpaceReclaimed uint64
}
// SecretCreateResponse contains the information returned to a client
// on the creation of a new secret.
type SecretCreateResponse struct {
// ID is the id of the created secret.
ID string
}
// SecretListOptions holds parameters to list secrets
type SecretListOptions struct {
Filters filters.Args
}
// ConfigCreateResponse contains the information returned to a client
// on the creation of a new config.
type ConfigCreateResponse struct {
// ID is the id of the created config.
ID string
}
// ConfigListOptions holds parameters to list configs
type ConfigListOptions struct {
Filters filters.Args
}
// PushResult contains the tag, manifest digest, and manifest size from the // PushResult contains the tag, manifest digest, and manifest size from the
// push. It's used to signal this information to the trust code in the client // push. It's used to signal this information to the trust code in the client
// so it can sign the manifest if necessary. // so it can sign the manifest if necessary.
@@ -446,42 +101,3 @@ type PushResult struct {
Digest string Digest string
Size int Size int
} }
// BuildResult contains the image id of a successful build
type BuildResult struct {
ID string
}
// BuildCache contains information about a build cache record.
type BuildCache struct {
// ID is the unique ID of the build cache record.
ID string
// Parent is the ID of the parent build cache record.
//
// Deprecated: deprecated in API v1.42 and up, as it was deprecated in BuildKit; use Parents instead.
Parent string `json:"Parent,omitempty"`
// Parents is the list of parent build cache record IDs.
Parents []string `json:" Parents,omitempty"`
// Type is the cache record type.
Type string
// Description is a description of the build-step that produced the build cache.
Description string
// InUse indicates if the build cache is in use.
InUse bool
// Shared indicates if the build cache is shared.
Shared bool
// Size is the amount of disk space used by the build cache (in bytes).
Size int64
// CreatedAt is the date and time at which the build cache was created.
CreatedAt time.Time
// LastUsedAt is the date and time at which the build cache was last used.
LastUsedAt *time.Time
UsageCount int
}
// BuildCachePruneOptions hold parameters to prune the build cache
type BuildCachePruneOptions struct {
All bool
KeepStorage int64
Filters filters.Args
}

View File

@@ -1,210 +1,241 @@
package types package types
import ( import (
"context"
"github.com/docker/docker/api/types/build"
"github.com/docker/docker/api/types/common"
"github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/storage"
"github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/api/types/volume"
) )
// ImagesPruneReport contains the response for Engine API: // IDResponse Response to an API call that returns just an Id.
// POST "/images/prune"
// //
// Deprecated: use [image.PruneReport]. // Deprecated: use either [container.CommitResponse] or [container.ExecCreateResponse]. It will be removed in the next release.
type ImagesPruneReport = image.PruneReport type IDResponse = common.IDResponse
// VolumesPruneReport contains the response for Engine API: // ContainerJSONBase contains response of Engine API GET "/containers/{name:.*}/json"
// POST "/volumes/prune". // for API version 1.18 and older.
// //
// Deprecated: use [volume.PruneReport]. // Deprecated: use [container.InspectResponse] or [container.ContainerJSONBase]. It will be removed in the next release.
type VolumesPruneReport = volume.PruneReport type ContainerJSONBase = container.ContainerJSONBase
// NetworkCreateRequest is the request message sent to the server for network create call. // ContainerJSON is the response for the GET "/containers/{name:.*}/json"
// endpoint.
// //
// Deprecated: use [network.CreateRequest]. // Deprecated: use [container.InspectResponse]. It will be removed in the next release.
type NetworkCreateRequest = network.CreateRequest type ContainerJSON = container.InspectResponse
// NetworkCreate is the expected body of the "create network" http request message // Container contains response of Engine API:
// GET "/containers/json"
// //
// Deprecated: use [network.CreateOptions]. // Deprecated: use [container.Summary].
type NetworkCreate = network.CreateOptions type Container = container.Summary
// NetworkListOptions holds parameters to filter the list of networks with. // ContainerState stores container's running state
// //
// Deprecated: use [network.ListOptions]. // Deprecated: use [container.State].
type NetworkListOptions = network.ListOptions type ContainerState = container.State
// NetworkCreateResponse is the response message sent by the server for network create call. // NetworkSettings exposes the network settings in the api.
// //
// Deprecated: use [network.CreateResponse]. // Deprecated: use [container.NetworkSettings].
type NetworkCreateResponse = network.CreateResponse type NetworkSettings = container.NetworkSettings
// NetworkInspectOptions holds parameters to inspect network. // NetworkSettingsBase holds networking state for a container when inspecting it.
// //
// Deprecated: use [network.InspectOptions]. // Deprecated: use [container.NetworkSettingsBase].
type NetworkInspectOptions = network.InspectOptions type NetworkSettingsBase = container.NetworkSettingsBase
// NetworkConnect represents the data to be used to connect a container to the network // DefaultNetworkSettings holds network information
// during the 2 release deprecation period.
// It will be removed in Docker 1.11.
// //
// Deprecated: use [network.ConnectOptions]. // Deprecated: use [container.DefaultNetworkSettings].
type NetworkConnect = network.ConnectOptions type DefaultNetworkSettings = container.DefaultNetworkSettings
// NetworkDisconnect represents the data to be used to disconnect a container from the network // SummaryNetworkSettings provides a summary of container's networks
// in /containers/json.
// //
// Deprecated: use [network.DisconnectOptions]. // Deprecated: use [container.NetworkSettingsSummary].
type NetworkDisconnect = network.DisconnectOptions type SummaryNetworkSettings = container.NetworkSettingsSummary
// EndpointResource contains network resources allocated and used for a container in a network. // Health states
// const (
// Deprecated: use [network.EndpointResource]. NoHealthcheck = container.NoHealthcheck // Deprecated: use [container.NoHealthcheck].
type EndpointResource = network.EndpointResource Starting = container.Starting // Deprecated: use [container.Starting].
Healthy = container.Healthy // Deprecated: use [container.Healthy].
Unhealthy = container.Unhealthy // Deprecated: use [container.Unhealthy].
)
// NetworkResource is the body of the "get network" http response message/ // Health stores information about the container's healthcheck results.
// //
// Deprecated: use [network.Inspect] or [network.Summary] (for list operations). // Deprecated: use [container.Health].
type NetworkResource = network.Inspect type Health = container.Health
// NetworksPruneReport contains the response for Engine API: // HealthcheckResult stores information about a single run of a healthcheck probe.
// POST "/networks/prune"
// //
// Deprecated: use [network.PruneReport]. // Deprecated: use [container.HealthcheckResult].
type NetworksPruneReport = network.PruneReport type HealthcheckResult = container.HealthcheckResult
// ExecConfig is a small subset of the Config struct that holds the configuration // MountPoint represents a mount point configuration inside the container.
// for the exec feature of docker. // This is used for reporting the mountpoints in use by a container.
// //
// Deprecated: use [container.ExecOptions]. // Deprecated: use [container.MountPoint].
type ExecConfig = container.ExecOptions type MountPoint = container.MountPoint
// ExecStartCheck is a temp struct used by execStart // Port An open port on a container
// Config fields is part of ExecConfig in runconfig package
// //
// Deprecated: use [container.ExecStartOptions] or [container.ExecAttachOptions]. // Deprecated: use [container.Port].
type ExecStartCheck = container.ExecStartOptions type Port = container.Port
// ContainerExecInspect holds information returned by exec inspect. // GraphDriverData Information about the storage driver used to store the container's and
// image's filesystem.
// //
// Deprecated: use [container.ExecInspect]. // Deprecated: use [storage.DriverData].
type ContainerExecInspect = container.ExecInspect type GraphDriverData = storage.DriverData
// ContainersPruneReport contains the response for Engine API: // RootFS returns Image's RootFS description including the layer IDs.
// POST "/containers/prune"
// //
// Deprecated: use [container.PruneReport]. // Deprecated: use [image.RootFS].
type ContainersPruneReport = container.PruneReport type RootFS = image.RootFS
// ContainerPathStat is used to encode the header from // ImageInspect contains response of Engine API:
// GET "/containers/{name:.*}/archive" // GET "/images/{name:.*}/json"
// "Name" is the file or directory name.
// //
// Deprecated: use [container.PathStat]. // Deprecated: use [image.InspectResponse].
type ContainerPathStat = container.PathStat type ImageInspect = image.InspectResponse
// CopyToContainerOptions holds information // RequestPrivilegeFunc is a function interface that clients can supply to
// about files to copy into a container. // retry operations after getting an authorization error.
// This function returns the registry authentication header value in base64
// format, or an error if the privilege request fails.
// //
// Deprecated: use [container.CopyToContainerOptions], // Deprecated: moved to [github.com/docker/docker/api/types/registry.RequestAuthConfig].
type CopyToContainerOptions = container.CopyToContainerOptions type RequestPrivilegeFunc func(context.Context) (string, error)
// ContainerStats contains response of Engine API: // SecretCreateResponse contains the information returned to a client
// GET "/stats" // on the creation of a new secret.
// //
// Deprecated: use [container.StatsResponseReader]. // Deprecated: use [swarm.SecretCreateResponse].
type ContainerStats = container.StatsResponseReader type SecretCreateResponse = swarm.SecretCreateResponse
// ThrottlingData stores CPU throttling stats of one running container. // SecretListOptions holds parameters to list secrets
// Not used on Windows.
// //
// Deprecated: use [container.ThrottlingData]. // Deprecated: use [swarm.SecretListOptions].
type ThrottlingData = container.ThrottlingData type SecretListOptions = swarm.SecretListOptions
// CPUUsage stores All CPU stats aggregated since container inception. // ConfigCreateResponse contains the information returned to a client
// on the creation of a new config.
// //
// Deprecated: use [container.CPUUsage]. // Deprecated: use [swarm.ConfigCreateResponse].
type CPUUsage = container.CPUUsage type ConfigCreateResponse = swarm.ConfigCreateResponse
// CPUStats aggregates and wraps all CPU related info of container // ConfigListOptions holds parameters to list configs
// //
// Deprecated: use [container.CPUStats]. // Deprecated: use [swarm.ConfigListOptions].
type CPUStats = container.CPUStats type ConfigListOptions = swarm.ConfigListOptions
// MemoryStats aggregates all memory stats since container inception on Linux. // NodeListOptions holds parameters to list nodes with.
// Windows returns stats for commit and private working set only.
// //
// Deprecated: use [container.MemoryStats]. // Deprecated: use [swarm.NodeListOptions].
type MemoryStats = container.MemoryStats type NodeListOptions = swarm.NodeListOptions
// BlkioStatEntry is one small entity to store a piece of Blkio stats // NodeRemoveOptions holds parameters to remove nodes with.
// Not used on Windows.
// //
// Deprecated: use [container.BlkioStatEntry]. // Deprecated: use [swarm.NodeRemoveOptions].
type BlkioStatEntry = container.BlkioStatEntry type NodeRemoveOptions = swarm.NodeRemoveOptions
// BlkioStats stores All IO service stats for data read and write. // TaskListOptions holds parameters to list tasks with.
// This is a Linux specific structure as the differences between expressing
// block I/O on Windows and Linux are sufficiently significant to make
// little sense attempting to morph into a combined structure.
// //
// Deprecated: use [container.BlkioStats]. // Deprecated: use [swarm.TaskListOptions].
type BlkioStats = container.BlkioStats type TaskListOptions = swarm.TaskListOptions
// StorageStats is the disk I/O stats for read/write on Windows. // ServiceCreateOptions contains the options to use when creating a service.
// //
// Deprecated: use [container.StorageStats]. // Deprecated: use [swarm.ServiceCreateOptions].
type StorageStats = container.StorageStats type ServiceCreateOptions = swarm.ServiceCreateOptions
// NetworkStats aggregates the network stats of one container // ServiceUpdateOptions contains the options to be used for updating services.
// //
// Deprecated: use [container.NetworkStats]. // Deprecated: use [swarm.ServiceCreateOptions].
type NetworkStats = container.NetworkStats type ServiceUpdateOptions = swarm.ServiceUpdateOptions
// PidsStats contains the stats of a container's pids const (
// RegistryAuthFromSpec = swarm.RegistryAuthFromSpec // Deprecated: use [swarm.RegistryAuthFromSpec].
// Deprecated: use [container.PidsStats]. RegistryAuthFromPreviousSpec = swarm.RegistryAuthFromPreviousSpec // Deprecated: use [swarm.RegistryAuthFromPreviousSpec].
type PidsStats = container.PidsStats )
// Stats is Ultimate struct aggregating all types of stats of one container // ServiceListOptions holds parameters to list services with.
// //
// Deprecated: use [container.Stats]. // Deprecated: use [swarm.ServiceListOptions].
type Stats = container.Stats type ServiceListOptions = swarm.ServiceListOptions
// StatsJSON is newly used Networks // ServiceInspectOptions holds parameters related to the "service inspect"
// operation.
// //
// Deprecated: use [container.StatsResponse]. // Deprecated: use [swarm.ServiceInspectOptions].
type StatsJSON = container.StatsResponse type ServiceInspectOptions = swarm.ServiceInspectOptions
// EventsOptions holds parameters to filter events with. // SwarmUnlockKeyResponse contains the response for Engine API:
// GET /swarm/unlockkey
// //
// Deprecated: use [events.ListOptions]. // Deprecated: use [swarm.UnlockKeyResponse].
type EventsOptions = events.ListOptions type SwarmUnlockKeyResponse = swarm.UnlockKeyResponse
// ImageSearchOptions holds parameters to search images with. // BuildCache contains information about a build cache record.
// //
// Deprecated: use [registry.SearchOptions]. // Deprecated: deprecated in API 1.49. Use [build.CacheRecord] instead.
type ImageSearchOptions = registry.SearchOptions type BuildCache = build.CacheRecord
// ImageImportSource holds source information for ImageImport // BuildCachePruneOptions hold parameters to prune the build cache
// //
// Deprecated: use [image.ImportSource]. // Deprecated: use [build.CachePruneOptions].
type ImageImportSource image.ImportSource type BuildCachePruneOptions = build.CachePruneOptions
// ImageLoadResponse returns information to the client about a load process. // BuildCachePruneReport contains the response for Engine API:
// POST "/build/prune"
// //
// Deprecated: use [image.LoadResponse]. // Deprecated: use [build.CachePruneReport].
type ImageLoadResponse = image.LoadResponse type BuildCachePruneReport = build.CachePruneReport
// ContainerNode stores information about the node that a container // BuildResult contains the image id of a successful build/
// is running on. It's only used by the Docker Swarm standalone API.
// //
// Deprecated: ContainerNode was used for the classic Docker Swarm standalone API. It will be removed in the next release. // Deprecated: use [build.Result].
type ContainerNode struct { type BuildResult = build.Result
ID string
IPAddress string `json:"IP"` // ImageBuildOptions holds the information
Addr string // necessary to build images.
Name string //
Cpus int // Deprecated: use [build.ImageBuildOptions].
Memory int64 type ImageBuildOptions = build.ImageBuildOptions
Labels map[string]string
} // ImageBuildOutput defines configuration for exporting a build result
//
// Deprecated: use [build.ImageBuildOutput].
type ImageBuildOutput = build.ImageBuildOutput
// ImageBuildResponse holds information
// returned by a server after building
// an image.
//
// Deprecated: use [build.ImageBuildResponse].
type ImageBuildResponse = build.ImageBuildResponse
// BuilderVersion sets the version of underlying builder to use
//
// Deprecated: use [build.BuilderVersion].
type BuilderVersion = build.BuilderVersion
const (
// BuilderV1 is the first generation builder in docker daemon
//
// Deprecated: use [build.BuilderV1].
BuilderV1 = build.BuilderV1
// BuilderBuildKit is builder based on moby/buildkit project
//
// Deprecated: use [build.BuilderBuildKit].
BuilderBuildKit = build.BuilderBuildKit
)

View File

@@ -1,4 +1,4 @@
package versions // import "github.com/docker/docker/api/types/versions" package versions
import ( import (
"strconv" "strconv"

View File

@@ -0,0 +1,8 @@
package volume
// DiskUsage contains disk usage for volumes.
type DiskUsage struct {
TotalSize int64
Reclaimable int64
Items []*Volume
}

View File

@@ -1,4 +1,4 @@
package volume // import "github.com/docker/docker/api/types/volume" package volume
import "github.com/docker/docker/api/types/filters" import "github.com/docker/docker/api/types/filters"

View File

@@ -1,4 +1,4 @@
package volume // import "github.com/docker/docker/api/types/volume" package volume
// UpdateOptions is configuration to update a Volume with. // UpdateOptions is configuration to update a Volume with.
type UpdateOptions struct { type UpdateOptions struct {

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -10,7 +10,7 @@ func (cli *Client) BuildCancel(ctx context.Context, id string) error {
query := url.Values{} query := url.Values{}
query.Set("id", id) query.Set("id", id)
serverResp, err := cli.post(ctx, "/build/cancel", query, nil, nil) resp, err := cli.post(ctx, "/build/cancel", query, nil, nil)
ensureReaderClosed(serverResp) ensureReaderClosed(resp)
return err return err
} }

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -6,38 +6,49 @@ import (
"net/url" "net/url"
"strconv" "strconv"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types/build"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
// BuildCachePrune requests the daemon to delete unused cache data // BuildCachePrune requests the daemon to delete unused cache data
func (cli *Client) BuildCachePrune(ctx context.Context, opts types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error) { func (cli *Client) BuildCachePrune(ctx context.Context, opts build.CachePruneOptions) (*build.CachePruneReport, error) {
if err := cli.NewVersionError(ctx, "1.31", "build prune"); err != nil { if err := cli.NewVersionError(ctx, "1.31", "build prune"); err != nil {
return nil, err return nil, err
} }
report := types.BuildCachePruneReport{}
query := url.Values{} query := url.Values{}
if opts.All { if opts.All {
query.Set("all", "1") query.Set("all", "1")
} }
if opts.KeepStorage != 0 {
query.Set("keep-storage", strconv.Itoa(int(opts.KeepStorage))) query.Set("keep-storage", strconv.Itoa(int(opts.KeepStorage)))
}
if opts.ReservedSpace != 0 {
query.Set("reserved-space", strconv.Itoa(int(opts.ReservedSpace)))
}
if opts.MaxUsedSpace != 0 {
query.Set("max-used-space", strconv.Itoa(int(opts.MaxUsedSpace)))
}
if opts.MinFreeSpace != 0 {
query.Set("min-free-space", strconv.Itoa(int(opts.MinFreeSpace)))
}
f, err := filters.ToJSON(opts.Filters) f, err := filters.ToJSON(opts.Filters)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "prune could not marshal filters option") return nil, errors.Wrap(err, "prune could not marshal filters option")
} }
query.Set("filters", f) query.Set("filters", f)
serverResp, err := cli.post(ctx, "/build/prune", query, nil, nil) resp, err := cli.post(ctx, "/build/prune", query, nil, nil)
defer ensureReaderClosed(serverResp) defer ensureReaderClosed(resp)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { report := build.CachePruneReport{}
if err := json.NewDecoder(resp.Body).Decode(&report); err != nil {
return nil, errors.Wrap(err, "error retrieving disk usage") return nil, errors.Wrap(err, "error retrieving disk usage")
} }

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -6,11 +6,11 @@ import (
"github.com/docker/docker/api/types/checkpoint" "github.com/docker/docker/api/types/checkpoint"
) )
type apiClientExperimental interface { // CheckpointAPIClient defines API client methods for the checkpoints.
CheckpointAPIClient //
} // Experimental: checkpoint and restore is still an experimental feature,
// and only available if the daemon is running with experimental features
// CheckpointAPIClient defines API client methods for the checkpoints // enabled.
type CheckpointAPIClient interface { type CheckpointAPIClient interface {
CheckpointCreate(ctx context.Context, container string, options checkpoint.CreateOptions) error CheckpointCreate(ctx context.Context, container string, options checkpoint.CreateOptions) error
CheckpointDelete(ctx context.Context, container string, options checkpoint.DeleteOptions) error CheckpointDelete(ctx context.Context, container string, options checkpoint.DeleteOptions) error

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -7,8 +7,13 @@ import (
) )
// CheckpointCreate creates a checkpoint from the given container with the given name // CheckpointCreate creates a checkpoint from the given container with the given name
func (cli *Client) CheckpointCreate(ctx context.Context, container string, options checkpoint.CreateOptions) error { func (cli *Client) CheckpointCreate(ctx context.Context, containerID string, options checkpoint.CreateOptions) error {
resp, err := cli.post(ctx, "/containers/"+container+"/checkpoints", nil, options, nil) containerID, err := trimID("container", containerID)
if err != nil {
return err
}
resp, err := cli.post(ctx, "/containers/"+containerID+"/checkpoints", nil, options, nil)
ensureReaderClosed(resp) ensureReaderClosed(resp)
return err return err
} }

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -9,6 +9,11 @@ import (
// CheckpointDelete deletes the checkpoint with the given name from the given container // CheckpointDelete deletes the checkpoint with the given name from the given container
func (cli *Client) CheckpointDelete(ctx context.Context, containerID string, options checkpoint.DeleteOptions) error { func (cli *Client) CheckpointDelete(ctx context.Context, containerID string, options checkpoint.DeleteOptions) error {
containerID, err := trimID("container", containerID)
if err != nil {
return err
}
query := url.Values{} query := url.Values{}
if options.CheckpointDir != "" { if options.CheckpointDir != "" {
query.Set("dir", options.CheckpointDir) query.Set("dir", options.CheckpointDir)

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -23,6 +23,6 @@ func (cli *Client) CheckpointList(ctx context.Context, container string, options
return checkpoints, err return checkpoints, err
} }
err = json.NewDecoder(resp.body).Decode(&checkpoints) err = json.NewDecoder(resp.Body).Decode(&checkpoints)
return checkpoints, err return checkpoints, err
} }

View File

@@ -2,7 +2,7 @@
Package client is a Go client for the Docker Engine API. Package client is a Go client for the Docker Engine API.
For more information about the Engine API, see the documentation: For more information about the Engine API, see the documentation:
https://docs.docker.com/engine/api/ https://docs.docker.com/reference/api/engine/
# Usage # Usage
@@ -39,7 +39,7 @@ For example, to list running containers (the equivalent of "docker ps"):
} }
} }
*/ */
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -59,7 +59,6 @@ import (
"github.com/docker/go-connections/sockets" "github.com/docker/go-connections/sockets"
"github.com/pkg/errors" "github.com/pkg/errors"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel/trace"
) )
// DummyHost is a hostname used for local communication. // DummyHost is a hostname used for local communication.
@@ -99,6 +98,9 @@ const DummyHost = "api.moby.localhost"
// recent version before negotiation was introduced. // recent version before negotiation was introduced.
const fallbackAPIVersion = "1.24" const fallbackAPIVersion = "1.24"
// Ensure that Client always implements APIClient.
var _ APIClient = &Client{}
// Client is the API client that performs all operations // Client is the API client that performs all operations
// against a docker server. // against a docker server.
type Client struct { type Client struct {
@@ -138,7 +140,7 @@ type Client struct {
// negotiateLock is used to single-flight the version negotiation process // negotiateLock is used to single-flight the version negotiation process
negotiateLock sync.Mutex negotiateLock sync.Mutex
tp trace.TracerProvider traceOpts []otelhttp.Option
// When the client transport is an *http.Transport (default) we need to do some extra things (like closing idle connections). // When the client transport is an *http.Transport (default) we need to do some extra things (like closing idle connections).
// Store the original transport as the http.Client transport will be wrapped with tracing libs. // Store the original transport as the http.Client transport will be wrapped with tracing libs.
@@ -200,6 +202,12 @@ func NewClientWithOpts(ops ...Opt) (*Client, error) {
client: client, client: client,
proto: hostURL.Scheme, proto: hostURL.Scheme,
addr: hostURL.Host, addr: hostURL.Host,
traceOpts: []otelhttp.Option{
otelhttp.WithSpanNameFormatter(func(_ string, req *http.Request) string {
return req.Method + " " + req.URL.Path
}),
},
} }
for _, op := range ops { for _, op := range ops {
@@ -227,13 +235,7 @@ func NewClientWithOpts(ops ...Opt) (*Client, error) {
} }
} }
c.client.Transport = otelhttp.NewTransport( c.client.Transport = otelhttp.NewTransport(c.client.Transport, c.traceOpts...)
c.client.Transport,
otelhttp.WithTracerProvider(c.tp),
otelhttp.WithSpanNameFormatter(func(_ string, req *http.Request) string {
return req.Method + " " + req.URL.Path
}),
)
return c, nil return c, nil
} }
@@ -247,6 +249,14 @@ func (cli *Client) tlsConfig() *tls.Config {
func defaultHTTPClient(hostURL *url.URL) (*http.Client, error) { func defaultHTTPClient(hostURL *url.URL) (*http.Client, error) {
transport := &http.Transport{} transport := &http.Transport{}
// Necessary to prevent long-lived processes using the
// client from leaking connections due to idle connections
// not being released.
// TODO: see if we can also address this from the server side,
// or in go-connections.
// see: https://github.com/moby/moby/issues/45539
transport.MaxIdleConns = 6
transport.IdleConnTimeout = 30 * time.Second
err := sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host) err := sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -296,8 +306,7 @@ func (cli *Client) getAPIPath(ctx context.Context, p string, query url.Values) s
var apiPath string var apiPath string
_ = cli.checkVersion(ctx) _ = cli.checkVersion(ctx)
if cli.version != "" { if cli.version != "" {
v := strings.TrimPrefix(cli.version, "v") apiPath = path.Join(cli.basePath, "/v"+strings.TrimPrefix(cli.version, "v"), p)
apiPath = path.Join(cli.basePath, "/v"+v, p)
} else { } else {
apiPath = path.Join(cli.basePath, p) apiPath = path.Join(cli.basePath, p)
} }
@@ -442,6 +451,10 @@ func (cli *Client) dialerFromTransport() func(context.Context, string, string) (
// //
// ["docker dial-stdio"]: https://github.com/docker/cli/pull/1014 // ["docker dial-stdio"]: https://github.com/docker/cli/pull/1014
func (cli *Client) Dialer() func(context.Context) (net.Conn, error) { func (cli *Client) Dialer() func(context.Context) (net.Conn, error) {
return cli.dialer()
}
func (cli *Client) dialer() func(context.Context) (net.Conn, error) {
return func(ctx context.Context) (net.Conn, error) { return func(ctx context.Context) (net.Conn, error) {
if dialFn := cli.dialerFromTransport(); dialFn != nil { if dialFn := cli.dialerFromTransport(); dialFn != nil {
return dialFn(ctx, cli.proto, cli.addr) return dialFn(ctx, cli.proto, cli.addr)

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -7,6 +7,7 @@ import (
"net/http" "net/http"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/build"
"github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/events" "github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
@@ -20,17 +21,23 @@ import (
) )
// CommonAPIClient is the common methods between stable and experimental versions of APIClient. // CommonAPIClient is the common methods between stable and experimental versions of APIClient.
type CommonAPIClient interface { //
// Deprecated: use [APIClient] instead. This type will be an alias for [APIClient] in the next release, and removed after.
type CommonAPIClient = stableAPIClient
// APIClient is an interface that clients that talk with a docker server must implement.
type APIClient interface {
stableAPIClient
CheckpointAPIClient // CheckpointAPIClient is still experimental.
}
type stableAPIClient interface {
ConfigAPIClient ConfigAPIClient
ContainerAPIClient ContainerAPIClient
DistributionAPIClient DistributionAPIClient
ImageAPIClient ImageAPIClient
NodeAPIClient
NetworkAPIClient NetworkAPIClient
PluginAPIClient PluginAPIClient
ServiceAPIClient
SwarmAPIClient
SecretAPIClient
SystemAPIClient SystemAPIClient
VolumeAPIClient VolumeAPIClient
ClientVersion() string ClientVersion() string
@@ -39,27 +46,43 @@ type CommonAPIClient interface {
ServerVersion(ctx context.Context) (types.Version, error) ServerVersion(ctx context.Context) (types.Version, error)
NegotiateAPIVersion(ctx context.Context) NegotiateAPIVersion(ctx context.Context)
NegotiateAPIVersionPing(types.Ping) NegotiateAPIVersionPing(types.Ping)
DialHijack(ctx context.Context, url, proto string, meta map[string][]string) (net.Conn, error) HijackDialer
Dialer() func(context.Context) (net.Conn, error) Dialer() func(context.Context) (net.Conn, error)
Close() error Close() error
SwarmManagementAPIClient
}
// SwarmManagementAPIClient defines all methods for managing Swarm-specific
// objects.
type SwarmManagementAPIClient interface {
SwarmAPIClient
NodeAPIClient
ServiceAPIClient
SecretAPIClient
ConfigAPIClient
}
// HijackDialer defines methods for a hijack dialer.
type HijackDialer interface {
DialHijack(ctx context.Context, url, proto string, meta map[string][]string) (net.Conn, error)
} }
// ContainerAPIClient defines API client methods for the containers // ContainerAPIClient defines API client methods for the containers
type ContainerAPIClient interface { type ContainerAPIClient interface {
ContainerAttach(ctx context.Context, container string, options container.AttachOptions) (types.HijackedResponse, error) ContainerAttach(ctx context.Context, container string, options container.AttachOptions) (types.HijackedResponse, error)
ContainerCommit(ctx context.Context, container string, options container.CommitOptions) (types.IDResponse, error) ContainerCommit(ctx context.Context, container string, options container.CommitOptions) (container.CommitResponse, error)
ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *ocispec.Platform, containerName string) (container.CreateResponse, error) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *ocispec.Platform, containerName string) (container.CreateResponse, error)
ContainerDiff(ctx context.Context, container string) ([]container.FilesystemChange, error) ContainerDiff(ctx context.Context, container string) ([]container.FilesystemChange, error)
ContainerExecAttach(ctx context.Context, execID string, options container.ExecAttachOptions) (types.HijackedResponse, error) ContainerExecAttach(ctx context.Context, execID string, options container.ExecAttachOptions) (types.HijackedResponse, error)
ContainerExecCreate(ctx context.Context, container string, options container.ExecOptions) (types.IDResponse, error) ContainerExecCreate(ctx context.Context, container string, options container.ExecOptions) (container.ExecCreateResponse, error)
ContainerExecInspect(ctx context.Context, execID string) (container.ExecInspect, error) ContainerExecInspect(ctx context.Context, execID string) (container.ExecInspect, error)
ContainerExecResize(ctx context.Context, execID string, options container.ResizeOptions) error ContainerExecResize(ctx context.Context, execID string, options container.ResizeOptions) error
ContainerExecStart(ctx context.Context, execID string, options container.ExecStartOptions) error ContainerExecStart(ctx context.Context, execID string, options container.ExecStartOptions) error
ContainerExport(ctx context.Context, container string) (io.ReadCloser, error) ContainerExport(ctx context.Context, container string) (io.ReadCloser, error)
ContainerInspect(ctx context.Context, container string) (types.ContainerJSON, error) ContainerInspect(ctx context.Context, container string) (container.InspectResponse, error)
ContainerInspectWithRaw(ctx context.Context, container string, getSize bool) (types.ContainerJSON, []byte, error) ContainerInspectWithRaw(ctx context.Context, container string, getSize bool) (container.InspectResponse, []byte, error)
ContainerKill(ctx context.Context, container, signal string) error ContainerKill(ctx context.Context, container, signal string) error
ContainerList(ctx context.Context, options container.ListOptions) ([]types.Container, error) ContainerList(ctx context.Context, options container.ListOptions) ([]container.Summary, error)
ContainerLogs(ctx context.Context, container string, options container.LogsOptions) (io.ReadCloser, error) ContainerLogs(ctx context.Context, container string, options container.LogsOptions) (io.ReadCloser, error)
ContainerPause(ctx context.Context, container string) error ContainerPause(ctx context.Context, container string) error
ContainerRemove(ctx context.Context, container string, options container.RemoveOptions) error ContainerRemove(ctx context.Context, container string, options container.RemoveOptions) error
@@ -71,9 +94,9 @@ type ContainerAPIClient interface {
ContainerStatsOneShot(ctx context.Context, container string) (container.StatsResponseReader, error) ContainerStatsOneShot(ctx context.Context, container string) (container.StatsResponseReader, error)
ContainerStart(ctx context.Context, container string, options container.StartOptions) error ContainerStart(ctx context.Context, container string, options container.StartOptions) error
ContainerStop(ctx context.Context, container string, options container.StopOptions) error ContainerStop(ctx context.Context, container string, options container.StopOptions) error
ContainerTop(ctx context.Context, container string, arguments []string) (container.ContainerTopOKBody, error) ContainerTop(ctx context.Context, container string, arguments []string) (container.TopResponse, error)
ContainerUnpause(ctx context.Context, container string) error ContainerUnpause(ctx context.Context, container string) error
ContainerUpdate(ctx context.Context, container string, updateConfig container.UpdateConfig) (container.ContainerUpdateOKBody, error) ContainerUpdate(ctx context.Context, container string, updateConfig container.UpdateConfig) (container.UpdateResponse, error)
ContainerWait(ctx context.Context, container string, condition container.WaitCondition) (<-chan container.WaitResponse, <-chan error) ContainerWait(ctx context.Context, container string, condition container.WaitCondition) (<-chan container.WaitResponse, <-chan error)
CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, container.PathStat, error) CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, container.PathStat, error)
CopyToContainer(ctx context.Context, container, path string, content io.Reader, options container.CopyToContainerOptions) error CopyToContainer(ctx context.Context, container, path string, content io.Reader, options container.CopyToContainerOptions) error
@@ -87,22 +110,34 @@ type DistributionAPIClient interface {
// ImageAPIClient defines API client methods for the images // ImageAPIClient defines API client methods for the images
type ImageAPIClient interface { type ImageAPIClient interface {
ImageBuild(ctx context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) ImageBuild(ctx context.Context, context io.Reader, options build.ImageBuildOptions) (build.ImageBuildResponse, error)
BuildCachePrune(ctx context.Context, opts types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error) BuildCachePrune(ctx context.Context, opts build.CachePruneOptions) (*build.CachePruneReport, error)
BuildCancel(ctx context.Context, id string) error BuildCancel(ctx context.Context, id string) error
ImageCreate(ctx context.Context, parentReference string, options image.CreateOptions) (io.ReadCloser, error) ImageCreate(ctx context.Context, parentReference string, options image.CreateOptions) (io.ReadCloser, error)
ImageHistory(ctx context.Context, image string) ([]image.HistoryResponseItem, error)
ImageImport(ctx context.Context, source image.ImportSource, ref string, options image.ImportOptions) (io.ReadCloser, error) ImageImport(ctx context.Context, source image.ImportSource, ref string, options image.ImportOptions) (io.ReadCloser, error)
ImageInspectWithRaw(ctx context.Context, image string) (types.ImageInspect, []byte, error)
ImageList(ctx context.Context, options image.ListOptions) ([]image.Summary, error) ImageList(ctx context.Context, options image.ListOptions) ([]image.Summary, error)
ImageLoad(ctx context.Context, input io.Reader, quiet bool) (image.LoadResponse, error)
ImagePull(ctx context.Context, ref string, options image.PullOptions) (io.ReadCloser, error) ImagePull(ctx context.Context, ref string, options image.PullOptions) (io.ReadCloser, error)
ImagePush(ctx context.Context, ref string, options image.PushOptions) (io.ReadCloser, error) ImagePush(ctx context.Context, ref string, options image.PushOptions) (io.ReadCloser, error)
ImageRemove(ctx context.Context, image string, options image.RemoveOptions) ([]image.DeleteResponse, error) ImageRemove(ctx context.Context, image string, options image.RemoveOptions) ([]image.DeleteResponse, error)
ImageSearch(ctx context.Context, term string, options registry.SearchOptions) ([]registry.SearchResult, error) ImageSearch(ctx context.Context, term string, options registry.SearchOptions) ([]registry.SearchResult, error)
ImageSave(ctx context.Context, images []string) (io.ReadCloser, error)
ImageTag(ctx context.Context, image, ref string) error ImageTag(ctx context.Context, image, ref string) error
ImagesPrune(ctx context.Context, pruneFilter filters.Args) (image.PruneReport, error) ImagesPrune(ctx context.Context, pruneFilter filters.Args) (image.PruneReport, error)
ImageInspect(ctx context.Context, image string, _ ...ImageInspectOption) (image.InspectResponse, error)
ImageHistory(ctx context.Context, image string, _ ...ImageHistoryOption) ([]image.HistoryResponseItem, error)
ImageLoad(ctx context.Context, input io.Reader, _ ...ImageLoadOption) (image.LoadResponse, error)
ImageSave(ctx context.Context, images []string, _ ...ImageSaveOption) (io.ReadCloser, error)
ImageAPIClientDeprecated
}
// ImageAPIClientDeprecated defines deprecated methods of the ImageAPIClient.
type ImageAPIClientDeprecated interface {
// ImageInspectWithRaw returns the image information and its raw representation.
//
// Deprecated: Use [Client.ImageInspect] instead. Raw response can be obtained using the [ImageInspectWithRawResponse] option.
ImageInspectWithRaw(ctx context.Context, image string) (image.InspectResponse, []byte, error)
} }
// NetworkAPIClient defines API client methods for the networks // NetworkAPIClient defines API client methods for the networks
@@ -120,8 +155,8 @@ type NetworkAPIClient interface {
// NodeAPIClient defines API client methods for the nodes // NodeAPIClient defines API client methods for the nodes
type NodeAPIClient interface { type NodeAPIClient interface {
NodeInspectWithRaw(ctx context.Context, nodeID string) (swarm.Node, []byte, error) NodeInspectWithRaw(ctx context.Context, nodeID string) (swarm.Node, []byte, error)
NodeList(ctx context.Context, options types.NodeListOptions) ([]swarm.Node, error) NodeList(ctx context.Context, options swarm.NodeListOptions) ([]swarm.Node, error)
NodeRemove(ctx context.Context, nodeID string, options types.NodeRemoveOptions) error NodeRemove(ctx context.Context, nodeID string, options swarm.NodeRemoveOptions) error
NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error
} }
@@ -141,22 +176,22 @@ type PluginAPIClient interface {
// ServiceAPIClient defines API client methods for the services // ServiceAPIClient defines API client methods for the services
type ServiceAPIClient interface { type ServiceAPIClient interface {
ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (swarm.ServiceCreateResponse, error) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options swarm.ServiceCreateOptions) (swarm.ServiceCreateResponse, error)
ServiceInspectWithRaw(ctx context.Context, serviceID string, options types.ServiceInspectOptions) (swarm.Service, []byte, error) ServiceInspectWithRaw(ctx context.Context, serviceID string, options swarm.ServiceInspectOptions) (swarm.Service, []byte, error)
ServiceList(ctx context.Context, options types.ServiceListOptions) ([]swarm.Service, error) ServiceList(ctx context.Context, options swarm.ServiceListOptions) ([]swarm.Service, error)
ServiceRemove(ctx context.Context, serviceID string) error ServiceRemove(ctx context.Context, serviceID string) error
ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (swarm.ServiceUpdateResponse, error) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options swarm.ServiceUpdateOptions) (swarm.ServiceUpdateResponse, error)
ServiceLogs(ctx context.Context, serviceID string, options container.LogsOptions) (io.ReadCloser, error) ServiceLogs(ctx context.Context, serviceID string, options container.LogsOptions) (io.ReadCloser, error)
TaskLogs(ctx context.Context, taskID string, options container.LogsOptions) (io.ReadCloser, error) TaskLogs(ctx context.Context, taskID string, options container.LogsOptions) (io.ReadCloser, error)
TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error)
TaskList(ctx context.Context, options types.TaskListOptions) ([]swarm.Task, error) TaskList(ctx context.Context, options swarm.TaskListOptions) ([]swarm.Task, error)
} }
// SwarmAPIClient defines API client methods for the swarm // SwarmAPIClient defines API client methods for the swarm
type SwarmAPIClient interface { type SwarmAPIClient interface {
SwarmInit(ctx context.Context, req swarm.InitRequest) (string, error) SwarmInit(ctx context.Context, req swarm.InitRequest) (string, error)
SwarmJoin(ctx context.Context, req swarm.JoinRequest) error SwarmJoin(ctx context.Context, req swarm.JoinRequest) error
SwarmGetUnlockKey(ctx context.Context) (types.SwarmUnlockKeyResponse, error) SwarmGetUnlockKey(ctx context.Context) (swarm.UnlockKeyResponse, error)
SwarmUnlock(ctx context.Context, req swarm.UnlockRequest) error SwarmUnlock(ctx context.Context, req swarm.UnlockRequest) error
SwarmLeave(ctx context.Context, force bool) error SwarmLeave(ctx context.Context, force bool) error
SwarmInspect(ctx context.Context) (swarm.Swarm, error) SwarmInspect(ctx context.Context) (swarm.Swarm, error)
@@ -185,8 +220,8 @@ type VolumeAPIClient interface {
// SecretAPIClient defines API client methods for secrets // SecretAPIClient defines API client methods for secrets
type SecretAPIClient interface { type SecretAPIClient interface {
SecretList(ctx context.Context, options types.SecretListOptions) ([]swarm.Secret, error) SecretList(ctx context.Context, options swarm.SecretListOptions) ([]swarm.Secret, error)
SecretCreate(ctx context.Context, secret swarm.SecretSpec) (types.SecretCreateResponse, error) SecretCreate(ctx context.Context, secret swarm.SecretSpec) (swarm.SecretCreateResponse, error)
SecretRemove(ctx context.Context, id string) error SecretRemove(ctx context.Context, id string) error
SecretInspectWithRaw(ctx context.Context, name string) (swarm.Secret, []byte, error) SecretInspectWithRaw(ctx context.Context, name string) (swarm.Secret, []byte, error)
SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error
@@ -194,8 +229,8 @@ type SecretAPIClient interface {
// ConfigAPIClient defines API client methods for configs // ConfigAPIClient defines API client methods for configs
type ConfigAPIClient interface { type ConfigAPIClient interface {
ConfigList(ctx context.Context, options types.ConfigListOptions) ([]swarm.Config, error) ConfigList(ctx context.Context, options swarm.ConfigListOptions) ([]swarm.Config, error)
ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (types.ConfigCreateResponse, error) ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (swarm.ConfigCreateResponse, error)
ConfigRemove(ctx context.Context, id string) error ConfigRemove(ctx context.Context, id string) error
ConfigInspectWithRaw(ctx context.Context, name string) (swarm.Config, []byte, error) ConfigInspectWithRaw(ctx context.Context, name string) (swarm.Config, []byte, error)
ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error

View File

@@ -1,6 +1,6 @@
//go:build !windows //go:build !windows
package client // import "github.com/docker/docker/client" package client
// DefaultDockerHost defines OS-specific default host if the DOCKER_HOST // DefaultDockerHost defines OS-specific default host if the DOCKER_HOST
// (EnvOverrideHost) environment variable is unset or empty. // (EnvOverrideHost) environment variable is unset or empty.

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
// DefaultDockerHost defines OS-specific default host if the DOCKER_HOST // DefaultDockerHost defines OS-specific default host if the DOCKER_HOST
// (EnvOverrideHost) environment variable is unset or empty. // (EnvOverrideHost) environment variable is unset or empty.

View File

@@ -1,16 +1,15 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
) )
// ConfigCreate creates a new config. // ConfigCreate creates a new config.
func (cli *Client) ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (types.ConfigCreateResponse, error) { func (cli *Client) ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (swarm.ConfigCreateResponse, error) {
var response types.ConfigCreateResponse var response swarm.ConfigCreateResponse
if err := cli.NewVersionError(ctx, "1.30", "config create"); err != nil { if err := cli.NewVersionError(ctx, "1.30", "config create"); err != nil {
return response, err return response, err
} }
@@ -20,6 +19,6 @@ func (cli *Client) ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (t
return response, err return response, err
} }
err = json.NewDecoder(resp.body).Decode(&response) err = json.NewDecoder(resp.Body).Decode(&response)
return response, err return response, err
} }

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"bytes" "bytes"
@@ -11,8 +11,9 @@ import (
// ConfigInspectWithRaw returns the config information with raw data // ConfigInspectWithRaw returns the config information with raw data
func (cli *Client) ConfigInspectWithRaw(ctx context.Context, id string) (swarm.Config, []byte, error) { func (cli *Client) ConfigInspectWithRaw(ctx context.Context, id string) (swarm.Config, []byte, error) {
if id == "" { id, err := trimID("contig", id)
return swarm.Config{}, nil, objectNotFoundError{object: "config", id: id} if err != nil {
return swarm.Config{}, nil, err
} }
if err := cli.NewVersionError(ctx, "1.30", "config inspect"); err != nil { if err := cli.NewVersionError(ctx, "1.30", "config inspect"); err != nil {
return swarm.Config{}, nil, err return swarm.Config{}, nil, err
@@ -23,7 +24,7 @@ func (cli *Client) ConfigInspectWithRaw(ctx context.Context, id string) (swarm.C
return swarm.Config{}, nil, err return swarm.Config{}, nil, err
} }
body, err := io.ReadAll(resp.body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return swarm.Config{}, nil, err return swarm.Config{}, nil, err
} }

View File

@@ -1,17 +1,16 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"net/url" "net/url"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
) )
// ConfigList returns the list of configs. // ConfigList returns the list of configs.
func (cli *Client) ConfigList(ctx context.Context, options types.ConfigListOptions) ([]swarm.Config, error) { func (cli *Client) ConfigList(ctx context.Context, options swarm.ConfigListOptions) ([]swarm.Config, error) {
if err := cli.NewVersionError(ctx, "1.30", "config list"); err != nil { if err := cli.NewVersionError(ctx, "1.30", "config list"); err != nil {
return nil, err return nil, err
} }
@@ -33,6 +32,6 @@ func (cli *Client) ConfigList(ctx context.Context, options types.ConfigListOptio
} }
var configs []swarm.Config var configs []swarm.Config
err = json.NewDecoder(resp.body).Decode(&configs) err = json.NewDecoder(resp.Body).Decode(&configs)
return configs, err return configs, err
} }

View File

@@ -1,9 +1,13 @@
package client // import "github.com/docker/docker/client" package client
import "context" import "context"
// ConfigRemove removes a config. // ConfigRemove removes a config.
func (cli *Client) ConfigRemove(ctx context.Context, id string) error { func (cli *Client) ConfigRemove(ctx context.Context, id string) error {
id, err := trimID("config", id)
if err != nil {
return err
}
if err := cli.NewVersionError(ctx, "1.30", "config remove"); err != nil { if err := cli.NewVersionError(ctx, "1.30", "config remove"); err != nil {
return err return err
} }

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -9,6 +9,10 @@ import (
// ConfigUpdate attempts to update a config // ConfigUpdate attempts to update a config
func (cli *Client) ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error { func (cli *Client) ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error {
id, err := trimID("config", id)
if err != nil {
return err
}
if err := cli.NewVersionError(ctx, "1.30", "config update"); err != nil { if err := cli.NewVersionError(ctx, "1.30", "config update"); err != nil {
return err return err
} }

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -33,7 +33,12 @@ import (
// //
// You can use github.com/docker/docker/pkg/stdcopy.StdCopy to demultiplex this // You can use github.com/docker/docker/pkg/stdcopy.StdCopy to demultiplex this
// stream. // stream.
func (cli *Client) ContainerAttach(ctx context.Context, container string, options container.AttachOptions) (types.HijackedResponse, error) { func (cli *Client) ContainerAttach(ctx context.Context, containerID string, options container.AttachOptions) (types.HijackedResponse, error) {
containerID, err := trimID("container", containerID)
if err != nil {
return types.HijackedResponse{}, err
}
query := url.Values{} query := url.Values{}
if options.Stream { if options.Stream {
query.Set("stream", "1") query.Set("stream", "1")
@@ -54,7 +59,7 @@ func (cli *Client) ContainerAttach(ctx context.Context, container string, option
query.Set("logs", "1") query.Set("logs", "1")
} }
return cli.postHijacked(ctx, "/containers/"+container+"/attach", query, nil, http.Header{ return cli.postHijacked(ctx, "/containers/"+containerID+"/attach", query, nil, http.Header{
"Content-Type": {"text/plain"}, "Content-Type": {"text/plain"},
}) })
} }

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -7,32 +7,36 @@ import (
"net/url" "net/url"
"github.com/distribution/reference" "github.com/distribution/reference"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/container"
) )
// ContainerCommit applies changes to a container and creates a new tagged image. // ContainerCommit applies changes to a container and creates a new tagged image.
func (cli *Client) ContainerCommit(ctx context.Context, container string, options container.CommitOptions) (types.IDResponse, error) { func (cli *Client) ContainerCommit(ctx context.Context, containerID string, options container.CommitOptions) (container.CommitResponse, error) {
containerID, err := trimID("container", containerID)
if err != nil {
return container.CommitResponse{}, err
}
var repository, tag string var repository, tag string
if options.Reference != "" { if options.Reference != "" {
ref, err := reference.ParseNormalizedNamed(options.Reference) ref, err := reference.ParseNormalizedNamed(options.Reference)
if err != nil { if err != nil {
return types.IDResponse{}, err return container.CommitResponse{}, err
} }
if _, isCanonical := ref.(reference.Canonical); isCanonical { if _, isCanonical := ref.(reference.Canonical); isCanonical {
return types.IDResponse{}, errors.New("refusing to create a tag with a digest reference") return container.CommitResponse{}, errors.New("refusing to create a tag with a digest reference")
} }
ref = reference.TagNameOnly(ref) ref = reference.TagNameOnly(ref)
if tagged, ok := ref.(reference.Tagged); ok { if tagged, ok := ref.(reference.Tagged); ok {
tag = tagged.Tag() tag = tagged.Tag()
} }
repository = reference.FamiliarName(ref) repository = ref.Name()
} }
query := url.Values{} query := url.Values{}
query.Set("container", container) query.Set("container", containerID)
query.Set("repo", repository) query.Set("repo", repository)
query.Set("tag", tag) query.Set("tag", tag)
query.Set("comment", options.Comment) query.Set("comment", options.Comment)
@@ -44,13 +48,13 @@ func (cli *Client) ContainerCommit(ctx context.Context, container string, option
query.Set("pause", "0") query.Set("pause", "0")
} }
var response types.IDResponse var response container.CommitResponse
resp, err := cli.post(ctx, "/commit", query, options.Config, nil) resp, err := cli.post(ctx, "/commit", query, options.Config, nil)
defer ensureReaderClosed(resp) defer ensureReaderClosed(resp)
if err != nil { if err != nil {
return response, err return response, err
} }
err = json.NewDecoder(resp.body).Decode(&response) err = json.NewDecoder(resp.Body).Decode(&response)
return response, err return response, err
} }

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -16,21 +16,30 @@ import (
// ContainerStatPath returns stat information about a path inside the container filesystem. // ContainerStatPath returns stat information about a path inside the container filesystem.
func (cli *Client) ContainerStatPath(ctx context.Context, containerID, path string) (container.PathStat, error) { func (cli *Client) ContainerStatPath(ctx context.Context, containerID, path string) (container.PathStat, error) {
query := url.Values{} containerID, err := trimID("container", containerID)
query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API.
urlStr := "/containers/" + containerID + "/archive"
response, err := cli.head(ctx, urlStr, query, nil)
defer ensureReaderClosed(response)
if err != nil { if err != nil {
return container.PathStat{}, err return container.PathStat{}, err
} }
return getContainerPathStatFromHeader(response.header)
query := url.Values{}
query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API.
resp, err := cli.head(ctx, "/containers/"+containerID+"/archive", query, nil)
defer ensureReaderClosed(resp)
if err != nil {
return container.PathStat{}, err
}
return getContainerPathStatFromHeader(resp.Header)
} }
// CopyToContainer copies content into the container filesystem. // CopyToContainer copies content into the container filesystem.
// Note that `content` must be a Reader for a TAR archive // Note that `content` must be a Reader for a TAR archive
func (cli *Client) CopyToContainer(ctx context.Context, containerID, dstPath string, content io.Reader, options container.CopyToContainerOptions) error { func (cli *Client) CopyToContainer(ctx context.Context, containerID, dstPath string, content io.Reader, options container.CopyToContainerOptions) error {
containerID, err := trimID("container", containerID)
if err != nil {
return err
}
query := url.Values{} query := url.Values{}
query.Set("path", filepath.ToSlash(dstPath)) // Normalize the paths used in the API. query.Set("path", filepath.ToSlash(dstPath)) // Normalize the paths used in the API.
// Do not allow for an existing directory to be overwritten by a non-directory and vice versa. // Do not allow for an existing directory to be overwritten by a non-directory and vice versa.
@@ -42,9 +51,7 @@ func (cli *Client) CopyToContainer(ctx context.Context, containerID, dstPath str
query.Set("copyUIDGID", "true") query.Set("copyUIDGID", "true")
} }
apiPath := "/containers/" + containerID + "/archive" response, err := cli.putRaw(ctx, "/containers/"+containerID+"/archive", query, content, nil)
response, err := cli.putRaw(ctx, apiPath, query, content, nil)
defer ensureReaderClosed(response) defer ensureReaderClosed(response)
if err != nil { if err != nil {
return err return err
@@ -56,11 +63,15 @@ func (cli *Client) CopyToContainer(ctx context.Context, containerID, dstPath str
// CopyFromContainer gets the content from the container and returns it as a Reader // CopyFromContainer gets the content from the container and returns it as a Reader
// for a TAR archive to manipulate it in the host. It's up to the caller to close the reader. // for a TAR archive to manipulate it in the host. It's up to the caller to close the reader.
func (cli *Client) CopyFromContainer(ctx context.Context, containerID, srcPath string) (io.ReadCloser, container.PathStat, error) { func (cli *Client) CopyFromContainer(ctx context.Context, containerID, srcPath string) (io.ReadCloser, container.PathStat, error) {
containerID, err := trimID("container", containerID)
if err != nil {
return nil, container.PathStat{}, err
}
query := make(url.Values, 1) query := make(url.Values, 1)
query.Set("path", filepath.ToSlash(srcPath)) // Normalize the paths used in the API. query.Set("path", filepath.ToSlash(srcPath)) // Normalize the paths used in the API.
apiPath := "/containers/" + containerID + "/archive" resp, err := cli.get(ctx, "/containers/"+containerID+"/archive", query, nil)
response, err := cli.get(ctx, apiPath, query, nil)
if err != nil { if err != nil {
return nil, container.PathStat{}, err return nil, container.PathStat{}, err
} }
@@ -71,11 +82,11 @@ func (cli *Client) CopyFromContainer(ctx context.Context, containerID, srcPath s
// copy it locally. Along with the stat info about the local destination, // copy it locally. Along with the stat info about the local destination,
// we have everything we need to handle the multiple possibilities there // we have everything we need to handle the multiple possibilities there
// can be when copying a file/dir from one location to another file/dir. // can be when copying a file/dir from one location to another file/dir.
stat, err := getContainerPathStatFromHeader(response.header) stat, err := getContainerPathStatFromHeader(resp.Header)
if err != nil { if err != nil {
return nil, stat, fmt.Errorf("unable to get resource stat from response: %s", err) return nil, stat, fmt.Errorf("unable to get resource stat from response: %s", err)
} }
return response.body, stat, err return resp.Body, stat, err
} }
func getContainerPathStatFromHeader(header http.Header) (container.PathStat, error) { func getContainerPathStatFromHeader(header http.Header) (container.PathStat, error) {

View File

@@ -1,10 +1,13 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"net/url" "net/url"
"path" "path"
"sort"
"strings"
"github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/network"
@@ -12,12 +15,6 @@ import (
ocispec "github.com/opencontainers/image-spec/specs-go/v1" ocispec "github.com/opencontainers/image-spec/specs-go/v1"
) )
type configWrapper struct {
*container.Config
HostConfig *container.HostConfig
NetworkingConfig *network.NetworkingConfig
}
// ContainerCreate creates a new container based on the given configuration. // ContainerCreate creates a new container based on the given configuration.
// It can be associated with a name, but it's not mandatory. // It can be associated with a name, but it's not mandatory.
func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *ocispec.Platform, containerName string) (container.CreateResponse, error) { func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *ocispec.Platform, containerName string) (container.CreateResponse, error) {
@@ -58,6 +55,22 @@ func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config
// When using API under 1.42, the Linux daemon doesn't respect the ConsoleSize // When using API under 1.42, the Linux daemon doesn't respect the ConsoleSize
hostConfig.ConsoleSize = [2]uint{0, 0} hostConfig.ConsoleSize = [2]uint{0, 0}
} }
if versions.LessThan(cli.ClientVersion(), "1.44") {
for _, m := range hostConfig.Mounts {
if m.BindOptions != nil {
// ReadOnlyNonRecursive can be safely ignored when API < 1.44
if m.BindOptions.ReadOnlyForceRecursive {
return response, errors.New("bind-recursive=readonly requires API v1.44 or later")
}
if m.BindOptions.NonRecursive && versions.LessThan(cli.ClientVersion(), "1.40") {
return response, errors.New("bind-recursive=disabled requires API v1.40 or later")
}
}
}
}
hostConfig.CapAdd = normalizeCapabilities(hostConfig.CapAdd)
hostConfig.CapDrop = normalizeCapabilities(hostConfig.CapDrop)
} }
// Since API 1.44, the container-wide MacAddress is deprecated and will trigger a WARNING if it's specified. // Since API 1.44, the container-wide MacAddress is deprecated and will trigger a WARNING if it's specified.
@@ -74,19 +87,19 @@ func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config
query.Set("name", containerName) query.Set("name", containerName)
} }
body := configWrapper{ body := container.CreateRequest{
Config: config, Config: config,
HostConfig: hostConfig, HostConfig: hostConfig,
NetworkingConfig: networkingConfig, NetworkingConfig: networkingConfig,
} }
serverResp, err := cli.post(ctx, "/containers/create", query, body, nil) resp, err := cli.post(ctx, "/containers/create", query, body, nil)
defer ensureReaderClosed(serverResp) defer ensureReaderClosed(resp)
if err != nil { if err != nil {
return response, err return response, err
} }
err = json.NewDecoder(serverResp.body).Decode(&response) err = json.NewDecoder(resp.Body).Decode(&response)
return response, err return response, err
} }
@@ -114,3 +127,42 @@ func hasEndpointSpecificMacAddress(networkingConfig *network.NetworkingConfig) b
} }
return false return false
} }
// allCapabilities is a magic value for "all capabilities"
const allCapabilities = "ALL"
// normalizeCapabilities normalizes capabilities to their canonical form,
// removes duplicates, and sorts the results.
//
// It is similar to [github.com/docker/docker/oci/caps.NormalizeLegacyCapabilities],
// but performs no validation based on supported capabilities.
func normalizeCapabilities(caps []string) []string {
var normalized []string
unique := make(map[string]struct{})
for _, c := range caps {
c = normalizeCap(c)
if _, ok := unique[c]; ok {
continue
}
unique[c] = struct{}{}
normalized = append(normalized, c)
}
sort.Strings(normalized)
return normalized
}
// normalizeCap normalizes a capability to its canonical format by upper-casing
// and adding a "CAP_" prefix (if not yet present). It also accepts the "ALL"
// magic-value.
func normalizeCap(cap string) string {
cap = strings.ToUpper(cap)
if cap == allCapabilities {
return cap
}
if !strings.HasPrefix(cap, "CAP_") {
cap = "CAP_" + cap
}
return cap
}

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -10,14 +10,21 @@ import (
// ContainerDiff shows differences in a container filesystem since it was started. // ContainerDiff shows differences in a container filesystem since it was started.
func (cli *Client) ContainerDiff(ctx context.Context, containerID string) ([]container.FilesystemChange, error) { func (cli *Client) ContainerDiff(ctx context.Context, containerID string) ([]container.FilesystemChange, error) {
var changes []container.FilesystemChange containerID, err := trimID("container", containerID)
serverResp, err := cli.get(ctx, "/containers/"+containerID+"/changes", url.Values{}, nil)
defer ensureReaderClosed(serverResp)
if err != nil { if err != nil {
return changes, err return nil, err
} }
err = json.NewDecoder(serverResp.body).Decode(&changes) resp, err := cli.get(ctx, "/containers/"+containerID+"/changes", url.Values{}, nil)
defer ensureReaderClosed(resp)
if err != nil {
return nil, err
}
var changes []container.FilesystemChange
err = json.NewDecoder(resp.Body).Decode(&changes)
if err != nil {
return nil, err
}
return changes, err return changes, err
} }

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -11,8 +11,11 @@ import (
) )
// ContainerExecCreate creates a new exec configuration to run an exec process. // ContainerExecCreate creates a new exec configuration to run an exec process.
func (cli *Client) ContainerExecCreate(ctx context.Context, container string, options container.ExecOptions) (types.IDResponse, error) { func (cli *Client) ContainerExecCreate(ctx context.Context, containerID string, options container.ExecOptions) (container.ExecCreateResponse, error) {
var response types.IDResponse containerID, err := trimID("container", containerID)
if err != nil {
return container.ExecCreateResponse{}, err
}
// Make sure we negotiated (if the client is configured to do so), // Make sure we negotiated (if the client is configured to do so),
// as code below contains API-version specific handling of options. // as code below contains API-version specific handling of options.
@@ -20,22 +23,24 @@ func (cli *Client) ContainerExecCreate(ctx context.Context, container string, op
// Normally, version-negotiation (if enabled) would not happen until // Normally, version-negotiation (if enabled) would not happen until
// the API request is made. // the API request is made.
if err := cli.checkVersion(ctx); err != nil { if err := cli.checkVersion(ctx); err != nil {
return response, err return container.ExecCreateResponse{}, err
} }
if err := cli.NewVersionError(ctx, "1.25", "env"); len(options.Env) != 0 && err != nil { if err := cli.NewVersionError(ctx, "1.25", "env"); len(options.Env) != 0 && err != nil {
return response, err return container.ExecCreateResponse{}, err
} }
if versions.LessThan(cli.ClientVersion(), "1.42") { if versions.LessThan(cli.ClientVersion(), "1.42") {
options.ConsoleSize = nil options.ConsoleSize = nil
} }
resp, err := cli.post(ctx, "/containers/"+container+"/exec", nil, options, nil) resp, err := cli.post(ctx, "/containers/"+containerID+"/exec", nil, options, nil)
defer ensureReaderClosed(resp) defer ensureReaderClosed(resp)
if err != nil { if err != nil {
return response, err return container.ExecCreateResponse{}, err
} }
err = json.NewDecoder(resp.body).Decode(&response)
var response container.ExecCreateResponse
err = json.NewDecoder(resp.Body).Decode(&response)
return response, err return response, err
} }
@@ -70,7 +75,7 @@ func (cli *Client) ContainerExecInspect(ctx context.Context, execID string) (con
return response, err return response, err
} }
err = json.NewDecoder(resp.body).Decode(&response) err = json.NewDecoder(resp.Body).Decode(&response)
ensureReaderClosed(resp) ensureReaderClosed(resp)
return response, err return response, err
} }

View File

@@ -1,4 +1,4 @@
package client // import "github.com/docker/docker/client" package client
import ( import (
"context" "context"
@@ -10,10 +10,15 @@ import (
// and returns them as an io.ReadCloser. It's up to the caller // and returns them as an io.ReadCloser. It's up to the caller
// to close the stream. // to close the stream.
func (cli *Client) ContainerExport(ctx context.Context, containerID string) (io.ReadCloser, error) { func (cli *Client) ContainerExport(ctx context.Context, containerID string) (io.ReadCloser, error) {
serverResp, err := cli.get(ctx, "/containers/"+containerID+"/export", url.Values{}, nil) containerID, err := trimID("container", containerID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return serverResp.body, nil resp, err := cli.get(ctx, "/containers/"+containerID+"/export", url.Values{}, nil)
if err != nil {
return nil, err
}
return resp.Body, nil
} }

Some files were not shown because too many files have changed in this diff Show More