diff --git a/build/build.go b/build/build.go index 8e47f2fd551f..993b8a1d9f7d 100644 --- a/build/build.go +++ b/build/build.go @@ -26,7 +26,7 @@ import ( "github.com/docker/buildx/util/resolver" "github.com/docker/buildx/util/waitmap" "github.com/docker/cli/opts" - imagetypes "github.com/docker/docker/api/types/image" + "github.com/docker/docker/api/types/image" "github.com/docker/docker/pkg/jsonmessage" "github.com/moby/buildkit/client" "github.com/moby/buildkit/client/llb" @@ -666,7 +666,7 @@ func pushWithMoby(ctx context.Context, d *driver.DriverHandle, name string, l pr return err } - rc, err := api.ImagePush(ctx, name, imagetypes.PushOptions{ + rc, err := api.ImagePush(ctx, name, image.PushOptions{ RegistryAuth: creds, }) if err != nil { @@ -745,11 +745,11 @@ func remoteDigestWithMoby(ctx context.Context, d *driver.DriverHandle, name stri if err != nil { return "", err } - image, _, err := api.ImageInspectWithRaw(ctx, name) + img, _, err := api.ImageInspectWithRaw(ctx, name) if err != nil { return "", err } - if len(image.RepoDigests) == 0 { + if len(img.RepoDigests) == 0 { return "", nil } remoteImage, err := api.DistributionInspect(ctx, name, creds) diff --git a/controller/build/build.go b/controller/build/build.go index 99aefdc5c5cb..917c562c277d 100644 --- a/controller/build/build.go +++ b/controller/build/build.go @@ -21,7 +21,7 @@ import ( "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/config" dockeropts "github.com/docker/cli/opts" - "github.com/docker/go-units" + "github.com/docker/docker/api/types/container" "github.com/moby/buildkit/client" "github.com/moby/buildkit/session/auth/authprovider" "github.com/moby/buildkit/util/grpcerrors" @@ -270,9 +270,9 @@ func controllerUlimitOpt2DockerUlimit(u *controllerapi.UlimitOpt) *dockeropts.Ul if u == nil { return nil } - values := make(map[string]*units.Ulimit) + values := make(map[string]*container.Ulimit) for k, v := range u.Values { - values[k] = &units.Ulimit{ + values[k] = &container.Ulimit{ Name: v.Name, Hard: v.Hard, Soft: v.Soft, diff --git a/driver/docker-container/driver.go b/driver/docker-container/driver.go index 14248817fc50..2eede55bb77a 100644 --- a/driver/docker-container/driver.go +++ b/driver/docker-container/driver.go @@ -18,9 +18,8 @@ import ( "github.com/docker/buildx/util/imagetools" "github.com/docker/buildx/util/progress" "github.com/docker/cli/opts" - dockertypes "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" - imagetypes "github.com/docker/docker/api/types/image" + "github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/system" @@ -96,7 +95,7 @@ func (d *Driver) create(ctx context.Context, l progress.SubLogger) error { if err != nil { return err } - rc, err := d.DockerAPI.ImageCreate(ctx, imageName, imagetypes.CreateOptions{ + rc, err := d.DockerAPI.ImageCreate(ctx, imageName, image.CreateOptions{ RegistryAuth: ra, }) if err != nil { @@ -256,17 +255,16 @@ func (d *Driver) copyToContainer(ctx context.Context, files map[string][]byte) e defer srcArchive.Close() baseDir := path.Dir(confutil.DefaultBuildKitConfigDir) - return d.DockerAPI.CopyToContainer(ctx, d.Name, baseDir, srcArchive, dockertypes.CopyToContainerOptions{}) + return d.DockerAPI.CopyToContainer(ctx, d.Name, baseDir, srcArchive, container.CopyToContainerOptions{}) } func (d *Driver) exec(ctx context.Context, cmd []string) (string, net.Conn, error) { - execConfig := dockertypes.ExecConfig{ + response, err := d.DockerAPI.ContainerExecCreate(ctx, d.Name, container.ExecOptions{ Cmd: cmd, AttachStdin: true, AttachStdout: true, AttachStderr: true, - } - response, err := d.DockerAPI.ContainerExecCreate(ctx, d.Name, execConfig) + }) if err != nil { return "", nil, err } @@ -276,7 +274,7 @@ func (d *Driver) exec(ctx context.Context, cmd []string) (string, net.Conn, erro return "", nil, errors.New("exec ID empty") } - resp, err := d.DockerAPI.ContainerExecAttach(ctx, execID, dockertypes.ExecStartCheck{}) + resp, err := d.DockerAPI.ContainerExecAttach(ctx, execID, container.ExecStartOptions{}) if err != nil { return "", nil, err } diff --git a/go.mod b/go.mod index 23c9b5cc6999..808a1a6f4081 100644 --- a/go.mod +++ b/go.mod @@ -15,9 +15,9 @@ require ( github.com/containerd/typeurl/v2 v2.1.1 github.com/creack/pty v1.1.21 github.com/distribution/reference v0.6.0 - github.com/docker/cli v26.1.4+incompatible + github.com/docker/cli v27.0.1+incompatible // master (v27.0-dev) github.com/docker/cli-docs-tool v0.7.0 - github.com/docker/docker v26.1.4+incompatible + github.com/docker/docker v27.0.1+incompatible // master (v27.0-dev) github.com/docker/go-units v0.5.0 github.com/gofrs/flock v0.8.1 github.com/gogo/protobuf v1.3.2 @@ -27,7 +27,7 @@ require ( github.com/hashicorp/go-cty-funcs v0.0.0-20230405223818-a090f58aa992 github.com/hashicorp/hcl/v2 v2.20.1 github.com/in-toto/in-toto-golang v0.5.0 - github.com/moby/buildkit v0.14.1 + github.com/moby/buildkit v0.14.1-0.20240625190127-aaaf86e5470b // master (v0.15-dev) github.com/moby/sys/mountinfo v0.7.1 github.com/moby/sys/signal v0.7.0 github.com/morikuni/aec v1.0.0 @@ -139,6 +139,7 @@ require ( github.com/secure-systems-lab/go-securesystemslib v0.4.0 // indirect github.com/shibumi/go-pathspec v1.3.0 // indirect github.com/theupdateframework/notary v0.7.0 // indirect + github.com/tonistiigi/go-csvvalue v0.0.0-20240619222358-bb8dd5cba3c2 // indirect github.com/tonistiigi/units v0.0.0-20180711220420-6950e57a87ea // indirect github.com/tonistiigi/vt100 v0.0.0-20240514184818-90bafcd6abab // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect diff --git a/go.sum b/go.sum index 7f891c8e6e07..262d825ed091 100644 --- a/go.sum +++ b/go.sum @@ -119,15 +119,15 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/denisenkom/go-mssqldb v0.0.0-20191128021309-1d7a30a10f73/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= -github.com/docker/cli v26.1.4+incompatible h1:I8PHdc0MtxEADqYJZvhBrW9bo8gawKwwenxRM7/rLu8= -github.com/docker/cli v26.1.4+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/cli v27.0.1+incompatible h1:d/OrlblkOTkhJ1IaAGD1bLgUBtFQC/oP0VjkFMIN+B0= +github.com/docker/cli v27.0.1+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/cli-docs-tool v0.7.0 h1:M2Da98Unz2kz3A5d4yeSGbhyOge2mfYSNjAFt01Rw0M= github.com/docker/cli-docs-tool v0.7.0/go.mod h1:zMjqTFCU361PRh8apiXzeAZ1Q/xupbIwTusYpzCXS/o= github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= 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 v26.1.4+incompatible h1:vuTpXDuoga+Z38m1OZHzl7NKisKWaWlhjQk7IDPSLsU= -github.com/docker/docker v26.1.4+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker v27.0.1+incompatible h1:AbszR+lCnR3f297p/g0arbQoyhAkImxQOR/XO9YZeIg= +github.com/docker/docker v27.0.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/docker-credential-helpers v0.8.2 h1:bX3YxiGzFP5sOXWc3bTPEXdEaZSeVMrFgOr3T+zrFAo= github.com/docker/docker-credential-helpers v0.8.2/go.mod h1:P3ci7E3lwkZg6XiHdRKft1KckHiO9a2rNtyFbZ/ry9M= github.com/docker/go v1.5.1-1.0.20160303222718-d30aec9fd63c h1:lzqkGL9b3znc+ZUgi7FlLnqjQhcXxkNM/quxIjBVMD0= @@ -298,8 +298,8 @@ github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZX github.com/mitchellh/mapstructure v0.0.0-20150613213606-2caf8efc9366/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/moby/buildkit v0.14.1 h1:2epLCZTkn4CikdImtsLtIa++7DzCimrrZCT1sway+oI= -github.com/moby/buildkit v0.14.1/go.mod h1:1XssG7cAqv5Bz1xcGMxJL123iCv5TYN4Z/qf647gfuk= +github.com/moby/buildkit v0.14.1-0.20240625190127-aaaf86e5470b h1:x1TdL3kMOFi3qdlAYBPVf4YzPD8fIZAjIjGfRycru8Q= +github.com/moby/buildkit v0.14.1-0.20240625190127-aaaf86e5470b/go.mod h1:ui4ZkNR6Z3kVMVqLY5JcoWcmlibi7TJL3bdzikvs5Yw= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= github.com/moby/locker v1.0.1 h1:fOXqR41zeveg4fFODix+1Ch4mj/gT0NE1XJbp/epuBg= @@ -348,8 +348,8 @@ github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3I github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug= github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM= -github.com/opencontainers/runtime-spec v1.1.0 h1:HHUyrt9mwHUjtasSbXSMvs4cyFxh+Bll4AjJ9odEGpg= -github.com/opencontainers/runtime-spec v1.1.0/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-spec v1.2.0 h1:z97+pHb3uELt/yiAWD691HNHQIF07bE7dzrbT927iTk= +github.com/opencontainers/runtime-spec v1.2.0/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/selinux v1.11.0 h1:+5Zbo97w3Lbmb3PeqQtpmTkMwsW5nRI3YaLpt7tQ7oU= github.com/opencontainers/selinux v1.11.0/go.mod h1:E5dMC3VPuVvVHDYmi78qvhJp8+M586T4DlDRYpFkyec= github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU= @@ -433,6 +433,8 @@ github.com/theupdateframework/notary v0.7.0 h1:QyagRZ7wlSpjT5N2qQAh/pN+DVqgekv4D github.com/theupdateframework/notary v0.7.0/go.mod h1:c9DRxcmhHmVLDay4/2fUYdISnHqbFDGRSlXPO0AhYWw= github.com/tonistiigi/fsutil v0.0.0-20240424095704-91a3fc46842c h1:+6wg/4ORAbnSoGDzg2Q1i3CeMcT/jjhye/ZfnBHy7/M= github.com/tonistiigi/fsutil v0.0.0-20240424095704-91a3fc46842c/go.mod h1:vbbYqJlnswsbJqWUcJN8fKtBhnEgldDrcagTgnBVKKM= +github.com/tonistiigi/go-csvvalue v0.0.0-20240619222358-bb8dd5cba3c2 h1:4dXTcm/McJMoXXFhqr+4rNL4WkLqMoHkdMhT4nU0Z28= +github.com/tonistiigi/go-csvvalue v0.0.0-20240619222358-bb8dd5cba3c2/go.mod h1:278M4p8WsNh3n4a1eqiFcV2FGk7wE5fwUpUom9mK9lE= github.com/tonistiigi/units v0.0.0-20180711220420-6950e57a87ea h1:SXhTLE6pb6eld/v/cCndK0AMpt1wiVFb/YYmqB3/QG0= github.com/tonistiigi/units v0.0.0-20180711220420-6950e57a87ea/go.mod h1:WPnis/6cRcDZSUvVmezrxJPkiO87ThFYsoUiMwWNDJk= github.com/tonistiigi/vt100 v0.0.0-20240514184818-90bafcd6abab h1:H6aJ0yKQ0gF49Qb2z5hI1UHxSQt4JMyxebFR15KnApw= diff --git a/vendor/github.com/docker/cli/AUTHORS b/vendor/github.com/docker/cli/AUTHORS index d6d23b3de3aa..ad1abd49642e 100644 --- a/vendor/github.com/docker/cli/AUTHORS +++ b/vendor/github.com/docker/cli/AUTHORS @@ -26,6 +26,7 @@ Akhil Mohan Akihiro Suda Akim Demaille Alan Thompson +Alano Terblanche Albert Callarisa Alberto Roura Albin Kerouanton @@ -65,6 +66,7 @@ Andrew Hsu Andrew Macpherson Andrew McDonnell Andrew Po +Andrew-Zipperer Andrey Petrov Andrii Berehuliak André Martins @@ -124,11 +126,13 @@ Bryan Bess Bryan Boreham Bryan Murphy bryfry +Calvin Liu Cameron Spear Cao Weiwei Carlo Mion Carlos Alexandro Becker Carlos de Paula +Casey Korver Ce Gao Cedric Davies Cezar Sa Espinola @@ -160,6 +164,8 @@ Christophe Vidal Christopher Biscardi Christopher Crone Christopher Jones +Christopher Petito <47751006+krissetto@users.noreply.github.com> +Christopher Petito Christopher Svensson Christy Norman Chun Chen @@ -212,6 +218,7 @@ David Cramer David Dooling David Gageot David Karlsson +David le Blanc David Lechner David Scott David Sheets @@ -298,6 +305,7 @@ Gang Qiao Gary Schaetz Genki Takiuchi George MacRorie +George Margaritis George Xie Gianluca Borello Gildas Cuisinier @@ -306,6 +314,7 @@ Gleb Stsenov Goksu Toprak Gou Rao Govind Rai +Grace Choi Graeme Wiebe Grant Reaber Greg Pflaum @@ -386,6 +395,7 @@ Jezeniel Zapanta Jian Zhang Jie Luo Jilles Oldenbeuving +Jim Chen Jim Galasyn Jim Lin Jimmy Leger @@ -416,6 +426,7 @@ John Willis Jon Johnson Jon Zeolla Jonatas Baldin +Jonathan A. Sternberg Jonathan Boulle Jonathan Lee Jonathan Lomas @@ -470,6 +481,7 @@ Kevin Woblick khaled souf Kim Eik Kir Kolyshkin +Kirill A. Korinsky Kotaro Yoshimatsu Krasi Georgiev Kris-Mikael Krister @@ -530,6 +542,7 @@ Marco Vedovati Marcus Martins Marianna Tessel Marius Ileana +Marius Meschter Marius Sturm Mark Oates Marsh Macy @@ -538,6 +551,7 @@ Mary Anthony Mason Fish Mason Malone Mateusz Major +Mathias Duedahl <64321057+Lussebullen@users.noreply.github.com> Mathieu Champlon Mathieu Rollet Matt Gucci @@ -547,6 +561,7 @@ Matthew Heon Matthieu Hauglustaine Mauro Porras P Max Shytikov +Max-Julian Pogner Maxime Petazzoni Maximillian Fan Xavier Mei ChunTao @@ -610,6 +625,7 @@ Nathan McCauley Neil Peterson Nick Adcock Nick Santos +Nick Sieger Nico Stapelbroek Nicola Kabar Nicolas Borboën @@ -704,6 +720,7 @@ Rory Hunter Ross Boucher Rubens Figueiredo Rui Cao +Rui JingAn Ryan Belgrave Ryan Detzel Ryan Stelly @@ -797,6 +814,7 @@ Tim Hockin Tim Sampson Tim Smith Tim Waugh +Tim Welsh Tim Wraight timfeirg Timothy Hobbs @@ -880,9 +898,11 @@ Zhang Wei Zhang Wentao ZhangHang zhenghenghuo +Zhiwei Liang Zhou Hao Zhoulin Xie Zhu Guihua +Zhuo Zhi Álex González Álvaro Lázaro Átila Camurça Alves diff --git a/vendor/github.com/docker/cli/NOTICE b/vendor/github.com/docker/cli/NOTICE index 58b19b6d15b9..1c40faaec612 100644 --- a/vendor/github.com/docker/cli/NOTICE +++ b/vendor/github.com/docker/cli/NOTICE @@ -14,6 +14,6 @@ United States and other governments. It is your responsibility to ensure that your use and/or transfer does not violate applicable laws. -For more information, please see https://www.bis.doc.gov +For more information, see https://www.bis.doc.gov See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/error.go b/vendor/github.com/docker/cli/cli-plugins/manager/error.go index f802da1c5c19..f7dc6c7c55cd 100644 --- a/vendor/github.com/docker/cli/cli-plugins/manager/error.go +++ b/vendor/github.com/docker/cli/cli-plugins/manager/error.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package manager diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/hooks.go b/vendor/github.com/docker/cli/cli-plugins/manager/hooks.go index 2e138b06d6f9..5125c56d06c2 100644 --- a/vendor/github.com/docker/cli/cli-plugins/manager/hooks.go +++ b/vendor/github.com/docker/cli/cli-plugins/manager/hooks.go @@ -1,6 +1,7 @@ package manager import ( + "context" "encoding/json" "strings" @@ -28,29 +29,36 @@ type HookPluginData struct { // a main CLI command was executed. It calls the hook subcommand for all // present CLI plugins that declare support for hooks in their metadata and // parses/prints their responses. -func RunCLICommandHooks(dockerCli command.Cli, rootCmd, subCommand *cobra.Command, cmdErrorMessage string) { +func RunCLICommandHooks(ctx context.Context, dockerCli command.Cli, rootCmd, subCommand *cobra.Command, cmdErrorMessage string) { commandName := strings.TrimPrefix(subCommand.CommandPath(), rootCmd.Name()+" ") flags := getCommandFlags(subCommand) - runHooks(dockerCli, rootCmd, subCommand, commandName, flags, cmdErrorMessage) + runHooks(ctx, dockerCli, rootCmd, subCommand, commandName, flags, cmdErrorMessage) } // RunPluginHooks is the entrypoint for the hooks execution flow // after a plugin command was just executed by the CLI. -func RunPluginHooks(dockerCli command.Cli, rootCmd, subCommand *cobra.Command, args []string) { +func RunPluginHooks(ctx context.Context, dockerCli command.Cli, rootCmd, subCommand *cobra.Command, args []string) { commandName := strings.Join(args, " ") flags := getNaiveFlags(args) - runHooks(dockerCli, rootCmd, subCommand, commandName, flags, "") + runHooks(ctx, dockerCli, rootCmd, subCommand, commandName, flags, "") } -func runHooks(dockerCli command.Cli, rootCmd, subCommand *cobra.Command, invokedCommand string, flags map[string]string, cmdErrorMessage string) { - nextSteps := invokeAndCollectHooks(dockerCli, rootCmd, subCommand, invokedCommand, flags, cmdErrorMessage) +func runHooks(ctx context.Context, dockerCli command.Cli, rootCmd, subCommand *cobra.Command, invokedCommand string, flags map[string]string, cmdErrorMessage string) { + nextSteps := invokeAndCollectHooks(ctx, dockerCli, rootCmd, subCommand, invokedCommand, flags, cmdErrorMessage) hooks.PrintNextSteps(dockerCli.Err(), nextSteps) } -func invokeAndCollectHooks(dockerCli command.Cli, rootCmd, subCmd *cobra.Command, subCmdStr string, flags map[string]string, cmdErrorMessage string) []string { +func invokeAndCollectHooks(ctx context.Context, dockerCli command.Cli, rootCmd, subCmd *cobra.Command, subCmdStr string, flags map[string]string, cmdErrorMessage string) []string { + // check if the context was cancelled before invoking hooks + select { + case <-ctx.Done(): + return nil + default: + } + pluginsCfg := dockerCli.ConfigFile().Plugins if pluginsCfg == nil { return nil @@ -68,7 +76,7 @@ func invokeAndCollectHooks(dockerCli command.Cli, rootCmd, subCmd *cobra.Command continue } - hookReturn, err := p.RunHook(HookPluginData{ + hookReturn, err := p.RunHook(ctx, HookPluginData{ RootCmd: match, Flags: flags, CommandError: cmdErrorMessage, diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/manager.go b/vendor/github.com/docker/cli/cli-plugins/manager/manager.go index 031b04f6bb49..9886830240bd 100644 --- a/vendor/github.com/docker/cli/cli-plugins/manager/manager.go +++ b/vendor/github.com/docker/cli/cli-plugins/manager/manager.go @@ -49,6 +49,16 @@ func IsNotFound(err error) bool { return ok } +// getPluginDirs returns the platform-specific locations to search for plugins +// in order of preference. +// +// Plugin-discovery is performed in the following order of preference: +// +// 1. The "cli-plugins" directory inside the CLIs [config.Path] (usually "~/.docker/cli-plugins"). +// 2. Additional plugin directories as configured through [ConfigFile.CLIPluginsExtraDirs]. +// 3. Platform-specific defaultSystemPluginDirs. +// +// [ConfigFile.CLIPluginsExtraDirs]: https://pkg.go.dev/github.com/docker/cli@v26.1.4+incompatible/cli/config/configfile#ConfigFile.CLIPluginsExtraDirs func getPluginDirs(cfg *configfile.ConfigFile) ([]string, error) { var pluginDirs []string diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/manager_unix.go b/vendor/github.com/docker/cli/cli-plugins/manager/manager_unix.go index 000c058df062..f546dc38496e 100644 --- a/vendor/github.com/docker/cli/cli-plugins/manager/manager_unix.go +++ b/vendor/github.com/docker/cli/cli-plugins/manager/manager_unix.go @@ -2,7 +2,19 @@ package manager +// defaultSystemPluginDirs are the platform-specific locations to search +// for plugins in order of preference. +// +// Plugin-discovery is performed in the following order of preference: +// +// 1. The "cli-plugins" directory inside the CLIs config-directory (usually "~/.docker/cli-plugins"). +// 2. Additional plugin directories as configured through [ConfigFile.CLIPluginsExtraDirs]. +// 3. Platform-specific defaultSystemPluginDirs (as defined below). +// +// [ConfigFile.CLIPluginsExtraDirs]: https://pkg.go.dev/github.com/docker/cli@v26.1.4+incompatible/cli/config/configfile#ConfigFile.CLIPluginsExtraDirs var defaultSystemPluginDirs = []string{ - "/usr/local/lib/docker/cli-plugins", "/usr/local/libexec/docker/cli-plugins", - "/usr/lib/docker/cli-plugins", "/usr/libexec/docker/cli-plugins", + "/usr/local/lib/docker/cli-plugins", + "/usr/local/libexec/docker/cli-plugins", + "/usr/lib/docker/cli-plugins", + "/usr/libexec/docker/cli-plugins", } diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/manager_windows.go b/vendor/github.com/docker/cli/cli-plugins/manager/manager_windows.go index 2ce5a759730e..e8b5598e5960 100644 --- a/vendor/github.com/docker/cli/cli-plugins/manager/manager_windows.go +++ b/vendor/github.com/docker/cli/cli-plugins/manager/manager_windows.go @@ -5,6 +5,16 @@ import ( "path/filepath" ) +// defaultSystemPluginDirs are the platform-specific locations to search +// for plugins in order of preference. +// +// Plugin-discovery is performed in the following order of preference: +// +// 1. The "cli-plugins" directory inside the CLIs config-directory (usually "~/.docker/cli-plugins"). +// 2. Additional plugin directories as configured through [ConfigFile.CLIPluginsExtraDirs]. +// 3. Platform-specific defaultSystemPluginDirs (as defined below). +// +// [ConfigFile.CLIPluginsExtraDirs]: https://pkg.go.dev/github.com/docker/cli@v26.1.4+incompatible/cli/config/configfile#ConfigFile.CLIPluginsExtraDirs var defaultSystemPluginDirs = []string{ filepath.Join(os.Getenv("ProgramData"), "Docker", "cli-plugins"), filepath.Join(os.Getenv("ProgramFiles"), "Docker", "cli-plugins"), diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/plugin.go b/vendor/github.com/docker/cli/cli-plugins/manager/plugin.go index 2cffafaccabb..877241e0b828 100644 --- a/vendor/github.com/docker/cli/cli-plugins/manager/plugin.go +++ b/vendor/github.com/docker/cli/cli-plugins/manager/plugin.go @@ -1,6 +1,7 @@ package manager import ( + "context" "encoding/json" "os" "os/exec" @@ -105,13 +106,13 @@ func newPlugin(c Candidate, cmds []*cobra.Command) (Plugin, error) { // RunHook executes the plugin's hooks command // and returns its unprocessed output. -func (p *Plugin) RunHook(hookData HookPluginData) ([]byte, error) { +func (p *Plugin) RunHook(ctx context.Context, hookData HookPluginData) ([]byte, error) { hDataBytes, err := json.Marshal(hookData) if err != nil { return nil, wrapAsPluginError(err, "failed to marshall hook data") } - pCmd := exec.Command(p.Path, p.Name, HookSubcommandName, string(hDataBytes)) + pCmd := exec.CommandContext(ctx, p.Path, p.Name, HookSubcommandName, string(hDataBytes)) pCmd.Env = os.Environ() pCmd.Env = append(pCmd.Env, ReexecEnvvar+"="+os.Args[0]) hookCmdOutput, err := pCmd.Output() diff --git a/vendor/github.com/docker/cli/cli-plugins/plugin/plugin.go b/vendor/github.com/docker/cli/cli-plugins/plugin/plugin.go index 05dd2e7c9afe..8cce73d9acda 100644 --- a/vendor/github.com/docker/cli/cli-plugins/plugin/plugin.go +++ b/vendor/github.com/docker/cli/cli-plugins/plugin/plugin.go @@ -36,13 +36,7 @@ func RunPlugin(dockerCli *command.DockerCli, plugin *cobra.Command, meta manager PersistentPreRunE = func(cmd *cobra.Command, _ []string) error { var err error persistentPreRunOnce.Do(func() { - cmdContext := cmd.Context() - // TODO: revisit and make sure this check makes sense - // see: https://github.com/docker/cli/pull/4599#discussion_r1422487271 - if cmdContext == nil { - cmdContext = context.TODO() - } - ctx, cancel := context.WithCancel(cmdContext) + ctx, cancel := context.WithCancel(cmd.Context()) cmd.SetContext(ctx) // Set up the context to cancel based on signalling via CLI socket. socket.ConnectAndWait(cancel) @@ -51,6 +45,7 @@ func RunPlugin(dockerCli *command.DockerCli, plugin *cobra.Command, meta manager if os.Getenv("DOCKER_CLI_PLUGIN_USE_DIAL_STDIO") != "" { opts = append(opts, withPluginClientConn(plugin.Name())) } + opts = append(opts, command.WithEnableGlobalMeterProvider(), command.WithEnableGlobalTracerProvider()) err = tcmd.Initialize(opts...) ogRunE := cmd.RunE if ogRunE == nil { diff --git a/vendor/github.com/docker/cli/cli-plugins/socket/socket.go b/vendor/github.com/docker/cli/cli-plugins/socket/socket.go index fc91e78d8fd3..7096b42b2e94 100644 --- a/vendor/github.com/docker/cli/cli-plugins/socket/socket.go +++ b/vendor/github.com/docker/cli/cli-plugins/socket/socket.go @@ -9,6 +9,8 @@ import ( "os" "runtime" "sync" + + "github.com/sirupsen/logrus" ) // EnvKey represents the well-known environment variable used to pass the @@ -30,6 +32,7 @@ func NewPluginServer(h func(net.Conn)) (*PluginServer, error) { if err != nil { return nil, err } + logrus.Trace("Plugin server listening on ", l.Addr()) if h == nil { h = func(net.Conn) {} @@ -92,6 +95,7 @@ func (pl *PluginServer) Addr() net.Addr { // // The error value is that of the underlying [net.Listner.Close] call. func (pl *PluginServer) Close() error { + logrus.Trace("Closing plugin server") // Close connections first to ensure the connections get io.EOF instead // of a connection reset. pl.closeAllConns() @@ -107,6 +111,10 @@ func (pl *PluginServer) closeAllConns() { pl.mu.Lock() defer pl.mu.Unlock() + if pl.closed { + return + } + // Prevent new connections from being accepted. pl.closed = true diff --git a/vendor/github.com/docker/cli/cli/cobra.go b/vendor/github.com/docker/cli/cli/cobra.go index d07a3b218a22..f6a69ae0701d 100644 --- a/vendor/github.com/docker/cli/cli/cobra.go +++ b/vendor/github.com/docker/cli/cli/cobra.go @@ -54,7 +54,7 @@ func setupCommonRootCommand(rootCmd *cobra.Command) (*cliflags.ClientOptions, *c rootCmd.SetHelpCommand(helpCommand) rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage") - rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help") + rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "use --help") rootCmd.PersistentFlags().Lookup("help").Hidden = true rootCmd.Annotations = map[string]string{ diff --git a/vendor/github.com/docker/cli/cli/command/cli.go b/vendor/github.com/docker/cli/cli/command/cli.go index 28253f8c16c1..06478c9c776e 100644 --- a/vendor/github.com/docker/cli/cli/command/cli.go +++ b/vendor/github.com/docker/cli/cli/command/cli.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package command @@ -44,7 +44,7 @@ const defaultInitTimeout = 2 * time.Second type Streams interface { In() *streams.In Out() *streams.Out - Err() io.Writer + Err() *streams.Out } // Cli represents the docker command line client. @@ -75,7 +75,7 @@ type DockerCli struct { options *cliflags.ClientOptions in *streams.In out *streams.Out - err io.Writer + err *streams.Out client client.APIClient serverInfo ServerInfo contentTrust bool @@ -92,6 +92,8 @@ type DockerCli struct { // this may be replaced by explicitly passing a context to functions that // need it. baseCtx context.Context + + enableGlobalMeter, enableGlobalTracer bool } // DefaultVersion returns api.defaultVersion. @@ -124,7 +126,7 @@ func (cli *DockerCli) Out() *streams.Out { } // Err returns the writer used for stderr -func (cli *DockerCli) Err() io.Writer { +func (cli *DockerCli) Err() *streams.Out { return cli.err } @@ -184,9 +186,18 @@ func (cli *DockerCli) BuildKitEnabled() (bool, error) { if _, ok := aliasMap["builder"]; ok { return true, nil } - // otherwise, assume BuildKit is enabled but - // not if wcow reported from server side - return cli.ServerInfo().OSType != "windows", nil + + si := cli.ServerInfo() + if si.BuildkitVersion == types.BuilderBuildKit { + // The daemon advertised BuildKit as the preferred builder; this may + // be either a Linux daemon or a Windows daemon with experimental + // BuildKit support enabled. + return true, nil + } + + // otherwise, assume BuildKit is enabled for Linux, but disabled for + // Windows / WCOW, which does not yet support BuildKit by default. + return si.OSType != "windows", nil } // HooksEnabled returns whether plugin hooks are enabled. @@ -275,8 +286,12 @@ func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions, ops ...CLIOption) } // TODO(krissetto): pass ctx to the funcs instead of using this - cli.createGlobalMeterProvider(cli.baseCtx) - cli.createGlobalTracerProvider(cli.baseCtx) + if cli.enableGlobalMeter { + cli.createGlobalMeterProvider(cli.baseCtx) + } + if cli.enableGlobalTracer { + cli.createGlobalTracerProvider(cli.baseCtx) + } return nil } @@ -315,7 +330,7 @@ func newAPIClientFromEndpoint(ep docker.Endpoint, configFile *configfile.ConfigF func resolveDockerEndpoint(s store.Reader, contextName string) (docker.Endpoint, error) { if s == nil { - return docker.Endpoint{}, fmt.Errorf("no context store initialized") + return docker.Endpoint{}, errors.New("no context store initialized") } ctxMeta, err := s.GetMetadata(contextName) if err != nil { @@ -546,7 +561,7 @@ func getServerHost(hosts []string, tlsOptions *tlsconfig.Options) (string, error case 1: host = hosts[0] default: - return "", errors.New("Please specify only one -H") + return "", errors.New("Specify only one -H") } return dopts.ParseHost(tlsOptions != nil, host) diff --git a/vendor/github.com/docker/cli/cli/command/cli_options.go b/vendor/github.com/docker/cli/cli/command/cli_options.go index 8e431bf8652e..eb2458768ce3 100644 --- a/vendor/github.com/docker/cli/cli/command/cli_options.go +++ b/vendor/github.com/docker/cli/cli/command/cli_options.go @@ -23,7 +23,7 @@ func WithStandardStreams() CLIOption { stdin, stdout, stderr := term.StdStreams() cli.in = streams.NewIn(stdin) cli.out = streams.NewOut(stdout) - cli.err = stderr + cli.err = streams.NewOut(stderr) return nil } } @@ -40,8 +40,9 @@ func WithBaseContext(ctx context.Context) CLIOption { // WithCombinedStreams uses the same stream for the output and error streams. func WithCombinedStreams(combined io.Writer) CLIOption { return func(cli *DockerCli) error { - cli.out = streams.NewOut(combined) - cli.err = combined + s := streams.NewOut(combined) + cli.out = s + cli.err = s return nil } } @@ -65,7 +66,7 @@ func WithOutputStream(out io.Writer) CLIOption { // WithErrorStream sets a cli error stream. func WithErrorStream(err io.Writer) CLIOption { return func(cli *DockerCli) error { - cli.err = err + cli.err = streams.NewOut(err) return nil } } diff --git a/vendor/github.com/docker/cli/cli/command/context.go b/vendor/github.com/docker/cli/cli/command/context.go index a82c8a7d6442..af2298bb5070 100644 --- a/vendor/github.com/docker/cli/cli/command/context.go +++ b/vendor/github.com/docker/cli/cli/command/context.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package command diff --git a/vendor/github.com/docker/cli/cli/command/defaultcontextstore.go b/vendor/github.com/docker/cli/cli/command/defaultcontextstore.go index 6783c54c93ce..2582257680c3 100644 --- a/vendor/github.com/docker/cli/cli/command/defaultcontextstore.go +++ b/vendor/github.com/docker/cli/cli/command/defaultcontextstore.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package command diff --git a/vendor/github.com/docker/cli/cli/command/events_utils.go b/vendor/github.com/docker/cli/cli/command/events_utils.go deleted file mode 100644 index bb656fbf90b7..000000000000 --- a/vendor/github.com/docker/cli/cli/command/events_utils.go +++ /dev/null @@ -1,51 +0,0 @@ -package command - -import ( - "sync" - - "github.com/docker/docker/api/types/events" - "github.com/sirupsen/logrus" -) - -// EventHandler is abstract interface for user to customize -// own handle functions of each type of events -// -// Deprecated: EventHandler is no longer used, and will be removed in the next release. -type EventHandler interface { - Handle(action events.Action, h func(events.Message)) - Watch(c <-chan events.Message) -} - -// InitEventHandler initializes and returns an EventHandler -// -// Deprecated: InitEventHandler is no longer used, and will be removed in the next release. -func InitEventHandler() EventHandler { - return &eventHandler{handlers: make(map[events.Action]func(events.Message))} -} - -type eventHandler struct { - handlers map[events.Action]func(events.Message) - mu sync.Mutex -} - -func (w *eventHandler) Handle(action events.Action, h func(events.Message)) { - w.mu.Lock() - w.handlers[action] = h - w.mu.Unlock() -} - -// Watch ranges over the passed in event chan and processes the events based on the -// handlers created for a given action. -// To stop watching, close the event chan. -func (w *eventHandler) Watch(c <-chan events.Message) { - for e := range c { - w.mu.Lock() - h, exists := w.handlers[e.Action] - w.mu.Unlock() - if !exists { - continue - } - logrus.Debugf("event handler: received event: %v", e) - go h(e) - } -} diff --git a/vendor/github.com/docker/cli/cli/command/formatter/container.go b/vendor/github.com/docker/cli/cli/command/formatter/container.go index 84765c73b4d2..aeaa03a6d3b1 100644 --- a/vendor/github.com/docker/cli/cli/command/formatter/container.go +++ b/vendor/github.com/docker/cli/cli/command/formatter/container.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package formatter diff --git a/vendor/github.com/docker/cli/cli/command/formatter/custom.go b/vendor/github.com/docker/cli/cli/command/formatter/custom.go index 2aec2d1d6229..ee7d14830e30 100644 --- a/vendor/github.com/docker/cli/cli/command/formatter/custom.go +++ b/vendor/github.com/docker/cli/cli/command/formatter/custom.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package formatter diff --git a/vendor/github.com/docker/cli/cli/command/formatter/formatter.go b/vendor/github.com/docker/cli/cli/command/formatter/formatter.go index fe64d9c1d621..4f1037725541 100644 --- a/vendor/github.com/docker/cli/cli/command/formatter/formatter.go +++ b/vendor/github.com/docker/cli/cli/command/formatter/formatter.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package formatter diff --git a/vendor/github.com/docker/cli/cli/command/formatter/reflect.go b/vendor/github.com/docker/cli/cli/command/formatter/reflect.go index 3181428aabb0..e2c0b28f53bd 100644 --- a/vendor/github.com/docker/cli/cli/command/formatter/reflect.go +++ b/vendor/github.com/docker/cli/cli/command/formatter/reflect.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package formatter diff --git a/vendor/github.com/docker/cli/cli/command/formatter/tabwriter/tabwriter.go b/vendor/github.com/docker/cli/cli/command/formatter/tabwriter/tabwriter.go index bc155298f6ff..1d908f58e990 100644 --- a/vendor/github.com/docker/cli/cli/command/formatter/tabwriter/tabwriter.go +++ b/vendor/github.com/docker/cli/cli/command/formatter/tabwriter/tabwriter.go @@ -106,7 +106,7 @@ type Writer struct { cell cell // current incomplete cell; cell.width is up to buf[pos] excluding ignored sections endChar byte // terminating char of escaped sequence (Escape for escapes, '>', ';' for HTML tags/entities, or 0) lines [][]cell // list of lines; each line is a list of cells - widths []int // list of column widths in runes - re-used during formatting + widths []int // list of column widths in runes - reused during formatting } // addLine adds a new line. @@ -115,7 +115,7 @@ type Writer struct { func (b *Writer) addLine(flushed bool) { // Grow slice instead of appending, // as that gives us an opportunity - // to re-use an existing []cell. + // to reuse an existing []cell. if n := len(b.lines) + 1; n <= cap(b.lines) { b.lines = b.lines[:n] b.lines[n-1] = b.lines[n-1][:0] @@ -159,7 +159,7 @@ func (b *Writer) reset() { // - the sizes and widths of processed text are kept in the lines list // which contains a list of cells for each line // - the widths list is a temporary list with current widths used during -// formatting; it is kept in Writer because it's re-used +// formatting; it is kept in Writer because it's reused // // |<---------- size ---------->| // | | diff --git a/vendor/github.com/docker/cli/cli/command/registry.go b/vendor/github.com/docker/cli/cli/command/registry.go index a1a499eee46a..ba97861a6b49 100644 --- a/vendor/github.com/docker/cli/cli/command/registry.go +++ b/vendor/github.com/docker/cli/cli/command/registry.go @@ -2,6 +2,7 @@ package command import ( "bufio" + "context" "fmt" "io" "os" @@ -10,6 +11,7 @@ import ( "github.com/distribution/reference" "github.com/docker/cli/cli/config/configfile" + "github.com/docker/cli/cli/config/credentials" configtypes "github.com/docker/cli/cli/config/types" "github.com/docker/cli/cli/hints" "github.com/docker/cli/cli/streams" @@ -27,14 +29,21 @@ const patSuggest = "You can log in with your password or a Personal Access " + // RegistryAuthenticationPrivilegedFunc returns a RequestPrivilegeFunc from the specified registry index info // for the given command. func RegistryAuthenticationPrivilegedFunc(cli Cli, index *registrytypes.IndexInfo, cmdName string) types.RequestPrivilegeFunc { - return func() (string, error) { - fmt.Fprintf(cli.Out(), "\nPlease login prior to %s:\n", cmdName) + return func(ctx context.Context) (string, error) { + fmt.Fprintf(cli.Out(), "\nLogin prior to %s:\n", cmdName) indexServer := registry.GetAuthConfigKey(index) isDefaultRegistry := indexServer == registry.IndexServer authConfig, err := GetDefaultAuthConfig(cli.ConfigFile(), true, indexServer, isDefaultRegistry) if err != nil { fmt.Fprintf(cli.Err(), "Unable to retrieve stored credentials for %s, error: %s.\n", indexServer, err) } + + select { + case <-ctx.Done(): + return "", ctx.Err() + default: + } + err = ConfigureAuth(cli, "", "", &authConfig, isDefaultRegistry) if err != nil { return "", err @@ -63,7 +72,7 @@ func ResolveAuthConfig(cfg *configfile.ConfigFile, index *registrytypes.IndexInf // If credentials for given serverAddress exists in the credential store, the configuration will be populated with values in it func GetDefaultAuthConfig(cfg *configfile.ConfigFile, checkCredStore bool, serverAddress string, isDefaultRegistry bool) (registrytypes.AuthConfig, error) { if !isDefaultRegistry { - serverAddress = registry.ConvertToHostname(serverAddress) + serverAddress = credentials.ConvertToHostname(serverAddress) } authconfig := configtypes.AuthConfig{} var err error diff --git a/vendor/github.com/docker/cli/cli/command/telemetry_docker.go b/vendor/github.com/docker/cli/cli/command/telemetry_docker.go index 5dc72e2bb525..94ab3a3929dd 100644 --- a/vendor/github.com/docker/cli/cli/command/telemetry_docker.go +++ b/vendor/github.com/docker/cli/cli/command/telemetry_docker.go @@ -1,11 +1,10 @@ // FIXME(jsternberg): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package command import ( "context" - "fmt" "net/url" "os" "path" @@ -85,7 +84,7 @@ func dockerExporterOTLPEndpoint(cli Cli) (endpoint string, secure bool) { // needs the scheme to use the correct resolver. // // We'll just handle this in a special way and add the unix:// back to the endpoint. - endpoint = fmt.Sprintf("unix://%s", path.Join(u.Host, u.Path)) + endpoint = "unix://" + path.Join(u.Host, u.Path) case "https": secure = true fallthrough diff --git a/vendor/github.com/docker/cli/cli/command/telemetry_options.go b/vendor/github.com/docker/cli/cli/command/telemetry_options.go new file mode 100644 index 000000000000..1d7baaa51cd0 --- /dev/null +++ b/vendor/github.com/docker/cli/cli/command/telemetry_options.go @@ -0,0 +1,25 @@ +package command + +// WithEnableGlobalMeterProvider configures the DockerCli to create a new +// MeterProvider from the initialized DockerCli struct, and set it as +// the global meter provider. +// +// WARNING: For internal use, don't depend on this. +func WithEnableGlobalMeterProvider() CLIOption { + return func(cli *DockerCli) error { + cli.enableGlobalMeter = true + return nil + } +} + +// WithEnableGlobalTracerProvider configures the DockerCli to create a new +// TracerProvider from the initialized DockerCli struct, and set it as +// the global tracer provider. +// +// WARNING: For internal use, don't depend on this. +func WithEnableGlobalTracerProvider() CLIOption { + return func(cli *DockerCli) error { + cli.enableGlobalTracer = true + return nil + } +} diff --git a/vendor/github.com/docker/cli/cli/command/telemetry_utils.go b/vendor/github.com/docker/cli/cli/command/telemetry_utils.go index 87b976ce69a7..905f8a4614c0 100644 --- a/vendor/github.com/docker/cli/cli/command/telemetry_utils.go +++ b/vendor/github.com/docker/cli/cli/command/telemetry_utils.go @@ -7,7 +7,6 @@ import ( "time" "github.com/docker/cli/cli/version" - "github.com/moby/term" "github.com/pkg/errors" "github.com/spf13/cobra" "go.opentelemetry.io/otel/attribute" @@ -101,12 +100,10 @@ func startCobraCommandTimer(mp metric.MeterProvider, attrs []attribute.KeyValue) } func stdioAttributes(streams Streams) []attribute.KeyValue { - // we don't wrap stderr, but we do wrap in/out - _, stderrTty := term.GetFdInfo(streams.Err()) return []attribute.KeyValue{ attribute.Bool("command.stdin.isatty", streams.In().IsTerminal()), attribute.Bool("command.stdout.isatty", streams.Out().IsTerminal()), - attribute.Bool("command.stderr.isatty", stderrTty), + attribute.Bool("command.stderr.isatty", streams.Err().IsTerminal()), } } diff --git a/vendor/github.com/docker/cli/cli/command/utils.go b/vendor/github.com/docker/cli/cli/command/utils.go index d7184f8c4e6a..48d2c4250ace 100644 --- a/vendor/github.com/docker/cli/cli/command/utils.go +++ b/vendor/github.com/docker/cli/cli/command/utils.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package command @@ -9,11 +9,9 @@ import ( "fmt" "io" "os" - "os/signal" "path/filepath" "runtime" "strings" - "syscall" "github.com/docker/cli/cli/streams" "github.com/docker/docker/api/types/filters" @@ -103,11 +101,6 @@ func PromptForConfirmation(ctx context.Context, ins io.Reader, outs io.Writer, m result := make(chan bool) - // Catch the termination signal and exit the prompt gracefully. - // The caller is responsible for properly handling the termination. - notifyCtx, notifyCancel := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM) - defer notifyCancel() - go func() { var res bool scanner := bufio.NewScanner(ins) @@ -121,8 +114,7 @@ func PromptForConfirmation(ctx context.Context, ins io.Reader, outs io.Writer, m }() select { - case <-notifyCtx.Done(): - // print a newline on termination + case <-ctx.Done(): _, _ = fmt.Fprintln(outs, "") return false, ErrPromptTerminated case r := <-result: diff --git a/vendor/github.com/docker/cli/cli/config/config.go b/vendor/github.com/docker/cli/cli/config/config.go index 952f6e71f4f7..5a518432601d 100644 --- a/vendor/github.com/docker/cli/cli/config/config.go +++ b/vendor/github.com/docker/cli/cli/config/config.go @@ -4,14 +4,15 @@ import ( "fmt" "io" "os" + "os/user" "path/filepath" + "runtime" "strings" "sync" "github.com/docker/cli/cli/config/configfile" "github.com/docker/cli/cli/config/credentials" "github.com/docker/cli/cli/config/types" - "github.com/docker/docker/pkg/homedir" "github.com/pkg/errors" ) @@ -42,12 +43,38 @@ func resetConfigDir() { initConfigDir = new(sync.Once) } +// getHomeDir returns the home directory of the current user with the help of +// environment variables depending on the target operating system. +// Returned path should be used with "path/filepath" to form new paths. +// +// On non-Windows platforms, it falls back to nss lookups, if the home +// directory cannot be obtained from environment-variables. +// +// If linking statically with cgo enabled against glibc, ensure the +// osusergo build tag is used. +// +// If needing to do nss lookups, do not disable cgo or set osusergo. +// +// getHomeDir is a copy of [pkg/homedir.Get] to prevent adding docker/docker +// as dependency for consumers that only need to read the config-file. +// +// [pkg/homedir.Get]: https://pkg.go.dev/github.com/docker/docker@v26.1.4+incompatible/pkg/homedir#Get +func getHomeDir() string { + home, _ := os.UserHomeDir() + if home == "" && runtime.GOOS != "windows" { + if u, err := user.Current(); err == nil { + return u.HomeDir + } + } + return home +} + // Dir returns the directory the configuration file is stored in func Dir() string { initConfigDir.Do(func() { configDir = os.Getenv(EnvOverrideConfigDir) if configDir == "" { - configDir = filepath.Join(homedir.Get(), configFileDir) + configDir = filepath.Join(getHomeDir(), configFileDir) } }) return configDir @@ -75,7 +102,7 @@ func Path(p ...string) (string, error) { } // LoadFromReader is a convenience function that creates a ConfigFile object from -// a reader +// a reader. It returns an error if configData is malformed. func LoadFromReader(configData io.Reader) (*configfile.ConfigFile, error) { configFile := configfile.ConfigFile{ AuthConfigs: make(map[string]types.AuthConfig), @@ -84,8 +111,14 @@ func LoadFromReader(configData io.Reader) (*configfile.ConfigFile, error) { return &configFile, err } -// Load reads the configuration files in the given directory, and sets up -// the auth config information and returns values. +// Load reads the configuration file ([ConfigFileName]) from the given directory. +// If no directory is given, it uses the default [Dir]. A [*configfile.ConfigFile] +// is returned containing the contents of the configuration file, or a default +// struct if no configfile exists in the given location. +// +// Load returns an error if a configuration file exists in the given location, +// but cannot be read, or is malformed. Consumers must handle errors to prevent +// overwriting an existing configuration file. func Load(configDir string) (*configfile.ConfigFile, error) { if configDir == "" { configDir = Dir() @@ -100,29 +133,37 @@ func load(configDir string) (*configfile.ConfigFile, error) { file, err := os.Open(filename) if err != nil { if os.IsNotExist(err) { - // - // if file is there but we can't stat it for any reason other - // than it doesn't exist then stop + // It is OK for no configuration file to be present, in which + // case we return a default struct. return configFile, nil } - // if file is there but we can't stat it for any reason other - // than it doesn't exist then stop - return configFile, nil + // Any other error happening when failing to read the file must be returned. + return configFile, errors.Wrap(err, "loading config file") } defer file.Close() err = configFile.LoadFromReader(file) if err != nil { - err = errors.Wrap(err, filename) + err = errors.Wrapf(err, "loading config file: %s: ", filename) } return configFile, err } // LoadDefaultConfigFile attempts to load the default config file and returns -// an initialized ConfigFile struct if none is found. +// a reference to the ConfigFile struct. If none is found or when failing to load +// the configuration file, it initializes a default ConfigFile struct. If no +// credentials-store is set in the configuration file, it attempts to discover +// the default store to use for the current platform. +// +// Important: LoadDefaultConfigFile prints a warning to stderr when failing to +// load the configuration file, but otherwise ignores errors. Consumers should +// consider using [Load] (and [credentials.DetectDefaultStore]) to detect errors +// when updating the configuration file, to prevent discarding a (malformed) +// configuration file. func LoadDefaultConfigFile(stderr io.Writer) *configfile.ConfigFile { configFile, err := load(Dir()) if err != nil { - _, _ = fmt.Fprintf(stderr, "WARNING: Error loading config file: %v\n", err) + // FIXME(thaJeztah): we should not proceed here to prevent overwriting existing (but malformed) config files; see https://github.com/docker/cli/issues/5075 + _, _ = fmt.Fprintln(stderr, "WARNING: Error", err) } if !configFile.ContainsAuth() { configFile.CredentialsStore = credentials.DetectDefaultStore(configFile.CredentialsStore) diff --git a/vendor/github.com/docker/cli/cli/config/credentials/file_store.go b/vendor/github.com/docker/cli/cli/config/credentials/file_store.go index ea30fc300634..99631bbf4cf7 100644 --- a/vendor/github.com/docker/cli/cli/config/credentials/file_store.go +++ b/vendor/github.com/docker/cli/cli/config/credentials/file_store.go @@ -1,6 +1,7 @@ package credentials import ( + "net/url" "strings" "github.com/docker/cli/cli/config/types" @@ -68,14 +69,14 @@ func (c *fileStore) IsFileStore() bool { // ConvertToHostname converts a registry url which has http|https prepended // to just an hostname. // Copied from github.com/docker/docker/registry.ConvertToHostname to reduce dependencies. -func ConvertToHostname(url string) string { - stripped := url - if strings.HasPrefix(url, "http://") { - stripped = strings.TrimPrefix(url, "http://") - } else if strings.HasPrefix(url, "https://") { - stripped = strings.TrimPrefix(url, "https://") +func ConvertToHostname(maybeURL string) string { + stripped := maybeURL + if strings.Contains(stripped, "://") { + u, err := url.Parse(stripped) + if err == nil && u.Hostname() != "" { + return u.Hostname() + } } - hostName, _, _ := strings.Cut(stripped, "/") return hostName } diff --git a/vendor/github.com/docker/cli/cli/connhelper/commandconn/commandconn.go b/vendor/github.com/docker/cli/cli/connhelper/commandconn/commandconn.go index f697370ed972..cfc2b86a25f9 100644 --- a/vendor/github.com/docker/cli/cli/connhelper/commandconn/commandconn.go +++ b/vendor/github.com/docker/cli/cli/connhelper/commandconn/commandconn.go @@ -149,7 +149,7 @@ func (c *commandConn) handleEOF(err error) error { c.stderrMu.Lock() stderr := c.stderr.String() c.stderrMu.Unlock() - return errors.Errorf("command %v has exited with %v, please make sure the URL is valid, and Docker 18.09 or later is installed on the remote host: stderr=%s", c.cmd.Args, werr, stderr) + return errors.Errorf("command %v has exited with %v, make sure the URL is valid, and Docker 18.09 or later is installed on the remote host: stderr=%s", c.cmd.Args, werr, stderr) } func ignorableCloseError(err error) bool { diff --git a/vendor/github.com/docker/cli/cli/context/store/metadatastore.go b/vendor/github.com/docker/cli/cli/context/store/metadatastore.go index 2bb6a20e8c61..0c6986fa7510 100644 --- a/vendor/github.com/docker/cli/cli/context/store/metadatastore.go +++ b/vendor/github.com/docker/cli/cli/context/store/metadatastore.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package store diff --git a/vendor/github.com/docker/cli/cli/context/store/store.go b/vendor/github.com/docker/cli/cli/context/store/store.go index 45bb76ce6664..44e9477fb014 100644 --- a/vendor/github.com/docker/cli/cli/context/store/store.go +++ b/vendor/github.com/docker/cli/cli/context/store/store.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package store diff --git a/vendor/github.com/docker/cli/cli/context/store/storeconfig.go b/vendor/github.com/docker/cli/cli/context/store/storeconfig.go index 7c2b42107b9f..aa516a191e29 100644 --- a/vendor/github.com/docker/cli/cli/context/store/storeconfig.go +++ b/vendor/github.com/docker/cli/cli/context/store/storeconfig.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package store @@ -14,7 +14,7 @@ type NamedTypeGetter struct { typeGetter TypeGetter } -// EndpointTypeGetter returns a NamedTypeGetter with the spcecified name and getter +// EndpointTypeGetter returns a NamedTypeGetter with the specified name and getter func EndpointTypeGetter(name string, getter TypeGetter) NamedTypeGetter { return NamedTypeGetter{ name: name, diff --git a/vendor/github.com/docker/cli/cli/manifest/store/store.go b/vendor/github.com/docker/cli/cli/manifest/store/store.go index dbf773063296..c4f8219cec7b 100644 --- a/vendor/github.com/docker/cli/cli/manifest/store/store.go +++ b/vendor/github.com/docker/cli/cli/manifest/store/store.go @@ -2,7 +2,6 @@ package store import ( "encoding/json" - "fmt" "os" "path/filepath" "strings" @@ -162,7 +161,7 @@ func newNotFoundError(ref string) *notFoundError { } func (n *notFoundError) Error() string { - return fmt.Sprintf("No such manifest: %s", n.object) + return "No such manifest: " + n.object } // NotFound interface diff --git a/vendor/github.com/docker/cli/cli/registry/client/client.go b/vendor/github.com/docker/cli/cli/registry/client/client.go index b2955d1bce5e..bbc7f4c58491 100644 --- a/vendor/github.com/docker/cli/cli/registry/client/client.go +++ b/vendor/github.com/docker/cli/cli/registry/client/client.go @@ -101,23 +101,23 @@ func (c *client) MountBlob(ctx context.Context, sourceRef reference.Canonical, t func (c *client) PutManifest(ctx context.Context, ref reference.Named, manifest distribution.Manifest) (digest.Digest, error) { repoEndpoint, err := newDefaultRepositoryEndpoint(ref, c.insecureRegistry) if err != nil { - return digest.Digest(""), err + return "", err } repoEndpoint.actions = trust.ActionsPushAndPull repo, err := c.getRepositoryForReference(ctx, ref, repoEndpoint) if err != nil { - return digest.Digest(""), err + return "", err } manifestService, err := repo.Manifests(ctx) if err != nil { - return digest.Digest(""), err + return "", err } _, opts, err := getManifestOptionsFromReference(ref) if err != nil { - return digest.Digest(""), err + return "", err } dgst, err := manifestService.Put(ctx, manifest, opts...) diff --git a/vendor/github.com/docker/cli/cli/registry/client/endpoint.go b/vendor/github.com/docker/cli/cli/registry/client/endpoint.go index bafd5505f43b..e06bfea50bc5 100644 --- a/vendor/github.com/docker/cli/cli/registry/client/endpoint.go +++ b/vendor/github.com/docker/cli/cli/registry/client/endpoint.go @@ -1,7 +1,6 @@ package client import ( - "fmt" "net" "net/http" "time" @@ -83,7 +82,6 @@ func getHTTPTransport(authConfig registrytypes.AuthConfig, endpoint registry.API Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, - DualStack: true, }).Dial, TLSHandshakeTimeout: 10 * time.Second, TLSClientConfig: endpoint.TLSConfig, @@ -126,7 +124,7 @@ type existingTokenHandler struct { } func (th *existingTokenHandler) AuthorizeRequest(req *http.Request, _ map[string]string) error { - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", th.token)) + req.Header.Set("Authorization", "Bearer "+th.token) return nil } diff --git a/vendor/github.com/docker/cli/cli/registry/client/fetcher.go b/vendor/github.com/docker/cli/cli/registry/client/fetcher.go index 093211d89a5c..3e4b36d309fc 100644 --- a/vendor/github.com/docker/cli/cli/registry/client/fetcher.go +++ b/vendor/github.com/docker/cli/cli/registry/client/fetcher.go @@ -270,7 +270,7 @@ func (c *client) iterateEndpoints(ctx context.Context, namedRef reference.Named, return newNotFoundError(namedRef.String()) } -// allEndpoints returns a list of endpoints ordered by priority (v2, https, v1). +// allEndpoints returns a list of endpoints ordered by priority (v2, http). func allEndpoints(namedRef reference.Named, insecure bool) ([]registry.APIEndpoint, error) { repoInfo, err := registry.ParseRepositoryInfo(namedRef) if err != nil { diff --git a/vendor/github.com/docker/cli/cli/trust/trust.go b/vendor/github.com/docker/cli/cli/trust/trust.go index 575d48f6de31..745cede76f05 100644 --- a/vendor/github.com/docker/cli/cli/trust/trust.go +++ b/vendor/github.com/docker/cli/cli/trust/trust.go @@ -119,7 +119,6 @@ func GetNotaryRepository(in io.Reader, out io.Writer, userAgent string, repoInfo Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, - DualStack: true, }).Dial, TLSHandshakeTimeout: 10 * time.Second, TLSClientConfig: cfg, diff --git a/vendor/github.com/docker/cli/opts/config.go b/vendor/github.com/docker/cli/opts/config.go index 3be0fa93dde0..1423ae3be585 100644 --- a/vendor/github.com/docker/cli/opts/config.go +++ b/vendor/github.com/docker/cli/opts/config.go @@ -2,6 +2,7 @@ package opts import ( "encoding/csv" + "errors" "fmt" "os" "strconv" @@ -68,7 +69,7 @@ func (o *ConfigOpt) Set(value string) error { } if options.ConfigName == "" { - return fmt.Errorf("source is required") + return errors.New("source is required") } if options.File.Name == "" { options.File.Name = options.ConfigName diff --git a/vendor/github.com/docker/cli/opts/file.go b/vendor/github.com/docker/cli/opts/file.go index 72b90e117f73..5cdd8e1386d1 100644 --- a/vendor/github.com/docker/cli/opts/file.go +++ b/vendor/github.com/docker/cli/opts/file.go @@ -18,7 +18,7 @@ type ErrBadKey struct { } func (e ErrBadKey) Error() string { - return fmt.Sprintf("poorly formatted environment: %s", e.msg) + return "poorly formatted environment: " + e.msg } func parseKeyValueFile(filename string, emptyFn func(string) (string, bool)) ([]string, error) { diff --git a/vendor/github.com/docker/cli/opts/mount.go b/vendor/github.com/docker/cli/opts/mount.go index 430b858e8fae..3a4ee31a27c7 100644 --- a/vendor/github.com/docker/cli/opts/mount.go +++ b/vendor/github.com/docker/cli/opts/mount.go @@ -165,11 +165,11 @@ func (m *MountOpt) Set(value string) error { } if mount.Type == "" { - return fmt.Errorf("type is required") + return errors.New("type is required") } if mount.Target == "" { - return fmt.Errorf("target is required") + return errors.New("target is required") } if mount.VolumeOptions != nil && mount.Type != mounttypes.TypeVolume { diff --git a/vendor/github.com/docker/cli/opts/network.go b/vendor/github.com/docker/cli/opts/network.go index e36ef405d121..413aec7b52e6 100644 --- a/vendor/github.com/docker/cli/opts/network.go +++ b/vendor/github.com/docker/cli/opts/network.go @@ -2,6 +2,7 @@ package opts import ( "encoding/csv" + "errors" "fmt" "regexp" "strings" @@ -83,11 +84,11 @@ func (n *NetworkOpt) Set(value string) error { //nolint:gocyclo } netOpt.DriverOpts[key] = val default: - return fmt.Errorf("invalid field key %s", key) + return errors.New("invalid field key " + key) } } if len(netOpt.Target) == 0 { - return fmt.Errorf("network name/id is not specified") + return errors.New("network name/id is not specified") } } else { netOpt.Target = value @@ -126,7 +127,7 @@ func parseDriverOpt(driverOpt string) (string, string, error) { // TODO(thaJeztah): should value be converted to lowercase as well, or only the key? key, value, ok := strings.Cut(strings.ToLower(driverOpt), "=") if !ok || key == "" { - return "", "", fmt.Errorf("invalid key value pair format in driver options") + return "", "", errors.New("invalid key value pair format in driver options") } key = strings.TrimSpace(key) value = strings.TrimSpace(value) diff --git a/vendor/github.com/docker/cli/opts/opts.go b/vendor/github.com/docker/cli/opts/opts.go index 80de16052c62..254d7eb12853 100644 --- a/vendor/github.com/docker/cli/opts/opts.go +++ b/vendor/github.com/docker/cli/opts/opts.go @@ -401,7 +401,7 @@ func ParseCPUs(value string) (int64, error) { } nano := cpu.Mul(cpu, big.NewRat(1e9, 1)) if !nano.IsInt() { - return 0, fmt.Errorf("value is too precise") + return 0, errors.New("value is too precise") } return nano.Num().Int64(), nil } @@ -409,14 +409,14 @@ func ParseCPUs(value string) (int64, error) { // ParseLink parses and validates the specified string as a link format (name:alias) func ParseLink(val string) (string, string, error) { if val == "" { - return "", "", fmt.Errorf("empty string specified for links") + return "", "", errors.New("empty string specified for links") } // We expect two parts, but restrict to three to allow detecting invalid formats. arr := strings.SplitN(val, ":", 3) // TODO(thaJeztah): clean up this logic!! if len(arr) > 2 { - return "", "", fmt.Errorf("bad format for links: %s", val) + return "", "", errors.New("bad format for links: " + val) } // TODO(thaJeztah): this should trim the "/" prefix as well?? if len(arr) == 1 { diff --git a/vendor/github.com/docker/cli/opts/parse.go b/vendor/github.com/docker/cli/opts/parse.go index 381648fe7344..584b55ef61f4 100644 --- a/vendor/github.com/docker/cli/opts/parse.go +++ b/vendor/github.com/docker/cli/opts/parse.go @@ -1,7 +1,7 @@ package opts import ( - "fmt" + "errors" "os" "strconv" "strings" @@ -81,12 +81,12 @@ func ParseRestartPolicy(policy string) (container.RestartPolicy, error) { p := container.RestartPolicy{} k, v, ok := strings.Cut(policy, ":") if ok && k == "" { - return container.RestartPolicy{}, fmt.Errorf("invalid restart policy format: no policy provided before colon") + return container.RestartPolicy{}, errors.New("invalid restart policy format: no policy provided before colon") } if v != "" { count, err := strconv.Atoi(v) if err != nil { - return container.RestartPolicy{}, fmt.Errorf("invalid restart policy format: maximum retry count must be an integer") + return container.RestartPolicy{}, errors.New("invalid restart policy format: maximum retry count must be an integer") } p.MaximumRetryCount = count } diff --git a/vendor/github.com/docker/cli/opts/port.go b/vendor/github.com/docker/cli/opts/port.go index fe41cdd2881f..2f2aa329c8ee 100644 --- a/vendor/github.com/docker/cli/opts/port.go +++ b/vendor/github.com/docker/cli/opts/port.go @@ -2,6 +2,7 @@ package opts import ( "encoding/csv" + "errors" "fmt" "net" "regexp" @@ -102,7 +103,7 @@ func (p *PortOpt) Set(value string) error { for _, portBindings := range portBindingMap { for _, portBinding := range portBindings { if portBinding.HostIP != "" { - return fmt.Errorf("hostip is not supported") + return errors.New("hostip is not supported") } } } diff --git a/vendor/github.com/docker/cli/opts/secret.go b/vendor/github.com/docker/cli/opts/secret.go index 750dbe4f301d..09d2b2b3be0f 100644 --- a/vendor/github.com/docker/cli/opts/secret.go +++ b/vendor/github.com/docker/cli/opts/secret.go @@ -2,6 +2,7 @@ package opts import ( "encoding/csv" + "errors" "fmt" "os" "strconv" @@ -62,12 +63,12 @@ func (o *SecretOpt) Set(value string) error { options.File.Mode = os.FileMode(m) default: - return fmt.Errorf("invalid field in secret request: %s", key) + return errors.New("invalid field in secret request: " + key) } } if options.SecretName == "" { - return fmt.Errorf("source is required") + return errors.New("source is required") } if options.File.Name == "" { options.File.Name = options.SecretName diff --git a/vendor/github.com/docker/cli/opts/ulimit.go b/vendor/github.com/docker/cli/opts/ulimit.go index 5176b999a56e..1409a109bce4 100644 --- a/vendor/github.com/docker/cli/opts/ulimit.go +++ b/vendor/github.com/docker/cli/opts/ulimit.go @@ -4,24 +4,27 @@ import ( "fmt" "sort" + "github.com/docker/docker/api/types/container" "github.com/docker/go-units" ) // UlimitOpt defines a map of Ulimits type UlimitOpt struct { - values *map[string]*units.Ulimit + values *map[string]*container.Ulimit } // NewUlimitOpt creates a new UlimitOpt. Ulimits are not validated. -func NewUlimitOpt(ref *map[string]*units.Ulimit) *UlimitOpt { +func NewUlimitOpt(ref *map[string]*container.Ulimit) *UlimitOpt { + // TODO(thaJeztah): why do we need a map with pointers here? if ref == nil { - ref = &map[string]*units.Ulimit{} + ref = &map[string]*container.Ulimit{} } return &UlimitOpt{ref} } // Set validates a Ulimit and sets its name as a key in UlimitOpt func (o *UlimitOpt) Set(val string) error { + // FIXME(thaJeztah): these functions also need to be moved over from go-units. l, err := units.ParseUlimit(val) if err != nil { return err @@ -43,8 +46,8 @@ func (o *UlimitOpt) String() string { } // GetList returns a slice of pointers to Ulimits. Values are sorted by name. -func (o *UlimitOpt) GetList() []*units.Ulimit { - ulimits := make([]*units.Ulimit, 0, len(*o.values)) +func (o *UlimitOpt) GetList() []*container.Ulimit { + ulimits := make([]*container.Ulimit, 0, len(*o.values)) for _, v := range *o.values { ulimits = append(ulimits, v) } diff --git a/vendor/github.com/docker/cli/templates/templates.go b/vendor/github.com/docker/cli/templates/templates.go index 993ac92f4c76..572ece8be79c 100644 --- a/vendor/github.com/docker/cli/templates/templates.go +++ b/vendor/github.com/docker/cli/templates/templates.go @@ -1,5 +1,5 @@ // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.19 +//go:build go1.21 package templates diff --git a/vendor/github.com/docker/docker/AUTHORS b/vendor/github.com/docker/docker/AUTHORS index 36315d429d1e..5f93eeb4e82a 100644 --- a/vendor/github.com/docker/docker/AUTHORS +++ b/vendor/github.com/docker/docker/AUTHORS @@ -10,6 +10,7 @@ Aaron Huslage Aaron L. Xu Aaron Lehmann Aaron Welch +Aaron Yoshitake Abel Muiño Abhijeet Kasurde Abhinandan Prativadi @@ -62,6 +63,7 @@ alambike Alan Hoyle Alan Scherger Alan Thompson +Alano Terblanche Albert Callarisa Albert Zhang Albin Kerouanton @@ -141,6 +143,7 @@ Andreas Tiefenthaler Andrei Gherzan Andrei Ushakov Andrei Vagin +Andrew Baxter <423qpsxzhh8k3h@s.rendaw.me> Andrew C. Bodine Andrew Clay Shafer Andrew Duckworth @@ -193,6 +196,7 @@ Anton Löfgren Anton Nikitin Anton Polonskiy Anton Tiurin +Antonio Aguilar Antonio Murdaca Antonis Kalipetis Antony Messerli @@ -221,7 +225,6 @@ Avi Das Avi Kivity Avi Miller Avi Vaid -ayoshitake Azat Khuyiyakhmetov Bao Yonglei Bardia Keyoumarsi @@ -316,6 +319,7 @@ Burke Libbey Byung Kang Caleb Spare Calen Pennington +Calvin Liu Cameron Boehmer Cameron Sparr Cameron Spear @@ -362,6 +366,7 @@ Chen Qiu Cheng-mean Liu Chengfei Shang Chengguang Xu +Chentianze Chenyang Yan chenyuzhu Chetan Birajdar @@ -409,6 +414,7 @@ Christopher Crone Christopher Currie Christopher Jones Christopher Latham +Christopher Petito Christopher Rigor Christy Norman Chun Chen @@ -777,6 +783,7 @@ Gabriel L. Somlo Gabriel Linder Gabriel Monroy Gabriel Nicolas Avellaneda +Gabriel Tomitsuka Gaetan de Villele Galen Sampson Gang Qiao @@ -792,6 +799,7 @@ Geoff Levand Geoffrey Bachelet Geon Kim George Kontridze +George Ma George MacRorie George Xie Georgi Hristozov @@ -913,6 +921,7 @@ Illo Abdulrahim Ilya Dmitrichenko Ilya Gusev Ilya Khlopotov +imalasong <2879499479@qq.com> imre Fitos inglesp Ingo Gottwald @@ -930,6 +939,7 @@ J Bruni J. Nunn Jack Danger Canty Jack Laxson +Jack Walker <90711509+j2walker@users.noreply.github.com> Jacob Atzen Jacob Edelman Jacob Tomlinson @@ -989,6 +999,7 @@ Jason Shepherd Jason Smith Jason Sommer Jason Stangroome +Jasper Siepkes Javier Bassi jaxgeller Jay @@ -1100,6 +1111,7 @@ Jon Johnson Jon Surrell Jon Wedaman Jonas Dohse +Jonas Geiler Jonas Heinrich Jonas Pfenniger Jonathan A. Schweder @@ -1267,6 +1279,7 @@ Lakshan Perera Lalatendu Mohanty Lance Chen Lance Kinley +Lars Andringa Lars Butler Lars Kellogg-Stedman Lars R. Damerow @@ -1673,6 +1686,7 @@ Patrick Böänziger Patrick Devine Patrick Haas Patrick Hemmer +Patrick St. laurent Patrick Stapleton Patrik Cyvoct pattichen @@ -1878,6 +1892,7 @@ Royce Remer Rozhnov Alexandr Rudolph Gottesheim Rui Cao +Rui JingAn Rui Lopes Ruilin Li Runshen Zhu @@ -2184,6 +2199,7 @@ Tomek Mańko Tommaso Visconti Tomoya Tabuchi Tomáš Hrčka +Tomáš Virtus tonic Tonny Xu Tony Abboud @@ -2228,6 +2244,7 @@ Victor I. Wood Victor Lyuboslavsky Victor Marmol Victor Palma +Victor Toni Victor Vieux Victoria Bialas Vijaya Kumar K @@ -2279,6 +2296,7 @@ Wassim Dhif Wataru Ishida Wayne Chang Wayne Song +weebney Weerasak Chongnguluam Wei Fu Wei Wu diff --git a/vendor/github.com/docker/docker/api/common.go b/vendor/github.com/docker/docker/api/common.go index b11c2fe02b12..f831735f840e 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 the current REST API. - DefaultVersion = "1.45" + DefaultVersion = "1.46" // MinSupportedAPIVersion is the minimum API version that can be supported // by the API server, specified as "major.minor". Note that the daemon diff --git a/vendor/github.com/docker/docker/api/swagger.yaml b/vendor/github.com/docker/docker/api/swagger.yaml index 43a780e99468..cc754bf1fd12 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.45" +basePath: "/v1.46" info: title: "Docker Engine API" - version: "1.45" + version: "1.46" 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.45) is used. - For example, calling `/info` is the same as calling `/v1.45/info`. Using the + If you omit the version-prefix, the current version of the API (v1.46) is used. + For example, calling `/info` is the same as calling `/v1.46/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, @@ -442,6 +442,21 @@ definitions: Mode: description: "The permission mode for the tmpfs mount in an integer." type: "integer" + Options: + description: | + The options to be passed to the tmpfs mount. An array of arrays. + Flag options should be provided as 1-length arrays. Other types + should be provided as as 2-length arrays, where the first item is + the key and the second the value. + type: "array" + items: + type: "array" + minItems: 1 + maxItems: 2 + items: + type: "string" + example: + [["noexec"]] RestartPolicy: description: | @@ -1198,13 +1213,6 @@ definitions: ContainerConfig: description: | Configuration for a container that is portable between hosts. - - When used as `ContainerConfig` field in an image, `ContainerConfig` is an - optional field containing the configuration of the container that was last - committed when creating the image. - - Previous versions of Docker builder used this field to store build cache, - and it is not in active use anymore. type: "object" properties: Hostname: @@ -1363,6 +1371,289 @@ definitions: type: "string" example: ["/bin/sh", "-c"] + ImageConfig: + description: | + Configuration of the image. These fields are used as defaults + when starting a container from the image. + type: "object" + properties: + Hostname: + description: | + The hostname to use for the container, as a valid RFC 1123 hostname. + +


+ + > **Deprecated**: this field is not part of the image specification and is + > always empty. It must not be used, and will be removed in API v1.47. + type: "string" + example: "" + Domainname: + description: | + The domain name to use for the container. + +


+ + > **Deprecated**: this field is not part of the image specification and is + > always empty. It must not be used, and will be removed in API v1.47. + type: "string" + example: "" + User: + description: "The user that commands are run as inside the container." + type: "string" + example: "web:web" + AttachStdin: + description: | + Whether to attach to `stdin`. + +


+ + > **Deprecated**: this field is not part of the image specification and is + > always false. It must not be used, and will be removed in API v1.47. + type: "boolean" + default: false + example: false + AttachStdout: + description: | + Whether to attach to `stdout`. + +


+ + > **Deprecated**: this field is not part of the image specification and is + > always false. It must not be used, and will be removed in API v1.47. + type: "boolean" + default: false + example: false + AttachStderr: + description: | + Whether to attach to `stderr`. + +


+ + > **Deprecated**: this field is not part of the image specification and is + > always false. It must not be used, and will be removed in API v1.47. + type: "boolean" + default: false + example: false + ExposedPorts: + description: | + An object mapping ports to an empty object in the form: + + `{"/": {}}` + type: "object" + x-nullable: true + additionalProperties: + type: "object" + enum: + - {} + default: {} + example: { + "80/tcp": {}, + "443/tcp": {} + } + Tty: + description: | + Attach standard streams to a TTY, including `stdin` if it is not closed. + +


+ + > **Deprecated**: this field is not part of the image specification and is + > always false. It must not be used, and will be removed in API v1.47. + type: "boolean" + default: false + example: false + OpenStdin: + description: | + Open `stdin` + +


+ + > **Deprecated**: this field is not part of the image specification and is + > always false. It must not be used, and will be removed in API v1.47. + type: "boolean" + default: false + example: false + StdinOnce: + description: | + Close `stdin` after one attached client disconnects. + +


+ + > **Deprecated**: this field is not part of the image specification and is + > always false. It must not be used, and will be removed in API v1.47. + type: "boolean" + default: false + example: false + Env: + description: | + A list of environment variables to set inside the container in the + form `["VAR=value", ...]`. A variable without `=` is removed from the + environment, rather than to have an empty value. + type: "array" + items: + type: "string" + example: + - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + Cmd: + description: | + Command to run specified as a string or an array of strings. + type: "array" + items: + type: "string" + example: ["/bin/sh"] + Healthcheck: + $ref: "#/definitions/HealthConfig" + ArgsEscaped: + description: "Command is already escaped (Windows only)" + type: "boolean" + default: false + example: false + x-nullable: true + Image: + description: | + The name (or reference) of the image to use when creating the container, + or which was used when the container was created. + +


+ + > **Deprecated**: this field is not part of the image specification and is + > always empty. It must not be used, and will be removed in API v1.47. + type: "string" + default: "" + example: "" + Volumes: + description: | + An object mapping mount point paths inside the container to empty + objects. + type: "object" + additionalProperties: + type: "object" + enum: + - {} + default: {} + example: + "/app/data": {} + "/app/config": {} + WorkingDir: + description: "The working directory for commands to run in." + type: "string" + example: "/public/" + Entrypoint: + description: | + The entry point for the container as a string or an array of strings. + + If the array consists of exactly one empty string (`[""]`) then the + entry point is reset to system default (i.e., the entry point used by + docker when there is no `ENTRYPOINT` instruction in the `Dockerfile`). + type: "array" + items: + type: "string" + example: [] + NetworkDisabled: + description: | + Disable networking for the container. + +


+ + > **Deprecated**: this field is not part of the image specification and is + > always omitted. It must not be used, and will be removed in API v1.47. + type: "boolean" + default: false + example: false + x-nullable: true + MacAddress: + description: | + MAC address of the container. + +


+ + > **Deprecated**: this field is not part of the image specification and is + > always omitted. It must not be used, and will be removed in API v1.47. + type: "string" + default: "" + example: "" + x-nullable: true + OnBuild: + description: | + `ONBUILD` metadata that were defined in the image's `Dockerfile`. + type: "array" + x-nullable: true + items: + type: "string" + example: [] + Labels: + description: "User-defined key/value metadata." + type: "object" + additionalProperties: + type: "string" + example: + com.example.some-label: "some-value" + com.example.some-other-label: "some-other-value" + StopSignal: + description: | + Signal to stop a container as a string or unsigned integer. + type: "string" + example: "SIGTERM" + x-nullable: true + StopTimeout: + description: | + Timeout to stop a container in seconds. + +


+ + > **Deprecated**: this field is not part of the image specification and is + > always omitted. It must not be used, and will be removed in API v1.47. + type: "integer" + default: 10 + x-nullable: true + Shell: + description: | + Shell for when `RUN`, `CMD`, and `ENTRYPOINT` uses a shell. + type: "array" + x-nullable: true + items: + type: "string" + example: ["/bin/sh", "-c"] + # FIXME(thaJeztah): temporarily using a full example to remove some "omitempty" fields. Remove once the fields are removed. + example: + "Hostname": "" + "Domainname": "" + "User": "web:web" + "AttachStdin": false + "AttachStdout": false + "AttachStderr": false + "ExposedPorts": { + "80/tcp": {}, + "443/tcp": {} + } + "Tty": false + "OpenStdin": false + "StdinOnce": false + "Env": ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"] + "Cmd": ["/bin/sh"] + "Healthcheck": { + "Test": ["string"], + "Interval": 0, + "Timeout": 0, + "Retries": 0, + "StartPeriod": 0, + "StartInterval": 0 + } + "ArgsEscaped": true + "Image": "" + "Volumes": { + "/app/data": {}, + "/app/config": {} + } + "WorkingDir": "/public/" + "Entrypoint": [] + "OnBuild": [] + "Labels": { + "com.example.some-label": "some-value", + "com.example.some-other-label": "some-other-value" + } + "StopSignal": "SIGTERM" + "Shell": ["/bin/sh", "-c"] + NetworkingConfig: description: | NetworkingConfig represents the container's networking configuration for @@ -1758,21 +2049,6 @@ definitions: format: "dateTime" x-nullable: true example: "2022-02-04T21:20:12.497794809Z" - Container: - description: | - The ID of the container that was used to create the image. - - Depending on how the image was created, this field may be empty. - - **Deprecated**: this field is kept for backward compatibility, but - will be removed in API v1.45. - type: "string" - example: "65974bc86f1770ae4bff79f651ebdbce166ae9aada632ee3fa9af3a264911735" - ContainerConfig: - description: | - **Deprecated**: this field is kept for backward compatibility, but - will be removed in API v1.45. - $ref: "#/definitions/ContainerConfig" DockerVersion: description: | The version of Docker that was used to build the image. @@ -1780,7 +2056,7 @@ definitions: Depending on how the image was created, this field may be empty. type: "string" x-nullable: false - example: "20.10.7" + example: "27.0.1" Author: description: | Name of the author that was specified when committing the image, or as @@ -1789,7 +2065,7 @@ definitions: x-nullable: false example: "" Config: - $ref: "#/definitions/ContainerConfig" + $ref: "#/definitions/ImageConfig" Architecture: description: | Hardware CPU architecture that the image runs on. @@ -1866,6 +2142,7 @@ definitions: format: "dateTime" example: "2022-02-28T14:40:02.623929178Z" x-nullable: true + ImageSummary: type: "object" x-go-name: "Summary" @@ -2380,6 +2657,24 @@ definitions: type: "string" example: "10.133.77.91" + NetworkCreateResponse: + description: "OK response to NetworkCreate operation" + type: "object" + title: "NetworkCreateResponse" + x-go-name: "CreateResponse" + required: [Id, Warning] + properties: + Id: + description: "The ID of the created network." + type: "string" + x-nullable: false + example: "b5c4fc71e8022147cd25de22b22173de4e3b170134117172eb595cb91b4e7e5d" + Warning: + description: "Warnings encountered when creating the container" + type: "string" + x-nullable: false + example: "" + BuildInfo: type: "object" properties: @@ -2579,6 +2874,17 @@ definitions: example: - "server_x" - "server_y" + DriverOpts: + description: | + DriverOpts is a mapping of driver options and values. These options + are passed directly to the driver and are driver specific. + type: "object" + x-nullable: true + additionalProperties: + type: "string" + example: + com.example.some-label: "some-value" + com.example.some-other-label: "some-other-value" # Operational data NetworkID: @@ -2622,17 +2928,6 @@ definitions: type: "integer" format: "int64" example: 64 - DriverOpts: - description: | - DriverOpts is a mapping of driver options and values. These options - are passed directly to the driver and are driver specific. - type: "object" - x-nullable: true - additionalProperties: - type: "string" - example: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" DNSNames: description: | List of all DNS names an endpoint has on a specific network. This @@ -3804,6 +4099,13 @@ definitions: but this is just provided for lookup/display purposes. The secret in the reference will be identified by its ID. type: "string" + OomScoreAdj: + type: "integer" + format: "int64" + description: | + An integer value containing the score given to the container in + order to tune OOM killer preferences. + example: 0 Configs: description: | Configs contains references to zero or more configs that will be @@ -4000,7 +4302,7 @@ definitions: `node.platform.os` | Node operating system | `node.platform.os==windows` `node.platform.arch` | Node architecture | `node.platform.arch==x86_64` `node.labels` | User-defined node labels | `node.labels.security==high` - `engine.labels` | Docker Engine's labels | `engine.labels.operatingsystem==ubuntu-14.04` + `engine.labels` | Docker Engine's labels | `engine.labels.operatingsystem==ubuntu-24.04` `engine.labels` apply to Docker Engine labels like operating system, drivers, etc. Swarm administrators add `node.labels` for operational @@ -4723,6 +5025,12 @@ definitions: properties: NetworkMode: type: "string" + Annotations: + description: "Arbitrary key-value metadata attached to container" + type: "object" + x-nullable: true + additionalProperties: + type: "string" NetworkSettings: description: "A summary of the container's network settings" type: "object" @@ -4991,7 +5299,7 @@ definitions: Version of the component type: "string" x-nullable: false - example: "19.03.12" + example: "27.0.1" Details: description: | Key/value pairs of strings with additional information about the @@ -5005,17 +5313,17 @@ definitions: Version: description: "The version of the daemon" type: "string" - example: "19.03.12" + example: "27.0.1" ApiVersion: description: | The default (and highest) API version that is supported by the daemon type: "string" - example: "1.40" + example: "1.46" MinAPIVersion: description: | The minimum API version that is supported by the daemon type: "string" - example: "1.12" + example: "1.24" GitCommit: description: | The Git commit of the source code that was used to build the daemon @@ -5026,7 +5334,7 @@ definitions: The version Go used to compile the daemon, and the version of the Go runtime in use. type: "string" - example: "go1.13.14" + example: "go1.21.11" Os: description: | The operating system that the daemon is running on ("linux" or "windows") @@ -5043,7 +5351,7 @@ definitions: This field is omitted when empty. type: "string" - example: "4.19.76-linuxkit" + example: "6.8.0-31-generic" Experimental: description: | Indicates if the daemon is started with experimental features enabled. @@ -5249,13 +5557,13 @@ definitions: information is queried from the HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ registry value, for example _"10.0 14393 (14393.1198.amd64fre.rs1_release_sec.170427-1353)"_. type: "string" - example: "4.9.38-moby" + example: "6.8.0-31-generic" OperatingSystem: description: | - Name of the host's operating system, for example: "Ubuntu 16.04.2 LTS" + Name of the host's operating system, for example: "Ubuntu 24.04 LTS" or "Windows Server 2016 Datacenter" type: "string" - example: "Alpine Linux v3.5" + example: "Ubuntu 24.04 LTS" OSVersion: description: | Version of the host's operating system @@ -5266,7 +5574,7 @@ definitions: > very existence, and the formatting of values, should not be considered > stable, and may change without notice. type: "string" - example: "16.04" + example: "24.04" OSType: description: | Generic type of the operating system of the host, as returned by the @@ -5368,7 +5676,7 @@ definitions: description: | Version string of the daemon. type: "string" - example: "24.0.2" + example: "27.0.1" Runtimes: description: | List of [OCI compliant](https://github.com/opencontainers/runtime-spec) @@ -5520,6 +5828,58 @@ definitions: example: - "/etc/cdi" - "/var/run/cdi" + Containerd: + $ref: "#/definitions/ContainerdInfo" + x-nullable: true + + ContainerdInfo: + description: | + Information for connecting to the containerd instance that is used by the daemon. + This is included for debugging purposes only. + type: "object" + properties: + Address: + description: "The address of the containerd socket." + type: "string" + example: "/run/containerd/containerd.sock" + Namespaces: + description: | + The namespaces that the daemon uses for running containers and + plugins in containerd. These namespaces can be configured in the + daemon configuration, and are considered to be used exclusively + by the daemon, Tampering with the containerd instance may cause + unexpected behavior. + + As these namespaces are considered to be exclusively accessed + by the daemon, it is not recommended to change these values, + or to change them to a value that is used by other systems, + such as cri-containerd. + type: "object" + properties: + Containers: + description: | + The default containerd namespace used for containers managed + by the daemon. + + The default namespace for containers is "moby", but will be + suffixed with the `.` of the remapped `root` if + user-namespaces are enabled and the containerd image-store + is used. + type: "string" + default: "moby" + example: "moby" + Plugins: + description: | + The default containerd namespace used for plugins managed by + the daemon. + + The default namespace for plugins is "plugins.moby", but will be + suffixed with the `.` of the remapped `root` if + user-namespaces are enabled and the containerd image-store + is used. + type: "string" + default: "plugins.moby" + example: "plugins.moby" # PluginsInfo is a temp struct holding Plugins name # registered with docker daemon. It is used by Info struct @@ -6372,6 +6732,8 @@ paths: SizeRootFs: 0 HostConfig: NetworkMode: "default" + Annotations: + io.kubernetes.docker.type: "container" NetworkSettings: Networks: bridge: @@ -6407,6 +6769,9 @@ paths: SizeRootFs: 0 HostConfig: NetworkMode: "default" + Annotations: + io.kubernetes.docker.type: "container" + io.kubernetes.sandbox.id: "3befe639bed0fd6afdd65fd1fa84506756f59360ec4adc270b0fdac9be22b4d3" NetworkSettings: Networks: bridge: @@ -6435,6 +6800,9 @@ paths: SizeRootFs: 0 HostConfig: NetworkMode: "default" + Annotations: + io.kubernetes.image.id: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" + io.kubernetes.image.name: "ubuntu:latest" NetworkSettings: Networks: bridge: @@ -6463,6 +6831,8 @@ paths: SizeRootFs: 0 HostConfig: NetworkMode: "default" + Annotations: + io.kubernetes.config.source: "api" NetworkSettings: Networks: bridge: @@ -8740,6 +9110,11 @@ paths: details. type: "string" required: true + - name: "platform" + in: "query" + description: "Select a platform-specific manifest to be pushed. OCI platform (JSON encoded)" + type: "string" + x-nullable: true tags: ["Image"] /images/{name}/tag: post: @@ -9188,7 +9563,7 @@ paths: Containers report these events: `attach`, `commit`, `copy`, `create`, `destroy`, `detach`, `die`, `exec_create`, `exec_detach`, `exec_start`, `exec_die`, `export`, `health_status`, `kill`, `oom`, `pause`, `rename`, `resize`, `restart`, `start`, `stop`, `top`, `unpause`, `update`, and `prune` - Images report these events: `delete`, `import`, `load`, `pull`, `push`, `save`, `tag`, `untag`, and `prune` + Images report these events: `create, `delete`, `import`, `load`, `pull`, `push`, `save`, `tag`, `untag`, and `prune` Volumes report these events: `create`, `mount`, `unmount`, `destroy`, and `prune` @@ -10144,19 +10519,9 @@ paths: - "application/json" responses: 201: - description: "No error" + description: "Network created successfully" schema: - type: "object" - title: "NetworkCreateResponse" - properties: - Id: - description: "The ID of the created network." - type: "string" - Warning: - type: "string" - example: - Id: "22be93d5babb089c5aab8dbc369042fad48ff791584ca2da2100db837a1c7c30" - Warning: "" + $ref: "#/definitions/NetworkCreateResponse" 400: description: "bad parameter" schema: @@ -10189,11 +10554,6 @@ paths: description: "The network's name." type: "string" example: "my_network" - CheckDuplicate: - description: | - Deprecated: CheckDuplicate is now always enabled. - type: "boolean" - example: true Driver: description: "Name of the network driver plugin to use." type: "string" @@ -11366,6 +11726,7 @@ paths: Mode: 384 SecretID: "fpjqlhnwb19zds35k8wn80lq9" SecretName: "example_org_domain_key" + OomScoreAdj: 0 LogDriver: Name: "json-file" Options: @@ -11518,6 +11879,7 @@ paths: Image: "busybox" Args: - "top" + OomScoreAdj: 0 Resources: Limits: {} Reservations: {} diff --git a/vendor/github.com/docker/docker/api/types/client.go b/vendor/github.com/docker/docker/api/types/client.go index 882201f0eae5..df791f02a0c3 100644 --- a/vendor/github.com/docker/docker/api/types/client.go +++ b/vendor/github.com/docker/docker/api/types/client.go @@ -2,43 +2,15 @@ package types // import "github.com/docker/docker/api/types" import ( "bufio" + "context" "io" "net" "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" ) -// ContainerExecInspect holds information returned by exec inspect. -type ContainerExecInspect struct { - ExecID string `json:"ID"` - ContainerID string - Running bool - ExitCode int - Pid int -} - -// CopyToContainerOptions holds information -// about files to copy into a container -type CopyToContainerOptions struct { - AllowOverwriteDirWithFile bool - CopyUIDGID bool -} - -// EventsOptions holds parameters to filter events with. -type EventsOptions struct { - Since string - Until string - Filters filters.Args -} - -// NetworkListOptions holds parameters to filter the list of networks with. -type NetworkListOptions struct { - Filters filters.Args -} - // NewHijackedResponse intializes a HijackedResponse type func NewHijackedResponse(conn net.Conn, mediaType string) HijackedResponse { return HijackedResponse{Conn: conn, Reader: bufio.NewReader(conn), mediaType: mediaType} @@ -101,7 +73,7 @@ type ImageBuildOptions struct { NetworkMode string ShmSize int64 Dockerfile string - Ulimits []*units.Ulimit + Ulimits []*container.Ulimit // BuildArgs needs to be a *string instead of just a string so that // we can tell the difference between "" (empty string) and no value // at all (nil). See the parsing of buildArgs in @@ -122,7 +94,7 @@ type ImageBuildOptions struct { Target string SessionID string Platform string - // Version specifies the version of the unerlying builder to use + // Version specifies the version of the underlying builder to use Version BuilderVersion // BuildID is an optional identifier that can be passed together with the // build request. The same identifier can be used to gracefully cancel the @@ -157,34 +129,13 @@ type ImageBuildResponse struct { OSType string } -// ImageImportSource holds source information for ImageImport -type ImageImportSource struct { - Source io.Reader // Source is the data to send to the server to create this image from. You must set SourceName to "-" to leverage this. - SourceName string // SourceName is the name of the image to pull. Set to "-" to leverage the Source attribute. -} - -// ImageLoadResponse returns information to the client about a load process. -type ImageLoadResponse struct { - // Body must be closed to avoid a resource leak - Body io.ReadCloser - JSON bool -} - // RequestPrivilegeFunc is a function interface that // clients can supply to retry operations after // getting an authorization error. // This function returns the registry authentication // header value in base 64 format, or an error // if the privilege request fails. -type RequestPrivilegeFunc func() (string, error) - -// ImageSearchOptions holds parameters to search images with. -type ImageSearchOptions struct { - RegistryAuth string - PrivilegeFunc RequestPrivilegeFunc - Filters filters.Args - Limit int -} +type RequestPrivilegeFunc func(context.Context) (string, error) // NodeListOptions holds parameters to list nodes with. type NodeListOptions struct { @@ -289,7 +240,7 @@ type PluginInstallOptions struct { RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry RemoteRef string // RemoteRef is the plugin name on the registry PrivilegeFunc RequestPrivilegeFunc - AcceptPermissionsFunc func(PluginPrivileges) (bool, error) + AcceptPermissionsFunc func(context.Context, PluginPrivileges) (bool, error) Args []string } diff --git a/vendor/github.com/docker/docker/api/types/configs.go b/vendor/github.com/docker/docker/api/types/configs.go deleted file mode 100644 index 945b6efadd60..000000000000 --- a/vendor/github.com/docker/docker/api/types/configs.go +++ /dev/null @@ -1,18 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -// ExecConfig is a small subset of the Config struct that holds the configuration -// for the exec feature of docker. -type ExecConfig struct { - User string // User that will run the command - Privileged bool // Is the container in privileged mode - Tty bool // Attach standard streams to a tty. - ConsoleSize *[2]uint `json:",omitempty"` // Initial console size [height, width] - AttachStdin bool // Attach the standard input, makes possible user interaction - AttachStderr bool // Attach the standard error - AttachStdout bool // Attach the standard output - Detach bool // Execute in detach mode - DetachKeys string // Escape keys for detach - Env []string // Environment variables - WorkingDir string // Working directory - Cmd []string // Execution commands and args -} diff --git a/vendor/github.com/docker/docker/api/types/container/config.go b/vendor/github.com/docker/docker/api/types/container/config.go index 86f46b74afc4..d6b03e8b2e9e 100644 --- a/vendor/github.com/docker/docker/api/types/container/config.go +++ b/vendor/github.com/docker/docker/api/types/container/config.go @@ -1,7 +1,6 @@ package container // import "github.com/docker/docker/api/types/container" import ( - "io" "time" "github.com/docker/docker/api/types/strslice" @@ -36,14 +35,6 @@ type StopOptions struct { // HealthConfig holds configuration settings for the HEALTHCHECK feature. type HealthConfig = dockerspec.HealthcheckConfig -// ExecStartOptions holds the options to start container's exec. -type ExecStartOptions struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer - ConsoleSize *[2]uint `json:",omitempty"` -} - // Config contains the configuration data about a container. // It should hold only portable information about the container. // Here, "portable" means "independent from the host we are running on". diff --git a/vendor/github.com/docker/docker/api/types/container/container.go b/vendor/github.com/docker/docker/api/types/container/container.go new file mode 100644 index 000000000000..711af12c9920 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/container.go @@ -0,0 +1,44 @@ +package container + +import ( + "io" + "os" + "time" +) + +// PruneReport contains the response for Engine API: +// POST "/containers/prune" +type PruneReport struct { + ContainersDeleted []string + SpaceReclaimed uint64 +} + +// PathStat is used to encode the header from +// GET "/containers/{name:.*}/archive" +// "Name" is the file or directory name. +type PathStat struct { + Name string `json:"name"` + Size int64 `json:"size"` + Mode os.FileMode `json:"mode"` + Mtime time.Time `json:"mtime"` + LinkTarget string `json:"linkTarget"` +} + +// CopyToContainerOptions holds information +// about files to copy into a container +type CopyToContainerOptions struct { + AllowOverwriteDirWithFile bool + CopyUIDGID bool +} + +// StatsResponseReader wraps an io.ReadCloser to read (a stream of) stats +// for a container, as produced by the GET "/stats" endpoint. +// +// The OSType field is set to the server's platform to allow +// platform-specific handling of the response. +// +// TODO(thaJeztah): remove this wrapper, and make OSType part of [StatsResponse]. +type StatsResponseReader struct { + Body io.ReadCloser `json:"body"` + OSType string `json:"ostype"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/create_request.go b/vendor/github.com/docker/docker/api/types/container/create_request.go new file mode 100644 index 000000000000..e98dd6ad449b --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/create_request.go @@ -0,0 +1,13 @@ +package container + +import "github.com/docker/docker/api/types/network" + +// CreateRequest is the request message sent to the server for container +// create calls. It is a config wrapper that holds the container [Config] +// (portable) and the corresponding [HostConfig] (non-portable) and +// [network.NetworkingConfig]. +type CreateRequest struct { + *Config + HostConfig *HostConfig `json:"HostConfig,omitempty"` + NetworkingConfig *network.NetworkingConfig `json:"NetworkingConfig,omitempty"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/exec.go b/vendor/github.com/docker/docker/api/types/container/exec.go new file mode 100644 index 000000000000..96093eb5cdb0 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/exec.go @@ -0,0 +1,43 @@ +package container + +// ExecOptions is a small subset of the Config struct that holds the configuration +// for the exec feature of docker. +type ExecOptions struct { + User string // User that will run the command + Privileged bool // Is the container in privileged mode + Tty bool // Attach standard streams to a tty. + ConsoleSize *[2]uint `json:",omitempty"` // Initial console size [height, width] + AttachStdin bool // Attach the standard input, makes possible user interaction + AttachStderr bool // Attach the standard error + AttachStdout bool // Attach the standard output + Detach bool // Execute in detach mode + DetachKeys string // Escape keys for detach + Env []string // Environment variables + WorkingDir string // Working directory + Cmd []string // Execution commands and args +} + +// ExecStartOptions is a temp struct used by execStart +// Config fields is part of ExecConfig in runconfig package +type ExecStartOptions struct { + // ExecStart will first check if it's detached + Detach bool + // Check if there's a tty + Tty bool + // Terminal size [height, width], unused if Tty == false + ConsoleSize *[2]uint `json:",omitempty"` +} + +// ExecAttachOptions is a temp struct used by execAttach. +// +// TODO(thaJeztah): make this a separate type; ContainerExecAttach does not use the Detach option, and cannot run detached. +type ExecAttachOptions = ExecStartOptions + +// ExecInspect holds information returned by exec inspect. +type ExecInspect struct { + ExecID string `json:"ID"` + ContainerID string + Running bool + ExitCode int + Pid int +} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig.go b/vendor/github.com/docker/docker/api/types/container/hostconfig.go index efb96266e8c8..727da8839cc2 100644 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig.go +++ b/vendor/github.com/docker/docker/api/types/container/hostconfig.go @@ -360,6 +360,12 @@ type LogConfig struct { Config map[string]string } +// Ulimit is an alias for [units.Ulimit], which may be moving to a different +// location or become a local type. This alias is to help transitioning. +// +// Users are recommended to use this alias instead of using [units.Ulimit] directly. +type Ulimit = units.Ulimit + // Resources contains container's resources (cgroups config, ulimits...) type Resources struct { // Applicable to all platforms @@ -387,14 +393,14 @@ type Resources struct { // KernelMemory specifies the kernel memory limit (in bytes) for the container. // Deprecated: kernel 5.4 deprecated kmem.limit_in_bytes. - KernelMemory int64 `json:",omitempty"` - KernelMemoryTCP int64 `json:",omitempty"` // Hard limit for kernel TCP buffer memory (in bytes) - MemoryReservation int64 // Memory soft limit (in bytes) - MemorySwap int64 // Total memory usage (memory + swap); set `-1` to enable unlimited swap - MemorySwappiness *int64 // Tuning container memory swappiness behaviour - OomKillDisable *bool // Whether to disable OOM Killer or not - PidsLimit *int64 // Setting PIDs limit for a container; Set `0` or `-1` for unlimited, or `null` to not change. - Ulimits []*units.Ulimit // List of ulimits to be set in the container + KernelMemory int64 `json:",omitempty"` + KernelMemoryTCP int64 `json:",omitempty"` // Hard limit for kernel TCP buffer memory (in bytes) + MemoryReservation int64 // Memory soft limit (in bytes) + MemorySwap int64 // Total memory usage (memory + swap); set `-1` to enable unlimited swap + MemorySwappiness *int64 // Tuning container memory swappiness behaviour + OomKillDisable *bool // Whether to disable OOM Killer or not + PidsLimit *int64 // Setting PIDs limit for a container; Set `0` or `-1` for unlimited, or `null` to not change. + Ulimits []*Ulimit // List of ulimits to be set in the container // Applicable to Windows CPUCount int64 `json:"CpuCount"` // CPU count diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go index 421329237838..cdee49ea3de1 100644 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go +++ b/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go @@ -9,24 +9,6 @@ func (i Isolation) IsValid() bool { return i.IsDefault() } -// NetworkName returns the name of the network stack. -func (n NetworkMode) NetworkName() string { - if n.IsBridge() { - return network.NetworkBridge - } else if n.IsHost() { - return network.NetworkHost - } else if n.IsContainer() { - return "container" - } else if n.IsNone() { - return network.NetworkNone - } else if n.IsDefault() { - return network.NetworkDefault - } else if n.IsUserDefined() { - return n.UserDefined() - } - return "" -} - // IsBridge indicates whether container uses the bridge network stack func (n NetworkMode) IsBridge() bool { return n == network.NetworkBridge @@ -41,3 +23,23 @@ func (n NetworkMode) IsHost() bool { func (n NetworkMode) IsUserDefined() bool { return !n.IsDefault() && !n.IsBridge() && !n.IsHost() && !n.IsNone() && !n.IsContainer() } + +// NetworkName returns the name of the network stack. +func (n NetworkMode) NetworkName() string { + switch { + case n.IsDefault(): + return network.NetworkDefault + case n.IsBridge(): + return network.NetworkBridge + case n.IsHost(): + return network.NetworkHost + case n.IsNone(): + return network.NetworkNone + case n.IsContainer(): + return "container" + case n.IsUserDefined(): + return n.UserDefined() + default: + return "" + } +} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go index 154667f4f0f7..f08545542cb6 100644 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go +++ b/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go @@ -2,6 +2,11 @@ package container // import "github.com/docker/docker/api/types/container" import "github.com/docker/docker/api/types/network" +// IsValid indicates if an isolation technology is valid +func (i Isolation) IsValid() bool { + return i.IsDefault() || i.IsHyperV() || i.IsProcess() +} + // IsBridge indicates whether container uses the bridge network stack // in windows it is given the name NAT func (n NetworkMode) IsBridge() bool { @@ -19,24 +24,24 @@ func (n NetworkMode) IsUserDefined() bool { return !n.IsDefault() && !n.IsNone() && !n.IsBridge() && !n.IsContainer() } -// IsValid indicates if an isolation technology is valid -func (i Isolation) IsValid() bool { - return i.IsDefault() || i.IsHyperV() || i.IsProcess() -} - // NetworkName returns the name of the network stack. func (n NetworkMode) NetworkName() string { - if n.IsDefault() { + switch { + case n.IsDefault(): return network.NetworkDefault - } else if n.IsBridge() { + case n.IsBridge(): return network.NetworkNat - } else if n.IsNone() { + case n.IsHost(): + // Windows currently doesn't support host network-mode, so + // this would currently never happen.. + return network.NetworkHost + case n.IsNone(): return network.NetworkNone - } else if n.IsContainer() { + case n.IsContainer(): return "container" - } else if n.IsUserDefined() { + case n.IsUserDefined(): return n.UserDefined() + default: + return "" } - - return "" } diff --git a/vendor/github.com/docker/docker/api/types/stats.go b/vendor/github.com/docker/docker/api/types/container/stats.go similarity index 96% rename from vendor/github.com/docker/docker/api/types/stats.go rename to vendor/github.com/docker/docker/api/types/container/stats.go index 20daebed14bd..3b3fb131a2bc 100644 --- a/vendor/github.com/docker/docker/api/types/stats.go +++ b/vendor/github.com/docker/docker/api/types/container/stats.go @@ -1,6 +1,4 @@ -// Package types is used for API stability in the types and response to the -// consumers of the API stats endpoint. -package types // import "github.com/docker/docker/api/types" +package container import "time" @@ -169,8 +167,10 @@ type Stats struct { MemoryStats MemoryStats `json:"memory_stats,omitempty"` } -// StatsJSON is newly used Networks -type StatsJSON struct { +// StatsResponse is newly used Networks. +// +// TODO(thaJeztah): unify with [Stats]. This wrapper was to account for pre-api v1.21 changes, see https://github.com/moby/moby/commit/d3379946ec96fb6163cb8c4517d7d5a067045801 +type StatsResponse struct { Stats Name string `json:"name,omitempty"` diff --git a/vendor/github.com/docker/docker/api/types/events/events.go b/vendor/github.com/docker/docker/api/types/events/events.go index 6dbcd92235c5..e225df4ec186 100644 --- a/vendor/github.com/docker/docker/api/types/events/events.go +++ b/vendor/github.com/docker/docker/api/types/events/events.go @@ -1,4 +1,5 @@ package events // import "github.com/docker/docker/api/types/events" +import "github.com/docker/docker/api/types/filters" // Type is used for event-types. type Type string @@ -125,3 +126,10 @@ type Message struct { Time int64 `json:"time,omitempty"` TimeNano int64 `json:"timeNano,omitempty"` } + +// ListOptions holds parameters to filter events with. +type ListOptions struct { + Since string + Until string + Filters filters.Args +} diff --git a/vendor/github.com/docker/docker/api/types/image/image.go b/vendor/github.com/docker/docker/api/types/image/image.go index 167df28c7b99..abb7ffd8052e 100644 --- a/vendor/github.com/docker/docker/api/types/image/image.go +++ b/vendor/github.com/docker/docker/api/types/image/image.go @@ -1,9 +1,47 @@ package image -import "time" +import ( + "io" + "time" +) // Metadata contains engine-local data about the image. type Metadata struct { // LastTagTime is the date and time at which the image was last tagged. LastTagTime time.Time `json:",omitempty"` } + +// PruneReport contains the response for Engine API: +// POST "/images/prune" +type PruneReport struct { + ImagesDeleted []DeleteResponse + SpaceReclaimed uint64 +} + +// LoadResponse returns information to the client about a load process. +// +// TODO(thaJeztah): remove this type, and just use an io.ReadCloser +// +// This type was added in https://github.com/moby/moby/pull/18878, related +// to https://github.com/moby/moby/issues/19177; +// +// Make docker load to output json when the response content type is json +// Swarm hijacks the response from docker load and returns JSON rather +// than plain text like the Engine does. This makes the API library to return +// information to figure that out. +// +// However the "load" endpoint unconditionally returns JSON; +// https://github.com/moby/moby/blob/7b9d2ef6e5518a3d3f3cc418459f8df786cfbbd1/api/server/router/image/image_routes.go#L248-L255 +// +// PR https://github.com/moby/moby/pull/21959 made the response-type depend +// on whether "quiet" was set, but this logic got changed in a follow-up +// https://github.com/moby/moby/pull/25557, which made the JSON response-type +// unconditionally, but the output produced depend on whether"quiet" was set. +// +// We should deprecated the "quiet" option, as it's really a client +// responsibility. +type LoadResponse struct { + // Body must be closed to avoid a resource leak + Body io.ReadCloser + JSON bool +} diff --git a/vendor/github.com/docker/docker/api/types/image/opts.go b/vendor/github.com/docker/docker/api/types/image/opts.go index c6b1f351b45f..8e32c9af8689 100644 --- a/vendor/github.com/docker/docker/api/types/image/opts.go +++ b/vendor/github.com/docker/docker/api/types/image/opts.go @@ -1,6 +1,18 @@ package image -import "github.com/docker/docker/api/types/filters" +import ( + "context" + "io" + + "github.com/docker/docker/api/types/filters" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" +) + +// ImportSource holds source information for ImageImport +type ImportSource struct { + Source io.Reader // Source is the data to send to the server to create this image from. You must set SourceName to "-" to leverage this. + SourceName string // SourceName is the name of the image to pull. Set to "-" to leverage the Source attribute. +} // ImportOptions holds information to import images from the client host. type ImportOptions struct { @@ -27,12 +39,28 @@ type PullOptions struct { // privilege request fails. // // Also see [github.com/docker/docker/api/types.RequestPrivilegeFunc]. - PrivilegeFunc func() (string, error) + PrivilegeFunc func(context.Context) (string, error) Platform string } // PushOptions holds information to push images. -type PushOptions PullOptions +type PushOptions struct { + All bool + RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry + + // PrivilegeFunc is a function that clients can supply to retry operations + // after getting an authorization error. This function returns the registry + // authentication header value in base64 encoded format, or an error if the + // privilege request fails. + // + // Also see [github.com/docker/docker/api/types.RequestPrivilegeFunc]. + PrivilegeFunc func(context.Context) (string, error) + + // Platform is an optional field that selects a specific platform to push + // when the image is a multi-platform image. + // Using this will only push a single platform-specific manifest. + Platform *ocispec.Platform `json:",omitempty"` +} // ListOptions holds parameters to list images with. type ListOptions struct { diff --git a/vendor/github.com/docker/docker/api/types/mount/mount.go b/vendor/github.com/docker/docker/api/types/mount/mount.go index 6fe04da25794..c68dcf65bd12 100644 --- a/vendor/github.com/docker/docker/api/types/mount/mount.go +++ b/vendor/github.com/docker/docker/api/types/mount/mount.go @@ -119,7 +119,11 @@ type TmpfsOptions struct { SizeBytes int64 `json:",omitempty"` // Mode of the tmpfs upon creation Mode os.FileMode `json:",omitempty"` - + // Options to be passed to the tmpfs mount. An array of arrays. Flag + // options should be provided as 1-length arrays. Other types should be + // provided as 2-length arrays, where the first item is the key and the + // second the value. + Options [][]string `json:",omitempty"` // TODO(stevvooe): There are several more tmpfs flags, specified in the // daemon, that are accepted. Only the most basic are added for now. // diff --git a/vendor/github.com/docker/docker/api/types/network/create_response.go b/vendor/github.com/docker/docker/api/types/network/create_response.go new file mode 100644 index 000000000000..c32b35bff522 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/network/create_response.go @@ -0,0 +1,19 @@ +package network + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// CreateResponse NetworkCreateResponse +// +// OK response to NetworkCreate operation +// swagger:model CreateResponse +type CreateResponse struct { + + // The ID of the created network. + // Required: true + ID string `json:"Id"` + + // Warnings encountered when creating the container + // Required: true + Warning string `json:"Warning"` +} diff --git a/vendor/github.com/docker/docker/api/types/network/endpoint.go b/vendor/github.com/docker/docker/api/types/network/endpoint.go index 9edd1c38d919..0fbb40b351c3 100644 --- a/vendor/github.com/docker/docker/api/types/network/endpoint.go +++ b/vendor/github.com/docker/docker/api/types/network/endpoint.go @@ -18,6 +18,7 @@ type EndpointSettings struct { // Once the container is running, it becomes operational data (it may contain a // generated address). MacAddress string + DriverOpts map[string]string // Operational data NetworkID string EndpointID string @@ -27,7 +28,6 @@ type EndpointSettings struct { IPv6Gateway string GlobalIPv6Address string GlobalIPv6PrefixLen int - DriverOpts map[string]string // DNSNames holds all the (non fully qualified) DNS names associated to this endpoint. First entry is used to // generate PTR records. DNSNames []string diff --git a/vendor/github.com/docker/docker/api/types/network/network.go b/vendor/github.com/docker/docker/api/types/network/network.go index f1f300f3d75b..c8db97a7e674 100644 --- a/vendor/github.com/docker/docker/api/types/network/network.go +++ b/vendor/github.com/docker/docker/api/types/network/network.go @@ -1,6 +1,8 @@ package network // import "github.com/docker/docker/api/types/network" import ( + "time" + "github.com/docker/docker/api/types/filters" ) @@ -17,6 +19,82 @@ const ( NetworkNat = "nat" ) +// CreateRequest is the request message sent to the server for network create call. +type CreateRequest struct { + CreateOptions + Name string // Name is the requested name of the network. + + // Deprecated: CheckDuplicate is deprecated since API v1.44, but it defaults to true when sent by the client + // package to older daemons. + CheckDuplicate *bool `json:",omitempty"` +} + +// CreateOptions holds options to create a network. +type CreateOptions struct { + Driver string // Driver is the driver-name used to create the network (e.g. `bridge`, `overlay`) + Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level). + EnableIPv6 *bool `json:",omitempty"` // EnableIPv6 represents whether to enable IPv6. + IPAM *IPAM // IPAM is the network's IP Address Management. + Internal bool // Internal represents if the network is used internal only. + Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. + Ingress bool // Ingress indicates the network is providing the routing-mesh for the swarm cluster. + ConfigOnly bool // ConfigOnly creates a config-only network. Config-only networks are place-holder networks for network configurations to be used by other networks. ConfigOnly networks cannot be used directly to run containers or services. + ConfigFrom *ConfigReference // ConfigFrom specifies the source which will provide the configuration for this network. The specified network must be a config-only network; see [CreateOptions.ConfigOnly]. + Options map[string]string // Options specifies the network-specific options to use for when creating the network. + Labels map[string]string // Labels holds metadata specific to the network being created. +} + +// ListOptions holds parameters to filter the list of networks with. +type ListOptions struct { + Filters filters.Args +} + +// InspectOptions holds parameters to inspect network. +type InspectOptions struct { + Scope string + Verbose bool +} + +// ConnectOptions represents the data to be used to connect a container to the +// network. +type ConnectOptions struct { + Container string + EndpointConfig *EndpointSettings `json:",omitempty"` +} + +// DisconnectOptions represents the data to be used to disconnect a container +// from the network. +type DisconnectOptions struct { + Container string + Force bool +} + +// Inspect is the body of the "get network" http response message. +type Inspect struct { + Name string // Name is the name of the network + ID string `json:"Id"` // ID uniquely identifies a network on a single machine + Created time.Time // Created is the time the network created + Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level) + Driver string // Driver is the Driver name used to create the network (e.g. `bridge`, `overlay`) + EnableIPv6 bool // EnableIPv6 represents whether to enable IPv6 + IPAM IPAM // IPAM is the network's IP Address Management + Internal bool // Internal represents if the network is used internal only + Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. + Ingress bool // Ingress indicates the network is providing the routing-mesh for the swarm cluster. + ConfigFrom ConfigReference // ConfigFrom specifies the source which will provide the configuration for this network. + ConfigOnly bool // ConfigOnly networks are place-holder networks for network configurations to be used by other networks. ConfigOnly networks cannot be used directly to run containers or services. + Containers map[string]EndpointResource // Containers contains endpoints belonging to the network + Options map[string]string // Options holds the network specific options to use for when creating the network + Labels map[string]string // Labels holds metadata specific to the network being created + Peers []PeerInfo `json:",omitempty"` // List of peer nodes for an overlay network + Services map[string]ServiceInfo `json:",omitempty"` +} + +// Summary is used as response when listing networks. It currently is an alias +// for [Inspect], but may diverge in the future, as not all information may +// be included when listing networks. +type Summary = Inspect + // Address represents an IP address type Address struct { Addr string @@ -45,6 +123,16 @@ type ServiceInfo struct { Tasks []Task } +// EndpointResource contains network resources allocated and used for a +// container in a network. +type EndpointResource struct { + Name string + EndpointID string + MacAddress string + IPv4Address string + IPv6Address string +} + // NetworkingConfig represents the container's networking configuration for each of its interfaces // Carries the networking configs specified in the `docker run` and `docker network connect` commands type NetworkingConfig struct { @@ -70,3 +158,9 @@ var acceptedFilters = map[string]bool{ func ValidateFilters(filter filters.Args) error { return filter.Validate(acceptedFilters) } + +// PruneReport contains the response for Engine API: +// POST "/networks/prune" +type PruneReport struct { + NetworksDeleted []string +} 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 6bbae93ef20e..75ee07b15f97 100644 --- a/vendor/github.com/docker/docker/api/types/registry/registry.go +++ b/vendor/github.com/docker/docker/api/types/registry/registry.go @@ -84,32 +84,6 @@ type IndexInfo struct { Official bool } -// SearchResult describes a search result returned from a registry -type SearchResult struct { - // StarCount indicates the number of stars this repository has - StarCount int `json:"star_count"` - // IsOfficial is true if the result is from an official repository. - IsOfficial bool `json:"is_official"` - // Name is the name of the repository - Name string `json:"name"` - // IsAutomated indicates whether the result is automated. - // - // Deprecated: the "is_automated" field is deprecated and will always be "false". - IsAutomated bool `json:"is_automated"` - // Description is a textual description of the repository - Description string `json:"description"` -} - -// SearchResults lists a collection search results returned from a registry -type SearchResults struct { - // Query contains the query string that generated the search results - Query string `json:"query"` - // NumResults indicates the number of results the query returned - NumResults int `json:"num_results"` - // Results is a slice containing the actual results for the search - Results []SearchResult `json:"results"` -} - // DistributionInspect describes the result obtained from contacting the // registry to retrieve image metadata type DistributionInspect struct { diff --git a/vendor/github.com/docker/docker/api/types/registry/search.go b/vendor/github.com/docker/docker/api/types/registry/search.go new file mode 100644 index 000000000000..a0a1eec5441b --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/registry/search.go @@ -0,0 +1,47 @@ +package registry + +import ( + "context" + + "github.com/docker/docker/api/types/filters" +) + +// SearchOptions holds parameters to search images with. +type SearchOptions struct { + RegistryAuth string + + // PrivilegeFunc is a [types.RequestPrivilegeFunc] the client can + // supply to retry operations after getting an authorization error. + // + // It must return the registry authentication header value in base64 + // format, or an error if the privilege request fails. + PrivilegeFunc func(context.Context) (string, error) + Filters filters.Args + Limit int +} + +// SearchResult describes a search result returned from a registry +type SearchResult struct { + // StarCount indicates the number of stars this repository has + StarCount int `json:"star_count"` + // IsOfficial is true if the result is from an official repository. + IsOfficial bool `json:"is_official"` + // Name is the name of the repository + Name string `json:"name"` + // IsAutomated indicates whether the result is automated. + // + // Deprecated: the "is_automated" field is deprecated and will always be "false". + IsAutomated bool `json:"is_automated"` + // Description is a textual description of the repository + Description string `json:"description"` +} + +// SearchResults lists a collection search results returned from a registry +type SearchResults struct { + // Query contains the query string that generated the search results + Query string `json:"query"` + // NumResults indicates the number of results the query returned + NumResults int `json:"num_results"` + // Results is a slice containing the actual results for the search + Results []SearchResult `json:"results"` +} diff --git a/vendor/github.com/docker/docker/api/types/swarm/container.go b/vendor/github.com/docker/docker/api/types/swarm/container.go index 65f61d2d209c..30e3de70c01c 100644 --- a/vendor/github.com/docker/docker/api/types/swarm/container.go +++ b/vendor/github.com/docker/docker/api/types/swarm/container.go @@ -5,7 +5,6 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/mount" - "github.com/docker/go-units" ) // DNSConfig specifies DNS related configurations in resolver configuration file (resolv.conf) @@ -115,5 +114,6 @@ type ContainerSpec struct { Sysctls map[string]string `json:",omitempty"` CapabilityAdd []string `json:",omitempty"` CapabilityDrop []string `json:",omitempty"` - Ulimits []*units.Ulimit `json:",omitempty"` + Ulimits []*container.Ulimit `json:",omitempty"` + OomScoreAdj int64 `json:",omitempty"` } diff --git a/vendor/github.com/docker/docker/api/types/system/info.go b/vendor/github.com/docker/docker/api/types/system/info.go index 89d4a0098e36..6791cf3284c4 100644 --- a/vendor/github.com/docker/docker/api/types/system/info.go +++ b/vendor/github.com/docker/docker/api/types/system/info.go @@ -75,6 +75,8 @@ type Info struct { DefaultAddressPools []NetworkAddressPool `json:",omitempty"` CDISpecDirs []string + Containerd *ContainerdInfo `json:",omitempty"` + // Legacy API fields for older API versions. legacyFields @@ -85,6 +87,43 @@ type Info struct { Warnings []string } +// ContainerdInfo holds information about the containerd instance used by the daemon. +type ContainerdInfo struct { + // Address is the path to the containerd socket. + Address string `json:",omitempty"` + // Namespaces is the containerd namespaces used by the daemon. + Namespaces ContainerdNamespaces +} + +// ContainerdNamespaces reflects the containerd namespaces used by the daemon. +// +// These namespaces can be configured in the daemon configuration, and are +// considered to be used exclusively by the daemon, +// +// As these namespaces are considered to be exclusively accessed +// by the daemon, it is not recommended to change these values, +// or to change them to a value that is used by other systems, +// such as cri-containerd. +type ContainerdNamespaces struct { + // Containers holds the default containerd namespace used for + // containers managed by the daemon. + // + // The default namespace for containers is "moby", but will be + // suffixed with the `.` of the remapped `root` if + // user-namespaces are enabled and the containerd image-store + // is used. + Containers string + + // Plugins holds the default containerd namespace used for + // plugins managed by the daemon. + // + // The default namespace for plugins is "moby", but will be + // suffixed with the `.` of the remapped `root` if + // user-namespaces are enabled and the containerd image-store + // is used. + Plugins string +} + type legacyFields struct { ExecutionDriver string `json:",omitempty"` // Deprecated: deprecated since API v1.25, but returned for older versions. } diff --git a/vendor/github.com/docker/docker/api/types/types.go b/vendor/github.com/docker/docker/api/types/types.go index 583b9cbecfa2..f0c648e15887 100644 --- a/vendor/github.com/docker/docker/api/types/types.go +++ b/vendor/github.com/docker/docker/api/types/types.go @@ -1,8 +1,6 @@ package types // import "github.com/docker/docker/api/types" import ( - "io" - "os" "time" "github.com/docker/docker/api/types/container" @@ -155,36 +153,13 @@ type Container struct { State string Status string HostConfig struct { - NetworkMode string `json:",omitempty"` + NetworkMode string `json:",omitempty"` + Annotations map[string]string `json:",omitempty"` } NetworkSettings *SummaryNetworkSettings Mounts []MountPoint } -// CopyConfig contains request body of Engine API: -// POST "/containers/"+containerID+"/copy" -type CopyConfig struct { - Resource string -} - -// ContainerPathStat is used to encode the header from -// GET "/containers/{name:.*}/archive" -// "Name" is the file or directory name. -type ContainerPathStat struct { - Name string `json:"name"` - Size int64 `json:"size"` - Mode os.FileMode `json:"mode"` - Mtime time.Time `json:"mtime"` - LinkTarget string `json:"linkTarget"` -} - -// ContainerStats contains response of Engine API: -// GET "/stats" -type ContainerStats struct { - Body io.ReadCloser `json:"body"` - OSType string `json:"ostype"` -} - // Ping contains response of Engine API: // GET "/_ping" type Ping struct { @@ -230,17 +205,6 @@ type Version struct { BuildTime string `json:",omitempty"` } -// ExecStartCheck is a temp struct used by execStart -// Config fields is part of ExecConfig in runconfig package -type ExecStartCheck struct { - // ExecStart will first check if it's detached - Detach bool - // Check if there's a tty - Tty bool - // Terminal size [height, width], unused if Tty == false - ConsoleSize *[2]uint `json:",omitempty"` -} - // HealthcheckResult stores information about a single run of a healthcheck probe type HealthcheckResult struct { Start time.Time // Start is the time this check started @@ -423,84 +387,6 @@ type MountPoint struct { Propagation mount.Propagation } -// NetworkResource is the body of the "get network" http response message -type NetworkResource struct { - Name string // Name is the requested name of the network - ID string `json:"Id"` // ID uniquely identifies a network on a single machine - Created time.Time // Created is the time the network created - Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level) - Driver string // Driver is the Driver name used to create the network (e.g. `bridge`, `overlay`) - EnableIPv6 bool // EnableIPv6 represents whether to enable IPv6 - IPAM network.IPAM // IPAM is the network's IP Address Management - Internal bool // Internal represents if the network is used internal only - Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. - Ingress bool // Ingress indicates the network is providing the routing-mesh for the swarm cluster. - ConfigFrom network.ConfigReference // ConfigFrom specifies the source which will provide the configuration for this network. - ConfigOnly bool // ConfigOnly networks are place-holder networks for network configurations to be used by other networks. ConfigOnly networks cannot be used directly to run containers or services. - Containers map[string]EndpointResource // Containers contains endpoints belonging to the network - Options map[string]string // Options holds the network specific options to use for when creating the network - Labels map[string]string // Labels holds metadata specific to the network being created - Peers []network.PeerInfo `json:",omitempty"` // List of peer nodes for an overlay network - Services map[string]network.ServiceInfo `json:",omitempty"` -} - -// EndpointResource contains network resources allocated and used for a container in a network -type EndpointResource struct { - Name string - EndpointID string - MacAddress string - IPv4Address string - IPv6Address string -} - -// NetworkCreate is the expected body of the "create network" http request message -type NetworkCreate struct { - // Deprecated: CheckDuplicate is deprecated since API v1.44, but it defaults to true when sent by the client - // package to older daemons. - CheckDuplicate bool `json:",omitempty"` - Driver string // Driver is the driver-name used to create the network (e.g. `bridge`, `overlay`) - Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level). - EnableIPv6 bool // EnableIPv6 represents whether to enable IPv6. - IPAM *network.IPAM // IPAM is the network's IP Address Management. - Internal bool // Internal represents if the network is used internal only. - Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. - Ingress bool // Ingress indicates the network is providing the routing-mesh for the swarm cluster. - ConfigOnly bool // ConfigOnly creates a config-only network. Config-only networks are place-holder networks for network configurations to be used by other networks. ConfigOnly networks cannot be used directly to run containers or services. - ConfigFrom *network.ConfigReference // ConfigFrom specifies the source which will provide the configuration for this network. The specified network must be a config-only network; see [NetworkCreate.ConfigOnly]. - Options map[string]string // Options specifies the network-specific options to use for when creating the network. - Labels map[string]string // Labels holds metadata specific to the network being created. -} - -// NetworkCreateRequest is the request message sent to the server for network create call. -type NetworkCreateRequest struct { - NetworkCreate - Name string // Name is the requested name of the network. -} - -// NetworkCreateResponse is the response message sent by the server for network create call -type NetworkCreateResponse struct { - ID string `json:"Id"` - Warning string -} - -// NetworkConnect represents the data to be used to connect a container to the network -type NetworkConnect struct { - Container string - EndpointConfig *network.EndpointSettings `json:",omitempty"` -} - -// NetworkDisconnect represents the data to be used to disconnect a container from the network -type NetworkDisconnect struct { - Container string - Force bool -} - -// NetworkInspectOptions holds parameters to inspect network -type NetworkInspectOptions struct { - Scope string - Verbose bool -} - // DiskUsageObject represents an object type used for disk usage query filtering. type DiskUsageObject string @@ -533,27 +419,6 @@ type DiskUsage struct { BuilderSize int64 `json:",omitempty"` // Deprecated: deprecated in API 1.38, and no longer used since API 1.40. } -// ContainersPruneReport contains the response for Engine API: -// POST "/containers/prune" -type ContainersPruneReport struct { - ContainersDeleted []string - SpaceReclaimed uint64 -} - -// VolumesPruneReport contains the response for Engine API: -// POST "/volumes/prune" -type VolumesPruneReport struct { - VolumesDeleted []string - SpaceReclaimed uint64 -} - -// ImagesPruneReport contains the response for Engine API: -// POST "/images/prune" -type ImagesPruneReport struct { - ImagesDeleted []image.DeleteResponse - SpaceReclaimed uint64 -} - // BuildCachePruneReport contains the response for Engine API: // POST "/build/prune" type BuildCachePruneReport struct { @@ -561,12 +426,6 @@ type BuildCachePruneReport struct { SpaceReclaimed uint64 } -// NetworksPruneReport contains the response for Engine API: -// POST "/networks/prune" -type NetworksPruneReport struct { - NetworksDeleted []string -} - // SecretCreateResponse contains the information returned to a client // on the creation of a new secret. type SecretCreateResponse struct { diff --git a/vendor/github.com/docker/docker/api/types/types_deprecated.go b/vendor/github.com/docker/docker/api/types/types_deprecated.go index 231a5cca4687..8edf70b7c885 100644 --- a/vendor/github.com/docker/docker/api/types/types_deprecated.go +++ b/vendor/github.com/docker/docker/api/types/types_deprecated.go @@ -1,35 +1,196 @@ package types import ( + "github.com/docker/docker/api/types/container" + "github.com/docker/docker/api/types/events" "github.com/docker/docker/api/types/image" + "github.com/docker/docker/api/types/network" + "github.com/docker/docker/api/types/registry" + "github.com/docker/docker/api/types/volume" ) -// ImageImportOptions holds information to import images from the client host. +// ImagesPruneReport contains the response for Engine API: +// POST "/images/prune" // -// Deprecated: use [image.ImportOptions]. -type ImageImportOptions = image.ImportOptions +// Deprecated: use [image.PruneReport]. +type ImagesPruneReport = image.PruneReport -// ImageCreateOptions holds information to create images. +// VolumesPruneReport contains the response for Engine API: +// POST "/volumes/prune". // -// Deprecated: use [image.CreateOptions]. -type ImageCreateOptions = image.CreateOptions +// Deprecated: use [volume.PruneReport]. +type VolumesPruneReport = volume.PruneReport -// ImagePullOptions holds information to pull images. +// NetworkCreateRequest is the request message sent to the server for network create call. // -// Deprecated: use [image.PullOptions]. -type ImagePullOptions = image.PullOptions +// Deprecated: use [network.CreateRequest]. +type NetworkCreateRequest = network.CreateRequest -// ImagePushOptions holds information to push images. +// NetworkCreate is the expected body of the "create network" http request message // -// Deprecated: use [image.PushOptions]. -type ImagePushOptions = image.PushOptions +// Deprecated: use [network.CreateOptions]. +type NetworkCreate = network.CreateOptions -// ImageListOptions holds parameters to list images with. +// NetworkListOptions holds parameters to filter the list of networks with. // -// Deprecated: use [image.ListOptions]. -type ImageListOptions = image.ListOptions +// Deprecated: use [network.ListOptions]. +type NetworkListOptions = network.ListOptions -// ImageRemoveOptions holds parameters to remove images. +// NetworkCreateResponse is the response message sent by the server for network create call. // -// Deprecated: use [image.RemoveOptions]. -type ImageRemoveOptions = image.RemoveOptions +// Deprecated: use [network.CreateResponse]. +type NetworkCreateResponse = network.CreateResponse + +// NetworkInspectOptions holds parameters to inspect network. +// +// Deprecated: use [network.InspectOptions]. +type NetworkInspectOptions = network.InspectOptions + +// NetworkConnect represents the data to be used to connect a container to the network +// +// Deprecated: use [network.ConnectOptions]. +type NetworkConnect = network.ConnectOptions + +// NetworkDisconnect represents the data to be used to disconnect a container from the network +// +// Deprecated: use [network.DisconnectOptions]. +type NetworkDisconnect = network.DisconnectOptions + +// EndpointResource contains network resources allocated and used for a container in a network. +// +// Deprecated: use [network.EndpointResource]. +type EndpointResource = network.EndpointResource + +// NetworkResource is the body of the "get network" http response message/ +// +// Deprecated: use [network.Inspect] or [network.Summary] (for list operations). +type NetworkResource = network.Inspect + +// NetworksPruneReport contains the response for Engine API: +// POST "/networks/prune" +// +// Deprecated: use [network.PruneReport]. +type NetworksPruneReport = network.PruneReport + +// ExecConfig is a small subset of the Config struct that holds the configuration +// for the exec feature of docker. +// +// Deprecated: use [container.ExecOptions]. +type ExecConfig = container.ExecOptions + +// ExecStartCheck is a temp struct used by execStart +// Config fields is part of ExecConfig in runconfig package +// +// Deprecated: use [container.ExecStartOptions] or [container.ExecAttachOptions]. +type ExecStartCheck = container.ExecStartOptions + +// ContainerExecInspect holds information returned by exec inspect. +// +// Deprecated: use [container.ExecInspect]. +type ContainerExecInspect = container.ExecInspect + +// ContainersPruneReport contains the response for Engine API: +// POST "/containers/prune" +// +// Deprecated: use [container.PruneReport]. +type ContainersPruneReport = container.PruneReport + +// ContainerPathStat is used to encode the header from +// GET "/containers/{name:.*}/archive" +// "Name" is the file or directory name. +// +// Deprecated: use [container.PathStat]. +type ContainerPathStat = container.PathStat + +// CopyToContainerOptions holds information +// about files to copy into a container. +// +// Deprecated: use [container.CopyToContainerOptions], +type CopyToContainerOptions = container.CopyToContainerOptions + +// ContainerStats contains response of Engine API: +// GET "/stats" +// +// Deprecated: use [container.StatsResponseReader]. +type ContainerStats = container.StatsResponseReader + +// ThrottlingData stores CPU throttling stats of one running container. +// Not used on Windows. +// +// Deprecated: use [container.ThrottlingData]. +type ThrottlingData = container.ThrottlingData + +// CPUUsage stores All CPU stats aggregated since container inception. +// +// Deprecated: use [container.CPUUsage]. +type CPUUsage = container.CPUUsage + +// CPUStats aggregates and wraps all CPU related info of container +// +// Deprecated: use [container.CPUStats]. +type CPUStats = container.CPUStats + +// MemoryStats aggregates all memory stats since container inception on Linux. +// Windows returns stats for commit and private working set only. +// +// Deprecated: use [container.MemoryStats]. +type MemoryStats = container.MemoryStats + +// BlkioStatEntry is one small entity to store a piece of Blkio stats +// Not used on Windows. +// +// Deprecated: use [container.BlkioStatEntry]. +type BlkioStatEntry = container.BlkioStatEntry + +// BlkioStats stores All IO service stats for data read and write. +// This is a Linux specific structure as the differences between expressing +// block I/O on Windows and Linux are sufficiently significant to make +// little sense attempting to morph into a combined structure. +// +// Deprecated: use [container.BlkioStats]. +type BlkioStats = container.BlkioStats + +// StorageStats is the disk I/O stats for read/write on Windows. +// +// Deprecated: use [container.StorageStats]. +type StorageStats = container.StorageStats + +// NetworkStats aggregates the network stats of one container +// +// Deprecated: use [container.NetworkStats]. +type NetworkStats = container.NetworkStats + +// PidsStats contains the stats of a container's pids +// +// Deprecated: use [container.PidsStats]. +type PidsStats = container.PidsStats + +// Stats is Ultimate struct aggregating all types of stats of one container +// +// Deprecated: use [container.Stats]. +type Stats = container.Stats + +// StatsJSON is newly used Networks +// +// Deprecated: use [container.StatsResponse]. +type StatsJSON = container.StatsResponse + +// EventsOptions holds parameters to filter events with. +// +// Deprecated: use [events.ListOptions]. +type EventsOptions = events.ListOptions + +// ImageSearchOptions holds parameters to search images with. +// +// Deprecated: use [registry.SearchOptions]. +type ImageSearchOptions = registry.SearchOptions + +// ImageImportSource holds source information for ImageImport +// +// Deprecated: use [image.ImportSource]. +type ImageImportSource image.ImportSource + +// ImageLoadResponse returns information to the client about a load process. +// +// Deprecated: use [image.LoadResponse]. +type ImageLoadResponse = image.LoadResponse diff --git a/vendor/github.com/docker/docker/api/types/volume/options.go b/vendor/github.com/docker/docker/api/types/volume/options.go index 8b0dd1389986..0b9645e006d3 100644 --- a/vendor/github.com/docker/docker/api/types/volume/options.go +++ b/vendor/github.com/docker/docker/api/types/volume/options.go @@ -6,3 +6,10 @@ import "github.com/docker/docker/api/types/filters" type ListOptions struct { Filters filters.Args } + +// PruneReport contains the response for Engine API: +// POST "/volumes/prune" +type PruneReport struct { + VolumesDeleted []string + SpaceReclaimed uint64 +} diff --git a/vendor/github.com/docker/docker/client/client.go b/vendor/github.com/docker/docker/client/client.go index f2eeb6c5702e..60d91bc65b5a 100644 --- a/vendor/github.com/docker/docker/client/client.go +++ b/vendor/github.com/docker/docker/client/client.go @@ -49,6 +49,8 @@ import ( "net/url" "path" "strings" + "sync" + "sync/atomic" "time" "github.com/docker/docker/api" @@ -131,7 +133,10 @@ type Client struct { negotiateVersion bool // negotiated indicates that API version negotiation took place - negotiated bool + negotiated atomic.Bool + + // negotiateLock is used to single-flight the version negotiation process + negotiateLock sync.Mutex tp trace.TracerProvider @@ -266,7 +271,16 @@ func (cli *Client) Close() error { // be negotiated when making the actual requests, and for which cases // we cannot do the negotiation lazily. func (cli *Client) checkVersion(ctx context.Context) error { - if !cli.manualOverride && cli.negotiateVersion && !cli.negotiated { + if !cli.manualOverride && cli.negotiateVersion && !cli.negotiated.Load() { + // Ensure exclusive write access to version and negotiated fields + cli.negotiateLock.Lock() + defer cli.negotiateLock.Unlock() + + // May have been set during last execution of critical zone + if cli.negotiated.Load() { + return nil + } + ping, err := cli.Ping(ctx) if err != nil { return err @@ -312,6 +326,10 @@ func (cli *Client) ClientVersion() string { // added (1.24). func (cli *Client) NegotiateAPIVersion(ctx context.Context) { if !cli.manualOverride { + // Avoid concurrent modification of version-related fields + cli.negotiateLock.Lock() + defer cli.negotiateLock.Unlock() + ping, err := cli.Ping(ctx) if err != nil { // FIXME(thaJeztah): Ping returns an error when failing to connect to the API; we should not swallow the error here, and instead returning it. @@ -336,6 +354,10 @@ func (cli *Client) NegotiateAPIVersion(ctx context.Context) { // added (1.24). func (cli *Client) NegotiateAPIVersionPing(pingResponse types.Ping) { if !cli.manualOverride { + // Avoid concurrent modification of version-related fields + cli.negotiateLock.Lock() + defer cli.negotiateLock.Unlock() + cli.negotiateAPIVersionPing(pingResponse) } } @@ -361,7 +383,7 @@ func (cli *Client) negotiateAPIVersionPing(pingResponse types.Ping) { // Store the results, so that automatic API version negotiation (if enabled) // won't be performed on the next request. if cli.negotiateVersion { - cli.negotiated = true + cli.negotiated.Store(true) } } diff --git a/vendor/github.com/docker/docker/client/container_copy.go b/vendor/github.com/docker/docker/client/container_copy.go index 883be7fa3451..8490a3b1565b 100644 --- a/vendor/github.com/docker/docker/client/container_copy.go +++ b/vendor/github.com/docker/docker/client/container_copy.go @@ -11,11 +11,11 @@ import ( "path/filepath" "strings" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" ) // ContainerStatPath returns stat information about a path inside the container filesystem. -func (cli *Client) ContainerStatPath(ctx context.Context, containerID, path string) (types.ContainerPathStat, error) { +func (cli *Client) ContainerStatPath(ctx context.Context, containerID, path string) (container.PathStat, error) { query := url.Values{} query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API. @@ -23,14 +23,14 @@ func (cli *Client) ContainerStatPath(ctx context.Context, containerID, path stri response, err := cli.head(ctx, urlStr, query, nil) defer ensureReaderClosed(response) if err != nil { - return types.ContainerPathStat{}, err + return container.PathStat{}, err } return getContainerPathStatFromHeader(response.header) } // CopyToContainer copies content into the container filesystem. // Note that `content` must be a Reader for a TAR archive -func (cli *Client) CopyToContainer(ctx context.Context, containerID, dstPath string, content io.Reader, options types.CopyToContainerOptions) error { +func (cli *Client) CopyToContainer(ctx context.Context, containerID, dstPath string, content io.Reader, options container.CopyToContainerOptions) error { query := url.Values{} query.Set("path", filepath.ToSlash(dstPath)) // Normalize the paths used in the API. // Do not allow for an existing directory to be overwritten by a non-directory and vice versa. @@ -55,14 +55,14 @@ func (cli *Client) CopyToContainer(ctx context.Context, containerID, dstPath str // CopyFromContainer gets the content from the container and returns it as a Reader // for a TAR archive to manipulate it in the host. It's up to the caller to close the reader. -func (cli *Client) CopyFromContainer(ctx context.Context, containerID, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) { +func (cli *Client) CopyFromContainer(ctx context.Context, containerID, srcPath string) (io.ReadCloser, container.PathStat, error) { query := make(url.Values, 1) query.Set("path", filepath.ToSlash(srcPath)) // Normalize the paths used in the API. apiPath := "/containers/" + containerID + "/archive" response, err := cli.get(ctx, apiPath, query, nil) if err != nil { - return nil, types.ContainerPathStat{}, err + return nil, container.PathStat{}, err } // In order to get the copy behavior right, we need to know information @@ -78,8 +78,8 @@ func (cli *Client) CopyFromContainer(ctx context.Context, containerID, srcPath s return response.body, stat, err } -func getContainerPathStatFromHeader(header http.Header) (types.ContainerPathStat, error) { - var stat types.ContainerPathStat +func getContainerPathStatFromHeader(header http.Header) (container.PathStat, error) { + var stat container.PathStat encodedStat := header.Get("X-Docker-Container-Path-Stat") statDecoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(encodedStat)) diff --git a/vendor/github.com/docker/docker/client/container_exec.go b/vendor/github.com/docker/docker/client/container_exec.go index 526a3876a4a7..9379448d1aef 100644 --- a/vendor/github.com/docker/docker/client/container_exec.go +++ b/vendor/github.com/docker/docker/client/container_exec.go @@ -6,11 +6,12 @@ import ( "net/http" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/versions" ) // ContainerExecCreate creates a new exec configuration to run an exec process. -func (cli *Client) ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error) { +func (cli *Client) ContainerExecCreate(ctx context.Context, container string, options container.ExecOptions) (types.IDResponse, error) { var response types.IDResponse // Make sure we negotiated (if the client is configured to do so), @@ -22,14 +23,14 @@ func (cli *Client) ContainerExecCreate(ctx context.Context, container string, co return response, err } - if err := cli.NewVersionError(ctx, "1.25", "env"); len(config.Env) != 0 && err != nil { + if err := cli.NewVersionError(ctx, "1.25", "env"); len(options.Env) != 0 && err != nil { return response, err } if versions.LessThan(cli.ClientVersion(), "1.42") { - config.ConsoleSize = nil + options.ConsoleSize = nil } - resp, err := cli.post(ctx, "/containers/"+container+"/exec", nil, config, nil) + resp, err := cli.post(ctx, "/containers/"+container+"/exec", nil, options, nil) defer ensureReaderClosed(resp) if err != nil { return response, err @@ -39,7 +40,7 @@ func (cli *Client) ContainerExecCreate(ctx context.Context, container string, co } // ContainerExecStart starts an exec process already created in the docker host. -func (cli *Client) ContainerExecStart(ctx context.Context, execID string, config types.ExecStartCheck) error { +func (cli *Client) ContainerExecStart(ctx context.Context, execID string, config container.ExecStartOptions) error { if versions.LessThan(cli.ClientVersion(), "1.42") { config.ConsoleSize = nil } @@ -52,7 +53,7 @@ func (cli *Client) ContainerExecStart(ctx context.Context, execID string, config // It returns a types.HijackedConnection with the hijacked connection // and the a reader to get output. It's up to the called to close // the hijacked connection by calling types.HijackedResponse.Close. -func (cli *Client) ContainerExecAttach(ctx context.Context, execID string, config types.ExecStartCheck) (types.HijackedResponse, error) { +func (cli *Client) ContainerExecAttach(ctx context.Context, execID string, config container.ExecAttachOptions) (types.HijackedResponse, error) { if versions.LessThan(cli.ClientVersion(), "1.42") { config.ConsoleSize = nil } @@ -62,8 +63,8 @@ func (cli *Client) ContainerExecAttach(ctx context.Context, execID string, confi } // ContainerExecInspect returns information about a specific exec process on the docker host. -func (cli *Client) ContainerExecInspect(ctx context.Context, execID string) (types.ContainerExecInspect, error) { - var response types.ContainerExecInspect +func (cli *Client) ContainerExecInspect(ctx context.Context, execID string) (container.ExecInspect, error) { + var response container.ExecInspect resp, err := cli.get(ctx, "/exec/"+execID+"/json", nil, nil) if err != nil { return response, err diff --git a/vendor/github.com/docker/docker/client/container_prune.go b/vendor/github.com/docker/docker/client/container_prune.go index ca509238447b..29c922da77e5 100644 --- a/vendor/github.com/docker/docker/client/container_prune.go +++ b/vendor/github.com/docker/docker/client/container_prune.go @@ -5,13 +5,13 @@ import ( "encoding/json" "fmt" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" ) // ContainersPrune requests the daemon to delete unused data -func (cli *Client) ContainersPrune(ctx context.Context, pruneFilters filters.Args) (types.ContainersPruneReport, error) { - var report types.ContainersPruneReport +func (cli *Client) ContainersPrune(ctx context.Context, pruneFilters filters.Args) (container.PruneReport, error) { + var report container.PruneReport if err := cli.NewVersionError(ctx, "1.25", "container prune"); err != nil { return report, err diff --git a/vendor/github.com/docker/docker/client/container_stats.go b/vendor/github.com/docker/docker/client/container_stats.go index 3fabb75f3211..b5641daee99d 100644 --- a/vendor/github.com/docker/docker/client/container_stats.go +++ b/vendor/github.com/docker/docker/client/container_stats.go @@ -4,12 +4,12 @@ import ( "context" "net/url" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/container" ) // ContainerStats returns near realtime stats for a given container. // It's up to the caller to close the io.ReadCloser returned. -func (cli *Client) ContainerStats(ctx context.Context, containerID string, stream bool) (types.ContainerStats, error) { +func (cli *Client) ContainerStats(ctx context.Context, containerID string, stream bool) (container.StatsResponseReader, error) { query := url.Values{} query.Set("stream", "0") if stream { @@ -18,10 +18,10 @@ func (cli *Client) ContainerStats(ctx context.Context, containerID string, strea resp, err := cli.get(ctx, "/containers/"+containerID+"/stats", query, nil) if err != nil { - return types.ContainerStats{}, err + return container.StatsResponseReader{}, err } - return types.ContainerStats{ + return container.StatsResponseReader{ Body: resp.body, OSType: getDockerOS(resp.header.Get("Server")), }, nil @@ -29,17 +29,17 @@ func (cli *Client) ContainerStats(ctx context.Context, containerID string, strea // ContainerStatsOneShot gets a single stat entry from a container. // It differs from `ContainerStats` in that the API should not wait to prime the stats -func (cli *Client) ContainerStatsOneShot(ctx context.Context, containerID string) (types.ContainerStats, error) { +func (cli *Client) ContainerStatsOneShot(ctx context.Context, containerID string) (container.StatsResponseReader, error) { query := url.Values{} query.Set("stream", "0") query.Set("one-shot", "1") resp, err := cli.get(ctx, "/containers/"+containerID+"/stats", query, nil) if err != nil { - return types.ContainerStats{}, err + return container.StatsResponseReader{}, err } - return types.ContainerStats{ + return container.StatsResponseReader{ Body: resp.body, OSType: getDockerOS(resp.header.Get("Server")), }, nil diff --git a/vendor/github.com/docker/docker/client/events.go b/vendor/github.com/docker/docker/client/events.go index a9c48a9288d4..d3ab26bed856 100644 --- a/vendor/github.com/docker/docker/client/events.go +++ b/vendor/github.com/docker/docker/client/events.go @@ -6,7 +6,6 @@ import ( "net/url" "time" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/events" "github.com/docker/docker/api/types/filters" timetypes "github.com/docker/docker/api/types/time" @@ -16,7 +15,7 @@ import ( // by cancelling the context. Once the stream has been completely read an io.EOF error will // be sent over the error channel. If an error is sent all processing will be stopped. It's up // to the caller to reopen the stream in the event of an error by reinvoking this method. -func (cli *Client) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) { +func (cli *Client) Events(ctx context.Context, options events.ListOptions) (<-chan events.Message, <-chan error) { messages := make(chan events.Message) errs := make(chan error, 1) @@ -68,7 +67,7 @@ func (cli *Client) Events(ctx context.Context, options types.EventsOptions) (<-c return messages, errs } -func buildEventsQueryParams(cliVersion string, options types.EventsOptions) (url.Values, error) { +func buildEventsQueryParams(cliVersion string, options events.ListOptions) (url.Values, error) { query := url.Values{} ref := time.Now() diff --git a/vendor/github.com/docker/docker/client/image_import.go b/vendor/github.com/docker/docker/client/image_import.go index 5a890b0c59ef..43d55eda8eca 100644 --- a/vendor/github.com/docker/docker/client/image_import.go +++ b/vendor/github.com/docker/docker/client/image_import.go @@ -7,13 +7,12 @@ import ( "strings" "github.com/distribution/reference" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/image" ) // ImageImport creates a new image based on the source options. // It returns the JSON content in the response body. -func (cli *Client) ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options image.ImportOptions) (io.ReadCloser, error) { +func (cli *Client) ImageImport(ctx context.Context, source image.ImportSource, ref string, options image.ImportOptions) (io.ReadCloser, error) { if ref != "" { // Check if the given image name can be resolved if _, err := reference.ParseNormalizedNamed(ref); err != nil { diff --git a/vendor/github.com/docker/docker/client/image_load.go b/vendor/github.com/docker/docker/client/image_load.go index c825206ea5e0..c68f0013e632 100644 --- a/vendor/github.com/docker/docker/client/image_load.go +++ b/vendor/github.com/docker/docker/client/image_load.go @@ -6,13 +6,13 @@ import ( "net/http" "net/url" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/image" ) // ImageLoad loads an image in the docker host from the client host. // It's up to the caller to close the io.ReadCloser in the // ImageLoadResponse returned by this function. -func (cli *Client) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) { +func (cli *Client) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (image.LoadResponse, error) { v := url.Values{} v.Set("quiet", "0") if quiet { @@ -22,9 +22,9 @@ func (cli *Client) ImageLoad(ctx context.Context, input io.Reader, quiet bool) ( "Content-Type": {"application/x-tar"}, }) if err != nil { - return types.ImageLoadResponse{}, err + return image.LoadResponse{}, err } - return types.ImageLoadResponse{ + return image.LoadResponse{ Body: resp.body, JSON: resp.header.Get("Content-Type") == "application/json", }, nil diff --git a/vendor/github.com/docker/docker/client/image_prune.go b/vendor/github.com/docker/docker/client/image_prune.go index 6b82d6ab6ca5..5ee987e248ae 100644 --- a/vendor/github.com/docker/docker/client/image_prune.go +++ b/vendor/github.com/docker/docker/client/image_prune.go @@ -5,13 +5,13 @@ import ( "encoding/json" "fmt" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" + "github.com/docker/docker/api/types/image" ) // ImagesPrune requests the daemon to delete unused data -func (cli *Client) ImagesPrune(ctx context.Context, pruneFilters filters.Args) (types.ImagesPruneReport, error) { - var report types.ImagesPruneReport +func (cli *Client) ImagesPrune(ctx context.Context, pruneFilters filters.Args) (image.PruneReport, error) { + var report image.PruneReport if err := cli.NewVersionError(ctx, "1.25", "image prune"); err != nil { return report, err diff --git a/vendor/github.com/docker/docker/client/image_pull.go b/vendor/github.com/docker/docker/client/image_pull.go index 6438cf6a96b2..1634c4c8006d 100644 --- a/vendor/github.com/docker/docker/client/image_pull.go +++ b/vendor/github.com/docker/docker/client/image_pull.go @@ -36,7 +36,7 @@ func (cli *Client) ImagePull(ctx context.Context, refStr string, options image.P resp, err := cli.tryImageCreate(ctx, query, options.RegistryAuth) if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil { - newAuthHeader, privilegeErr := options.PrivilegeFunc() + newAuthHeader, privilegeErr := options.PrivilegeFunc(ctx) if privilegeErr != nil { return nil, privilegeErr } diff --git a/vendor/github.com/docker/docker/client/image_push.go b/vendor/github.com/docker/docker/client/image_push.go index e6a6b11eeadd..16f9c4651d34 100644 --- a/vendor/github.com/docker/docker/client/image_push.go +++ b/vendor/github.com/docker/docker/client/image_push.go @@ -2,7 +2,9 @@ package client // import "github.com/docker/docker/client" import ( "context" + "encoding/json" "errors" + "fmt" "io" "net/http" "net/url" @@ -36,9 +38,23 @@ func (cli *Client) ImagePush(ctx context.Context, image string, options image.Pu } } + if options.Platform != nil { + if err := cli.NewVersionError(ctx, "1.46", "platform"); err != nil { + return nil, err + } + + p := *options.Platform + pJson, err := json.Marshal(p) + if err != nil { + return nil, fmt.Errorf("invalid platform: %v", err) + } + + query.Set("platform", string(pJson)) + } + resp, err := cli.tryImagePush(ctx, name, query, options.RegistryAuth) if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil { - newAuthHeader, privilegeErr := options.PrivilegeFunc() + newAuthHeader, privilegeErr := options.PrivilegeFunc(ctx) if privilegeErr != nil { return nil, privilegeErr } diff --git a/vendor/github.com/docker/docker/client/image_search.go b/vendor/github.com/docker/docker/client/image_search.go index 8971b139aed2..0a07457574fa 100644 --- a/vendor/github.com/docker/docker/client/image_search.go +++ b/vendor/github.com/docker/docker/client/image_search.go @@ -7,7 +7,6 @@ import ( "net/url" "strconv" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/registry" "github.com/docker/docker/errdefs" @@ -15,7 +14,7 @@ import ( // ImageSearch makes the docker host search by a term in a remote registry. // The list of results is not sorted in any fashion. -func (cli *Client) ImageSearch(ctx context.Context, term string, options types.ImageSearchOptions) ([]registry.SearchResult, error) { +func (cli *Client) ImageSearch(ctx context.Context, term string, options registry.SearchOptions) ([]registry.SearchResult, error) { var results []registry.SearchResult query := url.Values{} query.Set("term", term) @@ -34,7 +33,7 @@ func (cli *Client) ImageSearch(ctx context.Context, term string, options types.I resp, err := cli.tryImageSearch(ctx, query, options.RegistryAuth) defer ensureReaderClosed(resp) if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil { - newAuthHeader, privilegeErr := options.PrivilegeFunc() + newAuthHeader, privilegeErr := options.PrivilegeFunc(ctx) if privilegeErr != nil { return results, privilegeErr } diff --git a/vendor/github.com/docker/docker/client/interface.go b/vendor/github.com/docker/docker/client/interface.go index 45d233f253eb..cc60a5d13b48 100644 --- a/vendor/github.com/docker/docker/client/interface.go +++ b/vendor/github.com/docker/docker/client/interface.go @@ -50,11 +50,11 @@ type ContainerAPIClient interface { ContainerCommit(ctx context.Context, container string, options container.CommitOptions) (types.IDResponse, 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) + ContainerExecAttach(ctx context.Context, execID string, options container.ExecAttachOptions) (types.HijackedResponse, error) + ContainerExecCreate(ctx context.Context, container string, options container.ExecOptions) (types.IDResponse, error) + ContainerExecInspect(ctx context.Context, execID string) (container.ExecInspect, error) ContainerExecResize(ctx context.Context, execID string, options container.ResizeOptions) error - ContainerExecStart(ctx context.Context, execID string, config types.ExecStartCheck) error + ContainerExecStart(ctx context.Context, execID string, options container.ExecStartOptions) error ContainerExport(ctx context.Context, container string) (io.ReadCloser, error) ContainerInspect(ctx context.Context, container string) (types.ContainerJSON, error) ContainerInspectWithRaw(ctx context.Context, container string, getSize bool) (types.ContainerJSON, []byte, error) @@ -66,18 +66,18 @@ type ContainerAPIClient interface { ContainerRename(ctx context.Context, container, newContainerName string) error ContainerResize(ctx context.Context, container string, options container.ResizeOptions) error ContainerRestart(ctx context.Context, container string, options container.StopOptions) error - ContainerStatPath(ctx context.Context, container, path string) (types.ContainerPathStat, error) - ContainerStats(ctx context.Context, container string, stream bool) (types.ContainerStats, error) - ContainerStatsOneShot(ctx context.Context, container string) (types.ContainerStats, error) + ContainerStatPath(ctx context.Context, container, path string) (container.PathStat, error) + ContainerStats(ctx context.Context, container string, stream bool) (container.StatsResponseReader, error) + ContainerStatsOneShot(ctx context.Context, container string) (container.StatsResponseReader, error) ContainerStart(ctx context.Context, container string, options container.StartOptions) error ContainerStop(ctx context.Context, container string, options container.StopOptions) error ContainerTop(ctx context.Context, container string, arguments []string) (container.ContainerTopOKBody, error) ContainerUnpause(ctx context.Context, container string) error ContainerUpdate(ctx context.Context, container string, updateConfig container.UpdateConfig) (container.ContainerUpdateOKBody, error) ContainerWait(ctx context.Context, container string, condition container.WaitCondition) (<-chan container.WaitResponse, <-chan error) - CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) - CopyToContainer(ctx context.Context, container, path string, content io.Reader, options types.CopyToContainerOptions) error - ContainersPrune(ctx context.Context, pruneFilters filters.Args) (types.ContainersPruneReport, error) + CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, container.PathStat, error) + CopyToContainer(ctx context.Context, container, path string, content io.Reader, options container.CopyToContainerOptions) error + ContainersPrune(ctx context.Context, pruneFilters filters.Args) (container.PruneReport, error) } // DistributionAPIClient defines API client methods for the registry @@ -92,29 +92,29 @@ type ImageAPIClient interface { BuildCancel(ctx context.Context, id string) error ImageCreate(ctx context.Context, parentReference string, options image.CreateOptions) (io.ReadCloser, error) ImageHistory(ctx context.Context, image string) ([]image.HistoryResponseItem, error) - ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options image.ImportOptions) (io.ReadCloser, error) + ImageImport(ctx context.Context, source image.ImportSource, ref string, options image.ImportOptions) (io.ReadCloser, error) ImageInspectWithRaw(ctx context.Context, image string) (types.ImageInspect, []byte, error) ImageList(ctx context.Context, options image.ListOptions) ([]image.Summary, error) - ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) + ImageLoad(ctx context.Context, input io.Reader, quiet bool) (image.LoadResponse, error) ImagePull(ctx context.Context, ref string, options image.PullOptions) (io.ReadCloser, error) ImagePush(ctx context.Context, ref string, options image.PushOptions) (io.ReadCloser, error) ImageRemove(ctx context.Context, image string, options image.RemoveOptions) ([]image.DeleteResponse, error) - ImageSearch(ctx context.Context, term string, options types.ImageSearchOptions) ([]registry.SearchResult, error) + ImageSearch(ctx context.Context, term string, options registry.SearchOptions) ([]registry.SearchResult, error) ImageSave(ctx context.Context, images []string) (io.ReadCloser, error) ImageTag(ctx context.Context, image, ref string) error - ImagesPrune(ctx context.Context, pruneFilter filters.Args) (types.ImagesPruneReport, error) + ImagesPrune(ctx context.Context, pruneFilter filters.Args) (image.PruneReport, error) } // NetworkAPIClient defines API client methods for the networks type NetworkAPIClient interface { NetworkConnect(ctx context.Context, network, container string, config *network.EndpointSettings) error - NetworkCreate(ctx context.Context, name string, options types.NetworkCreate) (types.NetworkCreateResponse, error) + NetworkCreate(ctx context.Context, name string, options network.CreateOptions) (network.CreateResponse, error) NetworkDisconnect(ctx context.Context, network, container string, force bool) error - NetworkInspect(ctx context.Context, network string, options types.NetworkInspectOptions) (types.NetworkResource, error) - NetworkInspectWithRaw(ctx context.Context, network string, options types.NetworkInspectOptions) (types.NetworkResource, []byte, error) - NetworkList(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) + NetworkInspect(ctx context.Context, network string, options network.InspectOptions) (network.Inspect, error) + NetworkInspectWithRaw(ctx context.Context, network string, options network.InspectOptions) (network.Inspect, []byte, error) + NetworkList(ctx context.Context, options network.ListOptions) ([]network.Summary, error) NetworkRemove(ctx context.Context, network string) error - NetworksPrune(ctx context.Context, pruneFilter filters.Args) (types.NetworksPruneReport, error) + NetworksPrune(ctx context.Context, pruneFilter filters.Args) (network.PruneReport, error) } // NodeAPIClient defines API client methods for the nodes @@ -165,7 +165,7 @@ type SwarmAPIClient interface { // SystemAPIClient defines API client methods for the system type SystemAPIClient interface { - Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) + Events(ctx context.Context, options events.ListOptions) (<-chan events.Message, <-chan error) Info(ctx context.Context) (system.Info, error) RegistryLogin(ctx context.Context, auth registry.AuthConfig) (registry.AuthenticateOKBody, error) DiskUsage(ctx context.Context, options types.DiskUsageOptions) (types.DiskUsage, error) @@ -179,7 +179,7 @@ type VolumeAPIClient interface { VolumeInspectWithRaw(ctx context.Context, volumeID string) (volume.Volume, []byte, 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) + VolumesPrune(ctx context.Context, pruneFilter filters.Args) (volume.PruneReport, error) VolumeUpdate(ctx context.Context, volumeID string, version swarm.Version, options volume.UpdateOptions) error } diff --git a/vendor/github.com/docker/docker/client/network_connect.go b/vendor/github.com/docker/docker/client/network_connect.go index 571894613419..8daf89063569 100644 --- a/vendor/github.com/docker/docker/client/network_connect.go +++ b/vendor/github.com/docker/docker/client/network_connect.go @@ -3,13 +3,12 @@ package client // import "github.com/docker/docker/client" import ( "context" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/network" ) // NetworkConnect connects a container to an existent network in the docker host. func (cli *Client) NetworkConnect(ctx context.Context, networkID, containerID string, config *network.EndpointSettings) error { - nc := types.NetworkConnect{ + nc := network.ConnectOptions{ Container: containerID, EndpointConfig: config, } diff --git a/vendor/github.com/docker/docker/client/network_create.go b/vendor/github.com/docker/docker/client/network_create.go index d510feb3db9b..850e31cc971a 100644 --- a/vendor/github.com/docker/docker/client/network_create.go +++ b/vendor/github.com/docker/docker/client/network_create.go @@ -4,13 +4,13 @@ import ( "context" "encoding/json" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/versions" ) // NetworkCreate creates a new network in the docker host. -func (cli *Client) NetworkCreate(ctx context.Context, name string, options types.NetworkCreate) (types.NetworkCreateResponse, error) { - var response types.NetworkCreateResponse +func (cli *Client) NetworkCreate(ctx context.Context, name string, options network.CreateOptions) (network.CreateResponse, error) { + var response network.CreateResponse // Make sure we negotiated (if the client is configured to do so), // as code below contains API-version specific handling of options. @@ -21,12 +21,13 @@ func (cli *Client) NetworkCreate(ctx context.Context, name string, options types return response, err } - networkCreateRequest := types.NetworkCreateRequest{ - NetworkCreate: options, + networkCreateRequest := network.CreateRequest{ + CreateOptions: options, Name: name, } if versions.LessThan(cli.version, "1.44") { - networkCreateRequest.CheckDuplicate = true //nolint:staticcheck // ignore SA1019: CheckDuplicate is deprecated since API v1.44. + enabled := true + networkCreateRequest.CheckDuplicate = &enabled //nolint:staticcheck // ignore SA1019: CheckDuplicate is deprecated since API v1.44. } serverResp, err := cli.post(ctx, "/networks/create", nil, networkCreateRequest, nil) diff --git a/vendor/github.com/docker/docker/client/network_disconnect.go b/vendor/github.com/docker/docker/client/network_disconnect.go index dd1567665665..aaf428d85326 100644 --- a/vendor/github.com/docker/docker/client/network_disconnect.go +++ b/vendor/github.com/docker/docker/client/network_disconnect.go @@ -3,12 +3,15 @@ package client // import "github.com/docker/docker/client" import ( "context" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/network" ) // NetworkDisconnect disconnects a container from an existent network in the docker host. func (cli *Client) NetworkDisconnect(ctx context.Context, networkID, containerID string, force bool) error { - nd := types.NetworkDisconnect{Container: containerID, Force: force} + nd := network.DisconnectOptions{ + Container: containerID, + Force: force, + } resp, err := cli.post(ctx, "/networks/"+networkID+"/disconnect", nil, nd, nil) ensureReaderClosed(resp) return err diff --git a/vendor/github.com/docker/docker/client/network_inspect.go b/vendor/github.com/docker/docker/client/network_inspect.go index 0f90e2bb9028..afc47de6fa42 100644 --- a/vendor/github.com/docker/docker/client/network_inspect.go +++ b/vendor/github.com/docker/docker/client/network_inspect.go @@ -7,25 +7,20 @@ import ( "io" "net/url" - "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/network" ) // NetworkInspect returns the information for a specific network configured in the docker host. -func (cli *Client) NetworkInspect(ctx context.Context, networkID string, options types.NetworkInspectOptions) (types.NetworkResource, error) { +func (cli *Client) NetworkInspect(ctx context.Context, networkID string, options network.InspectOptions) (network.Inspect, error) { networkResource, _, err := cli.NetworkInspectWithRaw(ctx, networkID, options) return networkResource, err } // NetworkInspectWithRaw returns the information for a specific network configured in the docker host and its raw representation. -func (cli *Client) NetworkInspectWithRaw(ctx context.Context, networkID string, options types.NetworkInspectOptions) (types.NetworkResource, []byte, error) { +func (cli *Client) NetworkInspectWithRaw(ctx context.Context, networkID string, options network.InspectOptions) (network.Inspect, []byte, error) { if networkID == "" { - return types.NetworkResource{}, nil, objectNotFoundError{object: "network", id: networkID} + return network.Inspect{}, nil, objectNotFoundError{object: "network", id: networkID} } - var ( - networkResource types.NetworkResource - resp serverResponse - err error - ) query := url.Values{} if options.Verbose { query.Set("verbose", "true") @@ -33,17 +28,19 @@ func (cli *Client) NetworkInspectWithRaw(ctx context.Context, networkID string, if options.Scope != "" { query.Set("scope", options.Scope) } - resp, err = cli.get(ctx, "/networks/"+networkID, query, nil) + + resp, err := cli.get(ctx, "/networks/"+networkID, query, nil) defer ensureReaderClosed(resp) if err != nil { - return networkResource, nil, err + return network.Inspect{}, nil, err } - body, err := io.ReadAll(resp.body) + raw, err := io.ReadAll(resp.body) if err != nil { - return networkResource, nil, err + return network.Inspect{}, nil, err } - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&networkResource) - return networkResource, body, err + + var nw network.Inspect + err = json.NewDecoder(bytes.NewReader(raw)).Decode(&nw) + return nw, raw, err } diff --git a/vendor/github.com/docker/docker/client/network_list.go b/vendor/github.com/docker/docker/client/network_list.go index ed2acb55711d..72957d47fee4 100644 --- a/vendor/github.com/docker/docker/client/network_list.go +++ b/vendor/github.com/docker/docker/client/network_list.go @@ -5,12 +5,12 @@ import ( "encoding/json" "net/url" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" + "github.com/docker/docker/api/types/network" ) // NetworkList returns the list of networks configured in the docker host. -func (cli *Client) NetworkList(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) { +func (cli *Client) NetworkList(ctx context.Context, options network.ListOptions) ([]network.Summary, error) { query := url.Values{} if options.Filters.Len() > 0 { //nolint:staticcheck // ignore SA1019 for old code @@ -21,7 +21,7 @@ func (cli *Client) NetworkList(ctx context.Context, options types.NetworkListOpt query.Set("filters", filterJSON) } - var networkResources []types.NetworkResource + var networkResources []network.Summary resp, err := cli.get(ctx, "/networks", query, nil) defer ensureReaderClosed(resp) if err != nil { diff --git a/vendor/github.com/docker/docker/client/network_prune.go b/vendor/github.com/docker/docker/client/network_prune.go index 7b5f831ef750..708cc61a4b27 100644 --- a/vendor/github.com/docker/docker/client/network_prune.go +++ b/vendor/github.com/docker/docker/client/network_prune.go @@ -5,13 +5,13 @@ import ( "encoding/json" "fmt" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" + "github.com/docker/docker/api/types/network" ) // NetworksPrune requests the daemon to delete unused networks -func (cli *Client) NetworksPrune(ctx context.Context, pruneFilters filters.Args) (types.NetworksPruneReport, error) { - var report types.NetworksPruneReport +func (cli *Client) NetworksPrune(ctx context.Context, pruneFilters filters.Args) (network.PruneReport, error) { + var report network.PruneReport if err := cli.NewVersionError(ctx, "1.25", "network prune"); err != nil { return report, err diff --git a/vendor/github.com/docker/docker/client/plugin_install.go b/vendor/github.com/docker/docker/client/plugin_install.go index 69184619a2e3..a0d8c3500c57 100644 --- a/vendor/github.com/docker/docker/client/plugin_install.go +++ b/vendor/github.com/docker/docker/client/plugin_install.go @@ -84,7 +84,7 @@ func (cli *Client) checkPluginPermissions(ctx context.Context, query url.Values, resp, err := cli.tryPluginPrivileges(ctx, query, options.RegistryAuth) if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil { // todo: do inspect before to check existing name before checking privileges - newAuthHeader, privilegeErr := options.PrivilegeFunc() + newAuthHeader, privilegeErr := options.PrivilegeFunc(ctx) if privilegeErr != nil { ensureReaderClosed(resp) return nil, privilegeErr @@ -105,7 +105,7 @@ func (cli *Client) checkPluginPermissions(ctx context.Context, query url.Values, ensureReaderClosed(resp) if !options.AcceptAllPermissions && options.AcceptPermissionsFunc != nil && len(privileges) > 0 { - accept, err := options.AcceptPermissionsFunc(privileges) + accept, err := options.AcceptPermissionsFunc(ctx, privileges) if err != nil { return nil, err } diff --git a/vendor/github.com/docker/docker/client/request.go b/vendor/github.com/docker/docker/client/request.go index 50e213b50a08..6eea9b4e4f27 100644 --- a/vendor/github.com/docker/docker/client/request.go +++ b/vendor/github.com/docker/docker/client/request.go @@ -184,10 +184,10 @@ func (cli *Client) doRequest(req *http.Request) (serverResponse, error) { // `open //./pipe/docker_engine: Le fichier spécifié est introuvable.` if strings.Contains(err.Error(), `open //./pipe/docker_engine`) { // Checks if client is running with elevated privileges - if f, elevatedErr := os.Open("\\\\.\\PHYSICALDRIVE0"); elevatedErr == nil { + if f, elevatedErr := os.Open(`\\.\PHYSICALDRIVE0`); elevatedErr != nil { err = errors.Wrap(err, "in the default daemon configuration on Windows, the docker client must be run with elevated privileges to connect") } else { - f.Close() + _ = f.Close() err = errors.Wrap(err, "this error may indicate that the docker daemon is not running") } } @@ -278,7 +278,7 @@ func encodeData(data interface{}) (*bytes.Buffer, error) { func ensureReaderClosed(response serverResponse) { if response.body != nil { // Drain up to 512 bytes and close the body to let the Transport reuse the connection - io.CopyN(io.Discard, response.body, 512) - response.body.Close() + _, _ = io.CopyN(io.Discard, response.body, 512) + _ = response.body.Close() } } diff --git a/vendor/github.com/docker/docker/client/volume_prune.go b/vendor/github.com/docker/docker/client/volume_prune.go index 9333f6ee78e3..9b09c30fa6f6 100644 --- a/vendor/github.com/docker/docker/client/volume_prune.go +++ b/vendor/github.com/docker/docker/client/volume_prune.go @@ -5,13 +5,13 @@ import ( "encoding/json" "fmt" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" + "github.com/docker/docker/api/types/volume" ) // VolumesPrune requests the daemon to delete unused data -func (cli *Client) VolumesPrune(ctx context.Context, pruneFilters filters.Args) (types.VolumesPruneReport, error) { - var report types.VolumesPruneReport +func (cli *Client) VolumesPrune(ctx context.Context, pruneFilters filters.Args) (volume.PruneReport, error) { + var report volume.PruneReport if err := cli.NewVersionError(ctx, "1.25", "volume prune"); err != nil { return report, err diff --git a/vendor/github.com/docker/docker/pkg/archive/archive.go b/vendor/github.com/docker/docker/pkg/archive/archive.go index 43133a0950a1..61b7234a0485 100644 --- a/vendor/github.com/docker/docker/pkg/archive/archive.go +++ b/vendor/github.com/docker/docker/pkg/archive/archive.go @@ -98,24 +98,16 @@ func NewDefaultArchiver() *Archiver { type breakoutError error const ( - // Uncompressed represents the uncompressed. - Uncompressed Compression = iota - // Bzip2 is bzip2 compression algorithm. - Bzip2 - // Gzip is gzip compression algorithm. - Gzip - // Xz is xz compression algorithm. - Xz - // Zstd is zstd compression algorithm. - Zstd + Uncompressed Compression = 0 // Uncompressed represents the uncompressed. + Bzip2 Compression = 1 // Bzip2 is bzip2 compression algorithm. + Gzip Compression = 2 // Gzip is gzip compression algorithm. + Xz Compression = 3 // Xz is xz compression algorithm. + Zstd Compression = 4 // Zstd is zstd compression algorithm. ) const ( - // AUFSWhiteoutFormat is the default format for whiteouts - AUFSWhiteoutFormat WhiteoutFormat = iota - // OverlayWhiteoutFormat formats whiteout according to the overlay - // standard. - OverlayWhiteoutFormat + AUFSWhiteoutFormat WhiteoutFormat = 0 // AUFSWhiteoutFormat is the default format for whiteouts + OverlayWhiteoutFormat WhiteoutFormat = 1 // OverlayWhiteoutFormat formats whiteout according to the overlay standard. ) // IsArchivePath checks if the (possibly compressed) file at the given path @@ -159,7 +151,7 @@ func magicNumberMatcher(m []byte) matcher { // zstdMatcher detects zstd compression algorithm. // Zstandard compressed data is made of one or more frames. // There are two frame formats defined by Zstandard: Zstandard frames and Skippable frames. -// See https://tools.ietf.org/id/draft-kucherawy-dispatch-zstd-00.html#rfc.section.2 for more details. +// See https://datatracker.ietf.org/doc/html/rfc8878#section-3 for more details. func zstdMatcher() matcher { return func(source []byte) bool { if bytes.HasPrefix(source, zstdMagic) { @@ -541,8 +533,10 @@ func newTarAppender(idMapping idtools.IdentityMapping, writer io.Writer, chownOp } // CanonicalTarNameForPath canonicalizes relativePath to a POSIX-style path using -// forward slashes. It is an alias for filepath.ToSlash, which is a no-op on +// forward slashes. It is an alias for [filepath.ToSlash], which is a no-op on // Linux and Unix. +// +// Deprecated: use [filepath.ToSlash]. This function will be removed in the next release. func CanonicalTarNameForPath(relativePath string) string { return filepath.ToSlash(relativePath) } @@ -885,7 +879,7 @@ func NewTarballer(srcPath string, options *TarOptions) (*Tarballer, error) { 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), + srcPath: addLongPathPrefix(srcPath), options: options, pm: pm, pipeReader: pipeReader, @@ -1452,6 +1446,8 @@ func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) { // NewTempArchive reads the content of src into a temporary file, and returns the contents // of that file as an archive. The archive can only be read once - as soon as reading completes, // the file will be deleted. +// +// Deprecated: NewTempArchive is only used in tests and will be removed in the next release. func NewTempArchive(src io.Reader, dir string) (*TempArchive, error) { f, err := os.CreateTemp(dir, "") if err != nil { @@ -1473,6 +1469,8 @@ func NewTempArchive(src io.Reader, dir string) (*TempArchive, error) { // TempArchive is a temporary archive. The archive can only be read once - as soon as reading completes, // the file will be deleted. +// +// Deprecated: TempArchive is only used in tests and will be removed in the next release. type TempArchive struct { *os.File Size int64 // Pre-computed from Stat().Size() as a convenience diff --git a/vendor/github.com/docker/docker/pkg/archive/archive_linux.go b/vendor/github.com/docker/docker/pkg/archive/archive_linux.go index 2c3786cd50c8..a40278bc25ee 100644 --- a/vendor/github.com/docker/docker/pkg/archive/archive_linux.go +++ b/vendor/github.com/docker/docker/pkg/archive/archive_linux.go @@ -6,6 +6,7 @@ import ( "path/filepath" "strings" + "github.com/containerd/containerd/pkg/userns" "github.com/docker/docker/pkg/system" "github.com/pkg/errors" "golang.org/x/sys/unix" @@ -35,13 +36,18 @@ func (overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi os } if fi.Mode()&os.ModeDir != 0 { + opaqueXattrName := "trusted.overlay.opaque" + if userns.RunningInUserNS() { + opaqueXattrName = "user.overlay.opaque" + } + // convert opaque dirs to AUFS format by writing an empty file with the prefix - opaque, err := system.Lgetxattr(path, "trusted.overlay.opaque") + opaque, err := system.Lgetxattr(path, opaqueXattrName) if err != nil { return nil, err } if len(opaque) == 1 && opaque[0] == 'y' { - delete(hdr.PAXRecords, paxSchilyXattr+"trusted.overlay.opaque") + delete(hdr.PAXRecords, paxSchilyXattr+opaqueXattrName) // create a header for the whiteout file // it should inherit some properties from the parent, but be a regular file @@ -56,7 +62,7 @@ func (overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi os Gname: hdr.Gname, AccessTime: hdr.AccessTime, ChangeTime: hdr.ChangeTime, - } //#nosec G305 -- An archive is being created, not extracted. + } // #nosec G305 -- An archive is being created, not extracted. } } @@ -69,9 +75,14 @@ func (c overlayWhiteoutConverter) ConvertRead(hdr *tar.Header, path string) (boo // if a directory is marked as opaque by the AUFS special file, we need to translate that to overlay if base == WhiteoutOpaqueDir { - err := unix.Setxattr(dir, "trusted.overlay.opaque", []byte{'y'}, 0) + opaqueXattrName := "trusted.overlay.opaque" + if userns.RunningInUserNS() { + opaqueXattrName = "user.overlay.opaque" + } + + err := unix.Setxattr(dir, opaqueXattrName, []byte{'y'}, 0) if err != nil { - return false, errors.Wrapf(err, "setxattr(%q, trusted.overlay.opaque=y)", dir) + return false, errors.Wrapf(err, "setxattr(%q, %s=y)", dir, opaqueXattrName) } // don't write the file itself return false, err 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 ff59d0197525..f8192db52715 100644 --- a/vendor/github.com/docker/docker/pkg/archive/archive_unix.go +++ b/vendor/github.com/docker/docker/pkg/archive/archive_unix.go @@ -21,9 +21,9 @@ func init() { sysStat = statUnix } -// fixVolumePathPrefix does platform specific processing to ensure that if -// the path being passed in is not in a volume path format, convert it to one. -func fixVolumePathPrefix(srcPath string) string { +// addLongPathPrefix adds the Windows long path prefix to the path provided if +// it does not already have it. It is a no-op on platforms other than Windows. +func addLongPathPrefix(srcPath string) string { return srcPath } 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 09a25832e8f1..e25c64b415cf 100644 --- a/vendor/github.com/docker/docker/pkg/archive/archive_windows.go +++ b/vendor/github.com/docker/docker/pkg/archive/archive_windows.go @@ -4,15 +4,27 @@ import ( "archive/tar" "os" "path/filepath" + "strings" "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/longpath" ) -// fixVolumePathPrefix does platform specific processing to ensure that if -// the path being passed in is not in a volume path format, convert it to one. -func fixVolumePathPrefix(srcPath string) string { - return longpath.AddPrefix(srcPath) +// longPathPrefix is the longpath prefix for Windows file paths. +const longPathPrefix = `\\?\` + +// addLongPathPrefix adds the Windows long path prefix to the path provided if +// it does not already have it. It is a no-op on platforms other than Windows. +// +// addLongPathPrefix is a copy of [github.com/docker/docker/pkg/longpath.AddPrefix]. +func addLongPathPrefix(srcPath string) string { + if strings.HasPrefix(srcPath, longPathPrefix) { + return srcPath + } + if strings.HasPrefix(srcPath, `\\`) { + // This is a UNC path, so we need to add 'UNC' to the path as well. + return longPathPrefix + `UNC` + srcPath[1:] + } + return longPathPrefix + srcPath } // getWalkRoot calculates the root path when performing a TarWithOptions. diff --git a/vendor/github.com/docker/docker/pkg/archive/changes.go b/vendor/github.com/docker/docker/pkg/archive/changes.go index f9f16c925906..5f12ca4016a1 100644 --- a/vendor/github.com/docker/docker/pkg/archive/changes.go +++ b/vendor/github.com/docker/docker/pkg/archive/changes.go @@ -23,12 +23,9 @@ import ( type ChangeType int const ( - // ChangeModify represents the modify operation. - ChangeModify = iota - // ChangeAdd represents the add operation. - ChangeAdd - // ChangeDelete represents the delete operation. - ChangeDelete + ChangeModify = 0 // ChangeModify represents the modify operation. + ChangeAdd = 1 // ChangeAdd represents the add operation. + ChangeDelete = 2 // ChangeDelete represents the delete operation. ) func (c ChangeType) String() string { 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 13a7d3c0c638..28f741a25ddb 100644 --- a/vendor/github.com/docker/docker/pkg/archive/changes_other.go +++ b/vendor/github.com/docker/docker/pkg/archive/changes_other.go @@ -72,19 +72,23 @@ func collectFileInfo(sourceDir string) (*FileInfo, error) { return fmt.Errorf("collectFileInfo: Unexpectedly no parent for %s", relPath) } + s, err := system.Lstat(path) + if err != nil { + return err + } + info := &FileInfo{ name: filepath.Base(relPath), children: make(map[string]*FileInfo), parent: parent, + stat: s, } - s, err := system.Lstat(path) - if err != nil { - return err - } - info.stat = s - - info.capability, _ = system.Lgetxattr(path, "security.capability") + // system.Lgetxattr is only implemented on Linux and produces an error + // on other platforms. This code is intentionally left commented-out + // as a reminder to include this code if this would ever be implemented + // on other platforms. + // info.capability, _ = system.Lgetxattr(path, "security.capability") parent.children[info.name] = info diff --git a/vendor/github.com/docker/docker/pkg/archive/diff.go b/vendor/github.com/docker/docker/pkg/archive/diff.go index 318f59421202..e080e310ac8b 100644 --- a/vendor/github.com/docker/docker/pkg/archive/diff.go +++ b/vendor/github.com/docker/docker/pkg/archive/diff.go @@ -102,7 +102,7 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, continue } } - //#nosec G305 -- The joined path is guarded against path traversal. + // #nosec G305 -- The joined path is guarded against path traversal. path := filepath.Join(dest, hdr.Name) rel, err := filepath.Rel(dest, path) if err != nil { @@ -198,7 +198,7 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, } for _, hdr := range dirs { - //#nosec G305 -- The header was checked for path traversal before it was appended to the dirs slice. + // #nosec G305 -- The header was checked for path traversal before it was appended to the dirs slice. path := filepath.Join(dest, hdr.Name) if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { return 0, err diff --git a/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go b/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go index 82671d8cd55c..05da97b0e416 100644 --- a/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go +++ b/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go @@ -9,6 +9,7 @@ import ( // NewAtomicFileWriter returns WriteCloser so that writing to it writes to a // temporary file and closing it atomically changes the temporary file to // destination path. Writing and closing concurrently is not allowed. +// NOTE: umask is not considered for the file's permissions. func NewAtomicFileWriter(filename string, perm os.FileMode) (io.WriteCloser, error) { f, err := os.CreateTemp(filepath.Dir(filename), ".tmp-"+filepath.Base(filename)) if err != nil { @@ -26,7 +27,8 @@ func NewAtomicFileWriter(filename string, perm os.FileMode) (io.WriteCloser, err }, nil } -// AtomicWriteFile atomically writes data to a file named by filename. +// AtomicWriteFile atomically writes data to a file named by filename and with the specified permission bits. +// NOTE: umask is not considered for the file's permissions. func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error { f, err := NewAtomicFileWriter(filename, perm) if err != nil { diff --git a/vendor/github.com/docker/docker/pkg/longpath/longpath.go b/vendor/github.com/docker/docker/pkg/longpath/longpath.go deleted file mode 100644 index 1c5dde5218f1..000000000000 --- a/vendor/github.com/docker/docker/pkg/longpath/longpath.go +++ /dev/null @@ -1,43 +0,0 @@ -// 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 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) { - if strings.HasPrefix(path, `\\`) { - // This is a UNC path, so we need to add 'UNC' to the path as well. - path = Prefix + `UNC` + path[1:] - } else { - path = Prefix + path - } - } - 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/stringid/stringid.go b/vendor/github.com/docker/docker/pkg/stringid/stringid.go index d3d1014acf41..bffac8035e62 100644 --- a/vendor/github.com/docker/docker/pkg/stringid/stringid.go +++ b/vendor/github.com/docker/docker/pkg/stringid/stringid.go @@ -22,6 +22,8 @@ var ( // 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). +// +// Deprecated: this function is no longer used, and will be removed in the next release. func IsShortID(id string) bool { if len(id) != shortLen { return false @@ -62,6 +64,8 @@ func GenerateRandomID() string { } // ValidateID checks whether an ID string is a valid, full-length image ID. +// +// Deprecated: use [github.com/docker/docker/image/v1.ValidateID] instead. Will be removed in the next release. func ValidateID(id string) error { if len(id) != fullLen { return errors.New("image ID '" + id + "' is invalid") diff --git a/vendor/github.com/docker/docker/registry/auth.go b/vendor/github.com/docker/docker/registry/auth.go index f685892c1fde..905ccf5f5120 100644 --- a/vendor/github.com/docker/docker/registry/auth.go +++ b/vendor/github.com/docker/docker/registry/auth.go @@ -108,16 +108,18 @@ func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifi return nil, err } - tokenHandlerOptions := auth.TokenHandlerOptions{ - Transport: authTransport, - Credentials: creds, - OfflineAccess: true, - ClientID: AuthClientID, - Scopes: scopes, - } - tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions) - basicHandler := auth.NewBasicHandler(creds) - modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)) + authHandlers := []auth.AuthenticationHandler{ + auth.NewTokenHandlerWithOptions(auth.TokenHandlerOptions{ + Transport: authTransport, + Credentials: creds, + OfflineAccess: true, + ClientID: AuthClientID, + Scopes: scopes, + }), + auth.NewBasicHandler(creds), + } + + modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, authHandlers...)) return &http.Client{ Transport: transport.NewTransport(authTransport, modifiers...), diff --git a/vendor/github.com/docker/docker/registry/search.go b/vendor/github.com/docker/docker/registry/search.go index 5c79e9968b30..4ce90f55d4d6 100644 --- a/vendor/github.com/docker/docker/registry/search.go +++ b/vendor/github.com/docker/docker/registry/search.go @@ -112,16 +112,12 @@ func (s *Service) searchUnfiltered(ctx context.Context, term string, limit int, 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) + v2Client, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, []auth.Scope{ + auth.RegistryScope{Name: "catalog", Actions: []string{"search"}}, + }) if err != nil { return nil, err } diff --git a/vendor/github.com/moby/buildkit/client/build.go b/vendor/github.com/moby/buildkit/client/build.go index 5ba648177ec2..c27c1a60c0ea 100644 --- a/vendor/github.com/moby/buildkit/client/build.go +++ b/vendor/github.com/moby/buildkit/client/build.go @@ -2,6 +2,7 @@ package client import ( "context" + "maps" "github.com/moby/buildkit/client/buildid" gateway "github.com/moby/buildkit/frontend/gateway/client" @@ -42,12 +43,10 @@ func (c *Client) Build(ctx context.Context, opt SolveOpt, product string, buildF } cb := func(ref string, s *session.Session, opts map[string]string) error { - for k, v := range opts { - if feOpts == nil { - feOpts = map[string]string{} - } - feOpts[k] = v + if feOpts == nil { + feOpts = map[string]string{} } + maps.Copy(feOpts, opts) gwClient := c.gatewayClientForBuild(ref) g, err := grpcclient.New(ctx, feOpts, s.ID(), product, gwClient, gworkers) if err != nil { diff --git a/vendor/github.com/moby/buildkit/client/llb/async.go b/vendor/github.com/moby/buildkit/client/llb/async.go index cadbb5ef363e..97f0f980af91 100644 --- a/vendor/github.com/moby/buildkit/client/llb/async.go +++ b/vendor/github.com/moby/buildkit/client/llb/async.go @@ -6,16 +6,12 @@ import ( "github.com/moby/buildkit/solver/pb" "github.com/moby/buildkit/util/flightcontrol" digest "github.com/opencontainers/go-digest" - "github.com/pkg/errors" ) type asyncState struct { - f func(context.Context, State, *Constraints) (State, error) - prev State - target State - set bool - err error - g flightcontrol.Group[State] + f func(context.Context, State, *Constraints) (State, error) + prev State + g flightcontrol.CachedGroup[State] } func (as *asyncState) Output() Output { @@ -23,59 +19,33 @@ func (as *asyncState) Output() Output { } func (as *asyncState) Vertex(ctx context.Context, c *Constraints) Vertex { - err := as.Do(ctx, c) + target, err := as.Do(ctx, c) if err != nil { return &errVertex{err} } - if as.set { - out := as.target.Output() - if out == nil { - return nil - } - return out.Vertex(ctx, c) + out := target.Output() + if out == nil { + return nil } - return nil + return out.Vertex(ctx, c) } func (as *asyncState) ToInput(ctx context.Context, c *Constraints) (*pb.Input, error) { - err := as.Do(ctx, c) + target, err := as.Do(ctx, c) if err != nil { return nil, err } - if as.set { - out := as.target.Output() - if out == nil { - return nil, nil - } - return out.ToInput(ctx, c) + out := target.Output() + if out == nil { + return nil, nil } - return nil, nil + return out.ToInput(ctx, c) } -func (as *asyncState) Do(ctx context.Context, c *Constraints) error { - _, err := as.g.Do(ctx, "", func(ctx context.Context) (State, error) { - if as.set { - return as.target, as.err - } - res, err := as.f(ctx, as.prev, c) - if err != nil { - select { - case <-ctx.Done(): - if errors.Is(err, context.Cause(ctx)) { - return res, err - } - default: - } - } - as.target = res - as.err = err - as.set = true - return res, err +func (as *asyncState) Do(ctx context.Context, c *Constraints) (State, error) { + return as.g.Do(ctx, "", func(ctx context.Context) (State, error) { + return as.f(ctx, as.prev, c) }) - if err != nil { - return err - } - return as.err } type errVertex struct { diff --git a/vendor/github.com/moby/buildkit/client/llb/marshal.go b/vendor/github.com/moby/buildkit/client/llb/marshal.go index 48adaed80911..b82bab7c0be7 100644 --- a/vendor/github.com/moby/buildkit/client/llb/marshal.go +++ b/vendor/github.com/moby/buildkit/client/llb/marshal.go @@ -2,6 +2,7 @@ package llb import ( "io" + "maps" "github.com/containerd/containerd/platforms" "github.com/moby/buildkit/solver/pb" @@ -18,24 +19,17 @@ type Definition struct { } func (def *Definition) ToPB() *pb.Definition { - md := make(map[digest.Digest]pb.OpMetadata, len(def.Metadata)) - for k, v := range def.Metadata { - md[k] = v - } return &pb.Definition{ Def: def.Def, Source: def.Source, - Metadata: md, + Metadata: maps.Clone(def.Metadata), } } func (def *Definition) FromPB(x *pb.Definition) { def.Def = x.Def def.Source = x.Source - def.Metadata = make(map[digest.Digest]pb.OpMetadata) - for k, v := range x.Metadata { - def.Metadata[k] = v - } + def.Metadata = maps.Clone(x.Metadata) } func (def *Definition) Head() (digest.Digest, error) { diff --git a/vendor/github.com/moby/buildkit/client/llb/meta.go b/vendor/github.com/moby/buildkit/client/llb/meta.go index ab1021bd65f2..a9a9773b7325 100644 --- a/vendor/github.com/moby/buildkit/client/llb/meta.go +++ b/vendor/github.com/moby/buildkit/client/llb/meta.go @@ -5,6 +5,8 @@ import ( "fmt" "net" "path" + "slices" + "sync" "github.com/containerd/containerd/platforms" "github.com/google/shlex" @@ -111,16 +113,16 @@ func Reset(other State) StateOption { } } -func getEnv(s State) func(context.Context, *Constraints) (EnvList, error) { - return func(ctx context.Context, c *Constraints) (EnvList, error) { +func getEnv(s State) func(context.Context, *Constraints) (*EnvList, error) { + return func(ctx context.Context, c *Constraints) (*EnvList, error) { v, err := s.getValue(keyEnv)(ctx, c) if err != nil { return nil, err } if v != nil { - return v.(EnvList), nil + return v.(*EnvList), nil } - return EnvList{}, nil + return &EnvList{}, nil } } @@ -346,54 +348,83 @@ func getSecurity(s State) func(context.Context, *Constraints) (pb.SecurityMode, } } -type EnvList []KeyValue - -type KeyValue struct { - key string - value string +type EnvList struct { + parent *EnvList + key string + value string + del bool + once sync.Once + l int + values map[string]string + keys []string } -func (e EnvList) AddOrReplace(k, v string) EnvList { - e = e.Delete(k) - e = append(e, KeyValue{key: k, value: v}) - return e +func (e *EnvList) AddOrReplace(k, v string) *EnvList { + return &EnvList{ + parent: e, + key: k, + value: v, + l: e.l + 1, + } } -func (e EnvList) SetDefault(k, v string) EnvList { +func (e *EnvList) SetDefault(k, v string) *EnvList { if _, ok := e.Get(k); !ok { - e = append(e, KeyValue{key: k, value: v}) + return e.AddOrReplace(k, v) } return e } -func (e EnvList) Delete(k string) EnvList { - e = append([]KeyValue(nil), e...) - if i, ok := e.Index(k); ok { - return append(e[:i], e[i+1:]...) +func (e *EnvList) Delete(k string) EnvList { + return EnvList{ + parent: e, + key: k, + del: true, + l: e.l + 1, } - return e } -func (e EnvList) Get(k string) (string, bool) { - if index, ok := e.Index(k); ok { - return e[index].value, true - } - return "", false +func (e *EnvList) makeValues() { + m := make(map[string]string, e.l) + seen := make(map[string]struct{}, e.l) + keys := make([]string, 0, e.l) + e.keys = e.addValue(keys, m, seen) + e.values = m + slices.Reverse(e.keys) } -func (e EnvList) Index(k string) (int, bool) { - for i, kv := range e { - if kv.key == k { - return i, true - } +func (e *EnvList) addValue(keys []string, vals map[string]string, seen map[string]struct{}) []string { + if e.parent == nil { + return keys } - return -1, false + if _, ok := seen[e.key]; !e.del && !ok { + vals[e.key] = e.value + keys = append(keys, e.key) + } + seen[e.key] = struct{}{} + if e.parent != nil { + keys = e.parent.addValue(keys, vals, seen) + } + return keys +} + +func (e *EnvList) Get(k string) (string, bool) { + e.once.Do(e.makeValues) + v, ok := e.values[k] + return v, ok +} + +func (e *EnvList) Keys() []string { + e.once.Do(e.makeValues) + return e.keys } -func (e EnvList) ToArray() []string { - out := make([]string, 0, len(e)) - for _, kv := range e { - out = append(out, kv.key+"="+kv.value) +func (e *EnvList) ToArray() []string { + keys := e.Keys() + out := make([]string, 0, len(keys)) + for _, k := range keys { + v, _ := e.Get(k) + out = append(out, k+"="+v) } return out } diff --git a/vendor/github.com/moby/buildkit/client/llb/state.go b/vendor/github.com/moby/buildkit/client/llb/state.go index 1637e41770d6..df991acd96d3 100644 --- a/vendor/github.com/moby/buildkit/client/llb/state.go +++ b/vendor/github.com/moby/buildkit/client/llb/state.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "maps" "net" "strings" @@ -104,11 +105,11 @@ func (s State) getValue(k interface{}) func(context.Context, *Constraints) (inte } if s.async != nil { return func(ctx context.Context, c *Constraints) (interface{}, error) { - err := s.async.Do(ctx, c) + target, err := s.async.Do(ctx, c) if err != nil { return nil, err } - return s.async.target.getValue(k)(ctx, c) + return target.getValue(k)(ctx, c) } } if s.prev == nil { @@ -118,8 +119,13 @@ func (s State) getValue(k interface{}) func(context.Context, *Constraints) (inte } func (s State) Async(f func(context.Context, State, *Constraints) (State, error)) State { + as := &asyncState{ + f: f, + prev: s, + } + as.g.CacheError = true s2 := State{ - async: &asyncState{f: f, prev: s}, + async: as, } return s2 } @@ -345,16 +351,12 @@ func (s State) GetEnv(ctx context.Context, key string, co ...ConstraintsOpt) (st // Env returns a new [State] with the provided environment variable set. // See [Env] -func (s State) Env(ctx context.Context, co ...ConstraintsOpt) ([]string, error) { +func (s State) Env(ctx context.Context, co ...ConstraintsOpt) (*EnvList, error) { c := &Constraints{} for _, f := range co { f.SetConstraintsOption(c) } - env, err := getEnv(s)(ctx, c) - if err != nil { - return nil, err - } - return env.ToArray(), nil + return getEnv(s)(ctx, c) } // GetDir returns the current working directory for the state. @@ -566,9 +568,7 @@ func mergeMetadata(m1, m2 pb.OpMetadata) pb.OpMetadata { if m1.Description == nil { m1.Description = make(map[string]string) } - for k, v := range m2.Description { - m1.Description[k] = v - } + maps.Copy(m1.Description, m2.Description) } if m2.ExportCache != nil { m1.ExportCache = m2.ExportCache @@ -597,9 +597,7 @@ func WithDescription(m map[string]string) ConstraintsOpt { if c.Metadata.Description == nil { c.Metadata.Description = map[string]string{} } - for k, v := range m { - c.Metadata.Description[k] = v - } + maps.Copy(c.Metadata.Description, m) }) } diff --git a/vendor/github.com/moby/buildkit/client/solve.go b/vendor/github.com/moby/buildkit/client/solve.go index 6c4dcff67c41..44e66f23a56d 100644 --- a/vendor/github.com/moby/buildkit/client/solve.go +++ b/vendor/github.com/moby/buildkit/client/solve.go @@ -5,6 +5,7 @@ import ( "encoding/base64" "encoding/json" "io" + "maps" "os" "path/filepath" "strings" @@ -219,13 +220,8 @@ func (c *Client) solve(ctx context.Context, def *llb.Definition, runGateway runG }) } - frontendAttrs := map[string]string{} - for k, v := range opt.FrontendAttrs { - frontendAttrs[k] = v - } - for k, v := range cacheOpt.frontendAttrs { - frontendAttrs[k] = v - } + frontendAttrs := maps.Clone(opt.FrontendAttrs) + maps.Copy(frontendAttrs, cacheOpt.frontendAttrs) solveCtx, cancelSolve := context.WithCancelCause(ctx) var res *SolveResponse diff --git a/vendor/github.com/moby/buildkit/cmd/buildkitd/config/config.go b/vendor/github.com/moby/buildkit/cmd/buildkitd/config/config.go index d8da19ecafec..32eaa7bd615b 100644 --- a/vendor/github.com/moby/buildkit/cmd/buildkitd/config/config.go +++ b/vendor/github.com/moby/buildkit/cmd/buildkitd/config/config.go @@ -142,6 +142,8 @@ type ContainerdConfig struct { MaxParallelism int `toml:"max-parallelism"` + DefaultCgroupParent string `toml:"defaultCgroupParent"` + Rootless bool `toml:"rootless"` } diff --git a/vendor/github.com/moby/buildkit/frontend/attestations/parse.go b/vendor/github.com/moby/buildkit/frontend/attestations/parse.go index 00de649fdefe..a3d5ff5dbc24 100644 --- a/vendor/github.com/moby/buildkit/frontend/attestations/parse.go +++ b/vendor/github.com/moby/buildkit/frontend/attestations/parse.go @@ -1,10 +1,10 @@ package attestations import ( - "encoding/csv" "strings" "github.com/pkg/errors" + "github.com/tonistiigi/go-csvvalue" ) const ( @@ -63,8 +63,7 @@ func Parse(values map[string]string) (map[string]map[string]string, error) { if v == "" { continue } - csvReader := csv.NewReader(strings.NewReader(v)) - fields, err := csvReader.Read() + fields, err := csvvalue.Fields(v, nil) if err != nil { return nil, errors.Wrapf(err, "failed to parse %s", k) } diff --git a/vendor/github.com/moby/buildkit/frontend/dockerfile/linter/linter.go b/vendor/github.com/moby/buildkit/frontend/dockerfile/linter/linter.go new file mode 100644 index 000000000000..1fed40effbda --- /dev/null +++ b/vendor/github.com/moby/buildkit/frontend/dockerfile/linter/linter.go @@ -0,0 +1,146 @@ +package linter + +import ( + "fmt" + "strconv" + "strings" + + "github.com/moby/buildkit/frontend/dockerfile/parser" + "github.com/pkg/errors" +) + +type Config struct { + Warn LintWarnFunc + SkipRules []string + SkipAll bool + ReturnAsError bool +} + +type Linter struct { + SkippedRules map[string]struct{} + CalledRules []string + SkipAll bool + ReturnAsError bool + Warn LintWarnFunc +} + +func New(config *Config) *Linter { + toret := &Linter{ + SkippedRules: map[string]struct{}{}, + CalledRules: []string{}, + Warn: config.Warn, + } + toret.SkipAll = config.SkipAll + toret.ReturnAsError = config.ReturnAsError + for _, rule := range config.SkipRules { + toret.SkippedRules[rule] = struct{}{} + } + return toret +} + +func (lc *Linter) Run(rule LinterRuleI, location []parser.Range, txt ...string) { + if lc == nil || lc.Warn == nil || lc.SkipAll { + return + } + rulename := rule.RuleName() + if _, ok := lc.SkippedRules[rulename]; ok { + return + } + lc.CalledRules = append(lc.CalledRules, rulename) + rule.Run(lc.Warn, location, txt...) +} + +func (lc *Linter) Error() error { + if lc == nil || !lc.ReturnAsError { + return nil + } + if len(lc.CalledRules) == 0 { + return nil + } + var rules []string + uniqueRules := map[string]struct{}{} + for _, r := range lc.CalledRules { + uniqueRules[r] = struct{}{} + } + for r := range uniqueRules { + rules = append(rules, r) + } + return errors.Errorf("lint violation found for rules: %s", strings.Join(rules, ", ")) +} + +type LinterRuleI interface { + RuleName() string + Run(warn LintWarnFunc, location []parser.Range, txt ...string) +} + +type LinterRule[F any] struct { + Name string + Description string + URL string + Format F +} + +func (rule *LinterRule[F]) RuleName() string { + return rule.Name +} + +func (rule *LinterRule[F]) Run(warn LintWarnFunc, location []parser.Range, txt ...string) { + if len(txt) == 0 { + txt = []string{rule.Description} + } + short := strings.Join(txt, " ") + warn(rule.Name, rule.Description, rule.URL, short, location) +} + +func LintFormatShort(rulename, msg string, line int) string { + msg = fmt.Sprintf("%s: %s", rulename, msg) + if line > 0 { + msg = fmt.Sprintf("%s (line %d)", msg, line) + } + return msg +} + +type LintWarnFunc func(rulename, description, url, fmtmsg string, location []parser.Range) + +func ParseLintOptions(checkStr string) (*Config, error) { + checkStr = strings.TrimSpace(checkStr) + if checkStr == "" { + return &Config{}, nil + } + + parts := strings.SplitN(checkStr, ";", 2) + var skipSet []string + var errorOnWarn, skipAll bool + for _, p := range parts { + k, v, ok := strings.Cut(p, "=") + if !ok { + return nil, errors.Errorf("invalid check option %q", p) + } + k = strings.TrimSpace(k) + switch k { + case "skip": + v = strings.TrimSpace(v) + if v == "all" { + skipAll = true + } else { + skipSet = strings.Split(v, ",") + for i, rule := range skipSet { + skipSet[i] = strings.TrimSpace(rule) + } + } + case "error": + v, err := strconv.ParseBool(strings.TrimSpace(v)) + if err != nil { + return nil, errors.Wrapf(err, "failed to parse check option %q", p) + } + errorOnWarn = v + default: + return nil, errors.Errorf("invalid check option %q", k) + } + } + return &Config{ + SkipRules: skipSet, + SkipAll: skipAll, + ReturnAsError: errorOnWarn, + }, nil +} diff --git a/vendor/github.com/moby/buildkit/frontend/dockerfile/linter/ruleset.go b/vendor/github.com/moby/buildkit/frontend/dockerfile/linter/ruleset.go new file mode 100644 index 000000000000..6c70c8ee0c2e --- /dev/null +++ b/vendor/github.com/moby/buildkit/frontend/dockerfile/linter/ruleset.go @@ -0,0 +1,127 @@ +package linter + +import ( + "fmt" +) + +var ( + RuleStageNameCasing = LinterRule[func(string) string]{ + Name: "StageNameCasing", + Description: "Stage names should be lowercase", + URL: "https://docs.docker.com/go/dockerfile/rule/stage-name-casing/", + Format: func(stageName string) string { + return fmt.Sprintf("Stage name '%s' should be lowercase", stageName) + }, + } + RuleFromAsCasing = LinterRule[func(string, string) string]{ + Name: "FromAsCasing", + Description: "The 'as' keyword should match the case of the 'from' keyword", + URL: "https://docs.docker.com/go/dockerfile/rule/from-as-casing/", + Format: func(from, as string) string { + return fmt.Sprintf("'%s' and '%s' keywords' casing do not match", as, from) + }, + } + RuleNoEmptyContinuation = LinterRule[func() string]{ + Name: "NoEmptyContinuation", + Description: "Empty continuation lines will become errors in a future release", + URL: "https://docs.docker.com/go/dockerfile/rule/no-empty-continuation/", + Format: func() string { + return "Empty continuation line" + }, + } + RuleConsistentInstructionCasing = LinterRule[func(string, string) string]{ + Name: "ConsistentInstructionCasing", + Description: "All commands within the Dockerfile should use the same casing (either upper or lower)", + URL: "https://docs.docker.com/go/dockerfile/rule/consistent-instruction-casing/", + Format: func(violatingCommand, correctCasing string) string { + return fmt.Sprintf("Command '%s' should match the case of the command majority (%s)", violatingCommand, correctCasing) + }, + } + RuleDuplicateStageName = LinterRule[func(string) string]{ + Name: "DuplicateStageName", + Description: "Stage names should be unique", + URL: "https://docs.docker.com/go/dockerfile/rule/duplicate-stage-name/", + Format: func(stageName string) string { + return fmt.Sprintf("Duplicate stage name %q, stage names should be unique", stageName) + }, + } + RuleReservedStageName = LinterRule[func(string) string]{ + Name: "ReservedStageName", + Description: "Reserved words should not be used as stage names", + URL: "https://docs.docker.com/go/dockerfile/rule/reserved-stage-name/", + Format: func(reservedStageName string) string { + return fmt.Sprintf("Stage name should not use the same name as reserved stage %q", reservedStageName) + }, + } + RuleJSONArgsRecommended = LinterRule[func(instructionName string) string]{ + Name: "JSONArgsRecommended", + Description: "JSON arguments recommended for ENTRYPOINT/CMD to prevent unintended behavior related to OS signals", + URL: "https://docs.docker.com/go/dockerfile/rule/json-args-recommended/", + Format: func(instructionName string) string { + return fmt.Sprintf("JSON arguments recommended for %s to prevent unintended behavior related to OS signals", instructionName) + }, + } + RuleMaintainerDeprecated = LinterRule[func() string]{ + Name: "MaintainerDeprecated", + Description: "The MAINTAINER instruction is deprecated, use a label instead to define an image author", + URL: "https://docs.docker.com/go/dockerfile/rule/maintainer-deprecated/", + Format: func() string { + return "Maintainer instruction is deprecated in favor of using label" + }, + } + RuleUndefinedArgInFrom = LinterRule[func(string, string) string]{ + Name: "UndefinedArgInFrom", + Description: "FROM command must use declared ARGs", + URL: "https://docs.docker.com/go/dockerfile/rule/undefined-arg-in-from/", + Format: func(baseArg, suggest string) string { + out := fmt.Sprintf("FROM argument '%s' is not declared", baseArg) + if suggest != "" { + out += fmt.Sprintf(" (did you mean %s?)", suggest) + } + return out + }, + } + RuleWorkdirRelativePath = LinterRule[func(workdir string) string]{ + Name: "WorkdirRelativePath", + Description: "Relative workdir without an absolute workdir declared within the build can have unexpected results if the base image changes", + URL: "https://docs.docker.com/go/dockerfile/rule/workdir-relative-path/", + Format: func(workdir string) string { + return fmt.Sprintf("Relative workdir %q can have unexpected results if the base image changes", workdir) + }, + } + RuleUndefinedVar = LinterRule[func(string, string) string]{ + Name: "UndefinedVar", + Description: "Variables should be defined before their use", + URL: "https://docs.docker.com/go/dockerfile/rule/undefined-var/", + Format: func(arg, suggest string) string { + out := fmt.Sprintf("Usage of undefined variable '$%s'", arg) + if suggest != "" { + out += fmt.Sprintf(" (did you mean $%s?)", suggest) + } + return out + }, + } + RuleMultipleInstructionsDisallowed = LinterRule[func(instructionName string) string]{ + Name: "MultipleInstructionsDisallowed", + Description: "Multiple instructions of the same type should not be used in the same stage", + URL: "https://docs.docker.com/go/dockerfile/rule/multiple-instructions-disallowed/", + Format: func(instructionName string) string { + return fmt.Sprintf("Multiple %s instructions should not be used in the same stage because only the last one will be used", instructionName) + }, + } + RuleLegacyKeyValueFormat = LinterRule[func(cmdName string) string]{ + Name: "LegacyKeyValueFormat", + Description: "Legacy key/value format with whitespace separator should not be used", + URL: "https://docs.docker.com/go/dockerfile/rule/legacy-key-value-format/", + Format: func(cmdName string) string { + return fmt.Sprintf("\"%s key=value\" should be used instead of legacy \"%s key value\" format", cmdName, cmdName) + }, + } + RuleInvalidBaseImagePlatform = LinterRule[func(string, string, string) string]{ + Name: "InvalidBaseImagePlatform", + Description: "Base image platform does not match expected target platform", + Format: func(image, expected, actual string) string { + return fmt.Sprintf("Base image %s was pulled with platform %q, expected %q for current build", image, actual, expected) + }, + } +) diff --git a/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/line_parsers.go b/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/line_parsers.go index 4f621df7dad5..7bc67f487579 100644 --- a/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/line_parsers.go +++ b/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/line_parsers.go @@ -17,6 +17,7 @@ import ( var ( errDockerfileNotStringArray = errors.New("when using JSON array syntax, arrays must be comprised of strings only") + errDockerfileNotJSONArray = errors.New("not a JSON array") ) const ( @@ -58,11 +59,11 @@ func parseWords(rest string, d *directives) []string { words := []string{} phase := inSpaces - word := "" quote := '\000' blankOK := false var ch rune var chWidth int + var sbuilder strings.Builder for pos := 0; pos <= len(rest); pos += chWidth { if pos != len(rest) { @@ -79,18 +80,18 @@ func parseWords(rest string, d *directives) []string { phase = inWord // found it, fall through } if (phase == inWord || phase == inQuote) && (pos == len(rest)) { - if blankOK || len(word) > 0 { - words = append(words, word) + if blankOK || sbuilder.Len() > 0 { + words = append(words, sbuilder.String()) } break } if phase == inWord { if unicode.IsSpace(ch) { phase = inSpaces - if blankOK || len(word) > 0 { - words = append(words, word) + if blankOK || sbuilder.Len() > 0 { + words = append(words, sbuilder.String()) } - word = "" + sbuilder.Reset() blankOK = false continue } @@ -106,11 +107,11 @@ func parseWords(rest string, d *directives) []string { // If we're not quoted and we see an escape token, then always just // add the escape token plus the char to the word, even if the char // is a quote. - word += string(ch) + sbuilder.WriteRune(ch) pos += chWidth ch, chWidth = utf8.DecodeRuneInString(rest[pos:]) } - word += string(ch) + sbuilder.WriteRune(ch) continue } if phase == inQuote { @@ -124,10 +125,10 @@ func parseWords(rest string, d *directives) []string { continue // just skip the escape token at end } pos += chWidth - word += string(ch) + sbuilder.WriteRune(ch) ch, chWidth = utf8.DecodeRuneInString(rest[pos:]) } - word += string(ch) + sbuilder.WriteRune(ch) } } @@ -277,7 +278,7 @@ func parseString(rest string, d *directives) (*Node, map[string]bool, error) { func parseJSON(rest string) (*Node, map[string]bool, error) { rest = strings.TrimLeftFunc(rest, unicode.IsSpace) if !strings.HasPrefix(rest, "[") { - return nil, nil, errors.Errorf("Error parsing %q as a JSON array", rest) + return nil, nil, errDockerfileNotJSONArray } var myJSON []interface{} diff --git a/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/parser.go b/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/parser.go index 99fdb961fdb3..c70236ff7d56 100644 --- a/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/parser.go +++ b/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/parser.go @@ -114,7 +114,6 @@ type Heredoc struct { var ( dispatch map[string]func(string, *directives) (*Node, map[string]bool, error) reWhitespace = regexp.MustCompile(`[\t\v\f\r ]+`) - reComment = regexp.MustCompile(`^#.*$`) reHeredoc = regexp.MustCompile(`^(\d*)<<(-?)([^<]*)$`) reLeadingTabs = regexp.MustCompile(`(?m)^\t+`) ) @@ -169,8 +168,8 @@ func (d *directives) setEscapeToken(s string) error { // possibleParserDirective looks for parser directives, eg '# escapeToken='. // Parser directives must precede any builder instruction or other comments, // and cannot be repeated. -func (d *directives) possibleParserDirective(line string) error { - directive, err := d.parser.ParseLine([]byte(line)) +func (d *directives) possibleParserDirective(line []byte) error { + directive, err := d.parser.ParseLine(line) if err != nil { return err } @@ -284,6 +283,7 @@ func Parse(rwc io.Reader) (*Result, error) { scanner.Split(scanLines) warnings := []Warning{} var comments []string + buf := &bytes.Buffer{} var err error for scanner.Scan() { @@ -307,10 +307,12 @@ func Parse(rwc io.Reader) (*Result, error) { currentLine++ startLine := currentLine - line, isEndOfLine := trimContinuationCharacter(string(bytesRead), d) - if isEndOfLine && line == "" { + bytesRead, isEndOfLine := trimContinuationCharacter(bytesRead, d) + if isEndOfLine && len(bytesRead) == 0 { continue } + buf.Reset() + buf.Write(bytesRead) var hasEmptyContinuationLine bool for !isEndOfLine && scanner.Scan() { @@ -329,11 +331,12 @@ func Parse(rwc io.Reader) (*Result, error) { continue } - continuationLine := string(bytesRead) - continuationLine, isEndOfLine = trimContinuationCharacter(continuationLine, d) - line += continuationLine + bytesRead, isEndOfLine = trimContinuationCharacter(bytesRead, d) + buf.Write(bytesRead) } + line := buf.String() + if hasEmptyContinuationLine { warnings = append(warnings, Warning{ Short: "Empty continuation line found in: " + line, @@ -348,7 +351,7 @@ func Parse(rwc io.Reader) (*Result, error) { return nil, withLocation(err, startLine, currentLine) } - if child.canContainHeredoc() { + if child.canContainHeredoc() && strings.Contains(line, "<<") { heredocs, err := heredocsFromLine(line) if err != nil { return nil, withLocation(err, startLine, currentLine) @@ -415,7 +418,7 @@ func heredocFromMatch(match []string) (*Heredoc, error) { // If there are quotes in one but not the other, then we know that some // part of the heredoc word is quoted, so we shouldn't expand the content. shlex.RawQuotes = false - words, err := shlex.ProcessWords(rest, []string{}) + words, err := shlex.ProcessWords(rest, emptyEnvs{}) if err != nil { return nil, err } @@ -425,7 +428,7 @@ func heredocFromMatch(match []string) (*Heredoc, error) { } shlex.RawQuotes = true - wordsRaw, err := shlex.ProcessWords(rest, []string{}) + wordsRaw, err := shlex.ProcessWords(rest, emptyEnvs{}) if err != nil { return nil, err } @@ -466,7 +469,7 @@ func heredocsFromLine(line string) ([]Heredoc, error) { shlex.RawQuotes = true shlex.RawEscapes = true shlex.SkipUnsetEnv = true - words, _ := shlex.ProcessWords(line, []string{}) + words, _ := shlex.ProcessWords(line, emptyEnvs{}) var docs []Heredoc for _, word := range words { @@ -487,7 +490,10 @@ func ChompHeredocContent(src string) string { } func trimComments(src []byte) []byte { - return reComment.ReplaceAll(src, []byte{}) + if !isComment(src) { + return src + } + return nil } func trimLeadingWhitespace(src []byte) []byte { @@ -501,7 +507,8 @@ func trimNewline(src []byte) []byte { } func isComment(line []byte) bool { - return reComment.Match(trimLeadingWhitespace(trimNewline(line))) + line = trimLeadingWhitespace(line) + return len(line) > 0 && line[0] == '#' } func isEmptyContinuationLine(line []byte) bool { @@ -510,9 +517,9 @@ func isEmptyContinuationLine(line []byte) bool { var utf8bom = []byte{0xEF, 0xBB, 0xBF} -func trimContinuationCharacter(line string, d *directives) (string, bool) { - if d.lineContinuationRegex.MatchString(line) { - line = d.lineContinuationRegex.ReplaceAllString(line, "$1") +func trimContinuationCharacter(line []byte, d *directives) ([]byte, bool) { + if d.lineContinuationRegex.Match(line) { + line = d.lineContinuationRegex.ReplaceAll(line, []byte("$1")) return line, false } return line, true @@ -525,7 +532,7 @@ func processLine(d *directives, token []byte, stripLeftWhitespace bool) ([]byte, if stripLeftWhitespace { token = trimLeadingWhitespace(token) } - return trimComments(token), d.possibleParserDirective(string(token)) + return trimComments(token), d.possibleParserDirective(token) } // Variation of bufio.ScanLines that preserves the line endings @@ -550,3 +557,13 @@ func handleScannerError(err error) error { return err } } + +type emptyEnvs struct{} + +func (emptyEnvs) Get(string) (string, bool) { + return "", false +} + +func (emptyEnvs) Keys() []string { + return nil +} diff --git a/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/split_command.go b/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/split_command.go index c0261652f8e2..d1c87522e4f7 100644 --- a/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/split_command.go +++ b/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/split_command.go @@ -36,7 +36,7 @@ func extractBuilderFlags(line string) (string, []string, error) { words := []string{} phase := inSpaces - word := "" + sbuilder := &strings.Builder{} quote := '\000' blankOK := false var ch rune @@ -62,13 +62,14 @@ func extractBuilderFlags(line string) (string, []string, error) { phase = inWord // found something with "--", fall through } if (phase == inWord || phase == inQuote) && (pos == len(line)) { - if word != "--" && (blankOK || len(word) > 0) { + if word := sbuilder.String(); word != "--" && (blankOK || len(word) > 0) { words = append(words, word) } break } if phase == inWord { if unicode.IsSpace(ch) { + word := sbuilder.String() phase = inSpaces if word == "--" { return line[pos:], words, nil @@ -76,7 +77,7 @@ func extractBuilderFlags(line string) (string, []string, error) { if blankOK || len(word) > 0 { words = append(words, word) } - word = "" + sbuilder.Reset() blankOK = false continue } @@ -93,7 +94,9 @@ func extractBuilderFlags(line string) (string, []string, error) { pos++ ch = rune(line[pos]) } - word += string(ch) + if _, err := sbuilder.WriteRune(ch); err != nil { + return "", nil, err + } continue } if phase == inQuote { @@ -109,7 +112,9 @@ func extractBuilderFlags(line string) (string, []string, error) { pos++ ch = rune(line[pos]) } - word += string(ch) + if _, err := sbuilder.WriteRune(ch); err != nil { + return "", nil, err + } } } diff --git a/vendor/github.com/moby/buildkit/frontend/dockerfile/shell/equal_env_unix.go b/vendor/github.com/moby/buildkit/frontend/dockerfile/shell/equal_env_unix.go index f9aca5d9ef08..ec0c8fc744d5 100644 --- a/vendor/github.com/moby/buildkit/frontend/dockerfile/shell/equal_env_unix.go +++ b/vendor/github.com/moby/buildkit/frontend/dockerfile/shell/equal_env_unix.go @@ -9,3 +9,10 @@ package shell func EqualEnvKeys(from, to string) bool { return from == to } + +// NormalizeEnvKey returns the key in a normalized form that can be used +// for comparison. On Unix this is a no-op. On Windows this converts the +// key to uppercase. +func NormalizeEnvKey(key string) string { + return key +} diff --git a/vendor/github.com/moby/buildkit/frontend/dockerfile/shell/equal_env_windows.go b/vendor/github.com/moby/buildkit/frontend/dockerfile/shell/equal_env_windows.go index 7bbed9b20731..02eedcc490af 100644 --- a/vendor/github.com/moby/buildkit/frontend/dockerfile/shell/equal_env_windows.go +++ b/vendor/github.com/moby/buildkit/frontend/dockerfile/shell/equal_env_windows.go @@ -8,3 +8,10 @@ import "strings" func EqualEnvKeys(from, to string) bool { return strings.EqualFold(from, to) } + +// NormalizeEnvKey returns the key in a normalized form that can be used +// for comparison. On Unix this is a no-op. On Windows this converts the +// key to uppercase. +func NormalizeEnvKey(key string) string { + return strings.ToUpper(key) +} diff --git a/vendor/github.com/moby/buildkit/frontend/dockerfile/shell/lex.go b/vendor/github.com/moby/buildkit/frontend/dockerfile/shell/lex.go index 86df5b6c4336..0d74545d1ac6 100644 --- a/vendor/github.com/moby/buildkit/frontend/dockerfile/shell/lex.go +++ b/vendor/github.com/moby/buildkit/frontend/dockerfile/shell/lex.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "regexp" + "slices" "strings" "text/scanner" "unicode" @@ -11,6 +12,11 @@ import ( "github.com/pkg/errors" ) +type EnvGetter interface { + Get(string) (string, bool) + Keys() []string +} + // Lex performs shell word splitting and variable expansion. // // Lex takes a string and an array of env variables and @@ -18,12 +24,15 @@ import ( // tokens. Tries to mimic bash shell process. // It doesn't support all flavors of ${xx:...} formats but new ones can // be added by adding code to the "special ${} format processing" section +// +// It is not safe to call methods on a Lex instance concurrently. type Lex struct { escapeToken rune RawQuotes bool RawEscapes bool SkipProcessQuotes bool SkipUnsetEnv bool + shellWord shellWord } // NewLex creates a new Lex which uses escapeToken to escape quotes. @@ -35,8 +44,9 @@ func NewLex(escapeToken rune) *Lex { // and replace any env var references in 'word'. It will also // return variables in word which were not found in the 'env' list, // which is useful in later linting. -func (s *Lex) ProcessWord(word string, env []string) (string, map[string]struct{}, error) { - result, err := s.process(word, BuildEnvs(env)) +// TODO: rename +func (s *Lex) ProcessWord(word string, env EnvGetter) (string, map[string]struct{}, error) { + result, err := s.process(word, env, true) return result.Result, result.Unmatched, err } @@ -47,18 +57,11 @@ func (s *Lex) ProcessWord(word string, env []string) (string, map[string]struct{ // this splitting is done **after** the env var substitutions are done. // Note, each one is trimmed to remove leading and trailing spaces (unless // they are quoted", but ProcessWord retains spaces between words. -func (s *Lex) ProcessWords(word string, env []string) ([]string, error) { - result, err := s.process(word, BuildEnvs(env)) +func (s *Lex) ProcessWords(word string, env EnvGetter) ([]string, error) { + result, err := s.process(word, env, false) return result.Words, err } -// ProcessWordWithMap will use the 'env' list of environment variables, -// and replace any env var references in 'word'. -func (s *Lex) ProcessWordWithMap(word string, env map[string]string) (string, error) { - result, err := s.process(word, env) - return result.Result, err -} - type ProcessWordResult struct { Result string Words []string @@ -68,41 +71,28 @@ type ProcessWordResult struct { // ProcessWordWithMatches will use the 'env' list of environment variables, // replace any env var references in 'word' and return the env that were used. -func (s *Lex) ProcessWordWithMatches(word string, env map[string]string) (ProcessWordResult, error) { - sw := s.init(word, env) - word, words, err := sw.process(word) - return ProcessWordResult{ - Result: word, - Words: words, - Matched: sw.matches, - Unmatched: sw.nonmatches, - }, err +func (s *Lex) ProcessWordWithMatches(word string, env EnvGetter) (ProcessWordResult, error) { + return s.process(word, env, true) } -func (s *Lex) ProcessWordsWithMap(word string, env map[string]string) ([]string, error) { - result, err := s.process(word, env) - return result.Words, err -} - -func (s *Lex) init(word string, env map[string]string) *shellWord { - sw := &shellWord{ - envs: env, - escapeToken: s.escapeToken, - skipUnsetEnv: s.SkipUnsetEnv, - skipProcessQuotes: s.SkipProcessQuotes, - rawQuotes: s.RawQuotes, - rawEscapes: s.RawEscapes, - matches: make(map[string]struct{}), - nonmatches: make(map[string]struct{}), +func (s *Lex) initWord(word string, env EnvGetter, capture bool) *shellWord { + sw := &s.shellWord + sw.Lex = s + sw.envs = env + sw.capture = capture + sw.rawEscapes = s.RawEscapes + if capture { + sw.matches = nil + sw.nonmatches = nil } sw.scanner.Init(strings.NewReader(word)) return sw } -func (s *Lex) process(word string, env map[string]string) (*ProcessWordResult, error) { - sw := s.init(word, env) +func (s *Lex) process(word string, env EnvGetter, capture bool) (ProcessWordResult, error) { + sw := s.initWord(word, env, capture) word, words, err := sw.process(word) - return &ProcessWordResult{ + return ProcessWordResult{ Result: word, Words: words, Matched: sw.matches, @@ -111,15 +101,14 @@ func (s *Lex) process(word string, env map[string]string) (*ProcessWordResult, e } type shellWord struct { - scanner scanner.Scanner - envs map[string]string - escapeToken rune - rawQuotes bool - rawEscapes bool - skipUnsetEnv bool - skipProcessQuotes bool - matches map[string]struct{} - nonmatches map[string]struct{} + *Lex + wordsBuffer strings.Builder + scanner scanner.Scanner + envs EnvGetter + rawEscapes bool + capture bool // capture matches and nonmatches + matches map[string]struct{} + nonmatches map[string]struct{} } func (sw *shellWord) process(source string) (string, []string, error) { @@ -131,16 +120,16 @@ func (sw *shellWord) process(source string) (string, []string, error) { } type wordsStruct struct { - word string + buf *strings.Builder words []string inWord bool } func (w *wordsStruct) addChar(ch rune) { if unicode.IsSpace(ch) && w.inWord { - if len(w.word) != 0 { - w.words = append(w.words, w.word) - w.word = "" + if w.buf.Len() != 0 { + w.words = append(w.words, w.buf.String()) + w.buf.Reset() w.inWord = false } } else if !unicode.IsSpace(ch) { @@ -149,7 +138,7 @@ func (w *wordsStruct) addChar(ch rune) { } func (w *wordsStruct) addRawChar(ch rune) { - w.word += string(ch) + w.buf.WriteRune(ch) w.inWord = true } @@ -160,16 +149,16 @@ func (w *wordsStruct) addString(str string) { } func (w *wordsStruct) addRawString(str string) { - w.word += str + w.buf.WriteString(str) w.inWord = true } func (w *wordsStruct) getWords() []string { - if len(w.word) > 0 { - w.words = append(w.words, w.word) + if w.buf.Len() > 0 { + w.words = append(w.words, w.buf.String()) // Just in case we're called again by mistake - w.word = "" + w.buf.Reset() w.inWord = false } return w.words @@ -178,13 +167,18 @@ func (w *wordsStruct) getWords() []string { // Process the word, starting at 'pos', and stop when we get to the // end of the word or the 'stopChar' character func (sw *shellWord) processStopOn(stopChar rune, rawEscapes bool) (string, []string, error) { - var result bytes.Buffer + // result buffer can't be currently shared for shellWord as it is called internally + // by processDollar + var result strings.Builder + sw.wordsBuffer.Reset() var words wordsStruct + words.buf = &sw.wordsBuffer + // no need to initialize all the time var charFuncMapping = map[rune]func() (string, error){ '$': sw.processDollar, } - if !sw.skipProcessQuotes { + if !sw.SkipProcessQuotes { charFuncMapping['\''] = sw.processSingleQuote charFuncMapping['"'] = sw.processDoubleQuote } @@ -261,7 +255,7 @@ func (sw *shellWord) processSingleQuote() (string, error) { var result bytes.Buffer ch := sw.scanner.Next() - if sw.rawQuotes { + if sw.RawQuotes { result.WriteRune(ch) } @@ -271,7 +265,7 @@ func (sw *shellWord) processSingleQuote() (string, error) { case scanner.EOF: return "", errors.New("unexpected end of statement while looking for matching single-quote") case '\'': - if sw.rawQuotes { + if sw.RawQuotes { result.WriteRune(ch) } return result.String(), nil @@ -296,7 +290,7 @@ func (sw *shellWord) processDoubleQuote() (string, error) { var result bytes.Buffer ch := sw.scanner.Next() - if sw.rawQuotes { + if sw.RawQuotes { result.WriteRune(ch) } @@ -306,7 +300,7 @@ func (sw *shellWord) processDoubleQuote() (string, error) { return "", errors.New("unexpected end of statement while looking for matching double-quote") case '"': ch := sw.scanner.Next() - if sw.rawQuotes { + if sw.RawQuotes { result.WriteRune(ch) } return result.String(), nil @@ -350,7 +344,7 @@ func (sw *shellWord) processDollar() (string, error) { return "$", nil } value, found := sw.getEnv(name) - if !found && sw.skipUnsetEnv { + if !found && sw.SkipUnsetEnv { return "$" + name, nil } return value, nil @@ -373,7 +367,7 @@ func (sw *shellWord) processDollar() (string, error) { case '}': // Normal ${xx} case value, set := sw.getEnv(name) - if !set && sw.skipUnsetEnv { + if !set && sw.SkipUnsetEnv { return fmt.Sprintf("${%s}", name), nil } return value, nil @@ -395,7 +389,7 @@ func (sw *shellWord) processDollar() (string, error) { // Grab the current value of the variable in question so we // can use it to determine what to do based on the modifier value, set := sw.getEnv(name) - if sw.skipUnsetEnv && !set { + if sw.SkipUnsetEnv && !set { return fmt.Sprintf("${%s%s%s}", name, chs, word), nil } @@ -465,7 +459,7 @@ func (sw *shellWord) processDollar() (string, error) { } value, set := sw.getEnv(name) - if sw.skipUnsetEnv && !set { + if sw.SkipUnsetEnv && !set { return fmt.Sprintf("${%s/%s/%s}", name, pattern, replacement), nil } @@ -528,34 +522,51 @@ func isSpecialParam(char rune) bool { } func (sw *shellWord) getEnv(name string) (string, bool) { - for key, value := range sw.envs { - if EqualEnvKeys(name, key) { + v, ok := sw.envs.Get(name) + if ok { + if sw.capture { + if sw.matches == nil { + sw.matches = make(map[string]struct{}) + } sw.matches[name] = struct{}{} - return value, true } + return v, true + } + if sw.capture { + if sw.nonmatches == nil { + sw.nonmatches = make(map[string]struct{}) + } + sw.nonmatches[name] = struct{}{} } - sw.nonmatches[name] = struct{}{} return "", false } -func BuildEnvs(env []string) map[string]string { +func EnvsFromSlice(env []string) EnvGetter { envs := map[string]string{} - + keys := make([]string, 0, len(env)) for _, e := range env { - i := strings.Index(e, "=") + k, v, _ := strings.Cut(e, "=") + keys = append(keys, k) + envs[NormalizeEnvKey(k)] = v + } + return &envGetter{env: envs, keys: keys} +} - if i < 0 { - envs[e] = "" - } else { - k := e[:i] - v := e[i+1:] +type envGetter struct { + env map[string]string + keys []string +} - // overwrite value if key already exists - envs[k] = v - } - } +var _ EnvGetter = &envGetter{} - return envs +func (e *envGetter) Get(key string) (string, bool) { + key = NormalizeEnvKey(key) + v, ok := e.env[key] + return v, ok +} + +func (e *envGetter) Keys() []string { + return e.keys } // convertShellPatternToRegex converts a shell-like wildcard pattern @@ -647,11 +658,7 @@ func reversePattern(pattern string) string { func reverseString(str string) string { out := []rune(str) - outIdx := len(out) - 1 - for i := 0; i < outIdx; i++ { - out[i], out[outIdx] = out[outIdx], out[i] - outIdx-- - } + slices.Reverse(out) return string(out) } diff --git a/vendor/github.com/moby/buildkit/frontend/dockerui/attr.go b/vendor/github.com/moby/buildkit/frontend/dockerui/attr.go index 52ec012243ec..6a6aa55ca5af 100644 --- a/vendor/github.com/moby/buildkit/frontend/dockerui/attr.go +++ b/vendor/github.com/moby/buildkit/frontend/dockerui/attr.go @@ -1,7 +1,6 @@ package dockerui import ( - "encoding/csv" "net" "strconv" "strings" @@ -13,6 +12,7 @@ import ( "github.com/moby/buildkit/solver/pb" ocispecs "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" + "github.com/tonistiigi/go-csvvalue" ) func parsePlatforms(v string) ([]ocispecs.Platform, error) { @@ -45,8 +45,7 @@ func parseExtraHosts(v string) ([]llb.HostIP, error) { return nil, nil } out := make([]llb.HostIP, 0) - csvReader := csv.NewReader(strings.NewReader(v)) - fields, err := csvReader.Read() + fields, err := csvvalue.Fields(v, nil) if err != nil { return nil, err } @@ -80,8 +79,7 @@ func parseUlimits(v string) ([]pb.Ulimit, error) { return nil, nil } out := make([]pb.Ulimit, 0) - csvReader := csv.NewReader(strings.NewReader(v)) - fields, err := csvReader.Read() + fields, err := csvvalue.Fields(v, nil) if err != nil { return nil, err } diff --git a/vendor/github.com/moby/buildkit/frontend/dockerui/config.go b/vendor/github.com/moby/buildkit/frontend/dockerui/config.go index d99b3affa35f..c2f910283588 100644 --- a/vendor/github.com/moby/buildkit/frontend/dockerui/config.go +++ b/vendor/github.com/moby/buildkit/frontend/dockerui/config.go @@ -14,6 +14,7 @@ import ( controlapi "github.com/moby/buildkit/api/services/control" "github.com/moby/buildkit/client/llb" "github.com/moby/buildkit/frontend/attestations" + "github.com/moby/buildkit/frontend/dockerfile/linter" "github.com/moby/buildkit/frontend/gateway/client" "github.com/moby/buildkit/solver/pb" "github.com/moby/buildkit/util/flightcontrol" @@ -65,7 +66,7 @@ type Config struct { ShmSize int64 Target string Ulimits []pb.Ulimit - LinterConfig *string + LinterConfig *linter.Config CacheImports []client.CacheOptionsEntry TargetPlatforms []ocispecs.Platform // nil means default @@ -78,8 +79,7 @@ type Client struct { Config client client.Client ignoreCache []string - bctx *buildContext - g flightcontrol.Group[*buildContext] + g flightcontrol.CachedGroup[*buildContext] bopts client.BuildOpts dockerignore []byte @@ -281,21 +281,17 @@ func (bc *Client) init() error { bc.Hostname = opts[keyHostname] if v, ok := opts[keyDockerfileLintArg]; ok { - bc.LinterConfig = &v + bc.LinterConfig, err = linter.ParseLintOptions(v) + if err != nil { + return errors.Wrapf(err, "failed to parse %s", keyDockerfileLintArg) + } } return nil } func (bc *Client) buildContext(ctx context.Context) (*buildContext, error) { return bc.g.Do(ctx, "initcontext", func(ctx context.Context) (*buildContext, error) { - if bc.bctx != nil { - return bc.bctx, nil - } - bctx, err := bc.initContext(ctx) - if err == nil { - bc.bctx = bctx - } - return bctx, err + return bc.initContext(ctx) }) } diff --git a/vendor/github.com/moby/buildkit/identity/randomid.go b/vendor/github.com/moby/buildkit/identity/randomid.go index 2b8796f095b2..6b061fb8e4df 100644 --- a/vendor/github.com/moby/buildkit/identity/randomid.go +++ b/vendor/github.com/moby/buildkit/identity/randomid.go @@ -1,17 +1,15 @@ package identity import ( - cryptorand "crypto/rand" + "crypto/rand" "io" "math/big" - - "github.com/pkg/errors" ) var ( // idReader is used for random id generation. This declaration allows us to // replace it for testing. - idReader = cryptorand.Reader + idReader = rand.Reader ) // parameters for random identifier generation. We can tweak this when there is @@ -46,7 +44,7 @@ func NewID() string { var p [randomIDEntropyBytes]byte if _, err := io.ReadFull(idReader, p[:]); err != nil { - panic(errors.Wrap(err, "failed to read random bytes: %v")) + panic("failed to read random bytes: " + err.Error()) } p[0] |= 0x80 // set high bit to avoid the need for padding diff --git a/vendor/github.com/moby/buildkit/util/flightcontrol/cached.go b/vendor/github.com/moby/buildkit/util/flightcontrol/cached.go new file mode 100644 index 000000000000..aeaace7514ff --- /dev/null +++ b/vendor/github.com/moby/buildkit/util/flightcontrol/cached.go @@ -0,0 +1,63 @@ +package flightcontrol + +import ( + "context" + "sync" + + "github.com/pkg/errors" +) + +// Group is a flightcontrol synchronization group that memoizes the results of a function +// and returns the cached result if the function is called with the same key. +// Don't use with long-running groups as the results are cached indefinitely. +type CachedGroup[T any] struct { + // CacheError defines if error results should also be cached. + // It is not safe to change this value after the first call to Do. + // Context cancellation errors are never cached. + CacheError bool + g Group[T] + mu sync.Mutex + cache map[string]result[T] +} + +type result[T any] struct { + v T + err error +} + +// Do executes a context function syncronized by the key or returns the cached result for the key. +func (g *CachedGroup[T]) Do(ctx context.Context, key string, fn func(ctx context.Context) (T, error)) (T, error) { + return g.g.Do(ctx, key, func(ctx context.Context) (T, error) { + g.mu.Lock() + if v, ok := g.cache[key]; ok { + g.mu.Unlock() + if v.err != nil { + if g.CacheError { + return v.v, v.err + } + } else { + return v.v, nil + } + } + g.mu.Unlock() + v, err := fn(ctx) + if err != nil { + select { + case <-ctx.Done(): + if errors.Is(err, context.Cause(ctx)) { + return v, err + } + default: + } + } + if err == nil || g.CacheError { + g.mu.Lock() + if g.cache == nil { + g.cache = make(map[string]result[T]) + } + g.cache[key] = result[T]{v: v, err: err} + g.mu.Unlock() + } + return v, err + }) +} diff --git a/vendor/github.com/moby/buildkit/util/progress/multiwriter.go b/vendor/github.com/moby/buildkit/util/progress/multiwriter.go index 6810ad68b51f..673f9ab57d53 100644 --- a/vendor/github.com/moby/buildkit/util/progress/multiwriter.go +++ b/vendor/github.com/moby/buildkit/util/progress/multiwriter.go @@ -1,6 +1,7 @@ package progress import ( + "maps" "sort" "sync" "time" @@ -83,9 +84,7 @@ func (ps *MultiWriter) WriteRawProgress(p *Progress) error { meta := p.meta if len(ps.meta) > 0 { meta = map[string]interface{}{} - for k, v := range p.meta { - meta[k] = v - } + maps.Copy(meta, p.meta) for k, v := range ps.meta { if _, ok := meta[k]; !ok { meta[k] = v diff --git a/vendor/github.com/moby/buildkit/util/progress/progress.go b/vendor/github.com/moby/buildkit/util/progress/progress.go index fb193113a766..89b8a7dae4e6 100644 --- a/vendor/github.com/moby/buildkit/util/progress/progress.go +++ b/vendor/github.com/moby/buildkit/util/progress/progress.go @@ -3,6 +3,7 @@ package progress import ( "context" "io" + "maps" "sort" "sync" "time" @@ -207,9 +208,7 @@ func pipe() (*progressReader, *progressWriter, func(error)) { func newWriter(pw *progressWriter) *progressWriter { meta := make(map[string]interface{}) - for k, v := range pw.meta { - meta[k] = v - } + maps.Copy(meta, pw.meta) pw = &progressWriter{ reader: pw.reader, meta: meta, @@ -240,9 +239,7 @@ func (pw *progressWriter) WriteRawProgress(p *Progress) error { meta := p.meta if len(pw.meta) > 0 { meta = map[string]interface{}{} - for k, v := range p.meta { - meta[k] = v - } + maps.Copy(meta, p.meta) for k, v := range pw.meta { if _, ok := meta[k]; !ok { meta[k] = v diff --git a/vendor/github.com/moby/buildkit/util/progress/progressui/colors.go b/vendor/github.com/moby/buildkit/util/progress/progressui/colors.go index 9758f6b5d6bc..e48535960bf1 100644 --- a/vendor/github.com/moby/buildkit/util/progress/progressui/colors.go +++ b/vendor/github.com/moby/buildkit/util/progress/progressui/colors.go @@ -1,13 +1,13 @@ package progressui import ( - "encoding/csv" "errors" "strconv" "strings" "github.com/moby/buildkit/util/bklog" "github.com/morikuni/aec" + "github.com/tonistiigi/go-csvvalue" ) var termColorMap = map[string]aec.ANSI{ @@ -59,9 +59,9 @@ func setUserDefinedTermColors(colorsEnv string) { } func readBuildkitColorsEnv(colorsEnv string) []string { - csvReader := csv.NewReader(strings.NewReader(colorsEnv)) + csvReader := csvvalue.NewParser() csvReader.Comma = ':' - fields, err := csvReader.Read() + fields, err := csvReader.Fields(colorsEnv, nil) if err != nil { bklog.L.WithError(err).Warnf("Could not parse BUILDKIT_COLORS. Falling back to defaults.") return nil @@ -70,8 +70,7 @@ func readBuildkitColorsEnv(colorsEnv string) []string { } func readRGB(v string) aec.ANSI { - csvReader := csv.NewReader(strings.NewReader(v)) - fields, err := csvReader.Read() + fields, err := csvvalue.Fields(v, nil) if err != nil { bklog.L.WithError(err).Warnf("Could not parse value %s as valid comma-separated RGB color. Ignoring.", v) return nil diff --git a/vendor/github.com/moby/buildkit/util/testutil/integration/run.go b/vendor/github.com/moby/buildkit/util/testutil/integration/run.go index a336b82fbf7d..2c1804806575 100644 --- a/vendor/github.com/moby/buildkit/util/testutil/integration/run.go +++ b/vendor/github.com/moby/buildkit/util/testutil/integration/run.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + "maps" "math/rand" "os" "os/exec" @@ -137,9 +138,7 @@ func WithMirroredImages(m map[string]string) TestOpt { if tc.mirroredImages == nil { tc.mirroredImages = map[string]string{} } - for k, v := range m { - tc.mirroredImages[k] = v - } + maps.Copy(tc.mirroredImages, m) } } @@ -418,9 +417,7 @@ func prepareValueMatrix(tc testConf) []matrixValue { for _, c := range current { vv := newMatrixValue(featureName, featureValue, v) vv.fn = append(vv.fn, c.fn...) - for k, v := range c.values { - vv.values[k] = v - } + maps.Copy(vv.values, c.values) m = append(m, vv) } } diff --git a/vendor/github.com/tonistiigi/go-csvvalue/.golangci.yml b/vendor/github.com/tonistiigi/go-csvvalue/.golangci.yml new file mode 100644 index 000000000000..fc1224be3eea --- /dev/null +++ b/vendor/github.com/tonistiigi/go-csvvalue/.golangci.yml @@ -0,0 +1,30 @@ +run: + timeout: 10m + +linters: + enable: + - bodyclose + - depguard + - errname + - forbidigo + - gocritic + - gofmt + - goimports + - gosec + - gosimple + - govet + - importas + - ineffassign + - makezero + - misspell + - noctx + - nolintlint + - revive + - staticcheck + - typecheck + - unused + - whitespace + disable-all: true + +issues: + exclude-use-default: false diff --git a/vendor/github.com/tonistiigi/go-csvvalue/.yamllint.yml b/vendor/github.com/tonistiigi/go-csvvalue/.yamllint.yml new file mode 100644 index 000000000000..e190c1613ec2 --- /dev/null +++ b/vendor/github.com/tonistiigi/go-csvvalue/.yamllint.yml @@ -0,0 +1,13 @@ +ignore: | + /vendor + +extends: default + +yaml-files: + - '*.yaml' + - '*.yml' + +rules: + truthy: disable + line-length: disable + document-start: disable diff --git a/vendor/github.com/tonistiigi/go-csvvalue/Dockerfile b/vendor/github.com/tonistiigi/go-csvvalue/Dockerfile new file mode 100644 index 000000000000..fd144d9236e1 --- /dev/null +++ b/vendor/github.com/tonistiigi/go-csvvalue/Dockerfile @@ -0,0 +1,42 @@ +#syntax=docker/dockerfile:1.8 +#check=error=true + +ARG GO_VERSION=1.22 +ARG XX_VERSION=1.4.0 + +ARG COVER_FILENAME="cover.out" +ARG BENCH_FILENAME="bench.txt" + +FROM --platform=${BUILDPLATFORM} tonistiigi/xx:${XX_VERSION} AS xx + +FROM --platform=${BUILDPLATFORM} golang:${GO_VERSION}-alpine AS golang +COPY --link --from=xx / / +WORKDIR /src +ARG TARGETPLATFORM + +FROM golang AS build +RUN --mount=target=/root/.cache,type=cache \ + --mount=type=bind xx-go build . + +FROM golang AS runbench +ARG BENCH_FILENAME +RUN --mount=target=/root/.cache,type=cache \ + --mount=type=bind \ + xx-go test -v --run skip --bench . | tee /tmp/${BENCH_FILENAME} + +FROM scratch AS bench +ARG BENCH_FILENAME +COPY --from=runbench /tmp/${BENCH_FILENAME} / + +FROM golang AS runtest +ARG TESTFLAGS="-v" +ARG COVER_FILENAME +RUN --mount=target=/root/.cache,type=cache \ + --mount=type=bind \ + xx-go test -coverprofile=/tmp/${COVER_FILENAME} $TESTFLAGS . + +FROM scratch AS test +ARG COVER_FILENAME +COPY --from=runtest /tmp/${COVER_FILENAME} / + +FROM build diff --git a/vendor/github.com/tonistiigi/go-csvvalue/LICENSE b/vendor/github.com/tonistiigi/go-csvvalue/LICENSE new file mode 100644 index 000000000000..b3e072396a75 --- /dev/null +++ b/vendor/github.com/tonistiigi/go-csvvalue/LICENSE @@ -0,0 +1,22 @@ +MIT + +Copyright 2024 Tõnis Tiigi + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/tonistiigi/go-csvvalue/codecov.yml b/vendor/github.com/tonistiigi/go-csvvalue/codecov.yml new file mode 100644 index 000000000000..69cb76019a47 --- /dev/null +++ b/vendor/github.com/tonistiigi/go-csvvalue/codecov.yml @@ -0,0 +1 @@ +comment: false diff --git a/vendor/github.com/tonistiigi/go-csvvalue/csvvalue.go b/vendor/github.com/tonistiigi/go-csvvalue/csvvalue.go new file mode 100644 index 000000000000..727129298d0e --- /dev/null +++ b/vendor/github.com/tonistiigi/go-csvvalue/csvvalue.go @@ -0,0 +1,172 @@ +// Package csvvalue provides an efficient parser for a single line CSV value. +// It is more efficient than the standard library csv package for parsing many +// small values. For multi-line CSV parsing, the standard library is recommended. +package csvvalue + +import ( + "encoding/csv" + "errors" + "io" + "strings" + "unicode" + "unicode/utf8" +) + +var errInvalidDelim = errors.New("csv: invalid field or comment delimiter") + +var defaultParser = NewParser() + +// Fields parses the line with default parser and returns +// slice of fields for the record. If dst is nil, a new slice is allocated. +func Fields(inp string, dst []string) ([]string, error) { + return defaultParser.Fields(inp, dst) +} + +// Parser is a CSV parser for a single line value. +type Parser struct { + Comma rune + LazyQuotes bool + TrimLeadingSpace bool +} + +// NewParser returns a new Parser with default settings. +func NewParser() *Parser { + return &Parser{Comma: ','} +} + +// Fields parses the line and returns slice of fields for the record. +// If dst is nil, a new slice is allocated. +// For backward compatibility, a trailing newline is allowed. +func (r *Parser) Fields(line string, dst []string) ([]string, error) { + if !validDelim(r.Comma) { + return nil, errInvalidDelim + } + + if cap(dst) == 0 { + // imprecise estimate, strings.Count is fast + dst = make([]string, 0, 1+strings.Count(line, string(r.Comma))) + } else { + dst = dst[:0] + } + + const quoteLen = len(`"`) + var ( + pos int + commaLen = utf8.RuneLen(r.Comma) + trim = r.TrimLeadingSpace + ) + + // allow trailing newline for compatibility + if n := len(line); n > 0 && line[n-1] == '\n' { + if n > 1 && line[n-2] == '\r' { + line = line[:n-2] + } else { + line = line[:n-1] + } + } + + if len(line) == 0 { + return nil, io.EOF + } + +parseField: + for { + if trim { + i := strings.IndexFunc(line, func(r rune) bool { + return !unicode.IsSpace(r) + }) + if i < 0 { + i = len(line) + } + line = line[i:] + pos += i + } + if len(line) == 0 || line[0] != '"' { + // Non-quoted string field + i := strings.IndexRune(line, r.Comma) + var field string + if i >= 0 { + field = line[:i] + } else { + field = line + } + // Check to make sure a quote does not appear in field. + if !r.LazyQuotes { + if j := strings.IndexRune(field, '"'); j >= 0 { + return nil, parseErr(pos+j, csv.ErrBareQuote) + } + } + dst = append(dst, field) + if i >= 0 { + line = line[i+commaLen:] + pos += i + commaLen + continue + } + break + } + // Quoted string field + line = line[quoteLen:] + pos += quoteLen + halfOpen := false + for { + i := strings.IndexRune(line, '"') + if i >= 0 { + // Hit next quote. + if !halfOpen { + dst = append(dst, line[:i]) + } else { + appendToLast(dst, line[:i]) + } + halfOpen = false + line = line[i+quoteLen:] + pos += i + quoteLen + switch rn := nextRune(line); { + case rn == '"': + // `""` sequence (append quote). + appendToLast(dst, "\"") + line = line[quoteLen:] + pos += quoteLen + case rn == r.Comma: + // `",` sequence (end of field). + line = line[commaLen:] + pos += commaLen + continue parseField + case len(line) == 0: + break parseField + case r.LazyQuotes: + // `"` sequence (bare quote). + appendToLast(dst, "\"") + halfOpen = true + default: + // `"*` sequence (invalid non-escaped quote). + return nil, parseErr(pos-quoteLen, csv.ErrQuote) + } + } else { + if !r.LazyQuotes { + return nil, parseErr(pos, csv.ErrQuote) + } + // Hit end of line (copy all data so far). + dst = append(dst, line) + break parseField + } + } + } + return dst, nil +} + +func validDelim(r rune) bool { + return r != 0 && r != '"' && r != '\r' && r != '\n' && utf8.ValidRune(r) && r != utf8.RuneError +} + +func appendToLast(dst []string, s string) { + dst[len(dst)-1] += s +} + +func nextRune(b string) rune { + r, _ := utf8.DecodeRuneInString(b) + return r +} + +func parseErr(pos int, err error) error { + return &csv.ParseError{StartLine: 1, Line: 1, Column: pos + 1, Err: err} +} diff --git a/vendor/github.com/tonistiigi/go-csvvalue/docker-bake.hcl b/vendor/github.com/tonistiigi/go-csvvalue/docker-bake.hcl new file mode 100644 index 000000000000..6791f364a964 --- /dev/null +++ b/vendor/github.com/tonistiigi/go-csvvalue/docker-bake.hcl @@ -0,0 +1,68 @@ +variable "COVER_FILENAME" { + default = null +} + +variable "BENCH_FILENAME" { + default = null +} + +variable "GO_VERSION" { + default = null +} + +target "default" { + targets = ["build"] +} + +target "_all_platforms" { + platforms = [ + "linux/amd64", + "linux/arm64", + "linux/arm/v7", + "linux/arm/v6", + "linux/386", + "linux/ppc64le", + "linux/s390x", + "darwin/amd64", + "darwin/arm64", + "windows/amd64", + ] +} + +target "build" { + output = ["type=cacheonly"] + args = { + GO_VERSION = GO_VERSION + } +} + +target "build-all" { + inherits = ["build", "_all_platforms"] +} + +target "test" { + target = "test" + args = { + COVER_FILENAME = COVER_FILENAME + GO_VERSION = GO_VERSION + } + output = [COVER_FILENAME!=null?".":"type=cacheonly"] +} + +target "bench" { + target = "bench" + args = { + BENCH_FILENAME = BENCH_FILENAME + GO_VERSION = GO_VERSION + } + output = [BENCH_FILENAME!=null?".":"type=cacheonly"] +} + +target "lint" { + dockerfile = "hack/dockerfiles/lint.Dockerfile" + output = ["type=cacheonly"] +} + +target "lint-all" { + inherits = ["lint", "_all_platforms"] +} \ No newline at end of file diff --git a/vendor/github.com/tonistiigi/go-csvvalue/readme.md b/vendor/github.com/tonistiigi/go-csvvalue/readme.md new file mode 100644 index 000000000000..24712f038ee4 --- /dev/null +++ b/vendor/github.com/tonistiigi/go-csvvalue/readme.md @@ -0,0 +1,44 @@ +### go-csvvalue + +![GitHub Release](https://img.shields.io/github/v/release/tonistiigi/go-csvvalue) +[![Go Reference](https://pkg.go.dev/badge/github.com/tonistiigi/go-csvvalue.svg)](https://pkg.go.dev/github.com/tonistiigi/go-csvvalue) +![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/tonistiigi/go-csvvalue/ci.yml) +![Codecov](https://img.shields.io/codecov/c/github/tonistiigi/go-csvvalue) +![GitHub License](https://img.shields.io/github/license/tonistiigi/go-csvvalue) + + +`go-csvvalue` provides an efficient parser for a single-line CSV value. + +It is more efficient than the standard library `encoding/csv` package for parsing many small values. The main problem with stdlib implementation is that it calls `bufio.NewReader` internally, allocating 4KB of memory on each invocation. For multi-line CSV parsing, the standard library is still recommended. If you wish to optimize memory usage for `encoding/csv`, call `csv.NewReader` with an instance of `*bufio.Reader` that already has a 4KB buffer allocated and then reuse that buffer for all reads. + +For further memory optimization, an existing string slice can be optionally passed to be reused for returning the parsed fields. + +For backwards compatibility with stdlib record parser, the input may contain a trailing newline character. + +### Benchmark + +``` +goos: linux +goarch: amd64 +pkg: github.com/tonistiigi/go-csvvalue +cpu: AMD EPYC 7763 64-Core Processor +BenchmarkFields/stdlib/withcache-4 1109917 1103 ns/op 4520 B/op 14 allocs/op +BenchmarkFields/stdlib/nocache-4 1082838 1125 ns/op 4520 B/op 14 allocs/op +BenchmarkFields/csvvalue/withcache-4 28554976 42.12 ns/op 0 B/op 0 allocs/op +BenchmarkFields/csvvalue/nocache-4 13666134 83.77 ns/op 48 B/op 1 allocs/op +``` +``` +goos: darwin +goarch: arm64 +pkg: github.com/tonistiigi/go-csvvalue +BenchmarkFields/stdlib/nocache-10 1679923 784.9 ns/op 4520 B/op 14 allocs/op +BenchmarkFields/stdlib/withcache-10 1641891 826.9 ns/op 4520 B/op 14 allocs/op +BenchmarkFields/csvvalue/withcache-10 34399642 33.93 ns/op 0 B/op 0 allocs/op +BenchmarkFields/csvvalue/nocache-10 17441373 67.21 ns/op 48 B/op 1 allocs/op +PASS +``` + +### Credits + +This package is mostly based on `encoding/csv` implementation and also uses that package for compatibility testing. + diff --git a/vendor/modules.txt b/vendor/modules.txt index 0d4a84ce1e7a..d14e79a13259 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -216,7 +216,7 @@ github.com/davecgh/go-spew/spew # github.com/distribution/reference v0.6.0 ## explicit; go 1.20 github.com/distribution/reference -# github.com/docker/cli v26.1.4+incompatible +# github.com/docker/cli v27.0.1+incompatible ## explicit github.com/docker/cli/cli github.com/docker/cli/cli-plugins/hooks @@ -270,7 +270,7 @@ 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/distribution/uuid -# github.com/docker/docker v26.1.4+incompatible +# github.com/docker/docker v27.0.1+incompatible ## explicit github.com/docker/docker/api github.com/docker/docker/api/types @@ -298,7 +298,6 @@ github.com/docker/docker/pkg/homedir 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/namesgenerator github.com/docker/docker/pkg/pools github.com/docker/docker/pkg/stdcopy @@ -513,7 +512,7 @@ github.com/miekg/pkcs11 github.com/mitchellh/go-wordwrap # github.com/mitchellh/mapstructure v1.5.0 ## explicit; go 1.14 -# github.com/moby/buildkit v0.14.1 +# github.com/moby/buildkit v0.14.1-0.20240625190127-aaaf86e5470b ## explicit; go 1.21 github.com/moby/buildkit/api/services/control github.com/moby/buildkit/api/types @@ -533,6 +532,7 @@ github.com/moby/buildkit/exporter/containerimage/exptypes github.com/moby/buildkit/exporter/exptypes github.com/moby/buildkit/frontend/attestations github.com/moby/buildkit/frontend/dockerfile/command +github.com/moby/buildkit/frontend/dockerfile/linter github.com/moby/buildkit/frontend/dockerfile/parser github.com/moby/buildkit/frontend/dockerfile/shell github.com/moby/buildkit/frontend/dockerui @@ -718,6 +718,9 @@ github.com/theupdateframework/notary/tuf/validation ## explicit; go 1.20 github.com/tonistiigi/fsutil github.com/tonistiigi/fsutil/types +# github.com/tonistiigi/go-csvvalue v0.0.0-20240619222358-bb8dd5cba3c2 +## explicit; go 1.16 +github.com/tonistiigi/go-csvvalue # github.com/tonistiigi/units v0.0.0-20180711220420-6950e57a87ea ## explicit github.com/tonistiigi/units