From 9091e26596e945b1f4e1462dd03983f35662b399 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 20 Mar 2024 17:18:55 +0000 Subject: [PATCH] chore(deps): bump github.com/docker/docker Bumps [github.com/docker/docker](https://github.com/docker/docker) from 23.0.0-rc.1+incompatible to 24.0.9+incompatible. - [Release notes](https://github.com/docker/docker/releases) - [Commits](https://github.com/docker/docker/compare/v23.0.0-rc.1...v24.0.9) --- updated-dependencies: - dependency-name: github.com/docker/docker dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- go.mod | 2 +- go.sum | 5 +- .../github.com/MakeNowJust/heredoc/README.md | 104 ++--- vendor/github.com/docker/docker/AUTHORS | 18 + vendor/github.com/docker/docker/api/common.go | 2 +- .../github.com/docker/docker/api/swagger.yaml | 159 ++++--- .../docker/docker/api/types/auth.go | 25 +- .../docker/docker/api/types/client.go | 3 +- .../docker/docker/api/types/configs.go | 4 +- .../container/change_response_deprecated.go | 6 + .../docker/api/types/container/change_type.go | 15 + .../api/types/container/change_types.go | 23 ++ .../api/types/container/container_changes.go | 20 - .../docker/api/types/container/deprecated.go | 16 - .../api/types/container/filesystem_change.go | 19 + .../{host_config.go => hostconfig.go} | 129 +++--- .../docker/docker/api/types/deprecated.go | 14 - .../docker/docker/api/types/filters/errors.go | 37 ++ .../docker/docker/api/types/filters/parse.go | 56 ++- .../docker/docker/api/types/image/opts.go | 9 + .../docker/docker/api/types/image_summary.go | 13 +- .../docker/api/types/registry/authconfig.go | 99 +++++ .../docker/api/types/registry/registry.go | 6 +- .../docker/docker/api/types/time/timestamp.go | 40 +- .../docker/docker/api/types/types.go | 34 +- .../docker/api/types/versions/compare.go | 8 +- .../docker/api/types/volume/deprecated.go | 11 - .../builder/remotecontext/git/gitutils.go | 23 +- .../docker/docker/client/build_prune.go | 10 +- .../github.com/docker/docker/client/client.go | 60 ++- .../docker/docker/client/client_deprecated.go | 8 +- .../docker/docker/client/client_unix.go | 7 +- .../docker/docker/client/client_windows.go | 3 - .../docker/docker/client/container_create.go | 6 +- .../docker/docker/client/container_diff.go | 4 +- .../docker/docker/client/container_wait.go | 27 +- .../docker/client/distribution_inspect.go | 8 +- .../github.com/docker/docker/client/errors.go | 25 -- .../github.com/docker/docker/client/hijack.go | 13 +- .../docker/docker/client/image_create.go | 3 +- .../docker/docker/client/image_push.go | 3 +- .../docker/docker/client/image_search.go | 2 +- .../docker/docker/client/interface.go | 10 +- .../github.com/docker/docker/client/login.go | 3 +- .../github.com/docker/docker/client/ping.go | 6 +- .../docker/docker/client/plugin_install.go | 7 +- .../docker/docker/client/plugin_push.go | 4 +- .../docker/docker/client/plugin_upgrade.go | 3 +- .../docker/docker/client/request.go | 10 +- .../docker/docker/client/service_create.go | 3 +- .../docker/docker/client/service_update.go | 3 +- .../docker/docker/client/volume_list.go | 6 +- .../docker/docker/pkg/archive/README.md | 1 - .../docker/docker/pkg/archive/archive.go | 390 +++++++++--------- .../docker/docker/pkg/archive/archive_unix.go | 8 - .../docker/pkg/archive/archive_windows.go | 18 +- .../docker/pkg/archive/changes_other.go | 2 +- .../docker/docker/pkg/archive/copy.go | 36 +- .../docker/docker/pkg/archive/diff.go | 26 +- .../docker/docker/pkg/archive/path.go | 20 + .../docker/docker/pkg/archive/path_unix.go | 10 + .../docker/docker/pkg/archive/path_windows.go | 22 + .../docker/pkg/homedir/homedir_linux.go | 16 +- .../docker/pkg/homedir/homedir_others.go | 5 + .../docker/docker/pkg/idtools/idtools.go | 14 - .../docker/docker/pkg/idtools/idtools_unix.go | 106 ++--- .../docker/pkg/idtools/idtools_windows.go | 14 +- .../docker/pkg/idtools/usergroupadd_linux.go | 37 +- .../docker/docker/pkg/idtools/utils_unix.go | 5 - .../docker/docker/pkg/ioutils/bytespipe.go | 16 +- .../docker/docker/pkg/ioutils/readers.go | 21 + .../docker/docker/pkg/ioutils/temp_unix.go | 11 - .../docker/docker/pkg/ioutils/temp_windows.go | 16 - .../docker/pkg/ioutils/tempdir_deprecated.go | 10 + .../docker/docker/pkg/ioutils/writers.go | 10 +- .../docker/pkg/jsonmessage/jsonmessage.go | 92 +++-- .../docker/docker/pkg/longpath/longpath.go | 27 +- .../docker/docker/pkg/meminfo/meminfo.go | 26 ++ .../pkg/{system => meminfo}/meminfo_linux.go | 14 +- .../docker/pkg/meminfo/meminfo_unsupported.go | 11 + .../{system => meminfo}/meminfo_windows.go | 12 +- .../docker/docker/pkg/process/doc.go | 3 + .../docker/docker/pkg/process/process_unix.go | 82 ++++ .../docker/pkg/process/process_windows.go | 52 +++ .../docker/docker/pkg/stringid/README.md | 1 - .../docker/docker/pkg/stringid/stringid.go | 22 +- .../docker/docker/pkg/system/chtimes.go | 39 +- .../docker/pkg/system/chtimes_windows.go | 15 +- .../docker/pkg/system/filesys_deprecated.go | 35 -- .../docker/pkg/system/filesys_windows.go | 93 +++-- .../docker/docker/pkg/system/init.go | 22 - .../docker/docker/pkg/system/meminfo.go | 17 - .../docker/pkg/system/meminfo_deprecated.go | 16 + .../docker/pkg/system/meminfo_unsupported.go | 9 - .../docker/docker/pkg/system/path.go | 41 -- .../docker/pkg/system/path_deprecated.go | 18 + .../docker/docker/pkg/system/path_unix.go | 17 - .../docker/docker/pkg/system/path_windows.go | 48 --- .../docker/pkg/system/process_deprecated.go | 27 ++ .../docker/docker/pkg/system/process_unix.go | 46 --- .../docker/pkg/system/process_windows.go | 18 - .../docker/docker/pkg/system/stat_solaris.go | 13 - .../github.com/docker/docker/registry/auth.go | 13 +- .../docker/docker/registry/config.go | 4 +- .../docker/docker/registry/endpoint_v1.go | 8 +- .../docker/docker/registry/search.go | 139 +++++++ .../docker/docker/registry/service.go | 108 +---- .../docker/docker/registry/service_v2.go | 2 +- .../docker/docker/registry/session.go | 11 +- vendor/modules.txt | 4 +- 110 files changed, 1689 insertions(+), 1364 deletions(-) create mode 100644 vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go create mode 100644 vendor/github.com/docker/docker/api/types/container/change_type.go create mode 100644 vendor/github.com/docker/docker/api/types/container/change_types.go delete mode 100644 vendor/github.com/docker/docker/api/types/container/container_changes.go delete mode 100644 vendor/github.com/docker/docker/api/types/container/deprecated.go create mode 100644 vendor/github.com/docker/docker/api/types/container/filesystem_change.go rename vendor/github.com/docker/docker/api/types/container/{host_config.go => hostconfig.go} (84%) delete mode 100644 vendor/github.com/docker/docker/api/types/deprecated.go create mode 100644 vendor/github.com/docker/docker/api/types/filters/errors.go create mode 100644 vendor/github.com/docker/docker/api/types/image/opts.go create mode 100644 vendor/github.com/docker/docker/api/types/registry/authconfig.go delete mode 100644 vendor/github.com/docker/docker/api/types/volume/deprecated.go delete mode 100644 vendor/github.com/docker/docker/pkg/archive/README.md create mode 100644 vendor/github.com/docker/docker/pkg/archive/path.go create mode 100644 vendor/github.com/docker/docker/pkg/archive/path_unix.go create mode 100644 vendor/github.com/docker/docker/pkg/archive/path_windows.go delete mode 100644 vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go delete mode 100644 vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go create mode 100644 vendor/github.com/docker/docker/pkg/ioutils/tempdir_deprecated.go create mode 100644 vendor/github.com/docker/docker/pkg/meminfo/meminfo.go rename vendor/github.com/docker/docker/pkg/{system => meminfo}/meminfo_linux.go (79%) create mode 100644 vendor/github.com/docker/docker/pkg/meminfo/meminfo_unsupported.go rename vendor/github.com/docker/docker/pkg/{system => meminfo}/meminfo_windows.go (81%) create mode 100644 vendor/github.com/docker/docker/pkg/process/doc.go create mode 100644 vendor/github.com/docker/docker/pkg/process/process_unix.go create mode 100644 vendor/github.com/docker/docker/pkg/process/process_windows.go delete mode 100644 vendor/github.com/docker/docker/pkg/stringid/README.md delete mode 100644 vendor/github.com/docker/docker/pkg/system/filesys_deprecated.go delete mode 100644 vendor/github.com/docker/docker/pkg/system/init.go delete mode 100644 vendor/github.com/docker/docker/pkg/system/meminfo.go create mode 100644 vendor/github.com/docker/docker/pkg/system/meminfo_deprecated.go delete mode 100644 vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go delete mode 100644 vendor/github.com/docker/docker/pkg/system/path.go create mode 100644 vendor/github.com/docker/docker/pkg/system/path_deprecated.go delete mode 100644 vendor/github.com/docker/docker/pkg/system/path_unix.go delete mode 100644 vendor/github.com/docker/docker/pkg/system/path_windows.go create mode 100644 vendor/github.com/docker/docker/pkg/system/process_deprecated.go delete mode 100644 vendor/github.com/docker/docker/pkg/system/process_unix.go delete mode 100644 vendor/github.com/docker/docker/pkg/system/process_windows.go delete mode 100644 vendor/github.com/docker/docker/pkg/system/stat_solaris.go create mode 100644 vendor/github.com/docker/docker/registry/search.go diff --git a/go.mod b/go.mod index 927e74cccf..4bb4c95a75 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,7 @@ require ( github.com/creack/pty v1.1.17 github.com/docker/cli v23.0.0-rc.1+incompatible github.com/docker/distribution v2.8.2+incompatible - github.com/docker/docker v23.0.0-rc.1+incompatible + github.com/docker/docker v24.0.9+incompatible github.com/docker/go-connections v0.4.0 github.com/evanphx/json-patch v4.12.0+incompatible github.com/evanphx/json-patch/v5 v5.1.0 diff --git a/go.sum b/go.sum index d69324abbd..1242448d05 100644 --- a/go.sum +++ b/go.sum @@ -40,6 +40,7 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20210715213245-6c3934b029d8 h1:V8krnnfGj4pV65YLUm3C0/8bl7V5Nry2Pwvy3ru/wLc= github.com/AlecAivazis/survey/v2 v2.3.2 h1:TqTB+aDDCLYhf9/bD2TwSO8u8jDSmMUd2SUVO4gCnU8= github.com/AlecAivazis/survey/v2 v2.3.2/go.mod h1:TH2kPCDU3Kqq7pLbnCWwZXDBjnhZtmsCle5EiYDJ2fg= github.com/Azure/azure-sdk-for-go v16.2.1+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= @@ -159,8 +160,8 @@ github.com/docker/cli v23.0.0-rc.1+incompatible h1:Vl3pcUK4/LFAD56Ys3BrqgAtuwpWd github.com/docker/cli v23.0.0-rc.1+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v23.0.0-rc.1+incompatible h1:Dmn88McWuHc7BSNN1s6RtfhMmt6ZPQAYUEf7FhqpiQI= -github.com/docker/docker v23.0.0-rc.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker v24.0.9+incompatible h1:HPGzNmwfLZWdxHqK9/II92pyi1EpYKsAqcl4G0Of9v0= +github.com/docker/docker v24.0.9+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/docker-credential-helpers v0.7.0 h1:xtCHsjxogADNZcdv1pKUHXryefjlVRqWqIhk/uXJp0A= github.com/docker/docker-credential-helpers v0.7.0/go.mod h1:rETQfLdHNT3foU5kuNkFR1R1V12OJRRO5lzt2D1b5X0= github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= diff --git a/vendor/github.com/MakeNowJust/heredoc/README.md b/vendor/github.com/MakeNowJust/heredoc/README.md index 289ba31d6a..e9924d2974 100644 --- a/vendor/github.com/MakeNowJust/heredoc/README.md +++ b/vendor/github.com/MakeNowJust/heredoc/README.md @@ -1,52 +1,52 @@ -# heredoc - -[![Build Status](https://circleci.com/gh/MakeNowJust/heredoc.svg?style=svg)](https://circleci.com/gh/MakeNowJust/heredoc) [![GoDoc](https://godoc.org/github.com/MakeNowJusti/heredoc?status.svg)](https://godoc.org/github.com/MakeNowJust/heredoc) - -## About - -Package heredoc provides the here-document with keeping indent. - -## Install - -```console -$ go get github.com/MakeNowJust/heredoc -``` - -## Import - -```go -// usual -import "github.com/MakeNowJust/heredoc" -``` - -## Example - -```go -package main - -import ( - "fmt" - "github.com/MakeNowJust/heredoc" -) - -func main() { - fmt.Println(heredoc.Doc(` - Lorem ipsum dolor sit amet, consectetur adipisicing elit, - sed do eiusmod tempor incididunt ut labore et dolore magna - aliqua. Ut enim ad minim veniam, ... - `)) - // Output: - // Lorem ipsum dolor sit amet, consectetur adipisicing elit, - // sed do eiusmod tempor incididunt ut labore et dolore magna - // aliqua. Ut enim ad minim veniam, ... - // -} -``` - -## API Document - - - [heredoc - GoDoc](https://godoc.org/github.com/MakeNowJust/heredoc) - -## License - -This software is released under the MIT License, see LICENSE. +# heredoc + +[![Build Status](https://circleci.com/gh/MakeNowJust/heredoc.svg?style=svg)](https://circleci.com/gh/MakeNowJust/heredoc) [![GoDoc](https://godoc.org/github.com/MakeNowJusti/heredoc?status.svg)](https://godoc.org/github.com/MakeNowJust/heredoc) + +## About + +Package heredoc provides the here-document with keeping indent. + +## Install + +```console +$ go get github.com/MakeNowJust/heredoc +``` + +## Import + +```go +// usual +import "github.com/MakeNowJust/heredoc" +``` + +## Example + +```go +package main + +import ( + "fmt" + "github.com/MakeNowJust/heredoc" +) + +func main() { + fmt.Println(heredoc.Doc(` + Lorem ipsum dolor sit amet, consectetur adipisicing elit, + sed do eiusmod tempor incididunt ut labore et dolore magna + aliqua. Ut enim ad minim veniam, ... + `)) + // Output: + // Lorem ipsum dolor sit amet, consectetur adipisicing elit, + // sed do eiusmod tempor incididunt ut labore et dolore magna + // aliqua. Ut enim ad minim veniam, ... + // +} +``` + +## API Document + + - [heredoc - GoDoc](https://godoc.org/github.com/MakeNowJust/heredoc) + +## License + +This software is released under the MIT License, see LICENSE. diff --git a/vendor/github.com/docker/docker/AUTHORS b/vendor/github.com/docker/docker/AUTHORS index 0728bfe18f..b314181925 100644 --- a/vendor/github.com/docker/docker/AUTHORS +++ b/vendor/github.com/docker/docker/AUTHORS @@ -29,6 +29,7 @@ Adam Pointer Adam Singer Adam Walz Adam Williams +AdamKorcz Addam Hardy Aditi Rajagopal Aditya @@ -81,6 +82,7 @@ Alex Goodman Alex Nordlund Alex Olshansky Alex Samorukov +Alex Stockinger Alex Warhawk Alexander Artemenko Alexander Boyd @@ -198,6 +200,7 @@ Anusha Ragunathan Anyu Wang apocas Arash Deshmeh +arcosx ArikaChen Arko Dasgupta Arnaud Lefebvre @@ -241,6 +244,7 @@ Benjamin Atkin Benjamin Baker Benjamin Boudreau Benjamin Böhmke +Benjamin Wang Benjamin Yolken Benny Ng Benoit Chesneau @@ -634,6 +638,7 @@ Eng Zer Jun Enguerran Eohyung Lee epeterso +er0k Eric Barch Eric Curtin Eric G. Noriega @@ -754,6 +759,7 @@ Félix Baylac-Jacqué Félix Cantournet Gabe Rosenhouse Gabor Nagy +Gabriel Adrian Samfira Gabriel Goller Gabriel L. Somlo Gabriel Linder @@ -855,6 +861,7 @@ Hongbin Lu Hongxu Jia Honza Pokorny Hsing-Hui Hsu +Hsing-Yu (David) Chen hsinko <21551195@zju.edu.cn> Hu Keping Hu Tao @@ -887,6 +894,7 @@ Igor Dolzhikov Igor Karpovich Iliana Weller Ilkka Laukkanen +Illia Antypenko Illo Abdulrahim Ilya Dmitrichenko Ilya Gusev @@ -938,6 +946,7 @@ Jamie Hannaford Jamshid Afshar Jan Breig Jan Chren +Jan Garcia Jan Götte Jan Keromnes Jan Koprowski @@ -1206,6 +1215,7 @@ Kimbro Staken Kir Kolyshkin Kiran Gangadharan Kirill SIbirev +Kirk Easterson knappe Kohei Tsuruta Koichi Shiraishi @@ -1240,10 +1250,12 @@ Lars Kellogg-Stedman Lars R. Damerow Lars-Magnus Skog Laszlo Meszaros +Laura Brehm Laura Frank Laurent Bernaille Laurent Erignoux Laurie Voss +Leandro Motta Barros Leandro Siqueira Lee Calcote Lee Chao <932819864@qq.com> @@ -1563,6 +1575,7 @@ Nick Neisen Nick Parker Nick Payne Nick Russo +Nick Santos Nick Stenning Nick Stinemates Nick Wood @@ -1584,6 +1597,7 @@ NikolaMandic Nikolas Garofil Nikolay Edigaryev Nikolay Milovanov +ningmingxiao Nirmal Mehta Nishant Totla NIWA Hideyuki @@ -1615,6 +1629,7 @@ Omri Shiv Onur Filiz Oriol Francès Oscar Bonilla <6f6231@gmail.com> +oscar.chen <2972789494@qq.com> Oskar Niburski Otto Kekäläinen Ouyang Liduo @@ -1822,6 +1837,7 @@ Rory Hunter Rory McCune Ross Boucher Rovanion Luckey +Roy Reznik Royce Remer Rozhnov Alexandr Rudolph Gottesheim @@ -2271,6 +2287,7 @@ Xiaoyu Zhang xichengliudui <1693291525@qq.com> xiekeyang Ximo Guanter Gonzálbez +xin.li Xinbo Weng Xinfeng Liu Xinzi Zhou @@ -2282,6 +2299,7 @@ Yahya yalpul YAMADA Tsuyoshi Yamasaki Masahide +Yamazaki Masashi Yan Feng Yan Zhu Yang Bai diff --git a/vendor/github.com/docker/docker/api/common.go b/vendor/github.com/docker/docker/api/common.go index bee9b875a8..cba66bc462 100644 --- a/vendor/github.com/docker/docker/api/common.go +++ b/vendor/github.com/docker/docker/api/common.go @@ -3,7 +3,7 @@ package api // import "github.com/docker/docker/api" // Common constants for daemon and client. const ( // DefaultVersion of Current REST API - DefaultVersion = "1.42" + DefaultVersion = "1.43" // NoBaseImageSpecifier is the symbol used by the FROM // command to specify that no base image is to be used. diff --git a/vendor/github.com/docker/docker/api/swagger.yaml b/vendor/github.com/docker/docker/api/swagger.yaml index cda2827619..d98bc1bfd2 100644 --- a/vendor/github.com/docker/docker/api/swagger.yaml +++ b/vendor/github.com/docker/docker/api/swagger.yaml @@ -19,10 +19,10 @@ produces: consumes: - "application/json" - "text/plain" -basePath: "/v1.42" +basePath: "/v1.43" info: title: "Docker Engine API" - version: "1.42" + version: "1.43" x-logo: url: "https://docs.docker.com/assets/images/logo-docker-main.png" description: | @@ -55,8 +55,8 @@ info: the URL is not supported by the daemon, a HTTP `400 Bad Request` error message is returned. - If you omit the version-prefix, the current version of the API (v1.42) is used. - For example, calling `/info` is the same as calling `/v1.42/info`. Using the + If you omit the version-prefix, the current version of the API (v1.43) is used. + For example, calling `/info` is the same as calling `/v1.43/info`. Using the API without a version-prefix is deprecated and will be removed in a future release. Engine releases in the near future should support this version of the API, @@ -976,6 +976,13 @@ definitions: items: type: "integer" minimum: 0 + Annotations: + type: "object" + description: | + Arbitrary non-identifying metadata attached to container and + provided to the runtime when the container is started. + additionalProperties: + type: "string" # Applicable to UNIX platforms CapAdd: @@ -1122,6 +1129,7 @@ definitions: remapping option is enabled. ShmSize: type: "integer" + format: "int64" description: | Size of `/dev/shm` in bytes. If omitted, the system uses 64MB. minimum: 0 @@ -1610,6 +1618,34 @@ definitions: "WorkDir": "/var/lib/docker/overlay2/ef749362d13333e65fc95c572eb525abbe0052e16e086cb64bc3b98ae9aa6d74/work" } + FilesystemChange: + description: | + Change in the container's filesystem. + type: "object" + required: [Path, Kind] + properties: + Path: + description: | + Path to file or directory that has changed. + type: "string" + x-nullable: false + Kind: + $ref: "#/definitions/ChangeType" + + ChangeType: + description: | + Kind of change + + Can be one of: + + - `0`: Modified ("C") + - `1`: Added ("A") + - `2`: Deleted ("D") + type: "integer" + format: "uint8" + enum: [0, 1, 2] + x-nullable: false + ImageInspect: description: | Information about an image in the local image cache. @@ -1746,15 +1782,14 @@ definitions: Total size of the image including all layers it is composed of. In versions of Docker before v1.10, this field was calculated from - the image itself and all of its parent images. Docker v1.10 and up - store images self-contained, and no longer use a parent-chain, making - this field an equivalent of the Size field. + the image itself and all of its parent images. Images are now stored + self-contained, and no longer use a parent-chain, making this field + an equivalent of the Size field. - This field is kept for backward compatibility, but may be removed in - a future version of the API. + > **Deprecated**: this field is kept for backward compatibility, but + > will be removed in API v1.44. type: "integer" format: "int64" - x-nullable: false example: 1239828 GraphDriver: $ref: "#/definitions/GraphDriverData" @@ -1802,7 +1837,6 @@ definitions: - Created - Size - SharedSize - - VirtualSize - Labels - Containers properties: @@ -1888,19 +1922,17 @@ definitions: x-nullable: false example: 1239828 VirtualSize: - description: | + description: |- Total size of the image including all layers it is composed of. In versions of Docker before v1.10, this field was calculated from - the image itself and all of its parent images. Docker v1.10 and up - store images self-contained, and no longer use a parent-chain, making - this field an equivalent of the Size field. + the image itself and all of its parent images. Images are now stored + self-contained, and no longer use a parent-chain, making this field + an equivalent of the Size field. - This field is kept for backward compatibility, but may be removed in - a future version of the API. + Deprecated: this field is kept for backward compatibility, and will be removed in API v1.44. type: "integer" format: "int64" - x-nullable: false example: 172064416 Labels: description: "User-defined key/value metadata." @@ -2343,6 +2375,8 @@ definitions: type: "string" error: type: "string" + errorDetail: + $ref: "#/definitions/ErrorDetail" status: type: "string" progress: @@ -2977,8 +3011,6 @@ definitions: Name: "journald" - Type: "Log" Name: "json-file" - - Type: "Log" - Name: "logentries" - Type: "Log" Name: "splunk" - Type: "Log" @@ -4650,7 +4682,8 @@ definitions: example: false OOMKilled: description: | - Whether this container has been killed because it ran out of memory. + Whether a process within this container has been killed because it ran + out of memory since the container was last started. type: "boolean" example: false Dead: @@ -5033,7 +5066,7 @@ definitions: Go runtime (`GOOS`). Currently returned values are "linux" and "windows". A full list of - possible values can be found in the [Go documentation](https://golang.org/doc/install/source#environment). + possible values can be found in the [Go documentation](https://go.dev/doc/install/source#environment). type: "string" example: "linux" Architecture: @@ -5041,7 +5074,7 @@ definitions: Hardware architecture of the host, as returned by the Go runtime (`GOARCH`). - A full list of possible values can be found in the [Go documentation](https://golang.org/doc/install/source#environment). + A full list of possible values can be found in the [Go documentation](https://go.dev/doc/install/source#environment). type: "string" example: "x86_64" NCPU: @@ -5127,42 +5160,8 @@ definitions: ServerVersion: description: | Version string of the daemon. - - > **Note**: the [standalone Swarm API](https://docs.docker.com/swarm/swarm-api/) - > returns the Swarm version instead of the daemon version, for example - > `swarm/1.2.8`. type: "string" - example: "17.06.0-ce" - ClusterStore: - description: | - URL of the distributed storage backend. - - - The storage backend is used for multihost networking (to store - network and endpoint information) and by the node discovery mechanism. - -


- - > **Deprecated**: This field is only propagated when using standalone Swarm - > mode, and overlay networking using an external k/v store. Overlay - > networks with Swarm mode enabled use the built-in raft store, and - > this field will be empty. - type: "string" - example: "consul://consul.corp.example.com:8600/some/path" - ClusterAdvertise: - description: | - The network endpoint that the Engine advertises for the purpose of - node discovery. ClusterAdvertise is a `host:port` combination on which - the daemon is reachable by other hosts. - -


- - > **Deprecated**: This field is only propagated when using standalone Swarm - > mode, and overlay networking using an external k/v store. Overlay - > networks with Swarm mode enabled use the built-in raft store, and - > this field will be empty. - type: "string" - example: "node5.corp.example.com:8000" + example: "24.0.2" Runtimes: description: | List of [OCI compliant](https://github.com/opencontainers/runtime-spec) @@ -5240,7 +5239,8 @@ definitions: SecurityOptions: description: | List of security features that are enabled on the daemon, such as - apparmor, seccomp, SELinux, user-namespaces (userns), and rootless. + apparmor, seccomp, SELinux, user-namespaces (userns), rootless and + no-new-privileges. Additional configuration options for each security feature may be present, and are included as a comma-separated list of key/value @@ -5332,7 +5332,7 @@ definitions: type: "array" items: type: "string" - example: ["awslogs", "fluentd", "gcplogs", "gelf", "journald", "json-file", "logentries", "splunk", "syslog"] + example: ["awslogs", "fluentd", "gcplogs", "gelf", "journald", "json-file", "splunk", "syslog"] RegistryServiceConfig: @@ -6873,9 +6873,9 @@ paths: Returns which files in a container's filesystem have been added, deleted, or modified. The `Kind` of modification can be one of: - - `0`: Modified - - `1`: Added - - `2`: Deleted + - `0`: Modified ("C") + - `1`: Added ("A") + - `2`: Deleted ("D") operationId: "ContainerChanges" produces: ["application/json"] responses: @@ -6884,22 +6884,7 @@ paths: schema: type: "array" items: - type: "object" - x-go-name: "ContainerChangeResponseItem" - title: "ContainerChangeResponseItem" - description: "change item in response to ContainerChanges operation" - required: [Path, Kind] - properties: - Path: - description: "Path to file that has changed" - type: "string" - x-nullable: false - Kind: - description: "Kind of change" - type: "integer" - format: "uint8" - enum: [0, 1, 2] - x-nullable: false + $ref: "#/definitions/FilesystemChange" examples: application/json: - Path: "/dev" @@ -8226,7 +8211,7 @@ paths: Available filters: - - `until=`: duration relative to daemon's time, during which build cache was not used, in Go's duration format (e.g., '24h') + - `until=` remove cache older than ``. The `` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon's local time. - `id=` - `parent=` - `type=` @@ -8725,6 +8710,10 @@ paths: IdentityToken: "9cbaf023786cd7..." 204: description: "No error" + 401: + description: "Auth error" + schema: + $ref: "#/definitions/ErrorResponse" 500: description: "Server error" schema: @@ -9905,7 +9894,9 @@ paths: Id: "22be93d5babb089c5aab8dbc369042fad48ff791584ca2da2100db837a1c7c30" Warning: "" 403: - description: "operation not supported for pre-defined networks" + description: | + Forbidden operation. This happens when trying to create a network named after a pre-defined network, + or when trying to create an overlay network on a daemon which is not part of a Swarm cluster. schema: $ref: "#/definitions/ErrorResponse" 404: @@ -10368,6 +10359,12 @@ paths: default if omitted. required: true type: "string" + - name: "force" + in: "query" + description: | + Force disable a plugin even if still in use. + required: false + type: "boolean" tags: ["Plugin"] /plugins/{name}/upgrade: post: diff --git a/vendor/github.com/docker/docker/api/types/auth.go b/vendor/github.com/docker/docker/api/types/auth.go index ddf15bb182..9ee329a2fb 100644 --- a/vendor/github.com/docker/docker/api/types/auth.go +++ b/vendor/github.com/docker/docker/api/types/auth.go @@ -1,22 +1,7 @@ package types // import "github.com/docker/docker/api/types" +import "github.com/docker/docker/api/types/registry" -// AuthConfig contains authorization information for connecting to a Registry -type AuthConfig struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Auth string `json:"auth,omitempty"` - - // Email is an optional value associated with the username. - // This field is deprecated and will be removed in a later - // version of docker. - Email string `json:"email,omitempty"` - - ServerAddress string `json:"serveraddress,omitempty"` - - // IdentityToken is used to authenticate the user and get - // an access token for the registry. - IdentityToken string `json:"identitytoken,omitempty"` - - // RegistryToken is a bearer token to be sent to a registry - RegistryToken string `json:"registrytoken,omitempty"` -} +// AuthConfig contains authorization information for connecting to a Registry. +// +// Deprecated: use github.com/docker/docker/api/types/registry.AuthConfig +type AuthConfig = registry.AuthConfig diff --git a/vendor/github.com/docker/docker/api/types/client.go b/vendor/github.com/docker/docker/api/types/client.go index 97aca02306..d8cd306135 100644 --- a/vendor/github.com/docker/docker/api/types/client.go +++ b/vendor/github.com/docker/docker/api/types/client.go @@ -7,6 +7,7 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" + "github.com/docker/docker/api/types/registry" units "github.com/docker/go-units" ) @@ -180,7 +181,7 @@ type ImageBuildOptions struct { // 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]AuthConfig + AuthConfigs map[string]registry.AuthConfig Context io.Reader Labels map[string]string // squash the resulting image's layers to the parent diff --git a/vendor/github.com/docker/docker/api/types/configs.go b/vendor/github.com/docker/docker/api/types/configs.go index 7689f38b33..7d5930bbeb 100644 --- a/vendor/github.com/docker/docker/api/types/configs.go +++ b/vendor/github.com/docker/docker/api/types/configs.go @@ -3,7 +3,7 @@ package types // import "github.com/docker/docker/api/types" import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/network" - specs "github.com/opencontainers/image-spec/specs-go/v1" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" ) // configs holds structs used for internal communication between the @@ -16,7 +16,7 @@ type ContainerCreateConfig struct { Config *container.Config HostConfig *container.HostConfig NetworkingConfig *network.NetworkingConfig - Platform *specs.Platform + Platform *ocispec.Platform AdjustCPUShares bool } diff --git a/vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go b/vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go new file mode 100644 index 0000000000..6b4b47390d --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go @@ -0,0 +1,6 @@ +package container + +// ContainerChangeResponseItem change item in response to ContainerChanges operation +// +// Deprecated: use [FilesystemChange]. +type ContainerChangeResponseItem = FilesystemChange diff --git a/vendor/github.com/docker/docker/api/types/container/change_type.go b/vendor/github.com/docker/docker/api/types/container/change_type.go new file mode 100644 index 0000000000..fe8d6d3696 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/change_type.go @@ -0,0 +1,15 @@ +package container + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// ChangeType Kind of change +// +// Can be one of: +// +// - `0`: Modified ("C") +// - `1`: Added ("A") +// - `2`: Deleted ("D") +// +// swagger:model ChangeType +type ChangeType uint8 diff --git a/vendor/github.com/docker/docker/api/types/container/change_types.go b/vendor/github.com/docker/docker/api/types/container/change_types.go new file mode 100644 index 0000000000..3a3a83866e --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/change_types.go @@ -0,0 +1,23 @@ +package container + +const ( + // ChangeModify represents the modify operation. + ChangeModify ChangeType = 0 + // ChangeAdd represents the add operation. + ChangeAdd ChangeType = 1 + // ChangeDelete represents the delete operation. + ChangeDelete ChangeType = 2 +) + +func (ct ChangeType) String() string { + switch ct { + case ChangeModify: + return "C" + case ChangeAdd: + return "A" + case ChangeDelete: + return "D" + default: + return "" + } +} diff --git a/vendor/github.com/docker/docker/api/types/container/container_changes.go b/vendor/github.com/docker/docker/api/types/container/container_changes.go deleted file mode 100644 index 16dd5019ee..0000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_changes.go +++ /dev/null @@ -1,20 +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 -// ---------------------------------------------------------------------------- - -// ContainerChangeResponseItem change item in response to ContainerChanges operation -// swagger:model ContainerChangeResponseItem -type ContainerChangeResponseItem struct { - - // Kind of change - // Required: true - Kind uint8 `json:"Kind"` - - // Path to file that has changed - // Required: true - Path string `json:"Path"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/deprecated.go b/vendor/github.com/docker/docker/api/types/container/deprecated.go deleted file mode 100644 index 0cb70e3638..0000000000 --- a/vendor/github.com/docker/docker/api/types/container/deprecated.go +++ /dev/null @@ -1,16 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ContainerCreateCreatedBody OK response to ContainerCreate operation -// -// Deprecated: use CreateResponse -type ContainerCreateCreatedBody = CreateResponse - -// ContainerWaitOKBody OK response to ContainerWait operation -// -// Deprecated: use WaitResponse -type ContainerWaitOKBody = WaitResponse - -// ContainerWaitOKBodyError container waiting error, if any -// -// Deprecated: use WaitExitError -type ContainerWaitOKBodyError = WaitExitError diff --git a/vendor/github.com/docker/docker/api/types/container/filesystem_change.go b/vendor/github.com/docker/docker/api/types/container/filesystem_change.go new file mode 100644 index 0000000000..9e9c2ad1d5 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/filesystem_change.go @@ -0,0 +1,19 @@ +package container + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// FilesystemChange Change in the container's filesystem. +// +// swagger:model FilesystemChange +type FilesystemChange struct { + + // kind + // Required: true + Kind ChangeType `json:"Kind"` + + // Path to file or directory that has changed. + // + // Required: true + Path string `json:"Path"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/host_config.go b/vendor/github.com/docker/docker/api/types/container/hostconfig.go similarity index 84% rename from vendor/github.com/docker/docker/api/types/container/host_config.go rename to vendor/github.com/docker/docker/api/types/container/hostconfig.go index 100f434ce7..d4e6f55375 100644 --- a/vendor/github.com/docker/docker/api/types/container/host_config.go +++ b/vendor/github.com/docker/docker/api/types/container/hostconfig.go @@ -101,7 +101,8 @@ func (n IpcMode) IsShareable() bool { // IsContainer indicates whether the container uses another container's ipc namespace. func (n IpcMode) IsContainer() bool { - return strings.HasPrefix(string(n), string(IPCModeContainer)+":") + _, ok := containerID(string(n)) + return ok } // IsNone indicates whether container IpcMode is set to "none". @@ -116,15 +117,14 @@ func (n IpcMode) IsEmpty() bool { // Valid indicates whether the ipc mode is valid. func (n IpcMode) Valid() bool { + // TODO(thaJeztah): align with PidMode, and consider container-mode without a container name/ID to be invalid. return n.IsEmpty() || n.IsNone() || n.IsPrivate() || n.IsHost() || n.IsShareable() || n.IsContainer() } // Container returns the name of the container ipc stack is going to be used. -func (n IpcMode) Container() string { - if n.IsContainer() { - return strings.TrimPrefix(string(n), string(IPCModeContainer)+":") - } - return "" +func (n IpcMode) Container() (idOrName string) { + idOrName, _ = containerID(string(n)) + return idOrName } // NetworkMode represents the container network stack. @@ -147,17 +147,14 @@ func (n NetworkMode) IsPrivate() bool { // IsContainer indicates whether container uses a container network stack. func (n NetworkMode) IsContainer() bool { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" + _, ok := containerID(string(n)) + return ok } // ConnectedContainer is the id of the container which network this container is connected to. -func (n NetworkMode) ConnectedContainer() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" +func (n NetworkMode) ConnectedContainer() (idOrName string) { + idOrName, _ = containerID(string(n)) + return idOrName } // UserDefined indicates user-created network @@ -178,18 +175,12 @@ func (n UsernsMode) IsHost() bool { // IsPrivate indicates whether the container uses the a private userns. func (n UsernsMode) IsPrivate() bool { - return !(n.IsHost()) + return !n.IsHost() } // Valid indicates whether the userns is valid. func (n UsernsMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - default: - return false - } - return true + return n == "" || n.IsHost() } // CgroupSpec represents the cgroup to use for the container. @@ -197,22 +188,20 @@ type CgroupSpec string // IsContainer indicates whether the container is using another container cgroup func (c CgroupSpec) IsContainer() bool { - parts := strings.SplitN(string(c), ":", 2) - return len(parts) > 1 && parts[0] == "container" + _, ok := containerID(string(c)) + return ok } // Valid indicates whether the cgroup spec is valid. func (c CgroupSpec) Valid() bool { - return c.IsContainer() || c == "" + // TODO(thaJeztah): align with PidMode, and consider container-mode without a container name/ID to be invalid. + return c == "" || c.IsContainer() } -// Container returns the name of the container whose cgroup will be used. -func (c CgroupSpec) Container() string { - parts := strings.SplitN(string(c), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" +// Container returns the ID or name of the container whose cgroup will be used. +func (c CgroupSpec) Container() (idOrName string) { + idOrName, _ = containerID(string(c)) + return idOrName } // UTSMode represents the UTS namespace of the container. @@ -220,7 +209,7 @@ type UTSMode string // IsPrivate indicates whether the container uses its private UTS namespace. func (n UTSMode) IsPrivate() bool { - return !(n.IsHost()) + return !n.IsHost() } // IsHost indicates whether the container uses the host's UTS namespace. @@ -230,13 +219,7 @@ func (n UTSMode) IsHost() bool { // Valid indicates whether the UTS namespace is valid. func (n UTSMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - default: - return false - } - return true + return n == "" || n.IsHost() } // PidMode represents the pid namespace of the container. @@ -254,32 +237,19 @@ func (n PidMode) IsHost() bool { // IsContainer indicates whether the container uses a container's pid namespace. func (n PidMode) IsContainer() bool { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" + _, ok := containerID(string(n)) + return ok } // Valid indicates whether the pid namespace is valid. func (n PidMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - case "container": - if len(parts) != 2 || parts[1] == "" { - return false - } - default: - return false - } - return true + return n == "" || n.IsHost() || validContainer(string(n)) } // Container returns the name of the container whose pid namespace is going to be used. -func (n PidMode) Container() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" +func (n PidMode) Container() (idOrName string) { + idOrName, _ = containerID(string(n)) + return idOrName } // DeviceRequest represents a request for devices from a device driver. @@ -408,16 +378,17 @@ type UpdateConfig struct { // Portable information *should* appear in Config. type HostConfig struct { // Applicable to all platforms - Binds []string // List of volume bindings for this container - ContainerIDFile string // File (path) where the containerId is written - LogConfig LogConfig // Configuration of the logs for this container - NetworkMode NetworkMode // Network mode to use for the container - PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host - RestartPolicy RestartPolicy // Restart policy to be used for the container - AutoRemove bool // Automatically remove container when it exits - VolumeDriver string // Name of the volume driver used to mount volumes - VolumesFrom []string // List of volumes to take from other container - ConsoleSize [2]uint // Initial console size (height,width) + Binds []string // List of volume bindings for this container + ContainerIDFile string // File (path) where the containerId is written + LogConfig LogConfig // Configuration of the logs for this container + NetworkMode NetworkMode // Network mode to use for the container + PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host + RestartPolicy RestartPolicy // Restart policy to be used for the container + AutoRemove bool // Automatically remove container when it exits + VolumeDriver string // Name of the volume driver used to mount volumes + VolumesFrom []string // List of volumes to take from other container + ConsoleSize [2]uint // Initial console size (height,width) + Annotations map[string]string `json:",omitempty"` // Arbitrary non-identifying metadata attached to container and provided to the runtime // Applicable to UNIX platforms CapAdd strslice.StrSlice // List of kernel capabilities to add to the container @@ -463,3 +434,23 @@ type HostConfig struct { // Run a custom init inside the container, if null, use the daemon's configured settings Init *bool `json:",omitempty"` } + +// containerID splits "container:" values. It returns the container +// ID or name, and whether an ID/name was found. It returns an empty string and +// a "false" if the value does not have a "container:" prefix. Further validation +// of the returned, including checking if the value is empty, should be handled +// by the caller. +func containerID(val string) (idOrName string, ok bool) { + k, v, hasSep := strings.Cut(val, ":") + if !hasSep || k != "container" { + return "", false + } + return v, true +} + +// validContainer checks if the given value is a "container:" mode with +// a non-empty name/ID. +func validContainer(val string) bool { + id, ok := containerID(val) + return ok && id != "" +} diff --git a/vendor/github.com/docker/docker/api/types/deprecated.go b/vendor/github.com/docker/docker/api/types/deprecated.go deleted file mode 100644 index 216d1df0ff..0000000000 --- a/vendor/github.com/docker/docker/api/types/deprecated.go +++ /dev/null @@ -1,14 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -import "github.com/docker/docker/api/types/volume" - -// Volume volume -// -// Deprecated: use github.com/docker/docker/api/types/volume.Volume -type Volume = volume.Volume - -// VolumeUsageData Usage details about the volume. This information is used by the -// `GET /system/df` endpoint, and omitted in other endpoints. -// -// Deprecated: use github.com/docker/docker/api/types/volume.UsageData -type VolumeUsageData = volume.UsageData diff --git a/vendor/github.com/docker/docker/api/types/filters/errors.go b/vendor/github.com/docker/docker/api/types/filters/errors.go new file mode 100644 index 0000000000..f52f694408 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/filters/errors.go @@ -0,0 +1,37 @@ +package filters + +import "fmt" + +// invalidFilter indicates that the provided filter or its value is invalid +type invalidFilter struct { + Filter string + Value []string +} + +func (e invalidFilter) Error() string { + msg := "invalid filter" + if e.Filter != "" { + msg += " '" + e.Filter + if e.Value != nil { + msg = fmt.Sprintf("%s=%s", msg, e.Value) + } + msg += "'" + } + return msg +} + +// InvalidParameter marks this error as ErrInvalidParameter +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) +} diff --git a/vendor/github.com/docker/docker/api/types/filters/parse.go b/vendor/github.com/docker/docker/api/types/filters/parse.go index 52c190ec79..0c39ab5f18 100644 --- a/vendor/github.com/docker/docker/api/types/filters/parse.go +++ b/vendor/github.com/docker/docker/api/types/filters/parse.go @@ -10,7 +10,6 @@ import ( "strings" "github.com/docker/docker/api/types/versions" - "github.com/pkg/errors" ) // Args stores a mapping of keys to a set of multiple values. @@ -50,7 +49,7 @@ func (args Args) Keys() []string { // MarshalJSON returns a JSON byte representation of the Args func (args Args) MarshalJSON() ([]byte, error) { if len(args.fields) == 0 { - return []byte{}, nil + return []byte("{}"), nil } return json.Marshal(args.fields) } @@ -99,7 +98,7 @@ func FromJSON(p string) (Args, error) { // Fallback to parsing arguments in the legacy slice format deprecated := map[string][]string{} if legacyErr := json.Unmarshal(raw, &deprecated); legacyErr != nil { - return args, invalidFilter{errors.Wrap(err, "invalid filter")} + return args, &invalidFilter{} } args.fields = deprecatedArgs(deprecated) @@ -108,9 +107,6 @@ func FromJSON(p string) (Args, error) { // UnmarshalJSON populates the Args from JSON encode bytes func (args Args) UnmarshalJSON(raw []byte) error { - if len(raw) == 0 { - return nil - } return json.Unmarshal(raw, &args.fields) } @@ -166,13 +162,13 @@ func (args Args) MatchKVList(key string, sources map[string]string) bool { } for value := range fieldValues { - testKV := strings.SplitN(value, "=", 2) + testK, testV, hasValue := strings.Cut(value, "=") - v, ok := sources[testKV[0]] + v, ok := sources[testK] if !ok { return false } - if len(testKV) == 2 && testKV[1] != v { + if hasValue && testV != v { return false } } @@ -199,6 +195,38 @@ func (args Args) Match(field, source string) bool { return false } +// GetBoolOrDefault returns a boolean value of the key if the key is present +// and is intepretable as a boolean value. Otherwise the default value is returned. +// 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) { + fieldValues, ok := args.fields[key] + + if !ok { + return defaultValue, nil + } + + if len(fieldValues) == 0 { + return defaultValue, &invalidFilter{key, nil} + } + + isFalse := fieldValues["0"] || fieldValues["false"] + isTrue := fieldValues["1"] || fieldValues["true"] + + conflicting := isFalse && isTrue + invalid := !isFalse && !isTrue + + if conflicting || invalid { + return defaultValue, &invalidFilter{key, args.Get(key)} + } else if isFalse { + return false, nil + } else if isTrue { + return true, 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. func (args Args) ExactMatch(key, source string) bool { fieldValues, ok := args.fields[key] @@ -249,20 +277,12 @@ func (args Args) Contains(field string) bool { return ok } -type invalidFilter struct{ error } - -func (e invalidFilter) Error() string { - return e.error.Error() -} - -func (invalidFilter) InvalidParameter() {} - // Validate compared the set of accepted keys against the keys in the mapping. // An error is returned if any mapping keys are not in the accepted set. func (args Args) Validate(accepted map[string]bool) error { for name := range args.fields { if !accepted[name] { - return invalidFilter{errors.New("invalid filter '" + name + "'")} + return &invalidFilter{name, nil} } } return nil diff --git a/vendor/github.com/docker/docker/api/types/image/opts.go b/vendor/github.com/docker/docker/api/types/image/opts.go new file mode 100644 index 0000000000..3cefecb0da --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/image/opts.go @@ -0,0 +1,9 @@ +package image + +import ocispec "github.com/opencontainers/image-spec/specs-go/v1" + +// GetImageOpts holds parameters to inspect an image. +type GetImageOpts struct { + Platform *ocispec.Platform + Details bool +} diff --git a/vendor/github.com/docker/docker/api/types/image_summary.go b/vendor/github.com/docker/docker/api/types/image_summary.go index 90b983a25c..0f6f144840 100644 --- a/vendor/github.com/docker/docker/api/types/image_summary.go +++ b/vendor/github.com/docker/docker/api/types/image_summary.go @@ -85,13 +85,10 @@ type ImageSummary struct { // Total size of the image including all layers it is composed of. // // In versions of Docker before v1.10, this field was calculated from - // the image itself and all of its parent images. Docker v1.10 and up - // store images self-contained, and no longer use a parent-chain, making - // this field an equivalent of the Size field. + // the image itself and all of its parent images. Images are now stored + // self-contained, and no longer use a parent-chain, making this field + // an equivalent of the Size field. // - // This field is kept for backward compatibility, but may be removed in - // a future version of the API. - // - // Required: true - VirtualSize int64 `json:"VirtualSize"` + // Deprecated: this field is kept for backward compatibility, and will be removed in API v1.44. + VirtualSize int64 `json:"VirtualSize,omitempty"` } diff --git a/vendor/github.com/docker/docker/api/types/registry/authconfig.go b/vendor/github.com/docker/docker/api/types/registry/authconfig.go new file mode 100644 index 0000000000..97a924e374 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/registry/authconfig.go @@ -0,0 +1,99 @@ +package registry // import "github.com/docker/docker/api/types/registry" +import ( + "encoding/base64" + "encoding/json" + "io" + "strings" + + "github.com/pkg/errors" +) + +// AuthHeader is the name of the header used to send encoded registry +// authorization credentials for registry operations (push/pull). +const AuthHeader = "X-Registry-Auth" + +// AuthConfig contains authorization information for connecting to a Registry. +type AuthConfig struct { + Username string `json:"username,omitempty"` + Password string `json:"password,omitempty"` + Auth string `json:"auth,omitempty"` + + // Email is an optional value associated with the username. + // This field is deprecated and will be removed in a later + // version of docker. + Email string `json:"email,omitempty"` + + ServerAddress string `json:"serveraddress,omitempty"` + + // IdentityToken is used to authenticate the user and get + // an access token for the registry. + IdentityToken string `json:"identitytoken,omitempty"` + + // RegistryToken is a bearer token to be sent to a registry + RegistryToken string `json:"registrytoken,omitempty"` +} + +// EncodeAuthConfig serializes the auth configuration as a base64url encoded +// RFC4648, section 5) JSON string for sending through the X-Registry-Auth header. +// +// For details on base64url encoding, see: +// - RFC4648, section 5: https://tools.ietf.org/html/rfc4648#section-5 +func EncodeAuthConfig(authConfig AuthConfig) (string, error) { + buf, err := json.Marshal(authConfig) + if err != nil { + return "", errInvalidParameter{err} + } + return base64.URLEncoding.EncodeToString(buf), nil +} + +// DecodeAuthConfig decodes base64url encoded (RFC4648, section 5) JSON +// authentication information as sent through the X-Registry-Auth header. +// +// This function always returns an AuthConfig, even if an error occurs. It is up +// to the caller to decide if authentication is required, and if the error can +// be ignored. +// +// For details on base64url encoding, see: +// - RFC4648, section 5: https://tools.ietf.org/html/rfc4648#section-5 +func DecodeAuthConfig(authEncoded string) (*AuthConfig, error) { + if authEncoded == "" { + return &AuthConfig{}, nil + } + + authJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded)) + return decodeAuthConfigFromReader(authJSON) +} + +// DecodeAuthConfigBody decodes authentication information as sent as JSON in the +// body of a request. This function is to provide backward compatibility with old +// clients and API versions. Current clients and API versions expect authentication +// to be provided through the X-Registry-Auth header. +// +// 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, +// and if the error can be ignored. +func DecodeAuthConfigBody(rdr io.ReadCloser) (*AuthConfig, error) { + return decodeAuthConfigFromReader(rdr) +} + +func decodeAuthConfigFromReader(rdr io.Reader) (*AuthConfig, error) { + authConfig := &AuthConfig{} + if err := json.NewDecoder(rdr).Decode(authConfig); err != nil { + // always return an (empty) AuthConfig to increase compatibility with + // the existing API. + return &AuthConfig{}, invalid(err) + } + return authConfig, nil +} + +func invalid(err error) error { + return errInvalidParameter{errors.Wrap(err, "invalid X-Registry-Auth header")} +} + +type errInvalidParameter struct{ error } + +func (errInvalidParameter) InvalidParameter() {} + +func (e errInvalidParameter) Cause() error { return e.error } + +func (e errInvalidParameter) Unwrap() error { return e.error } diff --git a/vendor/github.com/docker/docker/api/types/registry/registry.go b/vendor/github.com/docker/docker/api/types/registry/registry.go index 62a88f5be8..b83f5d7b2e 100644 --- a/vendor/github.com/docker/docker/api/types/registry/registry.go +++ b/vendor/github.com/docker/docker/api/types/registry/registry.go @@ -4,7 +4,7 @@ import ( "encoding/json" "net" - v1 "github.com/opencontainers/image-spec/specs-go/v1" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" ) // ServiceConfig stores daemon registry services configuration. @@ -113,8 +113,8 @@ type SearchResults struct { type DistributionInspect struct { // Descriptor contains information about the manifest, including // the content addressable digest - Descriptor v1.Descriptor + Descriptor ocispec.Descriptor // Platforms contains the list of platforms supported by the image, // obtained by parsing the manifest - Platforms []v1.Platform + Platforms []ocispec.Platform } diff --git a/vendor/github.com/docker/docker/api/types/time/timestamp.go b/vendor/github.com/docker/docker/api/types/time/timestamp.go index 2a74b7a597..cab5c32e3f 100644 --- a/vendor/github.com/docker/docker/api/types/time/timestamp.go +++ b/vendor/github.com/docker/docker/api/types/time/timestamp.go @@ -95,37 +95,37 @@ func GetTimestamp(value string, reference time.Time) (string, error) { return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond())), nil } -// ParseTimestamps returns seconds and nanoseconds from a timestamp that has the -// format "%d.%09d", time.Unix(), int64(time.Nanosecond())) -// if the incoming nanosecond portion is longer or shorter than 9 digits it is -// converted to nanoseconds. The expectation is that the seconds and -// seconds will be used to create a time variable. For example: +// ParseTimestamps returns seconds and nanoseconds from a timestamp that has +// the format ("%d.%09d", time.Unix(), int64(time.Nanosecond())). +// If the incoming nanosecond portion is longer than 9 digits it is truncated. +// The expectation is that the seconds and nanoseconds will be used to create a +// time variable. For example: // -// seconds, nanoseconds, err := ParseTimestamp("1136073600.000000001",0) -// if err == nil since := time.Unix(seconds, nanoseconds) +// seconds, nanoseconds, _ := ParseTimestamp("1136073600.000000001",0) +// since := time.Unix(seconds, nanoseconds) // -// returns seconds as def(aultSeconds) if value == "" -func ParseTimestamps(value string, def int64) (int64, int64, error) { +// returns seconds as defaultSeconds if value == "" +func ParseTimestamps(value string, defaultSeconds int64) (seconds int64, nanoseconds int64, err error) { if value == "" { - return def, 0, nil + return defaultSeconds, 0, nil } return parseTimestamp(value) } -func parseTimestamp(value string) (int64, int64, error) { - sa := strings.SplitN(value, ".", 2) - s, err := strconv.ParseInt(sa[0], 10, 64) +func parseTimestamp(value string) (sec int64, nsec int64, err error) { + s, n, ok := strings.Cut(value, ".") + sec, err = strconv.ParseInt(s, 10, 64) if err != nil { - return s, 0, err + return sec, 0, err } - if len(sa) != 2 { - return s, 0, nil + if !ok { + return sec, 0, nil } - n, err := strconv.ParseInt(sa[1], 10, 64) + nsec, err = strconv.ParseInt(n, 10, 64) if err != nil { - return s, n, err + return sec, nsec, err } // should already be in nanoseconds but just in case convert n to nanoseconds - n = int64(float64(n) * math.Pow(float64(10), float64(9-len(sa[1])))) - return s, n, nil + nsec = int64(float64(nsec) * math.Pow(float64(10), float64(9-len(n)))) + return sec, nsec, nil } diff --git a/vendor/github.com/docker/docker/api/types/types.go b/vendor/github.com/docker/docker/api/types/types.go index 036405299e..b413e02000 100644 --- a/vendor/github.com/docker/docker/api/types/types.go +++ b/vendor/github.com/docker/docker/api/types/types.go @@ -123,9 +123,8 @@ type ImageInspect struct { // store images self-contained, and no longer use a parent-chain, making // this field an equivalent of the Size field. // - // This field is kept for backward compatibility, but may be removed in - // a future version of the API. - VirtualSize int64 // TODO(thaJeztah): deprecate this field + // Deprecated: Unused in API 1.43 and up, but kept for backward compatibility with older API versions. + VirtualSize int64 `json:"VirtualSize,omitempty"` // GraphDriver holds information about the storage driver used to store the // container's and image's filesystem. @@ -297,8 +296,6 @@ type Info struct { Labels []string ExperimentalBuild bool ServerVersion string - ClusterStore string `json:",omitempty"` // Deprecated: host-discovery and overlay networks with external k/v stores are deprecated - ClusterAdvertise string `json:",omitempty"` // Deprecated: host-discovery and overlay networks with external k/v stores are deprecated Runtimes map[string]Runtime DefaultRuntime string Swarm swarm.Info @@ -350,20 +347,19 @@ func DecodeSecurityOptions(opts []string) ([]SecurityOpt, error) { continue } secopt := SecurityOpt{} - split := strings.Split(opt, ",") - for _, s := range split { - kv := strings.SplitN(s, "=", 2) - if len(kv) != 2 { + for _, s := range strings.Split(opt, ",") { + k, v, ok := strings.Cut(s, "=") + if !ok { return nil, fmt.Errorf("invalid security option %q", s) } - if kv[0] == "" || kv[1] == "" { + if k == "" || v == "" { return nil, errors.New("invalid empty security option") } - if kv[0] == "name" { - secopt.Name = kv[1] + if k == "name" { + secopt.Name = v continue } - secopt.Options = append(secopt.Options, KeyValue{Key: kv[0], Value: kv[1]}) + secopt.Options = append(secopt.Options, KeyValue{Key: k, Value: v}) } so = append(so, secopt) } @@ -656,12 +652,18 @@ type Checkpoint struct { // Runtime describes an OCI runtime type Runtime struct { - Path string `json:"path"` + // "Legacy" runtime configuration for runc-compatible runtimes. + + Path string `json:"path,omitempty"` Args []string `json:"runtimeArgs,omitempty"` + // Shimv2 runtime configuration. Mutually exclusive with the legacy config above. + + Type string `json:"runtimeType,omitempty"` + Options map[string]interface{} `json:"options,omitempty"` + // This is exposed here only for internal use - // It is not currently supported to specify custom shim configs - Shim *ShimConfig `json:"-"` + ShimConfig *ShimConfig `json:"-"` } // ShimConfig is used by runtime to configure containerd shims diff --git a/vendor/github.com/docker/docker/api/types/versions/compare.go b/vendor/github.com/docker/docker/api/types/versions/compare.go index 489e917ee5..621725a36d 100644 --- a/vendor/github.com/docker/docker/api/types/versions/compare.go +++ b/vendor/github.com/docker/docker/api/types/versions/compare.go @@ -16,11 +16,11 @@ func compare(v1, v2 string) int { otherTab = strings.Split(v2, ".") ) - max := len(currTab) - if len(otherTab) > max { - max = len(otherTab) + maxVer := len(currTab) + if len(otherTab) > maxVer { + maxVer = len(otherTab) } - for i := 0; i < max; i++ { + for i := 0; i < maxVer; i++ { var currInt, otherInt int if len(currTab) > i { diff --git a/vendor/github.com/docker/docker/api/types/volume/deprecated.go b/vendor/github.com/docker/docker/api/types/volume/deprecated.go deleted file mode 100644 index ab622d8ccb..0000000000 --- a/vendor/github.com/docker/docker/api/types/volume/deprecated.go +++ /dev/null @@ -1,11 +0,0 @@ -package volume // import "github.com/docker/docker/api/types/volume" - -// VolumeCreateBody Volume configuration -// -// Deprecated: use CreateOptions -type VolumeCreateBody = CreateOptions - -// VolumeListOKBody Volume list response -// -// Deprecated: use ListResponse -type VolumeListOKBody = ListResponse diff --git a/vendor/github.com/docker/docker/builder/remotecontext/git/gitutils.go b/vendor/github.com/docker/docker/builder/remotecontext/git/gitutils.go index c20f8da75b..f9b2b4b9c4 100644 --- a/vendor/github.com/docker/docker/builder/remotecontext/git/gitutils.go +++ b/vendor/github.com/docker/docker/builder/remotecontext/git/gitutils.go @@ -4,12 +4,12 @@ import ( "net/http" "net/url" "os" + "os/exec" "path/filepath" "strings" "github.com/moby/sys/symlink" "github.com/pkg/errors" - exec "golang.org/x/sys/execabs" ) type gitRepo struct { @@ -97,15 +97,10 @@ func parseRemoteURL(remoteURL string) (gitRepo, error) { remoteURL = "https://" + remoteURL } - var fragment string if strings.HasPrefix(remoteURL, "git@") { // git@.. is not an URL, so cannot be parsed as URL - parts := strings.SplitN(remoteURL, "#", 2) - - repo.remote = parts[0] - if len(parts) == 2 { - fragment = parts[1] - } + var fragment string + repo.remote, fragment, _ = strings.Cut(remoteURL, "#") repo.ref, repo.subdir = getRefAndSubdir(fragment) } else { u, err := url.Parse(remoteURL) @@ -126,15 +121,11 @@ func parseRemoteURL(remoteURL string) (gitRepo, error) { } func getRefAndSubdir(fragment string) (ref string, subdir string) { - refAndDir := strings.SplitN(fragment, ":", 2) - ref = "master" - if len(refAndDir[0]) != 0 { - ref = refAndDir[0] - } - if len(refAndDir) > 1 && len(refAndDir[1]) != 0 { - subdir = refAndDir[1] + ref, subdir, _ = strings.Cut(fragment, ":") + if ref == "" { + ref = "master" } - return + return ref, subdir } func fetchArgs(remoteURL string, ref string) []string { diff --git a/vendor/github.com/docker/docker/client/build_prune.go b/vendor/github.com/docker/docker/client/build_prune.go index 397d67cdcf..2b6606236e 100644 --- a/vendor/github.com/docker/docker/client/build_prune.go +++ b/vendor/github.com/docker/docker/client/build_prune.go @@ -3,8 +3,8 @@ package client // import "github.com/docker/docker/client" import ( "context" "encoding/json" - "fmt" "net/url" + "strconv" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" @@ -23,12 +23,12 @@ func (cli *Client) BuildCachePrune(ctx context.Context, opts types.BuildCachePru if opts.All { query.Set("all", "1") } - query.Set("keep-storage", fmt.Sprintf("%d", opts.KeepStorage)) - filters, err := filters.ToJSON(opts.Filters) + query.Set("keep-storage", strconv.Itoa(int(opts.KeepStorage))) + f, err := filters.ToJSON(opts.Filters) if err != nil { return nil, errors.Wrap(err, "prune could not marshal filters option") } - query.Set("filters", filters) + query.Set("filters", f) serverResp, err := cli.post(ctx, "/build/prune", query, nil, nil) defer ensureReaderClosed(serverResp) @@ -38,7 +38,7 @@ func (cli *Client) BuildCachePrune(ctx context.Context, opts types.BuildCachePru } if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return nil, fmt.Errorf("Error retrieving disk usage: %v", err) + return nil, errors.Wrap(err, "error retrieving disk usage") } return &report, nil diff --git a/vendor/github.com/docker/docker/client/client.go b/vendor/github.com/docker/docker/client/client.go index 26a0fa2756..54fa36cca8 100644 --- a/vendor/github.com/docker/docker/client/client.go +++ b/vendor/github.com/docker/docker/client/client.go @@ -6,9 +6,10 @@ https://docs.docker.com/engine/api/ # Usage -You use the library by creating a client object and calling methods on it. The -client can be created either from environment variables with NewClientWithOpts(client.FromEnv), -or configured manually with NewClient(). +You use the library by constructing a client object using [NewClientWithOpts] +and calling methods on it. The client can be configured from environment +variables by passing the [FromEnv] option, or configured manually by passing any +of the other available [Opts]. For example, to list running containers (the equivalent of "docker ps"): @@ -55,6 +56,36 @@ import ( "github.com/pkg/errors" ) +// DummyHost is a hostname used for local communication. +// +// It acts as a valid formatted hostname for local connections (such as "unix://" +// or "npipe://") which do not require a hostname. It should never be resolved, +// but uses the special-purpose ".localhost" TLD (as defined in [RFC 2606, Section 2] +// and [RFC 6761, Section 6.3]). +// +// [RFC 7230, Section 5.4] defines that an empty header must be used for such +// cases: +// +// If the authority component is missing or undefined for the target URI, +// then a client MUST send a Host header field with an empty field-value. +// +// However, [Go stdlib] enforces the semantics of HTTP(S) over TCP, does not +// allow an empty header to be used, and requires req.URL.Scheme to be either +// "http" or "https". +// +// For further details, refer to: +// +// - https://github.com/docker/engine-api/issues/189 +// - https://github.com/golang/go/issues/13624 +// - https://github.com/golang/go/issues/61076 +// - https://github.com/moby/moby/issues/45935 +// +// [RFC 2606, Section 2]: https://www.rfc-editor.org/rfc/rfc2606.html#section-2 +// [RFC 6761, Section 6.3]: https://www.rfc-editor.org/rfc/rfc6761#section-6.3 +// [RFC 7230, Section 5.4]: https://datatracker.ietf.org/doc/html/rfc7230#section-5.4 +// [Go stdlib]: https://github.com/golang/go/blob/6244b1946bc2101b01955468f1be502dbadd6807/src/net/http/transport.go#L558-L569 +const DummyHost = "api.moby.localhost" + // ErrRedirect is the error returned by checkRedirect when the request is non-GET. var ErrRedirect = errors.New("unexpected redirect in response") @@ -125,7 +156,12 @@ func CheckRedirect(req *http.Request, via []*http.Request) error { // client.WithAPIVersionNegotiation(), // ) func NewClientWithOpts(ops ...Opt) (*Client, error) { - client, err := defaultHTTPClient(DefaultDockerHost) + hostURL, err := ParseHostURL(DefaultDockerHost) + if err != nil { + return nil, err + } + + client, err := defaultHTTPClient(hostURL) if err != nil { return nil, err } @@ -133,8 +169,8 @@ func NewClientWithOpts(ops ...Opt) (*Client, error) { host: DefaultDockerHost, version: api.DefaultVersion, client: client, - proto: defaultProto, - addr: defaultAddr, + proto: hostURL.Scheme, + addr: hostURL.Host, } for _, op := range ops { @@ -160,13 +196,12 @@ func NewClientWithOpts(ops ...Opt) (*Client, error) { return c, nil } -func defaultHTTPClient(host string) (*http.Client, error) { - hostURL, err := ParseHostURL(host) +func defaultHTTPClient(hostURL *url.URL) (*http.Client, error) { + transport := &http.Transport{} + err := sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host) if err != nil { return nil, err } - transport := &http.Transport{} - _ = sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host) return &http.Client{ Transport: transport, CheckRedirect: CheckRedirect, @@ -282,13 +317,12 @@ func (cli *Client) HTTPClient() *http.Client { // ParseHostURL parses a url string, validates the string is a host url, and // returns the parsed URL func ParseHostURL(host string) (*url.URL, error) { - protoAddrParts := strings.SplitN(host, "://", 2) - if len(protoAddrParts) == 1 { + proto, addr, ok := strings.Cut(host, "://") + if !ok || addr == "" { return nil, errors.Errorf("unable to parse docker host `%s`", host) } var basePath string - proto, addr := protoAddrParts[0], protoAddrParts[1] if proto == "tcp" { parsed, err := url.Parse("tcp://" + addr) if err != nil { diff --git a/vendor/github.com/docker/docker/client/client_deprecated.go b/vendor/github.com/docker/docker/client/client_deprecated.go index 54cdfc29a8..9e366ce20d 100644 --- a/vendor/github.com/docker/docker/client/client_deprecated.go +++ b/vendor/github.com/docker/docker/client/client_deprecated.go @@ -9,7 +9,11 @@ import "net/http" // It won't send any version information if the version number is empty. It is // highly recommended that you set a version or your client may break if the // server is upgraded. -// Deprecated: use NewClientWithOpts +// +// Deprecated: use [NewClientWithOpts] passing the [WithHost], [WithVersion], +// [WithHTTPClient] and [WithHTTPHeaders] options. We recommend enabling API +// version negotiation by passing the [WithAPIVersionNegotiation] option instead +// of WithVersion. func NewClient(host string, version string, client *http.Client, httpHeaders map[string]string) (*Client, error) { return NewClientWithOpts(WithHost(host), WithVersion(version), WithHTTPClient(client), WithHTTPHeaders(httpHeaders)) } @@ -17,7 +21,7 @@ func NewClient(host string, version string, client *http.Client, httpHeaders map // NewEnvClient initializes a new API client based on environment variables. // See FromEnv for a list of support environment variables. // -// Deprecated: use NewClientWithOpts(FromEnv) +// Deprecated: use [NewClientWithOpts] passing the [FromEnv] option. func NewEnvClient() (*Client, error) { return NewClientWithOpts(FromEnv) } diff --git a/vendor/github.com/docker/docker/client/client_unix.go b/vendor/github.com/docker/docker/client/client_unix.go index f0783f7085..319b738d3e 100644 --- a/vendor/github.com/docker/docker/client/client_unix.go +++ b/vendor/github.com/docker/docker/client/client_unix.go @@ -1,11 +1,8 @@ -//go:build linux || freebsd || openbsd || netbsd || darwin || solaris || illumos || dragonfly -// +build linux freebsd openbsd netbsd darwin solaris illumos dragonfly +//go:build !windows +// +build !windows package client // import "github.com/docker/docker/client" // DefaultDockerHost defines OS-specific default host if the DOCKER_HOST // (EnvOverrideHost) environment variable is unset or empty. const DefaultDockerHost = "unix:///var/run/docker.sock" - -const defaultProto = "unix" -const defaultAddr = "/var/run/docker.sock" diff --git a/vendor/github.com/docker/docker/client/client_windows.go b/vendor/github.com/docker/docker/client/client_windows.go index 5abe60457d..56572d1a27 100644 --- a/vendor/github.com/docker/docker/client/client_windows.go +++ b/vendor/github.com/docker/docker/client/client_windows.go @@ -3,6 +3,3 @@ package client // import "github.com/docker/docker/client" // DefaultDockerHost defines OS-specific default host if the DOCKER_HOST // (EnvOverrideHost) environment variable is unset or empty. const DefaultDockerHost = "npipe:////./pipe/docker_engine" - -const defaultProto = "npipe" -const defaultAddr = "//./pipe/docker_engine" diff --git a/vendor/github.com/docker/docker/client/container_create.go b/vendor/github.com/docker/docker/client/container_create.go index f82420b673..193a2bb562 100644 --- a/vendor/github.com/docker/docker/client/container_create.go +++ b/vendor/github.com/docker/docker/client/container_create.go @@ -9,7 +9,7 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/versions" - specs "github.com/opencontainers/image-spec/specs-go/v1" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" ) type configWrapper struct { @@ -20,7 +20,7 @@ type configWrapper struct { // ContainerCreate creates a new container based on the given configuration. // 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 *specs.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) { var response container.CreateResponse if err := cli.NewVersionError("1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil { @@ -75,7 +75,7 @@ func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config // Similar to containerd's platforms.Format(), but does allow components to be // omitted (e.g. pass "architecture" only, without "os": // https://github.com/containerd/containerd/blob/v1.5.2/platforms/platforms.go#L243-L263 -func formatPlatform(platform *specs.Platform) string { +func formatPlatform(platform *ocispec.Platform) string { if platform == nil { return "" } diff --git a/vendor/github.com/docker/docker/client/container_diff.go b/vendor/github.com/docker/docker/client/container_diff.go index 29dac8491d..c22c819a79 100644 --- a/vendor/github.com/docker/docker/client/container_diff.go +++ b/vendor/github.com/docker/docker/client/container_diff.go @@ -9,8 +9,8 @@ import ( ) // ContainerDiff shows differences in a container filesystem since it was started. -func (cli *Client) ContainerDiff(ctx context.Context, containerID string) ([]container.ContainerChangeResponseItem, error) { - var changes []container.ContainerChangeResponseItem +func (cli *Client) ContainerDiff(ctx context.Context, containerID string) ([]container.FilesystemChange, error) { + var changes []container.FilesystemChange serverResp, err := cli.get(ctx, "/containers/"+containerID+"/changes", url.Values{}, nil) defer ensureReaderClosed(serverResp) diff --git a/vendor/github.com/docker/docker/client/container_wait.go b/vendor/github.com/docker/docker/client/container_wait.go index 9aff716132..b7d80542c9 100644 --- a/vendor/github.com/docker/docker/client/container_wait.go +++ b/vendor/github.com/docker/docker/client/container_wait.go @@ -1,14 +1,19 @@ package client // import "github.com/docker/docker/client" import ( + "bytes" "context" "encoding/json" + "errors" + "io" "net/url" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/versions" ) +const containerWaitErrorMsgLimit = 2 * 1024 /* Max: 2KiB */ + // ContainerWait waits until the specified container is in a certain state // indicated by the given condition, either "not-running" (default), // "next-exit", or "removed". @@ -46,9 +51,27 @@ func (cli *Client) ContainerWait(ctx context.Context, containerID string, condit go func() { defer ensureReaderClosed(resp) + + body := resp.body + responseText := bytes.NewBuffer(nil) + stream := io.TeeReader(body, responseText) + var res container.WaitResponse - if err := json.NewDecoder(resp.body).Decode(&res); err != nil { - errC <- err + if err := json.NewDecoder(stream).Decode(&res); err != nil { + // NOTE(nicks): The /wait API does not work well with HTTP proxies. + // At any time, the proxy could cut off the response stream. + // + // But because the HTTP status has already been written, the proxy's + // only option is to write a plaintext error message. + // + // If there's a JSON parsing error, read the real error message + // off the body and send it to the client. + if errors.As(err, new(*json.SyntaxError)) { + _, _ = io.ReadAll(io.LimitReader(stream, containerWaitErrorMsgLimit)) + errC <- errors.New(responseText.String()) + } else { + errC <- err + } return } diff --git a/vendor/github.com/docker/docker/client/distribution_inspect.go b/vendor/github.com/docker/docker/client/distribution_inspect.go index 7f36c99a01..efab066d3b 100644 --- a/vendor/github.com/docker/docker/client/distribution_inspect.go +++ b/vendor/github.com/docker/docker/client/distribution_inspect.go @@ -5,13 +5,13 @@ import ( "encoding/json" "net/url" - registrytypes "github.com/docker/docker/api/types/registry" + "github.com/docker/docker/api/types/registry" ) // DistributionInspect returns the image digest with the full manifest. -func (cli *Client) DistributionInspect(ctx context.Context, image, encodedRegistryAuth string) (registrytypes.DistributionInspect, error) { +func (cli *Client) DistributionInspect(ctx context.Context, image, encodedRegistryAuth string) (registry.DistributionInspect, error) { // Contact the registry to retrieve digest and platform information - var distributionInspect registrytypes.DistributionInspect + var distributionInspect registry.DistributionInspect if image == "" { return distributionInspect, objectNotFoundError{object: "distribution", id: image} } @@ -23,7 +23,7 @@ func (cli *Client) DistributionInspect(ctx context.Context, image, encodedRegist if encodedRegistryAuth != "" { headers = map[string][]string{ - "X-Registry-Auth": {encodedRegistryAuth}, + registry.AuthHeader: {encodedRegistryAuth}, } } diff --git a/vendor/github.com/docker/docker/client/errors.go b/vendor/github.com/docker/docker/client/errors.go index e5a8a865f9..6878144c41 100644 --- a/vendor/github.com/docker/docker/client/errors.go +++ b/vendor/github.com/docker/docker/client/errors.go @@ -58,31 +58,6 @@ func (e objectNotFoundError) Error() string { return fmt.Sprintf("Error: No such %s: %s", e.object, e.id) } -// IsErrUnauthorized returns true if the error is caused -// when a remote registry authentication fails -// -// Deprecated: use errdefs.IsUnauthorized -func IsErrUnauthorized(err error) bool { - return errdefs.IsUnauthorized(err) -} - -type pluginPermissionDenied struct { - name string -} - -func (e pluginPermissionDenied) Error() string { - return "Permission denied while installing plugin " + e.name -} - -// IsErrNotImplemented returns true if the error is a NotImplemented error. -// This is returned by the API when a requested feature has not been -// implemented. -// -// Deprecated: use errdefs.IsNotImplemented -func IsErrNotImplemented(err error) bool { - return errdefs.IsNotImplemented(err) -} - // NewVersionError returns an error if the APIVersion required // if less than the current supported version func (cli *Client) NewVersionError(APIrequired, feature string) error { diff --git a/vendor/github.com/docker/docker/client/hijack.go b/vendor/github.com/docker/docker/client/hijack.go index 6bdacab10a..7e84865f69 100644 --- a/vendor/github.com/docker/docker/client/hijack.go +++ b/vendor/github.com/docker/docker/client/hijack.go @@ -23,14 +23,10 @@ func (cli *Client) postHijacked(ctx context.Context, path string, query url.Valu if err != nil { return types.HijackedResponse{}, err } - - apiPath := cli.getAPIPath(ctx, path, query) - req, err := http.NewRequest(http.MethodPost, apiPath, bodyEncoded) + req, err := cli.buildRequest(http.MethodPost, cli.getAPIPath(ctx, path, query), bodyEncoded, headers) if err != nil { return types.HijackedResponse{}, err } - req = cli.addHeaders(req, headers) - conn, mediaType, err := cli.setupHijackConn(ctx, req, "tcp") if err != nil { return types.HijackedResponse{}, err @@ -64,7 +60,6 @@ func fallbackDial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) { } func (cli *Client) setupHijackConn(ctx context.Context, req *http.Request, proto string) (net.Conn, string, error) { - req.Host = cli.addr req.Header.Set("Connection", "Upgrade") req.Header.Set("Upgrade", proto) @@ -80,8 +75,8 @@ func (cli *Client) setupHijackConn(ctx context.Context, req *http.Request, proto // state. Setting TCP KeepAlive on the socket connection will prohibit // ECONNTIMEOUT unless the socket connection truly is broken if tcpConn, ok := conn.(*net.TCPConn); ok { - tcpConn.SetKeepAlive(true) - tcpConn.SetKeepAlivePeriod(30 * time.Second) + _ = tcpConn.SetKeepAlive(true) + _ = tcpConn.SetKeepAlivePeriod(30 * time.Second) } clientconn := httputil.NewClientConn(conn, nil) @@ -96,7 +91,7 @@ func (cli *Client) setupHijackConn(ctx context.Context, req *http.Request, proto return nil, "", err } if resp.StatusCode != http.StatusSwitchingProtocols { - resp.Body.Close() + _ = resp.Body.Close() return nil, "", fmt.Errorf("unable to upgrade to %s, received %d", proto, resp.StatusCode) } } diff --git a/vendor/github.com/docker/docker/client/image_create.go b/vendor/github.com/docker/docker/client/image_create.go index b1c0227775..6a9b708f7d 100644 --- a/vendor/github.com/docker/docker/client/image_create.go +++ b/vendor/github.com/docker/docker/client/image_create.go @@ -8,6 +8,7 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/registry" ) // ImageCreate creates a new image based on the parent options. @@ -32,6 +33,6 @@ func (cli *Client) ImageCreate(ctx context.Context, parentReference string, opti } func (cli *Client) tryImageCreate(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} return cli.post(ctx, "/images/create", query, nil, headers) } diff --git a/vendor/github.com/docker/docker/client/image_push.go b/vendor/github.com/docker/docker/client/image_push.go index 845580d4a4..dd1b8f3471 100644 --- a/vendor/github.com/docker/docker/client/image_push.go +++ b/vendor/github.com/docker/docker/client/image_push.go @@ -8,6 +8,7 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/registry" "github.com/docker/docker/errdefs" ) @@ -49,6 +50,6 @@ func (cli *Client) ImagePush(ctx context.Context, image string, options types.Im } func (cli *Client) tryImagePush(ctx context.Context, imageID string, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} return cli.post(ctx, "/images/"+imageID+"/push", query, nil, headers) } diff --git a/vendor/github.com/docker/docker/client/image_search.go b/vendor/github.com/docker/docker/client/image_search.go index e69fa37225..5f0c49ed30 100644 --- a/vendor/github.com/docker/docker/client/image_search.go +++ b/vendor/github.com/docker/docker/client/image_search.go @@ -48,6 +48,6 @@ func (cli *Client) ImageSearch(ctx context.Context, term string, options types.I } func (cli *Client) tryImageSearch(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} return cli.get(ctx, "/images/search", query, headers) } diff --git a/vendor/github.com/docker/docker/client/interface.go b/vendor/github.com/docker/docker/client/interface.go index e9c1ed722e..7993c5a48f 100644 --- a/vendor/github.com/docker/docker/client/interface.go +++ b/vendor/github.com/docker/docker/client/interface.go @@ -15,7 +15,7 @@ import ( "github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/volume" - specs "github.com/opencontainers/image-spec/specs-go/v1" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" ) // CommonAPIClient is the common methods between stable and experimental versions of APIClient. @@ -47,8 +47,8 @@ type CommonAPIClient interface { type ContainerAPIClient interface { ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) - ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *specs.Platform, containerName string) (container.CreateResponse, error) - ContainerDiff(ctx context.Context, container string) ([]container.ContainerChangeResponseItem, 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) ContainerExecAttach(ctx context.Context, execID string, config types.ExecStartCheck) (types.HijackedResponse, error) ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error) ContainerExecInspect(ctx context.Context, execID string) (types.ContainerExecInspect, error) @@ -166,7 +166,7 @@ type SwarmAPIClient interface { type SystemAPIClient interface { Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) Info(ctx context.Context) (types.Info, error) - RegistryLogin(ctx context.Context, auth types.AuthConfig) (registry.AuthenticateOKBody, error) + RegistryLogin(ctx context.Context, auth registry.AuthConfig) (registry.AuthenticateOKBody, error) DiskUsage(ctx context.Context, options types.DiskUsageOptions) (types.DiskUsage, error) Ping(ctx context.Context) (types.Ping, error) } @@ -176,7 +176,7 @@ type VolumeAPIClient interface { VolumeCreate(ctx context.Context, options volume.CreateOptions) (volume.Volume, error) VolumeInspect(ctx context.Context, volumeID string) (volume.Volume, error) VolumeInspectWithRaw(ctx context.Context, volumeID string) (volume.Volume, []byte, error) - VolumeList(ctx context.Context, filter filters.Args) (volume.ListResponse, error) + VolumeList(ctx context.Context, options volume.ListOptions) (volume.ListResponse, error) VolumeRemove(ctx context.Context, volumeID string, force bool) error VolumesPrune(ctx context.Context, pruneFilter filters.Args) (types.VolumesPruneReport, error) VolumeUpdate(ctx context.Context, volumeID string, version swarm.Version, options volume.UpdateOptions) error diff --git a/vendor/github.com/docker/docker/client/login.go b/vendor/github.com/docker/docker/client/login.go index f058520638..19e985e0b9 100644 --- a/vendor/github.com/docker/docker/client/login.go +++ b/vendor/github.com/docker/docker/client/login.go @@ -5,13 +5,12 @@ import ( "encoding/json" "net/url" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/registry" ) // RegistryLogin authenticates the docker server with a given docker registry. // It returns unauthorizedError when the authentication fails. -func (cli *Client) RegistryLogin(ctx context.Context, auth types.AuthConfig) (registry.AuthenticateOKBody, error) { +func (cli *Client) RegistryLogin(ctx context.Context, auth registry.AuthConfig) (registry.AuthenticateOKBody, error) { resp, err := cli.post(ctx, "/auth", url.Values{}, auth, nil) defer ensureReaderClosed(resp) diff --git a/vendor/github.com/docker/docker/client/ping.go b/vendor/github.com/docker/docker/client/ping.go index 27e8695cb5..347ae71e02 100644 --- a/vendor/github.com/docker/docker/client/ping.go +++ b/vendor/github.com/docker/docker/client/ping.go @@ -64,10 +64,10 @@ func parsePingResponse(cli *Client, resp serverResponse) (types.Ping, error) { ping.BuilderVersion = types.BuilderVersion(bv) } if si := resp.header.Get("Swarm"); si != "" { - parts := strings.SplitN(si, "/", 2) + state, role, _ := strings.Cut(si, "/") ping.SwarmStatus = &swarm.Status{ - NodeState: swarm.LocalNodeState(parts[0]), - ControlAvailable: len(parts) == 2 && parts[1] == "manager", + NodeState: swarm.LocalNodeState(state), + ControlAvailable: role == "manager", } } err := cli.checkResponseErr(resp) diff --git a/vendor/github.com/docker/docker/client/plugin_install.go b/vendor/github.com/docker/docker/client/plugin_install.go index 012afe61ca..3a740ec4f6 100644 --- a/vendor/github.com/docker/docker/client/plugin_install.go +++ b/vendor/github.com/docker/docker/client/plugin_install.go @@ -8,6 +8,7 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/registry" "github.com/docker/docker/errdefs" "github.com/pkg/errors" ) @@ -67,12 +68,12 @@ func (cli *Client) PluginInstall(ctx context.Context, name string, options types } func (cli *Client) tryPluginPrivileges(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} return cli.get(ctx, "/plugins/privileges", query, headers) } func (cli *Client) tryPluginPull(ctx context.Context, query url.Values, privileges types.PluginPrivileges, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} return cli.post(ctx, "/plugins/pull", query, privileges, headers) } @@ -106,7 +107,7 @@ func (cli *Client) checkPluginPermissions(ctx context.Context, query url.Values, return nil, err } if !accept { - return nil, pluginPermissionDenied{options.RemoteRef} + return nil, errors.Errorf("permission denied while installing plugin %s", options.RemoteRef) } } return privileges, nil diff --git a/vendor/github.com/docker/docker/client/plugin_push.go b/vendor/github.com/docker/docker/client/plugin_push.go index d20bfe8447..18f9754c4c 100644 --- a/vendor/github.com/docker/docker/client/plugin_push.go +++ b/vendor/github.com/docker/docker/client/plugin_push.go @@ -3,11 +3,13 @@ package client // import "github.com/docker/docker/client" import ( "context" "io" + + "github.com/docker/docker/api/types/registry" ) // PluginPush pushes a plugin to a registry func (cli *Client) PluginPush(ctx context.Context, name string, registryAuth string) (io.ReadCloser, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} resp, err := cli.post(ctx, "/plugins/"+name+"/push", nil, nil, headers) if err != nil { return nil, err diff --git a/vendor/github.com/docker/docker/client/plugin_upgrade.go b/vendor/github.com/docker/docker/client/plugin_upgrade.go index 115cea945b..995d1fd2ca 100644 --- a/vendor/github.com/docker/docker/client/plugin_upgrade.go +++ b/vendor/github.com/docker/docker/client/plugin_upgrade.go @@ -7,6 +7,7 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/registry" "github.com/pkg/errors" ) @@ -34,6 +35,6 @@ func (cli *Client) PluginUpgrade(ctx context.Context, name string, options types } func (cli *Client) tryPluginUpgrade(ctx context.Context, query url.Values, privileges types.PluginPrivileges, name, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} return cli.post(ctx, "/plugins/"+name+"/upgrade", query, privileges, headers) } diff --git a/vendor/github.com/docker/docker/client/request.go b/vendor/github.com/docker/docker/client/request.go index c799095c12..bcedcf3bd9 100644 --- a/vendor/github.com/docker/docker/client/request.go +++ b/vendor/github.com/docker/docker/client/request.go @@ -96,16 +96,14 @@ func (cli *Client) buildRequest(method, path string, body io.Reader, headers hea return nil, err } req = cli.addHeaders(req, headers) + req.URL.Scheme = cli.scheme + req.URL.Host = cli.addr if cli.proto == "unix" || cli.proto == "npipe" { - // For local communications, it doesn't matter what the host is. We just - // need a valid and meaningful host name. (See #189) - req.Host = "docker" + // Override host header for non-tcp connections. + req.Host = DummyHost } - req.URL.Host = cli.addr - req.URL.Scheme = cli.scheme - if expectedPayload && req.Header.Get("Content-Type") == "" { req.Header.Set("Content-Type", "text/plain") } diff --git a/vendor/github.com/docker/docker/client/service_create.go b/vendor/github.com/docker/docker/client/service_create.go index 23024d0f8f..b6065b8eef 100644 --- a/vendor/github.com/docker/docker/client/service_create.go +++ b/vendor/github.com/docker/docker/client/service_create.go @@ -8,6 +8,7 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm" "github.com/opencontainers/go-digest" "github.com/pkg/errors" @@ -21,7 +22,7 @@ func (cli *Client) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, } if options.EncodedRegistryAuth != "" { - headers["X-Registry-Auth"] = []string{options.EncodedRegistryAuth} + headers[registry.AuthHeader] = []string{options.EncodedRegistryAuth} } // Make sure containerSpec is not nil when no runtime is set or the runtime is set to container diff --git a/vendor/github.com/docker/docker/client/service_update.go b/vendor/github.com/docker/docker/client/service_update.go index 8014b86258..ff8cded8be 100644 --- a/vendor/github.com/docker/docker/client/service_update.go +++ b/vendor/github.com/docker/docker/client/service_update.go @@ -6,6 +6,7 @@ import ( "net/url" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm" ) @@ -23,7 +24,7 @@ func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version } if options.EncodedRegistryAuth != "" { - headers["X-Registry-Auth"] = []string{options.EncodedRegistryAuth} + headers[registry.AuthHeader] = []string{options.EncodedRegistryAuth} } if options.RegistryAuthFrom != "" { diff --git a/vendor/github.com/docker/docker/client/volume_list.go b/vendor/github.com/docker/docker/client/volume_list.go index d8204f8db5..d5ea9827c7 100644 --- a/vendor/github.com/docker/docker/client/volume_list.go +++ b/vendor/github.com/docker/docker/client/volume_list.go @@ -10,13 +10,13 @@ import ( ) // VolumeList returns the volumes configured in the docker host. -func (cli *Client) VolumeList(ctx context.Context, filter filters.Args) (volume.ListResponse, error) { +func (cli *Client) VolumeList(ctx context.Context, options volume.ListOptions) (volume.ListResponse, error) { var volumes volume.ListResponse query := url.Values{} - if filter.Len() > 0 { + if options.Filters.Len() > 0 { //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cli.version, filter) + filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters) if err != nil { return volumes, err } diff --git a/vendor/github.com/docker/docker/pkg/archive/README.md b/vendor/github.com/docker/docker/pkg/archive/README.md deleted file mode 100644 index 7307d9694f..0000000000 --- a/vendor/github.com/docker/docker/pkg/archive/README.md +++ /dev/null @@ -1 +0,0 @@ -This code provides helper functions for dealing with archive files. diff --git a/vendor/github.com/docker/docker/pkg/archive/archive.go b/vendor/github.com/docker/docker/pkg/archive/archive.go index e9ac1e322e..34361a24ac 100644 --- a/vendor/github.com/docker/docker/pkg/archive/archive.go +++ b/vendor/github.com/docker/docker/pkg/archive/archive.go @@ -1,3 +1,4 @@ +// Package archive provides helper functions for dealing with archive files. package archive // import "github.com/docker/docker/pkg/archive" import ( @@ -11,6 +12,7 @@ import ( "fmt" "io" "os" + "os/exec" "path/filepath" "runtime" "strconv" @@ -28,7 +30,6 @@ import ( "github.com/moby/sys/sequential" "github.com/pkg/errors" "github.com/sirupsen/logrus" - exec "golang.org/x/sys/execabs" ) // ImpliedDirectoryMode represents the mode (Unix permissions) applied to directories that are implied by files in a @@ -111,16 +112,6 @@ const ( OverlayWhiteoutFormat ) -const ( - modeISDIR = 040000 // Directory - modeISFIFO = 010000 // FIFO - modeISREG = 0100000 // Regular file - modeISLNK = 0120000 // Symbolic link - modeISBLK = 060000 // Block special file - modeISCHR = 020000 // Character special file - modeISSOCK = 0140000 // Socket -) - // IsArchivePath checks if the (possibly compressed) file at the given path // starts with a tar file header. func IsArchivePath(path string) bool { @@ -469,9 +460,7 @@ func FileInfoHeaderNoLookups(fi os.FileInfo, link string) (*tar.Header, error) { // but is safe to call from a chrooted process. The AccessTime and ChangeTime // fields are not set in the returned header, ModTime is truncated to one-second // precision, and the Uname and Gname fields are only set when fi is a FileInfo -// value returned from tar.Header.FileInfo(). Also, regardless of Go version, -// this function fills file type bits (e.g. hdr.Mode |= modeISDIR), which have -// been deleted since Go 1.9 archive/tar. +// value returned from tar.Header.FileInfo(). func FileInfoHeader(name string, fi os.FileInfo, link string) (*tar.Header, error) { hdr, err := FileInfoHeaderNoLookups(fi, link) if err != nil { @@ -481,36 +470,11 @@ func FileInfoHeader(name string, fi os.FileInfo, link string) (*tar.Header, erro hdr.ModTime = hdr.ModTime.Truncate(time.Second) hdr.AccessTime = time.Time{} hdr.ChangeTime = time.Time{} - hdr.Mode = fillGo18FileTypeBits(int64(chmodTarEntry(os.FileMode(hdr.Mode))), fi) + hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) hdr.Name = canonicalTarName(name, fi.IsDir()) return hdr, nil } -// fillGo18FileTypeBits fills type bits which have been removed on Go 1.9 archive/tar -// https://github.com/golang/go/commit/66b5a2f -func fillGo18FileTypeBits(mode int64, fi os.FileInfo) int64 { - fm := fi.Mode() - switch { - case fm.IsRegular(): - mode |= modeISREG - case fi.IsDir(): - mode |= modeISDIR - case fm&os.ModeSymlink != 0: - mode |= modeISLNK - case fm&os.ModeDevice != 0: - if fm&os.ModeCharDevice != 0 { - mode |= modeISCHR - } else { - mode |= modeISBLK - } - case fm&os.ModeNamedPipe != 0: - mode |= modeISFIFO - case fm&os.ModeSocket != 0: - mode |= modeISSOCK - } - return mode -} - // ReadSecurityXattrToTarHeader reads security.capability xattr from filesystem // to a tar header func ReadSecurityXattrToTarHeader(path string, hdr *tar.Header) error { @@ -567,10 +531,17 @@ func newTarAppender(idMapping idtools.IdentityMapping, writer io.Writer, chownOp } } -// canonicalTarName provides a platform-independent and consistent posix-style +// CanonicalTarNameForPath canonicalizes relativePath to a POSIX-style path using +// forward slashes. It is an alias for filepath.ToSlash, which is a no-op on +// Linux and Unix. +func CanonicalTarNameForPath(relativePath string) string { + return filepath.ToSlash(relativePath) +} + +// canonicalTarName provides a platform-independent and consistent POSIX-style // path for files and directories to be archived regardless of the platform. func canonicalTarName(name string, isDir bool) string { - name = CanonicalTarNameForPath(name) + name = filepath.ToSlash(name) // suffix with '/' for directories if isDir && !strings.HasSuffix(name, "/") { @@ -711,7 +682,7 @@ func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, L } } - case tar.TypeReg, tar.TypeRegA: + case tar.TypeReg: // Source is regular file. We use sequential file access to avoid depleting // the standby list on Windows. On Linux, this equates to a regular os.OpenFile. file, err := sequential.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode()) @@ -850,10 +821,29 @@ func Tar(path string, compression Compression) (io.ReadCloser, error) { // TarWithOptions creates an archive from the directory at `path`, only including files whose relative // paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { - // Fix the source path to work with long path names. This is a no-op - // on platforms other than Windows. - srcPath = fixVolumePathPrefix(srcPath) + tb, err := NewTarballer(srcPath, options) + if err != nil { + return nil, err + } + go tb.Do() + return tb.Reader(), nil +} +// Tarballer is a lower-level interface to TarWithOptions which gives the caller +// control over which goroutine the archiving operation executes on. +type Tarballer struct { + srcPath string + options *TarOptions + pm *patternmatcher.PatternMatcher + pipeReader *io.PipeReader + pipeWriter *io.PipeWriter + compressWriter io.WriteCloser + whiteoutConverter tarWhiteoutConverter +} + +// NewTarballer constructs a new tarballer. The arguments are the same as for +// TarWithOptions. +func NewTarballer(srcPath string, options *TarOptions) (*Tarballer, error) { pm, err := patternmatcher.New(options.ExcludePatterns) if err != nil { return nil, err @@ -871,183 +861,201 @@ func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) return nil, err } - go func() { - ta := newTarAppender( - options.IDMap, - compressWriter, - options.ChownOpts, - ) - ta.WhiteoutConverter = whiteoutConverter - - defer func() { - // Make sure to check the error on Close. - if err := ta.TarWriter.Close(); err != nil { - logrus.Errorf("Can't close tar writer: %s", err) - } - if err := compressWriter.Close(); err != nil { - logrus.Errorf("Can't close compress writer: %s", err) - } - if err := pipeWriter.Close(); err != nil { - logrus.Errorf("Can't close pipe writer: %s", err) - } - }() + return &Tarballer{ + // Fix the source path to work with long path names. This is a no-op + // on platforms other than Windows. + srcPath: fixVolumePathPrefix(srcPath), + options: options, + pm: pm, + pipeReader: pipeReader, + pipeWriter: pipeWriter, + compressWriter: compressWriter, + whiteoutConverter: whiteoutConverter, + }, nil +} - // this buffer is needed for the duration of this piped stream - defer pools.BufioWriter32KPool.Put(ta.Buffer) +// Reader returns the reader for the created archive. +func (t *Tarballer) Reader() io.ReadCloser { + return t.pipeReader +} - // In general we log errors here but ignore them because - // during e.g. a diff operation the container can continue - // mutating the filesystem and we can see transient errors - // from this +// Do performs the archiving operation in the background. The resulting archive +// can be read from t.Reader(). Do should only be called once on each Tarballer +// instance. +func (t *Tarballer) Do() { + ta := newTarAppender( + t.options.IDMap, + t.compressWriter, + t.options.ChownOpts, + ) + ta.WhiteoutConverter = t.whiteoutConverter - stat, err := os.Lstat(srcPath) - if err != nil { - return + defer func() { + // Make sure to check the error on Close. + if err := ta.TarWriter.Close(); err != nil { + logrus.Errorf("Can't close tar writer: %s", err) } - - if !stat.IsDir() { - // We can't later join a non-dir with any includes because the - // 'walk' will error if "file/." is stat-ed and "file" is not a - // directory. So, we must split the source path and use the - // basename as the include. - if len(options.IncludeFiles) > 0 { - logrus.Warn("Tar: Can't archive a file with includes") - } - - dir, base := SplitPathDirEntry(srcPath) - srcPath = dir - options.IncludeFiles = []string{base} + if err := t.compressWriter.Close(); err != nil { + logrus.Errorf("Can't close compress writer: %s", err) } - - if len(options.IncludeFiles) == 0 { - options.IncludeFiles = []string{"."} + if err := t.pipeWriter.Close(); err != nil { + logrus.Errorf("Can't close pipe writer: %s", err) } + }() - seen := make(map[string]bool) - - for _, include := range options.IncludeFiles { - rebaseName := options.RebaseNames[include] + // this buffer is needed for the duration of this piped stream + defer pools.BufioWriter32KPool.Put(ta.Buffer) - var ( - parentMatchInfo []patternmatcher.MatchInfo - parentDirs []string - ) + // In general we log errors here but ignore them because + // during e.g. a diff operation the container can continue + // mutating the filesystem and we can see transient errors + // from this - walkRoot := getWalkRoot(srcPath, include) - filepath.Walk(walkRoot, func(filePath string, f os.FileInfo, err error) error { - if err != nil { - logrus.Errorf("Tar: Can't stat file %s to tar: %s", srcPath, err) - return nil - } + stat, err := os.Lstat(t.srcPath) + if err != nil { + return + } - relFilePath, err := filepath.Rel(srcPath, filePath) - if err != nil || (!options.IncludeSourceDir && relFilePath == "." && f.IsDir()) { - // Error getting relative path OR we are looking - // at the source directory path. Skip in both situations. - return nil - } + if !stat.IsDir() { + // We can't later join a non-dir with any includes because the + // 'walk' will error if "file/." is stat-ed and "file" is not a + // directory. So, we must split the source path and use the + // basename as the include. + if len(t.options.IncludeFiles) > 0 { + logrus.Warn("Tar: Can't archive a file with includes") + } - if options.IncludeSourceDir && include == "." && relFilePath != "." { - relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator)) - } + dir, base := SplitPathDirEntry(t.srcPath) + t.srcPath = dir + t.options.IncludeFiles = []string{base} + } - skip := false - - // If "include" is an exact match for the current file - // then even if there's an "excludePatterns" pattern that - // matches it, don't skip it. IOW, assume an explicit 'include' - // is asking for that file no matter what - which is true - // for some files, like .dockerignore and Dockerfile (sometimes) - if include != relFilePath { - for len(parentDirs) != 0 { - lastParentDir := parentDirs[len(parentDirs)-1] - if strings.HasPrefix(relFilePath, lastParentDir+string(os.PathSeparator)) { - break - } - parentDirs = parentDirs[:len(parentDirs)-1] - parentMatchInfo = parentMatchInfo[:len(parentMatchInfo)-1] - } + if len(t.options.IncludeFiles) == 0 { + t.options.IncludeFiles = []string{"."} + } - var matchInfo patternmatcher.MatchInfo - if len(parentMatchInfo) != 0 { - skip, matchInfo, err = pm.MatchesUsingParentResults(relFilePath, parentMatchInfo[len(parentMatchInfo)-1]) - } else { - skip, matchInfo, err = pm.MatchesUsingParentResults(relFilePath, patternmatcher.MatchInfo{}) - } - if err != nil { - logrus.Errorf("Error matching %s: %v", relFilePath, err) - return err - } + seen := make(map[string]bool) - if f.IsDir() { - parentDirs = append(parentDirs, relFilePath) - parentMatchInfo = append(parentMatchInfo, matchInfo) - } - } + for _, include := range t.options.IncludeFiles { + rebaseName := t.options.RebaseNames[include] - if skip { - // If we want to skip this file and its a directory - // then we should first check to see if there's an - // excludes pattern (e.g. !dir/file) that starts with this - // dir. If so then we can't skip this dir. + var ( + parentMatchInfo []patternmatcher.MatchInfo + parentDirs []string + ) - // Its not a dir then so we can just return/skip. - if !f.IsDir() { - return nil - } + walkRoot := getWalkRoot(t.srcPath, include) + filepath.WalkDir(walkRoot, func(filePath string, f os.DirEntry, err error) error { + if err != nil { + logrus.Errorf("Tar: Can't stat file %s to tar: %s", t.srcPath, err) + return nil + } - // No exceptions (!...) in patterns so just skip dir - if !pm.Exclusions() { - return filepath.SkipDir - } + relFilePath, err := filepath.Rel(t.srcPath, filePath) + if err != nil || (!t.options.IncludeSourceDir && relFilePath == "." && f.IsDir()) { + // Error getting relative path OR we are looking + // at the source directory path. Skip in both situations. + return nil + } - dirSlash := relFilePath + string(filepath.Separator) + if t.options.IncludeSourceDir && include == "." && relFilePath != "." { + relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator)) + } - for _, pat := range pm.Patterns() { - if !pat.Exclusion() { - continue - } - if strings.HasPrefix(pat.String()+string(filepath.Separator), dirSlash) { - // found a match - so can't skip this dir - return nil - } + skip := false + + // If "include" is an exact match for the current file + // then even if there's an "excludePatterns" pattern that + // matches it, don't skip it. IOW, assume an explicit 'include' + // is asking for that file no matter what - which is true + // for some files, like .dockerignore and Dockerfile (sometimes) + if include != relFilePath { + for len(parentDirs) != 0 { + lastParentDir := parentDirs[len(parentDirs)-1] + if strings.HasPrefix(relFilePath, lastParentDir+string(os.PathSeparator)) { + break } + parentDirs = parentDirs[:len(parentDirs)-1] + parentMatchInfo = parentMatchInfo[:len(parentMatchInfo)-1] + } - // No matching exclusion dir so just skip dir - return filepath.SkipDir + var matchInfo patternmatcher.MatchInfo + if len(parentMatchInfo) != 0 { + skip, matchInfo, err = t.pm.MatchesUsingParentResults(relFilePath, parentMatchInfo[len(parentMatchInfo)-1]) + } else { + skip, matchInfo, err = t.pm.MatchesUsingParentResults(relFilePath, patternmatcher.MatchInfo{}) + } + if err != nil { + logrus.Errorf("Error matching %s: %v", relFilePath, err) + return err + } + + if f.IsDir() { + parentDirs = append(parentDirs, relFilePath) + parentMatchInfo = append(parentMatchInfo, matchInfo) } + } + + if skip { + // If we want to skip this file and its a directory + // then we should first check to see if there's an + // excludes pattern (e.g. !dir/file) that starts with this + // dir. If so then we can't skip this dir. - if seen[relFilePath] { + // Its not a dir then so we can just return/skip. + if !f.IsDir() { return nil } - seen[relFilePath] = true - - // Rename the base resource. - if rebaseName != "" { - var replacement string - if rebaseName != string(filepath.Separator) { - // Special case the root directory to replace with an - // empty string instead so that we don't end up with - // double slashes in the paths. - replacement = rebaseName - } - relFilePath = strings.Replace(relFilePath, include, replacement, 1) + // No exceptions (!...) in patterns so just skip dir + if !t.pm.Exclusions() { + return filepath.SkipDir } - if err := ta.addTarFile(filePath, relFilePath); err != nil { - logrus.Errorf("Can't add file %s to tar: %s", filePath, err) - // if pipe is broken, stop writing tar stream to it - if err == io.ErrClosedPipe { - return err + dirSlash := relFilePath + string(filepath.Separator) + + for _, pat := range t.pm.Patterns() { + if !pat.Exclusion() { + continue + } + if strings.HasPrefix(pat.String()+string(filepath.Separator), dirSlash) { + // found a match - so can't skip this dir + return nil } } + + // No matching exclusion dir so just skip dir + return filepath.SkipDir + } + + if seen[relFilePath] { return nil - }) - } - }() + } + seen[relFilePath] = true + + // Rename the base resource. + if rebaseName != "" { + var replacement string + if rebaseName != string(filepath.Separator) { + // Special case the root directory to replace with an + // empty string instead so that we don't end up with + // double slashes in the paths. + replacement = rebaseName + } + + relFilePath = strings.Replace(relFilePath, include, replacement, 1) + } - return pipeReader, nil + if err := ta.addTarFile(filePath, relFilePath); err != nil { + logrus.Errorf("Can't add file %s to tar: %s", filePath, err) + // if pipe is broken, stop writing tar stream to it + if err == io.ErrClosedPipe { + return err + } + } + return nil + }) + } } // Unpack unpacks the decompressedArchive to dest with options. diff --git a/vendor/github.com/docker/docker/pkg/archive/archive_unix.go b/vendor/github.com/docker/docker/pkg/archive/archive_unix.go index 1a2aea2e65..92d8e23dd0 100644 --- a/vendor/github.com/docker/docker/pkg/archive/archive_unix.go +++ b/vendor/github.com/docker/docker/pkg/archive/archive_unix.go @@ -35,16 +35,8 @@ func getWalkRoot(srcPath string, include string) string { return strings.TrimSuffix(srcPath, string(filepath.Separator)) + string(filepath.Separator) + include } -// CanonicalTarNameForPath returns platform-specific filepath -// to canonical posix-style path for tar archival. p is relative -// path. -func CanonicalTarNameForPath(p string) string { - return p // already unix-style -} - // chmodTarEntry is used to adjust the file permissions used in tar header based // on the platform the archival is done. - func chmodTarEntry(perm os.FileMode) os.FileMode { return perm // noop for unix as golang APIs provide perm bits correctly } diff --git a/vendor/github.com/docker/docker/pkg/archive/archive_windows.go b/vendor/github.com/docker/docker/pkg/archive/archive_windows.go index 7260174bfb..09a25832e8 100644 --- a/vendor/github.com/docker/docker/pkg/archive/archive_windows.go +++ b/vendor/github.com/docker/docker/pkg/archive/archive_windows.go @@ -21,24 +21,14 @@ func getWalkRoot(srcPath string, include string) string { return filepath.Join(srcPath, include) } -// CanonicalTarNameForPath returns platform-specific filepath -// to canonical posix-style path for tar archival. p is relative -// path. -func CanonicalTarNameForPath(p string) string { - return filepath.ToSlash(p) -} - // chmodTarEntry is used to adjust the file permissions used in tar header based // on the platform the archival is done. func chmodTarEntry(perm os.FileMode) os.FileMode { - // perm &= 0755 // this 0-ed out tar flags (like link, regular file, directory marker etc.) - permPart := perm & os.ModePerm - noPermPart := perm &^ os.ModePerm - // Add the x bit: make everything +x from windows - permPart |= 0111 - permPart &= 0755 + // Remove group- and world-writable bits. + perm &= 0o755 - return noPermPart | permPart + // Add the x bit: make everything +x on Windows + return perm | 0o111 } func setHeaderForSpecialDevice(hdr *tar.Header, name string, stat interface{}) (err error) { diff --git a/vendor/github.com/docker/docker/pkg/archive/changes_other.go b/vendor/github.com/docker/docker/pkg/archive/changes_other.go index 0e4399a43b..833798bd11 100644 --- a/vendor/github.com/docker/docker/pkg/archive/changes_other.go +++ b/vendor/github.com/docker/docker/pkg/archive/changes_other.go @@ -41,7 +41,7 @@ func collectFileInfoForChanges(oldDir, newDir string) (*FileInfo, *FileInfo, err func collectFileInfo(sourceDir string) (*FileInfo, error) { root := newRootFileInfo() - err := filepath.Walk(sourceDir, func(path string, f os.FileInfo, err error) error { + err := filepath.WalkDir(sourceDir, func(path string, _ os.DirEntry, err error) error { if err != nil { return err } diff --git a/vendor/github.com/docker/docker/pkg/archive/copy.go b/vendor/github.com/docker/docker/pkg/archive/copy.go index f3111b79b1..0ea1596278 100644 --- a/vendor/github.com/docker/docker/pkg/archive/copy.go +++ b/vendor/github.com/docker/docker/pkg/archive/copy.go @@ -26,23 +26,23 @@ var ( // path (from before being processed by utility functions from the path or // filepath stdlib packages) ends with a trailing `/.` or `/`. If the cleaned // path already ends in a `.` path segment, then another is not added. If the -// clean path already ends in the separator, then another is not added. -func PreserveTrailingDotOrSeparator(cleanedPath string, originalPath string, sep byte) string { +// clean path already ends in a path separator, then another is not added. +func PreserveTrailingDotOrSeparator(cleanedPath string, originalPath string) string { // Ensure paths are in platform semantics - cleanedPath = strings.ReplaceAll(cleanedPath, "/", string(sep)) - originalPath = strings.ReplaceAll(originalPath, "/", string(sep)) + cleanedPath = normalizePath(cleanedPath) + originalPath = normalizePath(originalPath) if !specifiesCurrentDir(cleanedPath) && specifiesCurrentDir(originalPath) { - if !hasTrailingPathSeparator(cleanedPath, sep) { + if !hasTrailingPathSeparator(cleanedPath) { // Add a separator if it doesn't already end with one (a cleaned // path would only end in a separator if it is the root). - cleanedPath += string(sep) + cleanedPath += string(filepath.Separator) } cleanedPath += "." } - if !hasTrailingPathSeparator(cleanedPath, sep) && hasTrailingPathSeparator(originalPath, sep) { - cleanedPath += string(sep) + if !hasTrailingPathSeparator(cleanedPath) && hasTrailingPathSeparator(originalPath) { + cleanedPath += string(filepath.Separator) } return cleanedPath @@ -51,14 +51,14 @@ func PreserveTrailingDotOrSeparator(cleanedPath string, originalPath string, sep // assertsDirectory returns whether the given path is // asserted to be a directory, i.e., the path ends with // a trailing '/' or `/.`, assuming a path separator of `/`. -func assertsDirectory(path string, sep byte) bool { - return hasTrailingPathSeparator(path, sep) || specifiesCurrentDir(path) +func assertsDirectory(path string) bool { + return hasTrailingPathSeparator(path) || specifiesCurrentDir(path) } // hasTrailingPathSeparator returns whether the given // path ends with the system's path separator character. -func hasTrailingPathSeparator(path string, sep byte) bool { - return len(path) > 0 && path[len(path)-1] == sep +func hasTrailingPathSeparator(path string) bool { + return len(path) > 0 && path[len(path)-1] == filepath.Separator } // specifiesCurrentDir returns whether the given path specifies @@ -285,7 +285,7 @@ func PrepareArchiveCopy(srcContent io.Reader, srcInfo, dstInfo CopyInfo) (dstDir srcBase = srcInfo.RebaseName } return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil - case assertsDirectory(dstInfo.Path, os.PathSeparator): + case assertsDirectory(dstInfo.Path): // The destination does not exist and is asserted to be created as a // directory, but the source content is not a directory. This is an // error condition since you cannot create a directory from a file @@ -386,8 +386,8 @@ func CopyResource(srcPath, dstPath string, followLink bool) error { dstPath = normalizePath(dstPath) // Clean the source and destination paths. - srcPath = PreserveTrailingDotOrSeparator(filepath.Clean(srcPath), srcPath, os.PathSeparator) - dstPath = PreserveTrailingDotOrSeparator(filepath.Clean(dstPath), dstPath, os.PathSeparator) + srcPath = PreserveTrailingDotOrSeparator(filepath.Clean(srcPath), srcPath) + dstPath = PreserveTrailingDotOrSeparator(filepath.Clean(dstPath), dstPath) if srcInfo, err = CopyInfoSourcePath(srcPath, followLink); err != nil { return err @@ -450,7 +450,7 @@ func ResolveHostSourcePath(path string, followLink bool) (resolvedPath, rebaseNa // resolvedDirPath will have been cleaned (no trailing path separators) so // we can manually join it with the base path element. resolvedPath = resolvedDirPath + string(filepath.Separator) + basePath - if hasTrailingPathSeparator(path, os.PathSeparator) && + if hasTrailingPathSeparator(path) && filepath.Base(path) != filepath.Base(resolvedPath) { rebaseName = filepath.Base(path) } @@ -469,8 +469,8 @@ func GetRebaseName(path, resolvedPath string) (string, string) { resolvedPath += string(filepath.Separator) + "." } - if hasTrailingPathSeparator(path, os.PathSeparator) && - !hasTrailingPathSeparator(resolvedPath, os.PathSeparator) { + if hasTrailingPathSeparator(path) && + !hasTrailingPathSeparator(resolvedPath) { resolvedPath += string(filepath.Separator) } diff --git a/vendor/github.com/docker/docker/pkg/archive/diff.go b/vendor/github.com/docker/docker/pkg/archive/diff.go index 8eeccb608b..1a2fb971f9 100644 --- a/vendor/github.com/docker/docker/pkg/archive/diff.go +++ b/vendor/github.com/docker/docker/pkg/archive/diff.go @@ -87,7 +87,7 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, basename := filepath.Base(hdr.Name) aufsHardlinks[basename] = hdr if aufsTempdir == "" { - if aufsTempdir, err = os.MkdirTemp("", "dockerplnk"); err != nil { + if aufsTempdir, err = os.MkdirTemp(dest, "dockerplnk"); err != nil { return 0, err } defer os.RemoveAll(aufsTempdir) @@ -121,7 +121,7 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, if err != nil { return 0, err } - err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + err = filepath.WalkDir(dir, func(path string, info os.DirEntry, err error) error { if err != nil { if os.IsNotExist(err) { err = nil // parent was deleted @@ -132,8 +132,7 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, return nil } if _, exists := unpackedPaths[path]; !exists { - err := os.RemoveAll(path) - return err + return os.RemoveAll(path) } return nil }) @@ -224,6 +223,25 @@ func ApplyUncompressedLayer(dest string, layer io.Reader, options *TarOptions) ( return applyLayerHandler(dest, layer, options, false) } +// IsEmpty checks if the tar archive is empty (doesn't contain any entries). +func IsEmpty(rd io.Reader) (bool, error) { + decompRd, err := DecompressStream(rd) + if err != nil { + return true, fmt.Errorf("failed to decompress archive: %v", err) + } + defer decompRd.Close() + + tarReader := tar.NewReader(decompRd) + if _, err := tarReader.Next(); err != nil { + if err == io.EOF { + return true, nil + } + return false, fmt.Errorf("failed to read next archive header: %v", err) + } + + return false, nil +} + // do the bulk load of ApplyLayer, but allow for not calling DecompressStream func applyLayerHandler(dest string, layer io.Reader, options *TarOptions, decompress bool) (int64, error) { dest = filepath.Clean(dest) diff --git a/vendor/github.com/docker/docker/pkg/archive/path.go b/vendor/github.com/docker/docker/pkg/archive/path.go new file mode 100644 index 0000000000..888a697581 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/archive/path.go @@ -0,0 +1,20 @@ +package archive + +// CheckSystemDriveAndRemoveDriveLetter verifies that a path, if it includes a drive letter, +// is the system drive. +// On Linux: this is a no-op. +// On Windows: this does the following> +// CheckSystemDriveAndRemoveDriveLetter verifies and manipulates a Windows path. +// This is used, for example, when validating a user provided path in docker cp. +// If a drive letter is supplied, it must be the system drive. The drive letter +// is always removed. Also, it translates it to OS semantics (IOW / to \). We +// need the path in this syntax so that it can ultimately be concatenated with +// a Windows long-path which doesn't support drive-letters. Examples: +// C: --> Fail +// C:\ --> \ +// a --> a +// /a --> \a +// d:\ --> Fail +func CheckSystemDriveAndRemoveDriveLetter(path string) (string, error) { + return checkSystemDriveAndRemoveDriveLetter(path) +} diff --git a/vendor/github.com/docker/docker/pkg/archive/path_unix.go b/vendor/github.com/docker/docker/pkg/archive/path_unix.go new file mode 100644 index 0000000000..0b135aea75 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/archive/path_unix.go @@ -0,0 +1,10 @@ +//go:build !windows +// +build !windows + +package archive + +// checkSystemDriveAndRemoveDriveLetter is the non-Windows implementation +// of CheckSystemDriveAndRemoveDriveLetter +func checkSystemDriveAndRemoveDriveLetter(path string) (string, error) { + return path, nil +} diff --git a/vendor/github.com/docker/docker/pkg/archive/path_windows.go b/vendor/github.com/docker/docker/pkg/archive/path_windows.go new file mode 100644 index 0000000000..7e18c8e449 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/archive/path_windows.go @@ -0,0 +1,22 @@ +package archive + +import ( + "fmt" + "path/filepath" + "strings" +) + +// checkSystemDriveAndRemoveDriveLetter is the Windows implementation +// of CheckSystemDriveAndRemoveDriveLetter +func checkSystemDriveAndRemoveDriveLetter(path string) (string, error) { + if len(path) == 2 && string(path[1]) == ":" { + return "", fmt.Errorf("no relative path specified in %q", path) + } + if !filepath.IsAbs(path) || len(path) < 2 { + return filepath.FromSlash(path), nil + } + if string(path[1]) == ":" && !strings.EqualFold(string(path[0]), "c") { + return "", fmt.Errorf("the specified path is not on the system drive (C:)") + } + return filepath.FromSlash(path[2:]), nil +} diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go b/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go index 5e6310fdcd..ded1c7c8c6 100644 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go +++ b/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go @@ -64,13 +64,14 @@ func stick(f string) error { // GetDataHome returns XDG_DATA_HOME. // GetDataHome returns $HOME/.local/share and nil error if XDG_DATA_HOME is not set. +// If HOME and XDG_DATA_HOME are not set, getpwent(3) is consulted to determine the users home directory. // // See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html func GetDataHome() (string, error) { if xdgDataHome := os.Getenv("XDG_DATA_HOME"); xdgDataHome != "" { return xdgDataHome, nil } - home := os.Getenv("HOME") + home := Get() if home == "" { return "", errors.New("could not get either XDG_DATA_HOME or HOME") } @@ -79,15 +80,26 @@ func GetDataHome() (string, error) { // GetConfigHome returns XDG_CONFIG_HOME. // GetConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set. +// If HOME and XDG_CONFIG_HOME are not set, getpwent(3) is consulted to determine the users home directory. // // See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html func GetConfigHome() (string, error) { if xdgConfigHome := os.Getenv("XDG_CONFIG_HOME"); xdgConfigHome != "" { return xdgConfigHome, nil } - home := os.Getenv("HOME") + home := Get() if home == "" { return "", errors.New("could not get either XDG_CONFIG_HOME or HOME") } return filepath.Join(home, ".config"), nil } + +// GetLibHome returns $HOME/.local/lib +// If HOME is not set, getpwent(3) is consulted to determine the users home directory. +func GetLibHome() (string, error) { + home := Get() + if home == "" { + return "", errors.New("could not get HOME") + } + return filepath.Join(home, ".local/lib"), nil +} diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go b/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go index fc48e674c1..11f1bec985 100644 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go +++ b/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go @@ -26,3 +26,8 @@ func GetDataHome() (string, error) { func GetConfigHome() (string, error) { return "", errors.New("homedir.GetConfigHome() is not supported on this system") } + +// GetLibHome is unsupported on non-linux system. +func GetLibHome() (string, error) { + return "", errors.New("homedir.GetLibHome() is not supported on this system") +} diff --git a/vendor/github.com/docker/docker/pkg/idtools/idtools.go b/vendor/github.com/docker/docker/pkg/idtools/idtools.go index 1e0a89004a..79d682c694 100644 --- a/vendor/github.com/docker/docker/pkg/idtools/idtools.go +++ b/vendor/github.com/docker/docker/pkg/idtools/idtools.go @@ -162,20 +162,6 @@ func (i IdentityMapping) Empty() bool { return len(i.UIDMaps) == 0 && len(i.GIDMaps) == 0 } -// UIDs returns the mapping for UID. -// -// Deprecated: reference the UIDMaps field directly. -func (i IdentityMapping) UIDs() []IDMap { - return i.UIDMaps -} - -// GIDs returns the mapping for GID. -// -// Deprecated: reference the GIDMaps field directly. -func (i IdentityMapping) GIDs() []IDMap { - return i.GIDMaps -} - func createIDMap(subidRanges ranges) []IDMap { idMap := []IDMap{} diff --git a/vendor/github.com/docker/docker/pkg/idtools/idtools_unix.go b/vendor/github.com/docker/docker/pkg/idtools/idtools_unix.go index 03846b0307..2194c47d6e 100644 --- a/vendor/github.com/docker/docker/pkg/idtools/idtools_unix.go +++ b/vendor/github.com/docker/docker/pkg/idtools/idtools_unix.go @@ -11,32 +11,18 @@ import ( "os/exec" "path/filepath" "strconv" - "sync" "syscall" - "github.com/docker/docker/pkg/system" "github.com/opencontainers/runc/libcontainer/user" - "github.com/pkg/errors" -) - -var ( - entOnce sync.Once - getentCmd string ) func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting bool) error { - // make an array containing the original path asked for, plus (for mkAll == true) - // all path components leading up to the complete path that don't exist before we MkdirAll - // so that we can chown all of them properly at the end. If chownExisting is false, we won't - // chown the full directory path if it exists - - var paths []string path, err := filepath.Abs(path) if err != nil { return err } - stat, err := system.Stat(path) + stat, err := os.Stat(path) if err == nil { if !stat.IsDir() { return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} @@ -45,10 +31,15 @@ func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting return nil } - // short-circuit--we were called with an existing directory and chown was requested - return setPermissions(path, mode, owner.UID, owner.GID, stat) + // short-circuit -- we were called with an existing directory and chown was requested + return setPermissions(path, mode, owner, stat) } + // make an array containing the original path asked for, plus (for mkAll == true) + // all path components leading up to the complete path that don't exist before we MkdirAll + // so that we can chown all of them properly at the end. If chownExisting is false, we won't + // chown the full directory path if it exists + var paths []string if os.IsNotExist(err) { paths = []string{path} } @@ -62,54 +53,26 @@ func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting if dirPath == "/" { break } - if _, err := os.Stat(dirPath); err != nil && os.IsNotExist(err) { + if _, err = os.Stat(dirPath); err != nil && os.IsNotExist(err) { paths = append(paths, dirPath) } } - if err := system.MkdirAll(path, mode); err != nil { - return err - } - } else { - if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) { + if err = os.MkdirAll(path, mode); err != nil { return err } + } else if err = os.Mkdir(path, mode); err != nil { + return err } // even if it existed, we will chown the requested path + any subpaths that // didn't exist when we called MkdirAll for _, pathComponent := range paths { - if err := setPermissions(pathComponent, mode, owner.UID, owner.GID, nil); err != nil { + if err = setPermissions(pathComponent, mode, owner, nil); err != nil { return err } } return nil } -// CanAccess takes a valid (existing) directory and a uid, gid pair and determines -// if that uid, gid pair has access (execute bit) to the directory -func CanAccess(path string, pair Identity) bool { - statInfo, err := system.Stat(path) - if err != nil { - return false - } - fileMode := os.FileMode(statInfo.Mode()) - permBits := fileMode.Perm() - return accessible(statInfo.UID() == uint32(pair.UID), - statInfo.GID() == uint32(pair.GID), permBits) -} - -func accessible(isOwner, isGroup bool, perms os.FileMode) bool { - if isOwner && (perms&0100 == 0100) { - return true - } - if isGroup && (perms&0010 == 0010) { - return true - } - if perms&0001 == 0001 { - return true - } - return false -} - // LookupUser uses traditional local system files lookup (from libcontainer/user) on a username, // followed by a call to `getent` for supporting host configured non-files passwd and group dbs func LookupUser(name string) (user.User, error) { @@ -193,12 +156,15 @@ func getentGroup(name string) (user.Group, error) { } func callGetent(database, key string) (io.Reader, error) { - entOnce.Do(func() { getentCmd, _ = resolveBinary("getent") }) - // if no `getent` command on host, can't do anything else - if getentCmd == "" { - return nil, fmt.Errorf("unable to find getent command") + getentCmd, err := resolveBinary("getent") + // if no `getent` command within the execution environment, can't do anything else + if err != nil { + return nil, fmt.Errorf("unable to find getent command: %w", err) } - out, err := execCmd(getentCmd, database, key) + command := exec.Command(getentCmd, database, key) + // we run getent within container filesystem, but without /dev so /dev/null is not available for exec to mock stdin + command.Stdin = io.NopCloser(bytes.NewReader(nil)) + out, err := command.CombinedOutput() if err != nil { exitCode, errC := getExitCode(err) if errC != nil { @@ -234,36 +200,24 @@ func getExitCode(err error) (int, error) { // Normally a Chown is a no-op if uid/gid match, but in some cases this can still cause an error, e.g. if the // dir is on an NFS share, so don't call chown unless we absolutely must. // Likewise for setting permissions. -func setPermissions(p string, mode os.FileMode, uid, gid int, stat *system.StatT) error { +func setPermissions(p string, mode os.FileMode, owner Identity, stat os.FileInfo) error { if stat == nil { var err error - stat, err = system.Stat(p) + stat, err = os.Stat(p) if err != nil { return err } } - if os.FileMode(stat.Mode()).Perm() != mode.Perm() { + if stat.Mode().Perm() != mode.Perm() { if err := os.Chmod(p, mode.Perm()); err != nil { return err } } - if stat.UID() == uint32(uid) && stat.GID() == uint32(gid) { + ssi := stat.Sys().(*syscall.Stat_t) + if ssi.Uid == uint32(owner.UID) && ssi.Gid == uint32(owner.GID) { return nil } - return os.Chown(p, uid, gid) -} - -// NewIdentityMapping takes a requested username and -// using the data from /etc/sub{uid,gid} ranges, creates the -// proper uid and gid remapping ranges for that user/group pair -// -// Deprecated: Use LoadIdentityMapping. -func NewIdentityMapping(name string) (*IdentityMapping, error) { - m, err := LoadIdentityMapping(name) - if err != nil { - return nil, err - } - return &m, err + return os.Chown(p, owner.UID, owner.GID) } // LoadIdentityMapping takes a requested username and @@ -272,7 +226,7 @@ func NewIdentityMapping(name string) (*IdentityMapping, error) { func LoadIdentityMapping(name string) (IdentityMapping, error) { usr, err := LookupUser(name) if err != nil { - return IdentityMapping{}, fmt.Errorf("Could not get user for username %s: %v", name, err) + return IdentityMapping{}, fmt.Errorf("could not get user for username %s: %v", name, err) } subuidRanges, err := lookupSubUIDRanges(usr) @@ -302,7 +256,7 @@ func lookupSubUIDRanges(usr user.User) ([]IDMap, error) { } } if len(rangeList) == 0 { - return nil, errors.Errorf("no subuid ranges found for user %q", usr.Name) + return nil, fmt.Errorf("no subuid ranges found for user %q", usr.Name) } return createIDMap(rangeList), nil } @@ -319,7 +273,7 @@ func lookupSubGIDRanges(usr user.User) ([]IDMap, error) { } } if len(rangeList) == 0 { - return nil, errors.Errorf("no subgid ranges found for user %q", usr.Name) + return nil, fmt.Errorf("no subgid ranges found for user %q", usr.Name) } return createIDMap(rangeList), nil } diff --git a/vendor/github.com/docker/docker/pkg/idtools/idtools_windows.go b/vendor/github.com/docker/docker/pkg/idtools/idtools_windows.go index 0f5aadd496..32953f4563 100644 --- a/vendor/github.com/docker/docker/pkg/idtools/idtools_windows.go +++ b/vendor/github.com/docker/docker/pkg/idtools/idtools_windows.go @@ -19,16 +19,6 @@ const ( // permissions aren't set through this path, the identity isn't utilized. // Ownership is handled elsewhere, but in the future could be support here // too. -func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting bool) error { - if err := system.MkdirAll(path, mode); err != nil { - return err - } - return nil -} - -// CanAccess takes a valid (existing) directory and a uid, gid pair and determines -// if that uid, gid pair has access (execute bit) to the directory -// Windows does not require/support this function, so always return true -func CanAccess(path string, identity Identity) bool { - return true +func mkdirAs(path string, _ os.FileMode, _ Identity, _, _ bool) error { + return system.MkdirAll(path, 0) } diff --git a/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go b/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go index 3ad9255df2..f0c075e20f 100644 --- a/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go +++ b/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go @@ -2,6 +2,7 @@ package idtools // import "github.com/docker/docker/pkg/idtools" import ( "fmt" + "os/exec" "regexp" "sort" "strconv" @@ -32,21 +33,21 @@ const ( // mapping ranges in containers. func AddNamespaceRangesUser(name string) (int, int, error) { if err := addUser(name); err != nil { - return -1, -1, fmt.Errorf("Error adding user %q: %v", name, err) + return -1, -1, fmt.Errorf("error adding user %q: %v", name, err) } // Query the system for the created uid and gid pair - out, err := execCmd("id", name) + out, err := exec.Command("id", name).CombinedOutput() if err != nil { - return -1, -1, fmt.Errorf("Error trying to find uid/gid for new user %q: %v", name, err) + return -1, -1, fmt.Errorf("error trying to find uid/gid for new user %q: %v", name, err) } matches := idOutRegexp.FindStringSubmatch(strings.TrimSpace(string(out))) if len(matches) != 3 { - return -1, -1, fmt.Errorf("Can't find uid, gid from `id` output: %q", string(out)) + return -1, -1, fmt.Errorf("can't find uid, gid from `id` output: %q", string(out)) } uid, err := strconv.Atoi(matches[1]) if err != nil { - return -1, -1, fmt.Errorf("Can't convert found uid (%s) to int: %v", matches[1], err) + return -1, -1, fmt.Errorf("can't convert found uid (%s) to int: %v", matches[1], err) } gid, err := strconv.Atoi(matches[2]) if err != nil { @@ -57,7 +58,7 @@ func AddNamespaceRangesUser(name string) (int, int, error) { // do not get auto-created ranges in subuid/subgid) if err := createSubordinateRanges(name); err != nil { - return -1, -1, fmt.Errorf("Couldn't create subordinate ID ranges: %v", err) + return -1, -1, fmt.Errorf("couldn't create subordinate ID ranges: %v", err) } return uid, gid, nil } @@ -81,7 +82,7 @@ func addUser(name string) error { return fmt.Errorf("cannot add user; no useradd/adduser binary found") } - if out, err := execCmd(userCommand, args...); err != nil { + if out, err := exec.Command(userCommand, args...).CombinedOutput(); err != nil { return fmt.Errorf("failed to add user with error: %v; output: %q", err, string(out)) } return nil @@ -92,33 +93,35 @@ func createSubordinateRanges(name string) error { // by the distro tooling ranges, err := parseSubuid(name) if err != nil { - return fmt.Errorf("Error while looking for subuid ranges for user %q: %v", name, err) + return fmt.Errorf("error while looking for subuid ranges for user %q: %v", name, err) } if len(ranges) == 0 { // no UID ranges; let's create one startID, err := findNextUIDRange() if err != nil { - return fmt.Errorf("Can't find available subuid range: %v", err) + return fmt.Errorf("can't find available subuid range: %v", err) } - out, err := execCmd("usermod", "-v", fmt.Sprintf("%d-%d", startID, startID+defaultRangeLen-1), name) + idRange := fmt.Sprintf("%d-%d", startID, startID+defaultRangeLen-1) + out, err := exec.Command("usermod", "-v", idRange, name).CombinedOutput() if err != nil { - return fmt.Errorf("Unable to add subuid range to user: %q; output: %s, err: %v", name, out, err) + return fmt.Errorf("unable to add subuid range to user: %q; output: %s, err: %v", name, out, err) } } ranges, err = parseSubgid(name) if err != nil { - return fmt.Errorf("Error while looking for subgid ranges for user %q: %v", name, err) + return fmt.Errorf("error while looking for subgid ranges for user %q: %v", name, err) } if len(ranges) == 0 { // no GID ranges; let's create one startID, err := findNextGIDRange() if err != nil { - return fmt.Errorf("Can't find available subgid range: %v", err) + return fmt.Errorf("can't find available subgid range: %v", err) } - out, err := execCmd("usermod", "-w", fmt.Sprintf("%d-%d", startID, startID+defaultRangeLen-1), name) + idRange := fmt.Sprintf("%d-%d", startID, startID+defaultRangeLen-1) + out, err := exec.Command("usermod", "-w", idRange, name).CombinedOutput() if err != nil { - return fmt.Errorf("Unable to add subgid range to user: %q; output: %s, err: %v", name, out, err) + return fmt.Errorf("unable to add subgid range to user: %q; output: %s, err: %v", name, out, err) } } return nil @@ -127,7 +130,7 @@ func createSubordinateRanges(name string) error { func findNextUIDRange() (int, error) { ranges, err := parseSubuid("ALL") if err != nil { - return -1, fmt.Errorf("Couldn't parse all ranges in /etc/subuid file: %v", err) + return -1, fmt.Errorf("couldn't parse all ranges in /etc/subuid file: %v", err) } sort.Sort(ranges) return findNextRangeStart(ranges) @@ -136,7 +139,7 @@ func findNextUIDRange() (int, error) { func findNextGIDRange() (int, error) { ranges, err := parseSubgid("ALL") if err != nil { - return -1, fmt.Errorf("Couldn't parse all ranges in /etc/subgid file: %v", err) + return -1, fmt.Errorf("couldn't parse all ranges in /etc/subgid file: %v", err) } sort.Sort(ranges) return findNextRangeStart(ranges) diff --git a/vendor/github.com/docker/docker/pkg/idtools/utils_unix.go b/vendor/github.com/docker/docker/pkg/idtools/utils_unix.go index 540672af5a..05cc696365 100644 --- a/vendor/github.com/docker/docker/pkg/idtools/utils_unix.go +++ b/vendor/github.com/docker/docker/pkg/idtools/utils_unix.go @@ -25,8 +25,3 @@ func resolveBinary(binname string) (string, error) { } return "", fmt.Errorf("Binary %q does not resolve to a binary of that name in $PATH (%q)", binname, resolvedPath) } - -func execCmd(cmd string, arg ...string) ([]byte, error) { - execCmd := exec.Command(cmd, arg...) - return execCmd.CombinedOutput() -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go b/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go index d1dfdae0cc..c1cfa62fd2 100644 --- a/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go +++ b/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go @@ -29,11 +29,12 @@ var ( // and releases new byte slices to adjust to current needs, so the buffer // won't be overgrown after peak loads. type BytesPipe struct { - mu sync.Mutex - wait *sync.Cond - buf []*fixedBuffer - bufLen int - closeErr error // error to return from next Read. set to nil if not closed. + mu sync.Mutex + wait *sync.Cond + buf []*fixedBuffer + bufLen int + closeErr error // error to return from next Read. set to nil if not closed. + readBlock bool // check read BytesPipe is Wait() or not } // NewBytesPipe creates new BytesPipe, initialized by specified slice. @@ -85,6 +86,9 @@ loop0: // make sure the buffer doesn't grow too big from this write for bp.bufLen >= blockThreshold { + if bp.readBlock { + bp.wait.Broadcast() + } bp.wait.Wait() if bp.closeErr != nil { continue loop0 @@ -129,7 +133,9 @@ func (bp *BytesPipe) Read(p []byte) (n int, err error) { if bp.closeErr != nil { return 0, bp.closeErr } + bp.readBlock = true bp.wait.Wait() + bp.readBlock = false if bp.bufLen == 0 && bp.closeErr != nil { return 0, bp.closeErr } diff --git a/vendor/github.com/docker/docker/pkg/ioutils/readers.go b/vendor/github.com/docker/docker/pkg/ioutils/readers.go index de00b95e3f..d82ae93034 100644 --- a/vendor/github.com/docker/docker/pkg/ioutils/readers.go +++ b/vendor/github.com/docker/docker/pkg/ioutils/readers.go @@ -3,11 +3,15 @@ package ioutils // import "github.com/docker/docker/pkg/ioutils" import ( "context" "io" + "runtime/debug" + "sync/atomic" // make sure crypto.SHA256, crypto.sha512 and crypto.SHA384 are registered // TODO remove once https://github.com/opencontainers/go-digest/pull/64 is merged. _ "crypto/sha256" _ "crypto/sha512" + + "github.com/sirupsen/logrus" ) // ReadCloserWrapper wraps an io.Reader, and implements an io.ReadCloser @@ -16,10 +20,15 @@ import ( type ReadCloserWrapper struct { io.Reader closer func() error + closed atomic.Bool } // Close calls back the passed closer function func (r *ReadCloserWrapper) Close() error { + if !r.closed.CompareAndSwap(false, true) { + subsequentCloseWarn("ReadCloserWrapper") + return nil + } return r.closer() } @@ -87,6 +96,7 @@ type cancelReadCloser struct { cancel func() pR *io.PipeReader // Stream to read from pW *io.PipeWriter + closed atomic.Bool } // NewCancelReadCloser creates a wrapper that closes the ReadCloser when the @@ -146,6 +156,17 @@ func (p *cancelReadCloser) closeWithError(err error) { // Close closes the wrapper its underlying reader. It will cause // future calls to Read to return io.EOF. func (p *cancelReadCloser) Close() error { + if !p.closed.CompareAndSwap(false, true) { + subsequentCloseWarn("cancelReadCloser") + return nil + } p.closeWithError(io.EOF) return nil } + +func subsequentCloseWarn(name string) { + logrus.Error("subsequent attempt to close " + name) + if logrus.GetLevel() >= logrus.DebugLevel { + logrus.Errorf("stack trace: %s", string(debug.Stack())) + } +} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go b/vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go deleted file mode 100644 index 7489122309..0000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !windows -// +build !windows - -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import "os" - -// TempDir on Unix systems is equivalent to os.MkdirTemp. -func TempDir(dir, prefix string) (string, error) { - return os.MkdirTemp(dir, prefix) -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go b/vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go deleted file mode 100644 index a57fd9af6a..0000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go +++ /dev/null @@ -1,16 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "os" - - "github.com/docker/docker/pkg/longpath" -) - -// TempDir is the equivalent of os.MkdirTemp, except that the result is in Windows longpath format. -func TempDir(dir, prefix string) (string, error) { - tempDir, err := os.MkdirTemp(dir, prefix) - if err != nil { - return "", err - } - return longpath.AddPrefix(tempDir), nil -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/tempdir_deprecated.go b/vendor/github.com/docker/docker/pkg/ioutils/tempdir_deprecated.go new file mode 100644 index 0000000000..b3321602c2 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/ioutils/tempdir_deprecated.go @@ -0,0 +1,10 @@ +package ioutils + +import "github.com/docker/docker/pkg/longpath" + +// TempDir is the equivalent of [os.MkdirTemp], except that on Windows +// the result is in Windows longpath format. On Unix systems it is +// equivalent to [os.MkdirTemp]. +// +// Deprecated: use [longpath.MkdirTemp]. +var TempDir = longpath.MkdirTemp diff --git a/vendor/github.com/docker/docker/pkg/ioutils/writers.go b/vendor/github.com/docker/docker/pkg/ioutils/writers.go index 61c679497d..1f50602f28 100644 --- a/vendor/github.com/docker/docker/pkg/ioutils/writers.go +++ b/vendor/github.com/docker/docker/pkg/ioutils/writers.go @@ -1,6 +1,9 @@ package ioutils // import "github.com/docker/docker/pkg/ioutils" -import "io" +import ( + "io" + "sync/atomic" +) // NopWriter represents a type which write operation is nop. type NopWriter struct{} @@ -29,9 +32,14 @@ func (f *NopFlusher) Flush() {} type writeCloserWrapper struct { io.Writer closer func() error + closed atomic.Bool } func (r *writeCloserWrapper) Close() error { + if !r.closed.CompareAndSwap(false, true) { + subsequentCloseWarn("WriteCloserWrapper") + return nil + } return r.closer() } diff --git a/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go b/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go index cf8d04b1b2..035160c834 100644 --- a/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go +++ b/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go @@ -16,8 +16,8 @@ import ( // ensure the formatted time isalways the same number of characters. const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00" -// JSONError wraps a concrete Code and Message, `Code` is -// is an integer error code, `Message` is the error message. +// JSONError wraps a concrete Code and Message, Code is +// an integer error code, Message is the error message. type JSONError struct { Code int `json:"code,omitempty"` Message string `json:"message,omitempty"` @@ -27,20 +27,28 @@ func (e *JSONError) Error() string { return e.Message } -// JSONProgress describes a Progress. terminalFd is the fd of the current terminal, -// Start is the initial value for the operation. Current is the current status and -// value of the progress made towards Total. Total is the end value describing when -// we made 100% progress for an operation. +// JSONProgress describes a progress message in a JSON stream. type JSONProgress struct { + // Current is the current status and value of the progress made towards Total. + Current int64 `json:"current,omitempty"` + // Total is the end value describing when we made 100% progress for an operation. + Total int64 `json:"total,omitempty"` + // Start is the initial value for the operation. + Start int64 `json:"start,omitempty"` + // HideCounts. if true, hides the progress count indicator (xB/yB). + HideCounts bool `json:"hidecounts,omitempty"` + // Units is the unit to print for progress. It defaults to "bytes" if empty. + Units string `json:"units,omitempty"` + + // terminalFd is the fd of the current terminal, if any. It is used + // to get the terminal width. terminalFd uintptr - Current int64 `json:"current,omitempty"` - Total int64 `json:"total,omitempty"` - Start int64 `json:"start,omitempty"` - // If true, don't show xB/yB - HideCounts bool `json:"hidecounts,omitempty"` - Units string `json:"units,omitempty"` - nowFunc func() time.Time - winSize int + + // nowFunc is used to override the current time in tests. + nowFunc func() time.Time + + // winSize is used to override the terminal width in tests. + winSize int } func (p *JSONProgress) String() string { @@ -56,8 +64,7 @@ func (p *JSONProgress) String() string { if p.Total <= 0 { switch p.Units { case "": - current := units.HumanSize(float64(p.Current)) - return fmt.Sprintf("%8v", current) + return fmt.Sprintf("%8v", units.HumanSize(float64(p.Current))) default: return fmt.Sprintf("%d %s", p.Current, p.Units) } @@ -110,17 +117,17 @@ func (p *JSONProgress) String() string { return pbBox + numbersBox + timeLeftBox } -// shim for testing +// now returns the current time in UTC, but can be overridden in tests +// by setting JSONProgress.nowFunc to a custom function. func (p *JSONProgress) now() time.Time { - if p.nowFunc == nil { - p.nowFunc = func() time.Time { - return time.Now().UTC() - } + if p.nowFunc != nil { + return p.nowFunc() } - return p.nowFunc() + return time.Now().UTC() } -// shim for testing +// width returns the current terminal's width, but can be overridden +// in tests by setting JSONProgress.winSize to a non-zero value. func (p *JSONProgress) width() int { if p.winSize != 0 { return p.winSize @@ -164,13 +171,11 @@ func cursorDown(out io.Writer, l uint) { fmt.Fprint(out, aec.Down(l)) } -// Display displays the JSONMessage to `out`. If `isTerminal` is true, it will erase the -// entire current line when displaying the progressbar. +// Display prints the JSONMessage to out. If isTerminal is true, it erases +// the entire current line when displaying the progressbar. It returns an +// error if the [JSONMessage.Error] field is non-nil. func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error { if jm.Error != nil { - if jm.Error.Code == 401 { - return fmt.Errorf("authentication is required") - } return jm.Error } var endl string @@ -204,9 +209,22 @@ func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error { return nil } -// DisplayJSONMessagesStream displays a json message stream from `in` to `out`, `isTerminal` -// describes if `out` is a terminal. If this is the case, it will print `\n` at the end of -// each line and move the cursor while displaying. +// DisplayJSONMessagesStream reads a JSON message stream from in, and writes +// each [JSONMessage] to out. It returns an error if an invalid JSONMessage +// is received, or if a JSONMessage containers a non-zero [JSONMessage.Error]. +// +// Presentation of the JSONMessage depends on whether a terminal is attached, +// and on the terminal width. Progress bars ([JSONProgress]) are suppressed +// on narrower terminals (< 110 characters). +// +// - isTerminal describes if out is a terminal, in which case it prints +// a newline ("\n") at the end of each line and moves the cursor while +// displaying. +// - terminalFd is the fd of the current terminal (if any), and used +// to get the terminal width. +// - auxCallback allows handling the [JSONMessage.Aux] field. It is +// called if a JSONMessage contains an Aux field, in which case +// DisplayJSONMessagesStream does not present the JSONMessage. func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(JSONMessage)) error { var ( dec = json.NewDecoder(in) @@ -271,13 +289,19 @@ func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, return nil } -type stream interface { +// Stream is an io.Writer for output with utilities to get the output's file +// descriptor and to detect wether it's a terminal. +// +// it is subset of the streams.Out type in +// https://pkg.go.dev/github.com/docker/cli@v20.10.17+incompatible/cli/streams#Out +type Stream interface { io.Writer FD() uintptr IsTerminal() bool } -// DisplayJSONMessagesToStream prints json messages to the output stream -func DisplayJSONMessagesToStream(in io.Reader, stream stream, auxCallback func(JSONMessage)) error { +// DisplayJSONMessagesToStream prints json messages to the output Stream. It is +// used by the Docker CLI to print JSONMessage streams. +func DisplayJSONMessagesToStream(in io.Reader, stream Stream, auxCallback func(JSONMessage)) error { return DisplayJSONMessagesStream(in, stream, stream.FD(), stream.IsTerminal(), auxCallback) } diff --git a/vendor/github.com/docker/docker/pkg/longpath/longpath.go b/vendor/github.com/docker/docker/pkg/longpath/longpath.go index 4177affba2..1c5dde5218 100644 --- a/vendor/github.com/docker/docker/pkg/longpath/longpath.go +++ b/vendor/github.com/docker/docker/pkg/longpath/longpath.go @@ -1,17 +1,20 @@ -// longpath introduces some constants and helper functions for handling long paths -// in Windows, which are expected to be prepended with `\\?\` and followed by either -// a drive letter, a UNC server\share, or a volume identifier. - +// Package longpath introduces some constants and helper functions for handling +// long paths in Windows. +// +// Long paths are expected to be prepended with "\\?\" and followed by either a +// drive letter, a UNC server\share, or a volume identifier. package longpath // import "github.com/docker/docker/pkg/longpath" import ( + "os" + "runtime" "strings" ) // Prefix is the longpath prefix for Windows file paths. const Prefix = `\\?\` -// AddPrefix will add the Windows long path prefix to the path provided if +// AddPrefix adds the Windows long path prefix to the path provided if // it does not already have it. func AddPrefix(path string) string { if !strings.HasPrefix(path, Prefix) { @@ -24,3 +27,17 @@ func AddPrefix(path string) string { } return path } + +// MkdirTemp is the equivalent of [os.MkdirTemp], except that on Windows +// the result is in Windows longpath format. On Unix systems it is +// equivalent to [os.MkdirTemp]. +func MkdirTemp(dir, prefix string) (string, error) { + tempDir, err := os.MkdirTemp(dir, prefix) + if err != nil { + return "", err + } + if runtime.GOOS != "windows" { + return tempDir, nil + } + return AddPrefix(tempDir), nil +} diff --git a/vendor/github.com/docker/docker/pkg/meminfo/meminfo.go b/vendor/github.com/docker/docker/pkg/meminfo/meminfo.go new file mode 100644 index 0000000000..4f33ad26bf --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/meminfo/meminfo.go @@ -0,0 +1,26 @@ +// Package meminfo provides utilites to retrieve memory statistics of +// the host system. +package meminfo + +// Read retrieves memory statistics of the host system and returns a +// Memory type. It is only supported on Linux and Windows, and returns an +// error on other platforms. +func Read() (*Memory, error) { + return readMemInfo() +} + +// Memory contains memory statistics of the host system. +type Memory struct { + // Total usable RAM (i.e. physical RAM minus a few reserved bits and the + // kernel binary code). + MemTotal int64 + + // Amount of free memory. + MemFree int64 + + // Total amount of swap space available. + SwapTotal int64 + + // Amount of swap space that is currently unused. + SwapFree int64 +} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go b/vendor/github.com/docker/docker/pkg/meminfo/meminfo_linux.go similarity index 79% rename from vendor/github.com/docker/docker/pkg/system/meminfo_linux.go rename to vendor/github.com/docker/docker/pkg/meminfo/meminfo_linux.go index 02a7377c1f..0c1cd21d49 100644 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go +++ b/vendor/github.com/docker/docker/pkg/meminfo/meminfo_linux.go @@ -1,4 +1,4 @@ -package system // import "github.com/docker/docker/pkg/system" +package meminfo import ( "bufio" @@ -8,9 +8,9 @@ import ( "strings" ) -// ReadMemInfo retrieves memory statistics of the host system and returns a -// MemInfo type. -func ReadMemInfo() (*MemInfo, error) { +// readMemInfo retrieves memory statistics of the host system and returns a +// Memory type. +func readMemInfo() (*Memory, error) { file, err := os.Open("/proc/meminfo") if err != nil { return nil, err @@ -20,10 +20,10 @@ func ReadMemInfo() (*MemInfo, error) { } // parseMemInfo parses the /proc/meminfo file into -// a MemInfo object given an io.Reader to the file. +// a Memory object given an io.Reader to the file. // Throws error if there are problems reading from the file -func parseMemInfo(reader io.Reader) (*MemInfo, error) { - meminfo := &MemInfo{} +func parseMemInfo(reader io.Reader) (*Memory, error) { + meminfo := &Memory{} scanner := bufio.NewScanner(reader) memAvailable := int64(-1) for scanner.Scan() { diff --git a/vendor/github.com/docker/docker/pkg/meminfo/meminfo_unsupported.go b/vendor/github.com/docker/docker/pkg/meminfo/meminfo_unsupported.go new file mode 100644 index 0000000000..ebfadd5343 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/meminfo/meminfo_unsupported.go @@ -0,0 +1,11 @@ +//go:build !linux && !windows +// +build !linux,!windows + +package meminfo + +import "errors" + +// readMemInfo is not supported on platforms other than linux and windows. +func readMemInfo() (*Memory, error) { + return nil, errors.New("platform and architecture is not supported") +} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go b/vendor/github.com/docker/docker/pkg/meminfo/meminfo_windows.go similarity index 81% rename from vendor/github.com/docker/docker/pkg/system/meminfo_windows.go rename to vendor/github.com/docker/docker/pkg/meminfo/meminfo_windows.go index 124d2c502d..aa7d9375be 100644 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go +++ b/vendor/github.com/docker/docker/pkg/meminfo/meminfo_windows.go @@ -1,4 +1,4 @@ -package system // import "github.com/docker/docker/pkg/system" +package meminfo import ( "unsafe" @@ -26,17 +26,17 @@ type memorystatusex struct { ullAvailExtendedVirtual uint64 } -// ReadMemInfo retrieves memory statistics of the host system and returns a -// MemInfo type. -func ReadMemInfo() (*MemInfo, error) { +// readMemInfo retrieves memory statistics of the host system and returns a +// Memory type. +func readMemInfo() (*Memory, error) { msi := &memorystatusex{ dwLength: 64, } r1, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msi))) if r1 == 0 { - return &MemInfo{}, nil + return &Memory{}, nil } - return &MemInfo{ + return &Memory{ MemTotal: int64(msi.ullTotalPhys), MemFree: int64(msi.ullAvailPhys), SwapTotal: int64(msi.ullTotalPageFile), diff --git a/vendor/github.com/docker/docker/pkg/process/doc.go b/vendor/github.com/docker/docker/pkg/process/doc.go new file mode 100644 index 0000000000..dae536d7db --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/process/doc.go @@ -0,0 +1,3 @@ +// Package process provides a set of basic functions to manage individual +// processes. +package process diff --git a/vendor/github.com/docker/docker/pkg/process/process_unix.go b/vendor/github.com/docker/docker/pkg/process/process_unix.go new file mode 100644 index 0000000000..daf3923626 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/process/process_unix.go @@ -0,0 +1,82 @@ +//go:build !windows +// +build !windows + +package process + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "runtime" + "strconv" + + "golang.org/x/sys/unix" +) + +// Alive returns true if process with a given pid is running. It only considers +// positive PIDs; 0 (all processes in the current process group), -1 (all processes +// with a PID larger than 1), and negative (-n, all processes in process group +// "n") values for pid are never considered to be alive. +func Alive(pid int) bool { + if pid < 1 { + return false + } + switch runtime.GOOS { + case "darwin": + // OS X does not have a proc filesystem. Use kill -0 pid to judge if the + // process exists. From KILL(2): https://www.freebsd.org/cgi/man.cgi?query=kill&sektion=2&manpath=OpenDarwin+7.2.1 + // + // Sig may be one of the signals specified in sigaction(2) or it may + // be 0, in which case error checking is performed but no signal is + // actually sent. This can be used to check the validity of pid. + err := unix.Kill(pid, 0) + + // Either the PID was found (no error) or we get an EPERM, which means + // the PID exists, but we don't have permissions to signal it. + return err == nil || err == unix.EPERM + default: + _, err := os.Stat(filepath.Join("/proc", strconv.Itoa(pid))) + return err == nil + } +} + +// Kill force-stops a process. It only considers positive PIDs; 0 (all processes +// in the current process group), -1 (all processes with a PID larger than 1), +// and negative (-n, all processes in process group "n") values for pid are +// ignored. Refer to [KILL(2)] for details. +// +// [KILL(2)]: https://man7.org/linux/man-pages/man2/kill.2.html +func Kill(pid int) error { + if pid < 1 { + return fmt.Errorf("invalid PID (%d): only positive PIDs are allowed", pid) + } + err := unix.Kill(pid, unix.SIGKILL) + if err != nil && err != unix.ESRCH { + return err + } + return nil +} + +// Zombie return true if process has a state with "Z". It only considers positive +// PIDs; 0 (all processes in the current process group), -1 (all processes with +// a PID larger than 1), and negative (-n, all processes in process group "n") +// values for pid are ignored. Refer to [PROC(5)] for details. +// +// [PROC(5)]: https://man7.org/linux/man-pages/man5/proc.5.html +func Zombie(pid int) (bool, error) { + if pid < 1 { + return false, nil + } + data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + return false, err + } + if cols := bytes.SplitN(data, []byte(" "), 4); len(cols) >= 3 && string(cols[2]) == "Z" { + return true, nil + } + return false, nil +} diff --git a/vendor/github.com/docker/docker/pkg/process/process_windows.go b/vendor/github.com/docker/docker/pkg/process/process_windows.go new file mode 100644 index 0000000000..26158d09ec --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/process/process_windows.go @@ -0,0 +1,52 @@ +package process + +import ( + "os" + + "golang.org/x/sys/windows" +) + +// Alive returns true if process with a given pid is running. +func Alive(pid int) bool { + h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid)) + if err != nil { + return false + } + var c uint32 + err = windows.GetExitCodeProcess(h, &c) + _ = windows.CloseHandle(h) + if err != nil { + // From the GetExitCodeProcess function (processthreadsapi.h) API docs: + // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getexitcodeprocess + // + // The GetExitCodeProcess function returns a valid error code defined by the + // application only after the thread terminates. Therefore, an application should + // not use STILL_ACTIVE (259) as an error code (STILL_ACTIVE is a macro for + // STATUS_PENDING (minwinbase.h)). If a thread returns STILL_ACTIVE (259) as + // an error code, then applications that test for that value could interpret it + // to mean that the thread is still running, and continue to test for the + // completion of the thread after the thread has terminated, which could put + // the application into an infinite loop. + return c == uint32(windows.STATUS_PENDING) + } + return true +} + +// Kill force-stops a process. +func Kill(pid int) error { + p, err := os.FindProcess(pid) + if err == nil { + err = p.Kill() + if err != nil && err != os.ErrProcessDone { + return err + } + } + return nil +} + +// Zombie is not supported on Windows. +// +// TODO(thaJeztah): remove once we remove the stubs from pkg/system. +func Zombie(_ int) (bool, error) { + return false, nil +} diff --git a/vendor/github.com/docker/docker/pkg/stringid/README.md b/vendor/github.com/docker/docker/pkg/stringid/README.md deleted file mode 100644 index 37a5098fd9..0000000000 --- a/vendor/github.com/docker/docker/pkg/stringid/README.md +++ /dev/null @@ -1 +0,0 @@ -This package provides helper functions for dealing with string identifiers diff --git a/vendor/github.com/docker/docker/pkg/stringid/stringid.go b/vendor/github.com/docker/docker/pkg/stringid/stringid.go index 5fe071d628..d3d1014acf 100644 --- a/vendor/github.com/docker/docker/pkg/stringid/stringid.go +++ b/vendor/github.com/docker/docker/pkg/stringid/stringid.go @@ -4,21 +4,28 @@ package stringid // import "github.com/docker/docker/pkg/stringid" import ( "crypto/rand" "encoding/hex" - "fmt" + "errors" "regexp" "strconv" "strings" ) -const shortLen = 12 +const ( + shortLen = 12 + fullLen = 64 +) var ( validShortID = regexp.MustCompile("^[a-f0-9]{12}$") validHex = regexp.MustCompile(`^[a-f0-9]{64}$`) ) -// IsShortID determines if an arbitrary string *looks like* a short ID. +// IsShortID determines if id has the correct format and length for a short ID. +// It checks the IDs length and if it consists of valid characters for IDs (a-f0-9). func IsShortID(id string) bool { + if len(id) != shortLen { + return false + } return validShortID.MatchString(id) } @@ -54,10 +61,13 @@ func GenerateRandomID() string { } } -// ValidateID checks whether an ID string is a valid image ID. +// ValidateID checks whether an ID string is a valid, full-length image ID. func ValidateID(id string) error { - if ok := validHex.MatchString(id); !ok { - return fmt.Errorf("image ID %q is invalid", id) + if len(id) != fullLen { + return errors.New("image ID '" + id + "' is invalid") + } + if !validHex.MatchString(id) { + return errors.New("image ID '" + id + "' is invalid") } return nil } diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes.go b/vendor/github.com/docker/docker/pkg/system/chtimes.go index c26a4e24b6..6a6bca43ed 100644 --- a/vendor/github.com/docker/docker/pkg/system/chtimes.go +++ b/vendor/github.com/docker/docker/pkg/system/chtimes.go @@ -2,24 +2,41 @@ package system // import "github.com/docker/docker/pkg/system" import ( "os" + "syscall" "time" + "unsafe" ) -// Chtimes changes the access time and modified time of a file at the given path -func Chtimes(name string, atime time.Time, mtime time.Time) error { - unixMinTime := time.Unix(0, 0) - unixMaxTime := maxTime +// Used by Chtimes +var unixEpochTime, unixMaxTime time.Time - // If the modified time is prior to the Unix Epoch, or after the - // end of Unix Time, os.Chtimes has undefined behavior - // default to Unix Epoch in this case, just in case +func init() { + unixEpochTime = time.Unix(0, 0) + if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 { + // This is a 64 bit timespec + // os.Chtimes limits time to the following + // + // Note that this intentionally sets nsec (not sec), which sets both sec + // and nsec internally in time.Unix(); + // https://github.com/golang/go/blob/go1.19.2/src/time/time.go#L1364-L1380 + unixMaxTime = time.Unix(0, 1<<63-1) + } else { + // This is a 32 bit timespec + unixMaxTime = time.Unix(1<<31-1, 0) + } +} - if atime.Before(unixMinTime) || atime.After(unixMaxTime) { - atime = unixMinTime +// Chtimes changes the access time and modified time of a file at the given path. +// If the modified time is prior to the Unix Epoch (unixMinTime), or after the +// end of Unix Time (unixEpochTime), os.Chtimes has undefined behavior. In this +// case, Chtimes defaults to Unix Epoch, just in case. +func Chtimes(name string, atime time.Time, mtime time.Time) error { + if atime.Before(unixEpochTime) || atime.After(unixMaxTime) { + atime = unixEpochTime } - if mtime.Before(unixMinTime) || mtime.After(unixMaxTime) { - mtime = unixMinTime + if mtime.Before(unixEpochTime) || mtime.After(unixMaxTime) { + mtime = unixEpochTime } if err := os.Chtimes(name, atime, mtime); err != nil { diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go b/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go index 6664b8bcad..ab478f5c38 100644 --- a/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go +++ b/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go @@ -9,18 +9,17 @@ import ( // setCTime will set the create time on a file. On Windows, this requires // calling SetFileTime and explicitly including the create time. func setCTime(path string, ctime time.Time) error { - ctimespec := windows.NsecToTimespec(ctime.UnixNano()) - pathp, e := windows.UTF16PtrFromString(path) - if e != nil { - return e + pathp, err := windows.UTF16PtrFromString(path) + if err != nil { + return err } - h, e := windows.CreateFile(pathp, + h, err := windows.CreateFile(pathp, windows.FILE_WRITE_ATTRIBUTES, windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0) - if e != nil { - return e + if err != nil { + return err } defer windows.Close(h) - c := windows.NsecToFiletime(windows.TimespecToNsec(ctimespec)) + c := windows.NsecToFiletime(ctime.UnixNano()) return windows.SetFileTime(h, &c, nil, nil) } diff --git a/vendor/github.com/docker/docker/pkg/system/filesys_deprecated.go b/vendor/github.com/docker/docker/pkg/system/filesys_deprecated.go deleted file mode 100644 index b2ee006314..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/filesys_deprecated.go +++ /dev/null @@ -1,35 +0,0 @@ -package system - -import ( - "os" - - "github.com/moby/sys/sequential" -) - -// CreateSequential is deprecated. -// -// Deprecated: use os.Create or github.com/moby/sys/sequential.Create() -func CreateSequential(name string) (*os.File, error) { - return sequential.Create(name) -} - -// OpenSequential is deprecated. -// -// Deprecated: use os.Open or github.com/moby/sys/sequential.Open -func OpenSequential(name string) (*os.File, error) { - return sequential.Open(name) -} - -// OpenFileSequential is deprecated. -// -// Deprecated: use github.com/moby/sys/sequential.OpenFile() -func OpenFileSequential(name string, flag int, perm os.FileMode) (*os.File, error) { - return sequential.OpenFile(name, flag, perm) -} - -// TempFileSequential is deprecated. -// -// Deprecated: use os.CreateTemp or github.com/moby/sys/sequential.CreateTemp -func TempFileSequential(dir, prefix string) (f *os.File, err error) { - return sequential.CreateTemp(dir, prefix) -} diff --git a/vendor/github.com/docker/docker/pkg/system/filesys_windows.go b/vendor/github.com/docker/docker/pkg/system/filesys_windows.go index e3fa9f731c..92e972ea2e 100644 --- a/vendor/github.com/docker/docker/pkg/system/filesys_windows.go +++ b/vendor/github.com/docker/docker/pkg/system/filesys_windows.go @@ -9,28 +9,36 @@ import ( "golang.org/x/sys/windows" ) -const ( - // SddlAdministratorsLocalSystem is local administrators plus NT AUTHORITY\System - SddlAdministratorsLocalSystem = "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)" -) +// SddlAdministratorsLocalSystem is local administrators plus NT AUTHORITY\System. +const SddlAdministratorsLocalSystem = "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)" + +// volumePath is a regular expression to check if a path is a Windows +// volume path (e.g., "\\?\Volume{4c1b02c1-d990-11dc-99ae-806e6f6e6963}" +// or "\\?\Volume{4c1b02c1-d990-11dc-99ae-806e6f6e6963}\"). +var volumePath = regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}\\?$`) -// MkdirAllWithACL is a wrapper for MkdirAll that creates a directory -// with an appropriate SDDL defined ACL. -func MkdirAllWithACL(path string, perm os.FileMode, sddl string) error { - return mkdirall(path, true, sddl) +// MkdirAllWithACL is a custom version of os.MkdirAll modified for use on Windows +// so that it is both volume path aware, and can create a directory with +// an appropriate SDDL defined ACL. +func MkdirAllWithACL(path string, _ os.FileMode, sddl string) error { + sa, err := makeSecurityAttributes(sddl) + if err != nil { + return &os.PathError{Op: "mkdirall", Path: path, Err: err} + } + return mkdirall(path, sa) } -// MkdirAll implementation that is volume path aware for Windows. It can be used -// as a drop-in replacement for os.MkdirAll() +// MkdirAll is a custom version of os.MkdirAll that is volume path aware for +// Windows. It can be used as a drop-in replacement for os.MkdirAll. func MkdirAll(path string, _ os.FileMode) error { - return mkdirall(path, false, "") + return mkdirall(path, nil) } // mkdirall is a custom version of os.MkdirAll modified for use on Windows // so that it is both volume path aware, and can create a directory with // a DACL. -func mkdirall(path string, applyACL bool, sddl string) error { - if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) { +func mkdirall(path string, perm *windows.SecurityAttributes) error { + if volumePath.MatchString(path) { return nil } @@ -43,11 +51,7 @@ func mkdirall(path string, applyACL bool, sddl string) error { if dir.IsDir() { return nil } - return &os.PathError{ - Op: "mkdir", - Path: path, - Err: syscall.ENOTDIR, - } + return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} } // Slow path: make sure parent exists and then call Mkdir for path. @@ -62,20 +66,15 @@ func mkdirall(path string, applyACL bool, sddl string) error { } if j > 1 { - // Create parent - err = mkdirall(path[0:j-1], false, sddl) + // Create parent. + err = mkdirall(fixRootDirectory(path[:j-1]), perm) if err != nil { return err } } - // Parent now exists; invoke os.Mkdir or mkdirWithACL and use its result. - if applyACL { - err = mkdirWithACL(path, sddl) - } else { - err = os.Mkdir(path, 0) - } - + // Parent now exists; invoke Mkdir and use its result. + err = mkdirWithACL(path, perm) if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. @@ -95,24 +94,42 @@ func mkdirall(path string, applyACL bool, sddl string) error { // in golang to cater for creating a directory am ACL permitting full // access, with inheritance, to any subfolder/file for Built-in Administrators // and Local System. -func mkdirWithACL(name string, sddl string) error { - sa := windows.SecurityAttributes{Length: 0} - sd, err := windows.SecurityDescriptorFromString(sddl) - if err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} +func mkdirWithACL(name string, sa *windows.SecurityAttributes) error { + if sa == nil { + return os.Mkdir(name, 0) } - sa.Length = uint32(unsafe.Sizeof(sa)) - sa.InheritHandle = 1 - sa.SecurityDescriptor = sd namep, err := windows.UTF16PtrFromString(name) if err != nil { return &os.PathError{Op: "mkdir", Path: name, Err: err} } - e := windows.CreateDirectory(namep, &sa) - if e != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: e} + err = windows.CreateDirectory(namep, sa) + if err != nil { + return &os.PathError{Op: "mkdir", Path: name, Err: err} } return nil } + +// fixRootDirectory fixes a reference to a drive's root directory to +// have the required trailing slash. +func fixRootDirectory(p string) string { + if len(p) == len(`\\?\c:`) { + if os.IsPathSeparator(p[0]) && os.IsPathSeparator(p[1]) && p[2] == '?' && os.IsPathSeparator(p[3]) && p[5] == ':' { + return p + `\` + } + } + return p +} + +func makeSecurityAttributes(sddl string) (*windows.SecurityAttributes, error) { + var sa windows.SecurityAttributes + sa.Length = uint32(unsafe.Sizeof(sa)) + sa.InheritHandle = 1 + var err error + sa.SecurityDescriptor, err = windows.SecurityDescriptorFromString(sddl) + if err != nil { + return nil, err + } + return &sa, nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/init.go b/vendor/github.com/docker/docker/pkg/system/init.go deleted file mode 100644 index a17597aaba..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/init.go +++ /dev/null @@ -1,22 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "syscall" - "time" - "unsafe" -) - -// Used by chtimes -var maxTime time.Time - -func init() { - // chtimes initialization - if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 { - // This is a 64 bit timespec - // os.Chtimes limits time to the following - maxTime = time.Unix(0, 1<<63-1) - } else { - // This is a 32 bit timespec - maxTime = time.Unix(1<<31-1, 0) - } -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo.go b/vendor/github.com/docker/docker/pkg/system/meminfo.go deleted file mode 100644 index 6667eb84dc..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo.go +++ /dev/null @@ -1,17 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -// MemInfo contains memory statistics of the host system. -type MemInfo struct { - // Total usable RAM (i.e. physical RAM minus a few reserved bits and the - // kernel binary code). - MemTotal int64 - - // Amount of free memory. - MemFree int64 - - // Total amount of swap space available. - SwapTotal int64 - - // Amount of swap space that is currently unused. - SwapFree int64 -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_deprecated.go b/vendor/github.com/docker/docker/pkg/system/meminfo_deprecated.go new file mode 100644 index 0000000000..216519923e --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/meminfo_deprecated.go @@ -0,0 +1,16 @@ +package system + +import "github.com/docker/docker/pkg/meminfo" + +// MemInfo contains memory statistics of the host system. +// +// Deprecated: use [meminfo.Memory]. +type MemInfo = meminfo.Memory + +// ReadMemInfo retrieves memory statistics of the host system and returns a +// MemInfo type. +// +// Deprecated: use [meminfo.Read]. +func ReadMemInfo() (*meminfo.Memory, error) { + return meminfo.Read() +} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go b/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go deleted file mode 100644 index 207ee58ee6..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build !linux && !windows -// +build !linux,!windows - -package system // import "github.com/docker/docker/pkg/system" - -// ReadMemInfo is not supported on platforms other than linux and windows. -func ReadMemInfo() (*MemInfo, error) { - return nil, ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/docker/pkg/system/path.go b/vendor/github.com/docker/docker/pkg/system/path.go deleted file mode 100644 index 818b20efee..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/path.go +++ /dev/null @@ -1,41 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -const defaultUnixPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - -// DefaultPathEnv is unix style list of directories to search for -// executables. Each directory is separated from the next by a colon -// ':' character . -// For Windows containers, an empty string is returned as the default -// path will be set by the container, and Docker has no context of what the -// default path should be. -func DefaultPathEnv(os string) string { - if os == "windows" { - return "" - } - return defaultUnixPathEnv -} - -// PathVerifier defines the subset of a PathDriver that CheckSystemDriveAndRemoveDriveLetter -// actually uses in order to avoid system depending on containerd/continuity. -type PathVerifier interface { - IsAbs(string) bool -} - -// CheckSystemDriveAndRemoveDriveLetter verifies that a path, if it includes a drive letter, -// is the system drive. -// On Linux: this is a no-op. -// On Windows: this does the following> -// CheckSystemDriveAndRemoveDriveLetter verifies and manipulates a Windows path. -// This is used, for example, when validating a user provided path in docker cp. -// If a drive letter is supplied, it must be the system drive. The drive letter -// is always removed. Also, it translates it to OS semantics (IOW / to \). We -// need the path in this syntax so that it can ultimately be concatenated with -// a Windows long-path which doesn't support drive-letters. Examples: -// C: --> Fail -// C:\ --> \ -// a --> a -// /a --> \a -// d:\ --> Fail -func CheckSystemDriveAndRemoveDriveLetter(path string, driver PathVerifier) (string, error) { - return checkSystemDriveAndRemoveDriveLetter(path, driver) -} diff --git a/vendor/github.com/docker/docker/pkg/system/path_deprecated.go b/vendor/github.com/docker/docker/pkg/system/path_deprecated.go new file mode 100644 index 0000000000..5c95026c3d --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/path_deprecated.go @@ -0,0 +1,18 @@ +package system + +const defaultUnixPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + +// DefaultPathEnv is unix style list of directories to search for +// executables. Each directory is separated from the next by a colon +// ':' character . +// For Windows containers, an empty string is returned as the default +// path will be set by the container, and Docker has no context of what the +// default path should be. +// +// Deprecated: use oci.DefaultPathEnv +func DefaultPathEnv(os string) string { + if os == "windows" { + return "" + } + return defaultUnixPathEnv +} diff --git a/vendor/github.com/docker/docker/pkg/system/path_unix.go b/vendor/github.com/docker/docker/pkg/system/path_unix.go deleted file mode 100644 index 197a37a219..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/path_unix.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build !windows -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -// GetLongPathName converts Windows short pathnames to full pathnames. -// For example C:\Users\ADMIN~1 --> C:\Users\Administrator. -// It is a no-op on non-Windows platforms -func GetLongPathName(path string) (string, error) { - return path, nil -} - -// checkSystemDriveAndRemoveDriveLetter is the non-Windows implementation -// of CheckSystemDriveAndRemoveDriveLetter -func checkSystemDriveAndRemoveDriveLetter(path string, driver PathVerifier) (string, error) { - return path, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/path_windows.go b/vendor/github.com/docker/docker/pkg/system/path_windows.go deleted file mode 100644 index 7d375b0ddc..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/path_windows.go +++ /dev/null @@ -1,48 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "fmt" - "path/filepath" - "strings" - - "golang.org/x/sys/windows" -) - -// GetLongPathName converts Windows short pathnames to full pathnames. -// For example C:\Users\ADMIN~1 --> C:\Users\Administrator. -// It is a no-op on non-Windows platforms -func GetLongPathName(path string) (string, error) { - // See https://groups.google.com/forum/#!topic/golang-dev/1tufzkruoTg - p, err := windows.UTF16FromString(path) - if err != nil { - return "", err - } - b := p // GetLongPathName says we can reuse buffer - n, err := windows.GetLongPathName(&p[0], &b[0], uint32(len(b))) - if err != nil { - return "", err - } - if n > uint32(len(b)) { - b = make([]uint16, n) - _, err = windows.GetLongPathName(&p[0], &b[0], uint32(len(b))) - if err != nil { - return "", err - } - } - return windows.UTF16ToString(b), nil -} - -// checkSystemDriveAndRemoveDriveLetter is the Windows implementation -// of CheckSystemDriveAndRemoveDriveLetter -func checkSystemDriveAndRemoveDriveLetter(path string, driver PathVerifier) (string, error) { - if len(path) == 2 && string(path[1]) == ":" { - return "", fmt.Errorf("No relative path specified in %q", path) - } - if !driver.IsAbs(path) || len(path) < 2 { - return filepath.FromSlash(path), nil - } - if string(path[1]) == ":" && !strings.EqualFold(string(path[0]), "c") { - return "", fmt.Errorf("The specified path is not on the system drive (C:)") - } - return filepath.FromSlash(path[2:]), nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/process_deprecated.go b/vendor/github.com/docker/docker/pkg/system/process_deprecated.go new file mode 100644 index 0000000000..7b9f19acd5 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/process_deprecated.go @@ -0,0 +1,27 @@ +//go:build linux || freebsd || darwin || windows +// +build linux freebsd darwin windows + +package system + +import "github.com/docker/docker/pkg/process" + +var ( + // IsProcessAlive returns true if process with a given pid is running. + // + // Deprecated: use [process.Alive]. + IsProcessAlive = process.Alive + + // IsProcessZombie return true if process has a state with "Z" + // + // Deprecated: use [process.Zombie]. + // + // TODO(thaJeztah): remove the Windows implementation in process once we remove this stub. + IsProcessZombie = process.Zombie +) + +// KillProcess force-stops a process. +// +// Deprecated: use [process.Kill]. +func KillProcess(pid int) { + _ = process.Kill(pid) +} diff --git a/vendor/github.com/docker/docker/pkg/system/process_unix.go b/vendor/github.com/docker/docker/pkg/system/process_unix.go deleted file mode 100644 index 1c2c6a3096..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/process_unix.go +++ /dev/null @@ -1,46 +0,0 @@ -//go:build linux || freebsd || darwin -// +build linux freebsd darwin - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "fmt" - "os" - "strings" - "syscall" - - "golang.org/x/sys/unix" -) - -// IsProcessAlive returns true if process with a given pid is running. -func IsProcessAlive(pid int) bool { - err := unix.Kill(pid, syscall.Signal(0)) - if err == nil || err == unix.EPERM { - return true - } - - return false -} - -// KillProcess force-stops a process. -func KillProcess(pid int) { - unix.Kill(pid, unix.SIGKILL) -} - -// IsProcessZombie return true if process has a state with "Z" -// http://man7.org/linux/man-pages/man5/proc.5.html -func IsProcessZombie(pid int) (bool, error) { - statPath := fmt.Sprintf("/proc/%d/stat", pid) - dataBytes, err := os.ReadFile(statPath) - if err != nil { - // TODO(thaJeztah) should we ignore os.IsNotExist() here? ("/proc//stat" will be gone if the process exited) - return false, err - } - data := string(dataBytes) - sdata := strings.SplitN(data, " ", 4) - if len(sdata) >= 3 && sdata[2] == "Z" { - return true, nil - } - - return false, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/process_windows.go b/vendor/github.com/docker/docker/pkg/system/process_windows.go deleted file mode 100644 index 09bdfa0ca0..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/process_windows.go +++ /dev/null @@ -1,18 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "os" - -// IsProcessAlive returns true if process with a given pid is running. -func IsProcessAlive(pid int) bool { - _, err := os.FindProcess(pid) - - return err == nil -} - -// KillProcess force-stops a process. -func KillProcess(pid int) { - p, err := os.FindProcess(pid) - if err == nil { - _ = p.Kill() - } -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_solaris.go b/vendor/github.com/docker/docker/pkg/system/stat_solaris.go deleted file mode 100644 index 6a51ccd642..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_solaris.go +++ /dev/null @@ -1,13 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: s.Mode, - uid: s.Uid, - gid: s.Gid, - rdev: s.Rdev, - mtim: s.Mtim}, nil -} diff --git a/vendor/github.com/docker/docker/registry/auth.go b/vendor/github.com/docker/docker/registry/auth.go index 38f41db221..dd75a49f38 100644 --- a/vendor/github.com/docker/docker/registry/auth.go +++ b/vendor/github.com/docker/docker/registry/auth.go @@ -9,7 +9,6 @@ import ( "github.com/docker/distribution/registry/client/auth" "github.com/docker/distribution/registry/client/auth/challenge" "github.com/docker/distribution/registry/client/transport" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/registry" "github.com/pkg/errors" "github.com/sirupsen/logrus" @@ -19,7 +18,7 @@ import ( const AuthClientID = "docker" type loginCredentialStore struct { - authConfig *types.AuthConfig + authConfig *registry.AuthConfig } func (lcs loginCredentialStore) Basic(*url.URL) (string, string) { @@ -35,12 +34,12 @@ func (lcs loginCredentialStore) SetRefreshToken(u *url.URL, service, token strin } type staticCredentialStore struct { - auth *types.AuthConfig + auth *registry.AuthConfig } // NewStaticCredentialStore returns a credential store // which always returns the same credential values. -func NewStaticCredentialStore(auth *types.AuthConfig) auth.CredentialStore { +func NewStaticCredentialStore(auth *registry.AuthConfig) auth.CredentialStore { return staticCredentialStore{ auth: auth, } @@ -66,7 +65,7 @@ func (scs staticCredentialStore) SetRefreshToken(*url.URL, string, string) { // loginV2 tries to login to the v2 registry server. The given registry // endpoint will be pinged to get authorization challenges. These challenges // will be used to authenticate against the registry to validate credentials. -func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent string) (string, string, error) { +func loginV2(authConfig *registry.AuthConfig, endpoint APIEndpoint, userAgent string) (string, string, error) { var ( endpointStr = strings.TrimRight(endpoint.URL.String(), "/") + "/v2/" modifiers = Headers(userAgent, nil) @@ -138,7 +137,7 @@ func ConvertToHostname(url string) string { } // ResolveAuthConfig matches an auth configuration to a server address or a URL -func ResolveAuthConfig(authConfigs map[string]types.AuthConfig, index *registry.IndexInfo) types.AuthConfig { +func ResolveAuthConfig(authConfigs map[string]registry.AuthConfig, index *registry.IndexInfo) registry.AuthConfig { configKey := GetAuthConfigKey(index) // First try the happy case if c, found := authConfigs[configKey]; found || index.Official { @@ -154,7 +153,7 @@ func ResolveAuthConfig(authConfigs map[string]types.AuthConfig, index *registry. } // When all else fails, return an empty auth config - return types.AuthConfig{} + return registry.AuthConfig{} } // PingResponseError is used when the response from a ping diff --git a/vendor/github.com/docker/docker/registry/config.go b/vendor/github.com/docker/docker/registry/config.go index 2766306ac2..88f0e64edb 100644 --- a/vendor/github.com/docker/docker/registry/config.go +++ b/vendor/github.com/docker/docker/registry/config.go @@ -328,8 +328,8 @@ func ValidateMirror(val string) (string, error) { if uri.Scheme != "http" && uri.Scheme != "https" { return "", invalidParamf("invalid mirror: unsupported scheme %q in %q", uri.Scheme, uri) } - if (uri.Path != "" && uri.Path != "/") || uri.RawQuery != "" || uri.Fragment != "" { - return "", invalidParamf("invalid mirror: path, query, or fragment at end of the URI %q", uri) + if uri.RawQuery != "" || uri.Fragment != "" { + return "", invalidParamf("invalid mirror: query or fragment at end of the URI %q", uri) } if uri.User != nil { // strip password from output diff --git a/vendor/github.com/docker/docker/registry/endpoint_v1.go b/vendor/github.com/docker/docker/registry/endpoint_v1.go index c7e930c8ad..56257dc799 100644 --- a/vendor/github.com/docker/docker/registry/endpoint_v1.go +++ b/vendor/github.com/docker/docker/registry/endpoint_v1.go @@ -35,13 +35,13 @@ type v1Endpoint struct { // newV1Endpoint parses the given address to return a registry endpoint. // TODO: remove. This is only used by search. -func newV1Endpoint(index *registry.IndexInfo, userAgent string, metaHeaders http.Header) (*v1Endpoint, error) { +func newV1Endpoint(index *registry.IndexInfo, headers http.Header) (*v1Endpoint, error) { tlsConfig, err := newTLSConfig(index.Name, index.Secure) if err != nil { return nil, err } - endpoint, err := newV1EndpointFromStr(GetAuthConfigKey(index), tlsConfig, userAgent, metaHeaders) + endpoint, err := newV1EndpointFromStr(GetAuthConfigKey(index), tlsConfig, headers) if err != nil { return nil, err } @@ -100,7 +100,7 @@ func trimV1Address(address string) (string, error) { return address, nil } -func newV1EndpointFromStr(address string, tlsConfig *tls.Config, userAgent string, metaHeaders http.Header) (*v1Endpoint, error) { +func newV1EndpointFromStr(address string, tlsConfig *tls.Config, headers http.Header) (*v1Endpoint, error) { if !strings.HasPrefix(address, "http://") && !strings.HasPrefix(address, "https://") { address = "https://" + address } @@ -121,7 +121,7 @@ func newV1EndpointFromStr(address string, tlsConfig *tls.Config, userAgent strin return &v1Endpoint{ IsSecure: tlsConfig == nil || !tlsConfig.InsecureSkipVerify, URL: uri, - client: httpClient(transport.NewTransport(tr, Headers(userAgent, metaHeaders)...)), + client: httpClient(transport.NewTransport(tr, Headers("", headers)...)), }, nil } diff --git a/vendor/github.com/docker/docker/registry/search.go b/vendor/github.com/docker/docker/registry/search.go new file mode 100644 index 0000000000..60b86ea228 --- /dev/null +++ b/vendor/github.com/docker/docker/registry/search.go @@ -0,0 +1,139 @@ +package registry // import "github.com/docker/docker/registry" + +import ( + "context" + "net/http" + "strconv" + "strings" + + "github.com/docker/docker/api/types/filters" + "github.com/docker/docker/api/types/registry" + "github.com/docker/docker/errdefs" + + "github.com/docker/distribution/registry/client/auth" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" +) + +var acceptedSearchFilterTags = map[string]bool{ + "is-automated": true, + "is-official": true, + "stars": true, +} + +// Search queries the public registry for repositories matching the specified +// search term and filters. +func (s *Service) Search(ctx context.Context, searchFilters filters.Args, term string, limit int, authConfig *registry.AuthConfig, headers map[string][]string) ([]registry.SearchResult, error) { + if err := searchFilters.Validate(acceptedSearchFilterTags); err != nil { + return nil, err + } + + isAutomated, err := searchFilters.GetBoolOrDefault("is-automated", false) + if err != nil { + return nil, err + } + isOfficial, err := searchFilters.GetBoolOrDefault("is-official", false) + if err != nil { + return nil, err + } + + hasStarFilter := 0 + if searchFilters.Contains("stars") { + hasStars := searchFilters.Get("stars") + for _, hasStar := range hasStars { + iHasStar, err := strconv.Atoi(hasStar) + if err != nil { + return nil, errdefs.InvalidParameter(errors.Wrapf(err, "invalid filter 'stars=%s'", hasStar)) + } + if iHasStar > hasStarFilter { + hasStarFilter = iHasStar + } + } + } + + unfilteredResult, err := s.searchUnfiltered(ctx, term, limit, authConfig, headers) + if err != nil { + return nil, err + } + + filteredResults := []registry.SearchResult{} + for _, result := range unfilteredResult.Results { + if searchFilters.Contains("is-automated") { + if isAutomated != result.IsAutomated { + continue + } + } + if searchFilters.Contains("is-official") { + if isOfficial != result.IsOfficial { + continue + } + } + if searchFilters.Contains("stars") { + if result.StarCount < hasStarFilter { + continue + } + } + filteredResults = append(filteredResults, result) + } + + return filteredResults, nil +} + +func (s *Service) searchUnfiltered(ctx context.Context, term string, limit int, authConfig *registry.AuthConfig, headers http.Header) (*registry.SearchResults, error) { + // TODO Use ctx when searching for repositories + if hasScheme(term) { + return nil, invalidParamf("invalid repository name: repository name (%s) should not have a scheme", term) + } + + indexName, remoteName := splitReposSearchTerm(term) + + // Search is a long-running operation, just lock s.config to avoid block others. + s.mu.RLock() + index, err := newIndexInfo(s.config, indexName) + s.mu.RUnlock() + + if err != nil { + return nil, err + } + if index.Official { + // If pull "library/foo", it's stored locally under "foo" + remoteName = strings.TrimPrefix(remoteName, "library/") + } + + endpoint, err := newV1Endpoint(index, headers) + if err != nil { + return nil, err + } + + var client *http.Client + if authConfig != nil && authConfig.IdentityToken != "" && authConfig.Username != "" { + creds := NewStaticCredentialStore(authConfig) + scopes := []auth.Scope{ + auth.RegistryScope{ + Name: "catalog", + Actions: []string{"search"}, + }, + } + + // TODO(thaJeztah); is there a reason not to include other headers here? (originally added in 19d48f0b8ba59eea9f2cac4ad1c7977712a6b7ac) + modifiers := Headers(headers.Get("User-Agent"), nil) + v2Client, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes) + if err != nil { + return nil, err + } + // Copy non transport http client features + v2Client.Timeout = endpoint.client.Timeout + v2Client.CheckRedirect = endpoint.client.CheckRedirect + v2Client.Jar = endpoint.client.Jar + + logrus.Debugf("using v2 client for search to %s", endpoint.URL) + client = v2Client + } else { + client = endpoint.client + if err := authorizeClient(client, authConfig, endpoint); err != nil { + return nil, err + } + } + + return newSession(client, endpoint).searchRepositories(remoteName, limit) +} diff --git a/vendor/github.com/docker/docker/registry/service.go b/vendor/github.com/docker/docker/registry/service.go index 25b116a279..b848065b3c 100644 --- a/vendor/github.com/docker/docker/registry/service.go +++ b/vendor/github.com/docker/docker/registry/service.go @@ -3,56 +3,40 @@ package registry // import "github.com/docker/docker/registry" import ( "context" "crypto/tls" - "net/http" "net/url" "strings" "sync" "github.com/docker/distribution/reference" - "github.com/docker/distribution/registry/client/auth" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/registry" "github.com/docker/docker/errdefs" "github.com/sirupsen/logrus" ) -// Service is the interface defining what a registry service should implement. -type Service interface { - Auth(ctx context.Context, authConfig *types.AuthConfig, userAgent string) (status, token string, err error) - LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) - LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) - ResolveRepository(name reference.Named) (*RepositoryInfo, error) - Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registry.SearchResults, error) - ServiceConfig() *registry.ServiceConfig - LoadAllowNondistributableArtifacts([]string) error - LoadMirrors([]string) error - LoadInsecureRegistries([]string) error -} - -// defaultService is a registry service. It tracks configuration data such as a list +// Service is a registry service. It tracks configuration data such as a list // of mirrors. -type defaultService struct { +type Service struct { config *serviceConfig mu sync.RWMutex } // NewService returns a new instance of defaultService ready to be // installed into an engine. -func NewService(options ServiceOptions) (Service, error) { +func NewService(options ServiceOptions) (*Service, error) { config, err := newServiceConfig(options) - return &defaultService{config: config}, err + return &Service{config: config}, err } // ServiceConfig returns a copy of the public registry service's configuration. -func (s *defaultService) ServiceConfig() *registry.ServiceConfig { +func (s *Service) ServiceConfig() *registry.ServiceConfig { s.mu.RLock() defer s.mu.RUnlock() return s.config.copy() } // LoadAllowNondistributableArtifacts loads allow-nondistributable-artifacts registries for Service. -func (s *defaultService) LoadAllowNondistributableArtifacts(registries []string) error { +func (s *Service) LoadAllowNondistributableArtifacts(registries []string) error { s.mu.Lock() defer s.mu.Unlock() @@ -60,7 +44,7 @@ func (s *defaultService) LoadAllowNondistributableArtifacts(registries []string) } // LoadMirrors loads registry mirrors for Service -func (s *defaultService) LoadMirrors(mirrors []string) error { +func (s *Service) LoadMirrors(mirrors []string) error { s.mu.Lock() defer s.mu.Unlock() @@ -68,7 +52,7 @@ func (s *defaultService) LoadMirrors(mirrors []string) error { } // LoadInsecureRegistries loads insecure registries for Service -func (s *defaultService) LoadInsecureRegistries(registries []string) error { +func (s *Service) LoadInsecureRegistries(registries []string) error { s.mu.Lock() defer s.mu.Unlock() @@ -78,7 +62,7 @@ func (s *defaultService) LoadInsecureRegistries(registries []string) error { // Auth contacts the public registry with the provided credentials, // and returns OK if authentication was successful. // It can be used to verify the validity of a client's credentials. -func (s *defaultService) Auth(ctx context.Context, authConfig *types.AuthConfig, userAgent string) (status, token string, err error) { +func (s *Service) Auth(ctx context.Context, authConfig *registry.AuthConfig, userAgent string) (status, token string, err error) { // TODO Use ctx when searching for repositories var registryHostName = IndexHostname @@ -129,69 +113,9 @@ func splitReposSearchTerm(reposName string) (string, string) { return nameParts[0], nameParts[1] } -// Search queries the public registry for images matching the specified -// search terms, and returns the results. -func (s *defaultService) Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registry.SearchResults, error) { - // TODO Use ctx when searching for repositories - if hasScheme(term) { - return nil, invalidParamf("invalid repository name: repository name (%s) should not have a scheme", term) - } - - indexName, remoteName := splitReposSearchTerm(term) - - // Search is a long-running operation, just lock s.config to avoid block others. - s.mu.RLock() - index, err := newIndexInfo(s.config, indexName) - s.mu.RUnlock() - - if err != nil { - return nil, err - } - if index.Official { - // If pull "library/foo", it's stored locally under "foo" - remoteName = strings.TrimPrefix(remoteName, "library/") - } - - endpoint, err := newV1Endpoint(index, userAgent, headers) - if err != nil { - return nil, err - } - - var client *http.Client - if authConfig != nil && authConfig.IdentityToken != "" && authConfig.Username != "" { - creds := NewStaticCredentialStore(authConfig) - scopes := []auth.Scope{ - auth.RegistryScope{ - Name: "catalog", - Actions: []string{"search"}, - }, - } - - modifiers := Headers(userAgent, nil) - v2Client, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes) - if err != nil { - return nil, err - } - // Copy non transport http client features - v2Client.Timeout = endpoint.client.Timeout - v2Client.CheckRedirect = endpoint.client.CheckRedirect - v2Client.Jar = endpoint.client.Jar - - logrus.Debugf("using v2 client for search to %s", endpoint.URL) - client = v2Client - } else { - client = endpoint.client - if err := authorizeClient(client, authConfig, endpoint); err != nil { - return nil, err - } - } - - return newSession(client, endpoint).searchRepositories(remoteName, limit) -} - // ResolveRepository splits a repository name into its components // and configuration of the associated registry. -func (s *defaultService) ResolveRepository(name reference.Named) (*RepositoryInfo, error) { +func (s *Service) ResolveRepository(name reference.Named) (*RepositoryInfo, error) { s.mu.RLock() defer s.mu.RUnlock() return newRepositoryInfo(s.config, name) @@ -210,7 +134,7 @@ type APIEndpoint struct { // LookupPullEndpoints creates a list of v2 endpoints to try to pull from, in order of preference. // It gives preference to mirrors over the actual registry, and HTTPS over plain HTTP. -func (s *defaultService) LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) { +func (s *Service) LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) { s.mu.RLock() defer s.mu.RUnlock() @@ -219,7 +143,7 @@ func (s *defaultService) LookupPullEndpoints(hostname string) (endpoints []APIEn // LookupPushEndpoints creates a list of v2 endpoints to try to push to, in order of preference. // It gives preference to HTTPS over plain HTTP. Mirrors are not included. -func (s *defaultService) LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) { +func (s *Service) LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) { s.mu.RLock() defer s.mu.RUnlock() @@ -233,3 +157,11 @@ func (s *defaultService) LookupPushEndpoints(hostname string) (endpoints []APIEn } return endpoints, err } + +// IsInsecureRegistry returns true if the registry at given host is configured as +// insecure registry. +func (s *Service) IsInsecureRegistry(host string) bool { + s.mu.RLock() + defer s.mu.RUnlock() + return !s.config.isSecureIndex(host) +} diff --git a/vendor/github.com/docker/docker/registry/service_v2.go b/vendor/github.com/docker/docker/registry/service_v2.go index d4352583fa..c8c545d21f 100644 --- a/vendor/github.com/docker/docker/registry/service_v2.go +++ b/vendor/github.com/docker/docker/registry/service_v2.go @@ -7,7 +7,7 @@ import ( "github.com/docker/go-connections/tlsconfig" ) -func (s *defaultService) lookupV2Endpoints(hostname string) (endpoints []APIEndpoint, err error) { +func (s *Service) lookupV2Endpoints(hostname string) (endpoints []APIEndpoint, err error) { ana := s.config.allowNondistributableArtifacts(hostname) if hostname == DefaultNamespace || hostname == IndexHostname { diff --git a/vendor/github.com/docker/docker/registry/session.go b/vendor/github.com/docker/docker/registry/session.go index 6418e2d6b2..86a5cd9edf 100644 --- a/vendor/github.com/docker/docker/registry/session.go +++ b/vendor/github.com/docker/docker/registry/session.go @@ -11,7 +11,6 @@ import ( "strings" "sync" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/registry" "github.com/docker/docker/errdefs" "github.com/docker/docker/pkg/ioutils" @@ -28,7 +27,7 @@ type session struct { type authTransport struct { http.RoundTripper - *types.AuthConfig + *registry.AuthConfig alwaysSetBasicAuth bool token []string @@ -50,7 +49,7 @@ type authTransport struct { // If the server sends a token without the client having requested it, it is ignored. // // This RoundTripper also has a CancelRequest method important for correct timeout handling. -func newAuthTransport(base http.RoundTripper, authConfig *types.AuthConfig, alwaysSetBasicAuth bool) *authTransport { +func newAuthTransport(base http.RoundTripper, authConfig *registry.AuthConfig, alwaysSetBasicAuth bool) *authTransport { if base == nil { base = http.DefaultTransport } @@ -145,7 +144,7 @@ func (tr *authTransport) CancelRequest(req *http.Request) { } } -func authorizeClient(client *http.Client, authConfig *types.AuthConfig, endpoint *v1Endpoint) error { +func authorizeClient(client *http.Client, authConfig *registry.AuthConfig, endpoint *v1Endpoint) error { var alwaysSetBasicAuth bool // If we're working with a standalone private registry over HTTPS, send Basic Auth headers @@ -207,10 +206,10 @@ func (r *session) searchRepositories(term string, limit int) (*registry.SearchRe } defer res.Body.Close() if res.StatusCode != http.StatusOK { - return nil, &jsonmessage.JSONError{ + return nil, errdefs.Unknown(&jsonmessage.JSONError{ Message: fmt.Sprintf("Unexpected status code %d", res.StatusCode), Code: res.StatusCode, - } + }) } result := new(registry.SearchResults) return result, errors.Wrap(json.NewDecoder(res.Body).Decode(result), "error decoding registry search results") diff --git a/vendor/modules.txt b/vendor/modules.txt index 413f415bb8..cb9195b992 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -120,7 +120,7 @@ github.com/docker/distribution/registry/client/auth/challenge github.com/docker/distribution/registry/client/transport github.com/docker/distribution/registry/storage/cache github.com/docker/distribution/registry/storage/cache/memory -# github.com/docker/docker v23.0.0-rc.1+incompatible +# github.com/docker/docker v24.0.9+incompatible ## explicit github.com/docker/docker/api github.com/docker/docker/api/types @@ -147,7 +147,9 @@ github.com/docker/docker/pkg/idtools github.com/docker/docker/pkg/ioutils github.com/docker/docker/pkg/jsonmessage github.com/docker/docker/pkg/longpath +github.com/docker/docker/pkg/meminfo github.com/docker/docker/pkg/pools +github.com/docker/docker/pkg/process github.com/docker/docker/pkg/progress github.com/docker/docker/pkg/streamformatter github.com/docker/docker/pkg/stringid