From 5400a48aafdd853542fa83b70a11c7ae02f30509 Mon Sep 17 00:00:00 2001 From: Brian Goff Date: Sat, 9 Sep 2023 22:27:44 +0000 Subject: [PATCH] Plumb contexts through commands This is to prepare for otel support. Signed-off-by: Brian Goff Signed-off-by: Sebastiaan van Stijn --- cli/command/builder/prune.go | 10 +++++----- cli/command/checkpoint/create.go | 6 +++--- cli/command/checkpoint/list.go | 6 +++--- cli/command/checkpoint/remove.go | 6 +++--- cli/command/cli.go | 13 ++++++++++--- cli/command/cli_options.go | 10 ++++++++++ cli/command/config/create.go | 5 ++--- cli/command/config/inspect.go | 5 ++--- cli/command/config/ls.go | 5 ++--- cli/command/config/remove.go | 5 ++--- cli/command/container/attach.go | 2 +- cli/command/container/commit.go | 6 ++---- cli/command/container/cp.go | 6 ++---- cli/command/container/cp_test.go | 15 ++++++++------- cli/command/container/create.go | 6 +++--- cli/command/container/create_test.go | 1 + cli/command/container/diff.go | 6 ++---- cli/command/container/exec.go | 2 +- cli/command/container/exec_test.go | 8 ++++---- cli/command/container/export.go | 6 +++--- cli/command/container/inspect.go | 5 ++--- cli/command/container/kill.go | 5 ++--- cli/command/container/list.go | 6 ++---- cli/command/container/logs.go | 6 ++---- cli/command/container/logs_test.go | 3 ++- cli/command/container/pause.go | 6 ++---- cli/command/container/port.go | 6 ++---- cli/command/container/prune.go | 10 +++++----- cli/command/container/rename.go | 6 ++---- cli/command/container/restart.go | 5 ++--- cli/command/container/rm.go | 6 ++---- cli/command/container/run.go | 10 +++++----- cli/command/container/run_test.go | 2 ++ cli/command/container/start.go | 6 +++--- cli/command/container/stats.go | 9 +++------ cli/command/container/stop.go | 6 +++--- cli/command/container/top.go | 6 ++---- cli/command/container/unpause.go | 6 ++---- cli/command/container/update.go | 6 ++---- cli/command/container/wait.go | 6 ++---- cli/command/image/build.go | 6 +++--- cli/command/image/build_test.go | 8 ++++---- cli/command/image/history.go | 6 ++---- cli/command/image/import.go | 6 +++--- cli/command/image/inspect.go | 6 ++---- cli/command/image/list.go | 6 ++---- cli/command/image/load.go | 6 +++--- cli/command/image/prune.go | 10 +++++----- cli/command/image/pull.go | 5 ++--- cli/command/image/push.go | 6 ++---- cli/command/image/remove.go | 5 ++--- cli/command/image/save.go | 6 +++--- cli/command/image/tag.go | 6 ++---- cli/command/manifest/create_list.go | 5 ++--- cli/command/manifest/inspect.go | 5 ++--- cli/command/manifest/push.go | 5 ++--- cli/command/manifest/rm.go | 5 +++-- cli/command/network/connect.go | 6 +++--- cli/command/network/create.go | 6 +++--- cli/command/network/disconnect.go | 6 +++--- cli/command/network/inspect.go | 6 ++---- cli/command/network/list.go | 6 +++--- cli/command/network/prune.go | 10 +++++----- cli/command/network/remove.go | 6 +++--- cli/command/node/demote.go | 7 ++++--- cli/command/node/inspect.go | 5 ++--- cli/command/node/list.go | 5 ++--- cli/command/node/promote.go | 7 ++++--- cli/command/node/ps.go | 5 ++--- cli/command/node/remove.go | 5 ++--- cli/command/node/update.go | 9 ++++----- cli/command/plugin/create.go | 6 ++---- cli/command/plugin/disable.go | 6 +++--- cli/command/plugin/enable.go | 6 +++--- cli/command/plugin/inspect.go | 5 ++--- cli/command/plugin/install.go | 5 ++--- cli/command/plugin/list.go | 6 +++--- cli/command/plugin/push.go | 6 ++---- cli/command/plugin/remove.go | 6 ++---- cli/command/plugin/set.go | 4 +--- cli/command/plugin/upgrade.go | 5 ++--- cli/command/registry/login.go | 5 ++--- cli/command/registry/login_test.go | 2 +- cli/command/registry/logout.go | 5 +++-- cli/command/registry/search.go | 5 ++--- cli/command/secret/create.go | 5 ++--- cli/command/secret/inspect.go | 5 ++--- cli/command/secret/ls.go | 5 ++--- cli/command/secret/remove.go | 5 ++--- cli/command/service/create.go | 14 ++++++-------- cli/command/service/create_test.go | 13 +++++++++---- cli/command/service/inspect.go | 5 ++--- cli/command/service/list.go | 5 ++--- cli/command/service/logs.go | 6 ++---- cli/command/service/parse.go | 6 ++---- cli/command/service/ps.go | 5 ++--- cli/command/service/ps_test.go | 7 +++++-- cli/command/service/remove.go | 6 ++---- cli/command/service/rollback.go | 5 ++--- cli/command/service/scale.go | 5 ++--- cli/command/service/update.go | 17 ++++++++--------- cli/command/service/update_test.go | 6 ++++-- cli/command/stack/cmd.go | 2 +- cli/command/stack/deploy.go | 2 +- cli/command/stack/list.go | 7 ++++--- cli/command/stack/ps.go | 2 +- cli/command/stack/remove.go | 2 +- cli/command/stack/services.go | 7 ++++--- cli/command/stack/swarm/deploy.go | 4 +--- cli/command/stack/swarm/deploy_composefile.go | 2 +- cli/command/stack/swarm/list.go | 4 ++-- cli/command/stack/swarm/ps.go | 3 +-- cli/command/stack/swarm/remove.go | 3 +-- cli/command/stack/swarm/services.go | 3 +-- cli/command/swarm/ca.go | 5 ++--- cli/command/swarm/init.go | 5 ++--- cli/command/swarm/join.go | 5 ++--- cli/command/swarm/join_token.go | 5 ++--- cli/command/swarm/leave.go | 5 ++--- cli/command/swarm/unlock.go | 5 ++--- cli/command/swarm/unlock_key.go | 5 ++--- cli/command/swarm/update.go | 5 ++--- cli/command/system/df.go | 6 +++--- cli/command/system/dial_stdio.go | 7 ++++--- cli/command/system/events.go | 6 +++--- cli/command/system/info.go | 5 ++--- cli/command/system/inspect.go | 6 +++--- cli/command/system/prune.go | 9 +++++---- cli/command/system/version.go | 6 +++--- cli/command/trust/common.go | 3 +-- cli/command/trust/inspect.go | 13 +++++++------ cli/command/trust/inspect_pretty.go | 5 +++-- cli/command/trust/revoke.go | 5 ++--- cli/command/trust/sign.go | 5 ++--- cli/command/trust/signer_add.go | 9 ++++----- cli/command/trust/signer_remove.go | 9 ++++----- cli/command/trust/signer_remove_test.go | 12 ++++++++---- cli/command/volume/create.go | 6 +++--- cli/command/volume/inspect.go | 6 ++---- cli/command/volume/list.go | 6 +++--- cli/command/volume/prune.go | 10 +++++----- cli/command/volume/remove.go | 5 ++--- cli/command/volume/update.go | 5 ++--- cli/compose/convert/service.go | 12 ++++++++---- cli/compose/convert/service_test.go | 6 ++++-- .../plugins/nopersistentprerun/main.go | 3 +-- 146 files changed, 409 insertions(+), 470 deletions(-) diff --git a/cli/command/builder/prune.go b/cli/command/builder/prune.go index 30215601ed..6286218cac 100644 --- a/cli/command/builder/prune.go +++ b/cli/command/builder/prune.go @@ -30,7 +30,7 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command { Short: "Remove build cache", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - spaceReclaimed, output, err := runPrune(dockerCli, options) + spaceReclaimed, output, err := runPrune(cmd.Context(), dockerCli, options) if err != nil { return err } @@ -58,7 +58,7 @@ const ( allCacheWarning = `WARNING! This will remove all build cache. Are you sure you want to continue?` ) -func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { +func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { pruneFilters := options.filter.Value() pruneFilters = command.PruneFilters(dockerCli, pruneFilters) @@ -70,7 +70,7 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint6 return 0, "", nil } - report, err := dockerCli.Client().BuildCachePrune(context.Background(), types.BuildCachePruneOptions{ + report, err := dockerCli.Client().BuildCachePrune(ctx, types.BuildCachePruneOptions{ All: options.all, KeepStorage: options.keepStorage.Value(), Filters: pruneFilters, @@ -93,6 +93,6 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint6 } // CachePrune executes a prune command for build cache -func CachePrune(dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) { - return runPrune(dockerCli, pruneOptions{force: true, all: all, filter: filter}) +func CachePrune(ctx context.Context, dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) { + return runPrune(ctx, dockerCli, pruneOptions{force: true, all: all, filter: filter}) } diff --git a/cli/command/checkpoint/create.go b/cli/command/checkpoint/create.go index e0b73f35ae..e72bbb9b12 100644 --- a/cli/command/checkpoint/create.go +++ b/cli/command/checkpoint/create.go @@ -28,7 +28,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { opts.container = args[0] opts.checkpoint = args[1] - return runCreate(dockerCli, opts) + return runCreate(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: completion.NoComplete, } @@ -40,8 +40,8 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runCreate(dockerCli command.Cli, opts createOptions) error { - err := dockerCli.Client().CheckpointCreate(context.Background(), opts.container, checkpoint.CreateOptions{ +func runCreate(ctx context.Context, dockerCli command.Cli, opts createOptions) error { + err := dockerCli.Client().CheckpointCreate(ctx, opts.container, checkpoint.CreateOptions{ CheckpointID: opts.checkpoint, CheckpointDir: opts.checkpointDir, Exit: !opts.leaveRunning, diff --git a/cli/command/checkpoint/list.go b/cli/command/checkpoint/list.go index 1bbf867dff..bddea60acd 100644 --- a/cli/command/checkpoint/list.go +++ b/cli/command/checkpoint/list.go @@ -24,7 +24,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { Short: "List checkpoints for a container", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runList(dockerCli, args[0], opts) + return runList(cmd.Context(), dockerCli, args[0], opts) }, ValidArgsFunction: completion.ContainerNames(dockerCli, false), } @@ -35,8 +35,8 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runList(dockerCli command.Cli, container string, opts listOptions) error { - checkpoints, err := dockerCli.Client().CheckpointList(context.Background(), container, checkpoint.ListOptions{ +func runList(ctx context.Context, dockerCli command.Cli, container string, opts listOptions) error { + checkpoints, err := dockerCli.Client().CheckpointList(ctx, container, checkpoint.ListOptions{ CheckpointDir: opts.checkpointDir, }) if err != nil { diff --git a/cli/command/checkpoint/remove.go b/cli/command/checkpoint/remove.go index f98903e4f5..ba8d4095da 100644 --- a/cli/command/checkpoint/remove.go +++ b/cli/command/checkpoint/remove.go @@ -22,7 +22,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { Short: "Remove a checkpoint", Args: cli.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - return runRemove(dockerCli, args[0], args[1], opts) + return runRemove(cmd.Context(), dockerCli, args[0], args[1], opts) }, } @@ -32,8 +32,8 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runRemove(dockerCli command.Cli, container string, checkpointID string, opts removeOptions) error { - return dockerCli.Client().CheckpointDelete(context.Background(), container, checkpoint.DeleteOptions{ +func runRemove(ctx context.Context, dockerCli command.Cli, container string, checkpointID string, opts removeOptions) error { + return dockerCli.Client().CheckpointDelete(ctx, container, checkpoint.DeleteOptions{ CheckpointID: checkpointID, CheckpointDir: opts.checkpointDir, }) diff --git a/cli/command/cli.go b/cli/command/cli.go index ce623b194f..ae2d6c93e2 100644 --- a/cli/command/cli.go +++ b/cli/command/cli.go @@ -82,6 +82,11 @@ type DockerCli struct { dockerEndpoint docker.Endpoint contextStoreConfig store.Config initTimeout time.Duration + + // baseCtx is the base context used for internal operations. In the future + // this may be replaced by explicitly passing a context to functions that + // need it. + baseCtx context.Context } // DefaultVersion returns api.defaultVersion. @@ -320,8 +325,7 @@ func (cli *DockerCli) getInitTimeout() time.Duration { } func (cli *DockerCli) initializeFromClient() { - ctx := context.Background() - ctx, cancel := context.WithTimeout(ctx, cli.getInitTimeout()) + ctx, cancel := context.WithTimeout(cli.baseCtx, cli.getInitTimeout()) defer cancel() ping, err := cli.client.Ping(ctx) @@ -441,6 +445,9 @@ func (cli *DockerCli) initialize() error { return } } + if cli.baseCtx == nil { + cli.baseCtx = context.Background() + } cli.initializeFromClient() }) return cli.initErr @@ -484,7 +491,7 @@ func NewDockerCli(ops ...CLIOption) (*DockerCli, error) { } ops = append(defaultOps, ops...) - cli := &DockerCli{} + cli := &DockerCli{baseCtx: context.Background()} if err := cli.Apply(ops...); err != nil { return nil, err } diff --git a/cli/command/cli_options.go b/cli/command/cli_options.go index 5528e0f4f8..858155b635 100644 --- a/cli/command/cli_options.go +++ b/cli/command/cli_options.go @@ -1,6 +1,7 @@ package command import ( + "context" "io" "os" "strconv" @@ -35,6 +36,15 @@ func WithStandardStreams() CLIOption { } } +// WithBaseContext sets the base context of a cli. It is used to propagate +// the context from the command line to the client. +func WithBaseContext(ctx context.Context) CLIOption { + return func(cli *DockerCli) error { + cli.baseCtx = ctx + return nil + } +} + // WithCombinedStreams uses the same stream for the output and error streams. func WithCombinedStreams(combined io.Writer) CLIOption { return func(cli *DockerCli) error { diff --git a/cli/command/config/create.go b/cli/command/config/create.go index dc79277d4c..965d2ddc74 100644 --- a/cli/command/config/create.go +++ b/cli/command/config/create.go @@ -35,7 +35,7 @@ func newConfigCreateCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { createOpts.Name = args[0] createOpts.File = args[1] - return RunConfigCreate(dockerCli, createOpts) + return RunConfigCreate(cmd.Context(), dockerCli, createOpts) }, ValidArgsFunction: completion.NoComplete, } @@ -48,9 +48,8 @@ func newConfigCreateCommand(dockerCli command.Cli) *cobra.Command { } // RunConfigCreate creates a config with the given options. -func RunConfigCreate(dockerCli command.Cli, options CreateOptions) error { +func RunConfigCreate(ctx context.Context, dockerCli command.Cli, options CreateOptions) error { client := dockerCli.Client() - ctx := context.Background() var in io.Reader = dockerCli.In() if options.File != "-" { diff --git a/cli/command/config/inspect.go b/cli/command/config/inspect.go index 617a98830c..f795f85bc8 100644 --- a/cli/command/config/inspect.go +++ b/cli/command/config/inspect.go @@ -27,7 +27,7 @@ func newConfigInspectCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.Names = args - return RunConfigInspect(dockerCli, opts) + return RunConfigInspect(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return completeNames(dockerCli)(cmd, args, toComplete) @@ -40,9 +40,8 @@ func newConfigInspectCommand(dockerCli command.Cli) *cobra.Command { } // RunConfigInspect inspects the given Swarm config. -func RunConfigInspect(dockerCli command.Cli, opts InspectOptions) error { +func RunConfigInspect(ctx context.Context, dockerCli command.Cli, opts InspectOptions) error { client := dockerCli.Client() - ctx := context.Background() if opts.Pretty { opts.Format = "pretty" diff --git a/cli/command/config/ls.go b/cli/command/config/ls.go index 8fbabd2301..c8cb4337e0 100644 --- a/cli/command/config/ls.go +++ b/cli/command/config/ls.go @@ -31,7 +31,7 @@ func newConfigListCommand(dockerCli command.Cli) *cobra.Command { Short: "List configs", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return RunConfigList(dockerCli, listOpts) + return RunConfigList(cmd.Context(), dockerCli, listOpts) }, ValidArgsFunction: completion.NoComplete, } @@ -45,9 +45,8 @@ func newConfigListCommand(dockerCli command.Cli) *cobra.Command { } // RunConfigList lists Swarm configs. -func RunConfigList(dockerCli command.Cli, options ListOptions) error { +func RunConfigList(ctx context.Context, dockerCli command.Cli, options ListOptions) error { client := dockerCli.Client() - ctx := context.Background() configs, err := client.ConfigList(ctx, types.ConfigListOptions{Filters: options.Filter.Value()}) if err != nil { diff --git a/cli/command/config/remove.go b/cli/command/config/remove.go index 0818d601c6..cd5403db05 100644 --- a/cli/command/config/remove.go +++ b/cli/command/config/remove.go @@ -26,7 +26,7 @@ func newConfigRemoveCommand(dockerCli command.Cli) *cobra.Command { opts := RemoveOptions{ Names: args, } - return RunConfigRemove(dockerCli, opts) + return RunConfigRemove(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return completeNames(dockerCli)(cmd, args, toComplete) @@ -35,9 +35,8 @@ func newConfigRemoveCommand(dockerCli command.Cli) *cobra.Command { } // RunConfigRemove removes the given Swarm configs. -func RunConfigRemove(dockerCli command.Cli, opts RemoveOptions) error { +func RunConfigRemove(ctx context.Context, dockerCli command.Cli, opts RemoveOptions) error { client := dockerCli.Client() - ctx := context.Background() var errs []string diff --git a/cli/command/container/attach.go b/cli/command/container/attach.go index 0c4b963ee3..ea90273707 100644 --- a/cli/command/container/attach.go +++ b/cli/command/container/attach.go @@ -53,7 +53,7 @@ func NewAttachCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctr = args[0] - return RunAttach(context.Background(), dockerCli, ctr, &opts) + return RunAttach(cmd.Context(), dockerCli, ctr, &opts) }, Annotations: map[string]string{ "aliases": "docker container attach, docker attach", diff --git a/cli/command/container/commit.go b/cli/command/container/commit.go index 26171656d1..076c38b692 100644 --- a/cli/command/container/commit.go +++ b/cli/command/container/commit.go @@ -35,7 +35,7 @@ func NewCommitCommand(dockerCli command.Cli) *cobra.Command { if len(args) > 1 { options.reference = args[1] } - return runCommit(dockerCli, &options) + return runCommit(cmd.Context(), dockerCli, &options) }, Annotations: map[string]string{ "aliases": "docker container commit, docker commit", @@ -56,9 +56,7 @@ func NewCommitCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runCommit(dockerCli command.Cli, options *commitOptions) error { - ctx := context.Background() - +func runCommit(ctx context.Context, dockerCli command.Cli, options *commitOptions) error { response, err := dockerCli.Client().ContainerCommit(ctx, options.container, container.CommitOptions{ Reference: options.reference, Comment: options.comment, diff --git a/cli/command/container/cp.go b/cli/command/container/cp.go index b7f1fe6c39..b6c05d37b0 100644 --- a/cli/command/container/cp.go +++ b/cli/command/container/cp.go @@ -151,7 +151,7 @@ func NewCopyCommand(dockerCli command.Cli) *cobra.Command { // User did not specify "quiet" flag; suppress output if no terminal is attached opts.quiet = !dockerCli.Out().IsTerminal() } - return runCopy(dockerCli, opts) + return runCopy(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{ "aliases": "docker container cp, docker cp", @@ -169,7 +169,7 @@ func progressHumanSize(n int64) string { return units.HumanSizeWithPrecision(float64(n), 3) } -func runCopy(dockerCli command.Cli, opts copyOptions) error { +func runCopy(ctx context.Context, dockerCli command.Cli, opts copyOptions) error { srcContainer, srcPath := splitCpArg(opts.source) destContainer, destPath := splitCpArg(opts.destination) @@ -191,8 +191,6 @@ func runCopy(dockerCli command.Cli, opts copyOptions) error { copyConfig.container = destContainer } - ctx := context.Background() - switch direction { case fromContainer: return copyFromContainer(ctx, dockerCli, copyConfig) diff --git a/cli/command/container/cp_test.go b/cli/command/container/cp_test.go index 6c9581f8e2..6a40518a27 100644 --- a/cli/command/container/cp_test.go +++ b/cli/command/container/cp_test.go @@ -1,6 +1,7 @@ package container import ( + "context" "io" "os" "runtime" @@ -41,7 +42,7 @@ func TestRunCopyWithInvalidArguments(t *testing.T) { } for _, testcase := range testcases { t.Run(testcase.doc, func(t *testing.T) { - err := runCopy(test.NewFakeCli(nil), testcase.options) + err := runCopy(context.TODO(), test.NewFakeCli(nil), testcase.options) assert.Error(t, err, testcase.expectedErr) }) } @@ -58,7 +59,7 @@ func TestRunCopyFromContainerToStdout(t *testing.T) { } options := copyOptions{source: "container:/path", destination: "-"} cli := test.NewFakeCli(fakeClient) - err := runCopy(cli, options) + err := runCopy(context.TODO(), cli, options) assert.NilError(t, err) assert.Check(t, is.Equal(tarContent, cli.OutBuffer().String())) assert.Check(t, is.Equal("", cli.ErrBuffer().String())) @@ -78,7 +79,7 @@ func TestRunCopyFromContainerToFilesystem(t *testing.T) { } options := copyOptions{source: "container:/path", destination: destDir.Path(), quiet: true} cli := test.NewFakeCli(fakeClient) - err := runCopy(cli, options) + err := runCopy(context.TODO(), cli, options) assert.NilError(t, err) assert.Check(t, is.Equal("", cli.OutBuffer().String())) assert.Check(t, is.Equal("", cli.ErrBuffer().String())) @@ -106,7 +107,7 @@ func TestRunCopyFromContainerToFilesystemMissingDestinationDirectory(t *testing. destination: destDir.Join("missing", "foo"), } cli := test.NewFakeCli(fakeClient) - err := runCopy(cli, options) + err := runCopy(context.TODO(), cli, options) assert.ErrorContains(t, err, destDir.Join("missing")) } @@ -119,7 +120,7 @@ func TestRunCopyToContainerFromFileWithTrailingSlash(t *testing.T) { destination: "container:/path", } cli := test.NewFakeCli(&fakeClient{}) - err := runCopy(cli, options) + err := runCopy(context.TODO(), cli, options) expectedError := "not a directory" if runtime.GOOS == "windows" { @@ -134,7 +135,7 @@ func TestRunCopyToContainerSourceDoesNotExist(t *testing.T) { destination: "container:/path", } cli := test.NewFakeCli(&fakeClient{}) - err := runCopy(cli, options) + err := runCopy(context.TODO(), cli, options) expected := "no such file or directory" if runtime.GOOS == "windows" { expected = "cannot find the file specified" @@ -193,7 +194,7 @@ func TestSplitCpArg(t *testing.T) { func TestRunCopyFromContainerToFilesystemIrregularDestination(t *testing.T) { options := copyOptions{source: "container:/dev/null", destination: "/dev/random"} cli := test.NewFakeCli(nil) - err := runCopy(cli, options) + err := runCopy(context.TODO(), cli, options) assert.Assert(t, err != nil) expected := `"/dev/random" must be a directory or a regular file` assert.ErrorContains(t, err, expected) diff --git a/cli/command/container/create.go b/cli/command/container/create.go index 26b3170ac8..beaad77fd0 100644 --- a/cli/command/container/create.go +++ b/cli/command/container/create.go @@ -55,7 +55,7 @@ func NewCreateCommand(dockerCli command.Cli) *cobra.Command { if len(args) > 1 { copts.Args = args[1:] } - return runCreate(dockerCli, cmd.Flags(), &options, copts) + return runCreate(cmd.Context(), dockerCli, cmd.Flags(), &options, copts) }, Annotations: map[string]string{ "aliases": "docker container create, docker create", @@ -80,7 +80,7 @@ func NewCreateCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runCreate(dockerCli command.Cli, flags *pflag.FlagSet, options *createOptions, copts *containerOptions) error { +func runCreate(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, options *createOptions, copts *containerOptions) error { if err := validatePullOpt(options.pull); err != nil { reportError(dockerCli.Err(), "create", err.Error(), true) return cli.StatusError{StatusCode: 125} @@ -104,7 +104,7 @@ func runCreate(dockerCli command.Cli, flags *pflag.FlagSet, options *createOptio reportError(dockerCli.Err(), "create", err.Error(), true) return cli.StatusError{StatusCode: 125} } - id, err := createContainer(context.Background(), dockerCli, containerCfg, options) + id, err := createContainer(ctx, dockerCli, containerCfg, options) if err != nil { return err } diff --git a/cli/command/container/create_test.go b/cli/command/container/create_test.go index 2233532064..546da0d095 100644 --- a/cli/command/container/create_test.go +++ b/cli/command/container/create_test.go @@ -181,6 +181,7 @@ func TestCreateContainerImagePullPolicyInvalid(t *testing.T) { t.Run(tc.PullPolicy, func(t *testing.T) { dockerCli := test.NewFakeCli(&fakeClient{}) err := runCreate( + context.TODO(), dockerCli, &pflag.FlagSet{}, &createOptions{pull: tc.PullPolicy}, diff --git a/cli/command/container/diff.go b/cli/command/container/diff.go index c0951b28f5..15699f5dbb 100644 --- a/cli/command/container/diff.go +++ b/cli/command/container/diff.go @@ -25,7 +25,7 @@ func NewDiffCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.container = args[0] - return runDiff(dockerCli, &opts) + return runDiff(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container diff, docker diff", @@ -34,12 +34,10 @@ func NewDiffCommand(dockerCli command.Cli) *cobra.Command { } } -func runDiff(dockerCli command.Cli, opts *diffOptions) error { +func runDiff(ctx context.Context, dockerCli command.Cli, opts *diffOptions) error { if opts.container == "" { return errors.New("Container name cannot be empty") } - ctx := context.Background() - changes, err := dockerCli.Client().ContainerDiff(ctx, opts.container) if err != nil { return err diff --git a/cli/command/container/exec.go b/cli/command/container/exec.go index db89c68b38..625f4571e3 100644 --- a/cli/command/container/exec.go +++ b/cli/command/container/exec.go @@ -52,7 +52,7 @@ func NewExecCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { container = args[0] options.Command = args[1:] - return RunExec(context.Background(), dockerCli, container, options) + return RunExec(cmd.Context(), dockerCli, container, options) }, ValidArgsFunction: completion.ContainerNames(dockerCli, false, func(container types.Container) bool { return container.State != "paused" diff --git a/cli/command/container/exec_test.go b/cli/command/container/exec_test.go index 4bc52c9243..aeb877e634 100644 --- a/cli/command/container/exec_test.go +++ b/cli/command/container/exec_test.go @@ -192,16 +192,16 @@ func TestRunExec(t *testing.T) { for _, testcase := range testcases { t.Run(testcase.doc, func(t *testing.T) { - cli := test.NewFakeCli(&testcase.client) + fakeCLI := test.NewFakeCli(&testcase.client) - err := RunExec(context.Background(), cli, "thecontainer", testcase.options) + err := RunExec(context.TODO(), fakeCLI, "thecontainer", testcase.options) if testcase.expectedError != "" { assert.ErrorContains(t, err, testcase.expectedError) } else if !assert.Check(t, err) { return } - assert.Check(t, is.Equal(testcase.expectedOut, cli.OutBuffer().String())) - assert.Check(t, is.Equal(testcase.expectedErr, cli.ErrBuffer().String())) + assert.Check(t, is.Equal(testcase.expectedOut, fakeCLI.OutBuffer().String())) + assert.Check(t, is.Equal(testcase.expectedErr, fakeCLI.ErrBuffer().String())) }) } } diff --git a/cli/command/container/export.go b/cli/command/container/export.go index 1871686d93..e9afa7dbe1 100644 --- a/cli/command/container/export.go +++ b/cli/command/container/export.go @@ -26,7 +26,7 @@ func NewExportCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.container = args[0] - return runExport(dockerCli, opts) + return runExport(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{ "aliases": "docker container export, docker export", @@ -41,7 +41,7 @@ func NewExportCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runExport(dockerCli command.Cli, opts exportOptions) error { +func runExport(ctx context.Context, dockerCli command.Cli, opts exportOptions) error { if opts.output == "" && dockerCli.Out().IsTerminal() { return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect") } @@ -52,7 +52,7 @@ func runExport(dockerCli command.Cli, opts exportOptions) error { clnt := dockerCli.Client() - responseBody, err := clnt.ContainerExport(context.Background(), opts.container) + responseBody, err := clnt.ContainerExport(ctx, opts.container) if err != nil { return err } diff --git a/cli/command/container/inspect.go b/cli/command/container/inspect.go index 70c2609fac..2d1d96c18a 100644 --- a/cli/command/container/inspect.go +++ b/cli/command/container/inspect.go @@ -27,7 +27,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.refs = args - return runInspect(dockerCli, opts) + return runInspect(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: completion.ContainerNames(dockerCli, true), } @@ -39,9 +39,8 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runInspect(dockerCli command.Cli, opts inspectOptions) error { +func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error { client := dockerCli.Client() - ctx := context.Background() getRefFunc := func(ref string) (any, []byte, error) { return client.ContainerInspectWithRaw(ctx, ref, opts.size) diff --git a/cli/command/container/kill.go b/cli/command/container/kill.go index 2483a22437..96ce22e5ae 100644 --- a/cli/command/container/kill.go +++ b/cli/command/container/kill.go @@ -28,7 +28,7 @@ func NewKillCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.containers = args - return runKill(dockerCli, &opts) + return runKill(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container kill, docker kill", @@ -41,9 +41,8 @@ func NewKillCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runKill(dockerCli command.Cli, opts *killOptions) error { +func runKill(ctx context.Context, dockerCli command.Cli, opts *killOptions) error { var errs []string - ctx := context.Background() errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error { return dockerCli.Client().ContainerKill(ctx, container, opts.signal) }) diff --git a/cli/command/container/list.go b/cli/command/container/list.go index 21fa45a34b..7e466b02e3 100644 --- a/cli/command/container/list.go +++ b/cli/command/container/list.go @@ -38,7 +38,7 @@ func NewPsCommand(dockerCLI command.Cli) *cobra.Command { Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { options.sizeChanged = cmd.Flags().Changed("size") - return runPs(dockerCLI, &options) + return runPs(cmd.Context(), dockerCLI, &options) }, Annotations: map[string]string{ "category-top": "3", @@ -114,9 +114,7 @@ func buildContainerListOptions(options *psOptions) (*container.ListOptions, erro return listOptions, nil } -func runPs(dockerCLI command.Cli, options *psOptions) error { - ctx := context.Background() - +func runPs(ctx context.Context, dockerCLI command.Cli, options *psOptions) error { if len(options.format) == 0 { // load custom psFormat from CLI config (if any) options.format = dockerCLI.ConfigFile().PsFormat diff --git a/cli/command/container/logs.go b/cli/command/container/logs.go index 5855529e0a..3d536f721b 100644 --- a/cli/command/container/logs.go +++ b/cli/command/container/logs.go @@ -33,7 +33,7 @@ func NewLogsCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.container = args[0] - return runLogs(dockerCli, &opts) + return runLogs(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container logs, docker logs", @@ -52,9 +52,7 @@ func NewLogsCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runLogs(dockerCli command.Cli, opts *logsOptions) error { - ctx := context.Background() - +func runLogs(ctx context.Context, dockerCli command.Cli, opts *logsOptions) error { c, err := dockerCli.Client().ContainerInspect(ctx, opts.container) if err != nil { return err diff --git a/cli/command/container/logs_test.go b/cli/command/container/logs_test.go index a12fbde37e..e1d238e6f9 100644 --- a/cli/command/container/logs_test.go +++ b/cli/command/container/logs_test.go @@ -1,6 +1,7 @@ package container import ( + "context" "io" "strings" "testing" @@ -46,7 +47,7 @@ func TestRunLogs(t *testing.T) { t.Run(testcase.doc, func(t *testing.T) { cli := test.NewFakeCli(&testcase.client) - err := runLogs(cli, testcase.options) + err := runLogs(context.TODO(), cli, testcase.options) if testcase.expectedError != "" { assert.ErrorContains(t, err, testcase.expectedError) } else if !assert.Check(t, err) { diff --git a/cli/command/container/pause.go b/cli/command/container/pause.go index aec3c4cb17..8323827e8d 100644 --- a/cli/command/container/pause.go +++ b/cli/command/container/pause.go @@ -27,7 +27,7 @@ func NewPauseCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.containers = args - return runPause(dockerCli, &opts) + return runPause(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container pause, docker pause", @@ -38,9 +38,7 @@ func NewPauseCommand(dockerCli command.Cli) *cobra.Command { } } -func runPause(dockerCli command.Cli, opts *pauseOptions) error { - ctx := context.Background() - +func runPause(ctx context.Context, dockerCli command.Cli, opts *pauseOptions) error { var errs []string errChan := parallelOperation(ctx, opts.containers, dockerCli.Client().ContainerPause) for _, container := range opts.containers { diff --git a/cli/command/container/port.go b/cli/command/container/port.go index e8e39efa21..915ecf057d 100644 --- a/cli/command/container/port.go +++ b/cli/command/container/port.go @@ -36,7 +36,7 @@ func NewPortCommand(dockerCli command.Cli) *cobra.Command { if len(args) > 1 { opts.port = args[1] } - return runPort(dockerCli, &opts) + return runPort(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container port, docker port", @@ -52,9 +52,7 @@ func NewPortCommand(dockerCli command.Cli) *cobra.Command { // TODO(thaJeztah): currently this defaults to show the TCP port if no // proto is specified. We should consider changing this to "any" protocol // for the given private port. -func runPort(dockerCli command.Cli, opts *portOptions) error { - ctx := context.Background() - +func runPort(ctx context.Context, dockerCli command.Cli, opts *portOptions) error { c, err := dockerCli.Client().ContainerInspect(ctx, opts.container) if err != nil { return err diff --git a/cli/command/container/prune.go b/cli/command/container/prune.go index 868560ef71..0db41092e8 100644 --- a/cli/command/container/prune.go +++ b/cli/command/container/prune.go @@ -26,7 +26,7 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command { Short: "Remove all stopped containers", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - spaceReclaimed, output, err := runPrune(dockerCli, options) + spaceReclaimed, output, err := runPrune(cmd.Context(), dockerCli, options) if err != nil { return err } @@ -50,14 +50,14 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command { const warning = `WARNING! This will remove all stopped containers. Are you sure you want to continue?` -func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { +func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { pruneFilters := command.PruneFilters(dockerCli, options.filter.Value()) if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) { return 0, "", nil } - report, err := dockerCli.Client().ContainersPrune(context.Background(), pruneFilters) + report, err := dockerCli.Client().ContainersPrune(ctx, pruneFilters) if err != nil { return 0, "", err } @@ -75,6 +75,6 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint6 // RunPrune calls the Container Prune API // This returns the amount of space reclaimed and a detailed output string -func RunPrune(dockerCli command.Cli, _ bool, filter opts.FilterOpt) (uint64, string, error) { - return runPrune(dockerCli, pruneOptions{force: true, filter: filter}) +func RunPrune(ctx context.Context, dockerCli command.Cli, _ bool, filter opts.FilterOpt) (uint64, string, error) { + return runPrune(ctx, dockerCli, pruneOptions{force: true, filter: filter}) } diff --git a/cli/command/container/rename.go b/cli/command/container/rename.go index faed72b51a..a871e38d1e 100644 --- a/cli/command/container/rename.go +++ b/cli/command/container/rename.go @@ -28,7 +28,7 @@ func NewRenameCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { opts.oldName = args[0] opts.newName = args[1] - return runRename(dockerCli, &opts) + return runRename(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container rename, docker rename", @@ -38,9 +38,7 @@ func NewRenameCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runRename(dockerCli command.Cli, opts *renameOptions) error { - ctx := context.Background() - +func runRename(ctx context.Context, dockerCli command.Cli, opts *renameOptions) error { oldName := strings.TrimSpace(opts.oldName) newName := strings.TrimSpace(opts.newName) diff --git a/cli/command/container/restart.go b/cli/command/container/restart.go index ce22b2c270..0ac4fa985e 100644 --- a/cli/command/container/restart.go +++ b/cli/command/container/restart.go @@ -32,7 +32,7 @@ func NewRestartCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { opts.containers = args opts.timeoutChanged = cmd.Flags().Changed("time") - return runRestart(dockerCli, &opts) + return runRestart(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container restart, docker restart", @@ -46,8 +46,7 @@ func NewRestartCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runRestart(dockerCli command.Cli, opts *restartOptions) error { - ctx := context.Background() +func runRestart(ctx context.Context, dockerCli command.Cli, opts *restartOptions) error { var errs []string var timeout *int if opts.timeoutChanged { diff --git a/cli/command/container/rm.go b/cli/command/container/rm.go index a06c076902..171e8e81e9 100644 --- a/cli/command/container/rm.go +++ b/cli/command/container/rm.go @@ -33,7 +33,7 @@ func NewRmCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.containers = args - return runRm(dockerCli, &opts) + return runRm(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container rm, docker container remove, docker rm", @@ -48,9 +48,7 @@ func NewRmCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runRm(dockerCli command.Cli, opts *rmOptions) error { - ctx := context.Background() - +func runRm(ctx context.Context, dockerCli command.Cli, opts *rmOptions) error { var errs []string errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, ctrID string) error { ctrID = strings.Trim(ctrID, "/") diff --git a/cli/command/container/run.go b/cli/command/container/run.go index 92e9b1ee33..2c4e8d41ea 100644 --- a/cli/command/container/run.go +++ b/cli/command/container/run.go @@ -42,7 +42,7 @@ func NewRunCommand(dockerCli command.Cli) *cobra.Command { if len(args) > 1 { copts.Args = args[1:] } - return runRun(dockerCli, cmd.Flags(), &options, copts) + return runRun(cmd.Context(), dockerCli, cmd.Flags(), &options, copts) }, ValidArgsFunction: completion.ImageNames(dockerCli), Annotations: map[string]string{ @@ -89,7 +89,7 @@ func NewRunCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runRun(dockerCli command.Cli, flags *pflag.FlagSet, ropts *runOptions, copts *containerOptions) error { +func runRun(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, ropts *runOptions, copts *containerOptions) error { if err := validatePullOpt(ropts.pull); err != nil { reportError(dockerCli.Err(), "run", err.Error(), true) return cli.StatusError{StatusCode: 125} @@ -114,11 +114,11 @@ func runRun(dockerCli command.Cli, flags *pflag.FlagSet, ropts *runOptions, copt reportError(dockerCli.Err(), "run", err.Error(), true) return cli.StatusError{StatusCode: 125} } - return runContainer(dockerCli, ropts, copts, containerCfg) + return runContainer(ctx, dockerCli, ropts, copts, containerCfg) } //nolint:gocyclo -func runContainer(dockerCli command.Cli, runOpts *runOptions, copts *containerOptions, containerCfg *containerConfig) error { +func runContainer(ctx context.Context, dockerCli command.Cli, runOpts *runOptions, copts *containerOptions, containerCfg *containerConfig) error { config := containerCfg.Config stdout, stderr := dockerCli.Out(), dockerCli.Err() apiClient := dockerCli.Client() @@ -140,7 +140,7 @@ func runContainer(dockerCli command.Cli, runOpts *runOptions, copts *containerOp config.StdinOnce = false } - ctx, cancelFun := context.WithCancel(context.Background()) + ctx, cancelFun := context.WithCancel(ctx) defer cancelFun() containerID, err := createContainer(ctx, dockerCli, containerCfg, &runOpts.createOptions) diff --git a/cli/command/container/run_test.go b/cli/command/container/run_test.go index d901c20aa7..f2416f7d5a 100644 --- a/cli/command/container/run_test.go +++ b/cli/command/container/run_test.go @@ -1,6 +1,7 @@ package container import ( + "context" "errors" "fmt" "io" @@ -97,6 +98,7 @@ func TestRunContainerImagePullPolicyInvalid(t *testing.T) { t.Run(tc.PullPolicy, func(t *testing.T) { dockerCli := test.NewFakeCli(&fakeClient{}) err := runRun( + context.TODO(), dockerCli, &pflag.FlagSet{}, &runOptions{createOptions: createOptions{pull: tc.PullPolicy}}, diff --git a/cli/command/container/start.go b/cli/command/container/start.go index f750e36b5d..4a2fe1988a 100644 --- a/cli/command/container/start.go +++ b/cli/command/container/start.go @@ -45,7 +45,7 @@ func NewStartCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.Containers = args - return RunStart(dockerCli, &opts) + return RunStart(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container start, docker start", @@ -72,8 +72,8 @@ func NewStartCommand(dockerCli command.Cli) *cobra.Command { // RunStart executes a `start` command // //nolint:gocyclo -func RunStart(dockerCli command.Cli, opts *StartOptions) error { - ctx, cancelFun := context.WithCancel(context.Background()) +func RunStart(ctx context.Context, dockerCli command.Cli, opts *StartOptions) error { + ctx, cancelFun := context.WithCancel(ctx) defer cancelFun() switch { diff --git a/cli/command/container/stats.go b/cli/command/container/stats.go index cd5f9038ac..1e20445a5d 100644 --- a/cli/command/container/stats.go +++ b/cli/command/container/stats.go @@ -39,7 +39,7 @@ func NewStatsCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(0), RunE: func(cmd *cobra.Command, args []string) error { opts.containers = args - return runStats(dockerCli, &opts) + return runStats(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container stats, docker stats", @@ -59,12 +59,10 @@ func NewStatsCommand(dockerCli command.Cli) *cobra.Command { // This shows real-time information on CPU usage, memory usage, and network I/O. // //nolint:gocyclo -func runStats(dockerCli command.Cli, opts *statsOptions) error { +func runStats(ctx context.Context, dockerCli command.Cli, opts *statsOptions) error { showAll := len(opts.containers) == 0 closeChan := make(chan error) - ctx := context.Background() - // monitorContainerEvents watches for container creation and removal (only // used when calling `docker stats` without arguments). monitorContainerEvents := func(started chan<- struct{}, c chan events.Message, stopped <-chan struct{}) { @@ -96,8 +94,7 @@ func runStats(dockerCli command.Cli, opts *statsOptions) error { // Get the daemonOSType if not set already if daemonOSType == "" { - svctx := context.Background() - sv, err := dockerCli.Client().ServerVersion(svctx) + sv, err := dockerCli.Client().ServerVersion(ctx) if err != nil { return err } diff --git a/cli/command/container/stop.go b/cli/command/container/stop.go index 1cff0741b8..c221fb4448 100644 --- a/cli/command/container/stop.go +++ b/cli/command/container/stop.go @@ -32,7 +32,7 @@ func NewStopCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { opts.containers = args opts.timeoutChanged = cmd.Flags().Changed("time") - return runStop(dockerCli, &opts) + return runStop(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container stop, docker stop", @@ -46,13 +46,13 @@ func NewStopCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runStop(dockerCli command.Cli, opts *stopOptions) error { +func runStop(ctx context.Context, dockerCli command.Cli, opts *stopOptions) error { var timeout *int if opts.timeoutChanged { timeout = &opts.timeout } - errChan := parallelOperation(context.Background(), opts.containers, func(ctx context.Context, id string) error { + errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, id string) error { return dockerCli.Client().ContainerStop(ctx, id, container.StopOptions{ Signal: opts.signal, Timeout: timeout, diff --git a/cli/command/container/top.go b/cli/command/container/top.go index 0ba6557cd7..411fcbbf79 100644 --- a/cli/command/container/top.go +++ b/cli/command/container/top.go @@ -29,7 +29,7 @@ func NewTopCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { opts.container = args[0] opts.args = args[1:] - return runTop(dockerCli, &opts) + return runTop(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container top, docker top", @@ -43,9 +43,7 @@ func NewTopCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runTop(dockerCli command.Cli, opts *topOptions) error { - ctx := context.Background() - +func runTop(ctx context.Context, dockerCli command.Cli, opts *topOptions) error { procList, err := dockerCli.Client().ContainerTop(ctx, opts.container, opts.args) if err != nil { return err diff --git a/cli/command/container/unpause.go b/cli/command/container/unpause.go index 1e155c7c8a..3d82dcff80 100644 --- a/cli/command/container/unpause.go +++ b/cli/command/container/unpause.go @@ -27,7 +27,7 @@ func NewUnpauseCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.containers = args - return runUnpause(dockerCli, &opts) + return runUnpause(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container unpause, docker unpause", @@ -39,9 +39,7 @@ func NewUnpauseCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runUnpause(dockerCli command.Cli, opts *unpauseOptions) error { - ctx := context.Background() - +func runUnpause(ctx context.Context, dockerCli command.Cli, opts *unpauseOptions) error { var errs []string errChan := parallelOperation(ctx, opts.containers, dockerCli.Client().ContainerUnpause) for _, container := range opts.containers { diff --git a/cli/command/container/update.go b/cli/command/container/update.go index 0e53ceb9df..7ea668830b 100644 --- a/cli/command/container/update.go +++ b/cli/command/container/update.go @@ -47,7 +47,7 @@ func NewUpdateCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { options.containers = args options.nFlag = cmd.Flags().NFlag() - return runUpdate(dockerCli, &options) + return runUpdate(cmd.Context(), dockerCli, &options) }, Annotations: map[string]string{ "aliases": "docker container update, docker update", @@ -86,7 +86,7 @@ func NewUpdateCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runUpdate(dockerCli command.Cli, options *updateOptions) error { +func runUpdate(ctx context.Context, dockerCli command.Cli, options *updateOptions) error { var err error if options.nFlag == 0 { @@ -126,8 +126,6 @@ func runUpdate(dockerCli command.Cli, options *updateOptions) error { RestartPolicy: restartPolicy, } - ctx := context.Background() - var ( warns []string errs []string diff --git a/cli/command/container/wait.go b/cli/command/container/wait.go index df782e3a75..91cca5b6aa 100644 --- a/cli/command/container/wait.go +++ b/cli/command/container/wait.go @@ -26,7 +26,7 @@ func NewWaitCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.containers = args - return runWait(dockerCli, &opts) + return runWait(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "aliases": "docker container wait, docker wait", @@ -37,9 +37,7 @@ func NewWaitCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runWait(dockerCli command.Cli, opts *waitOptions) error { - ctx := context.Background() - +func runWait(ctx context.Context, dockerCli command.Cli, opts *waitOptions) error { var errs []string for _, container := range opts.containers { resultC, errC := dockerCli.Client().ContainerWait(ctx, container, "") diff --git a/cli/command/image/build.go b/cli/command/image/build.go index 732f093e3a..61a5ed4dbb 100644 --- a/cli/command/image/build.go +++ b/cli/command/image/build.go @@ -101,7 +101,7 @@ func NewBuildCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { options.context = args[0] - return runBuild(dockerCli, options) + return runBuild(cmd.Context(), dockerCli, options) }, Annotations: map[string]string{ "category-top": "4", @@ -172,7 +172,7 @@ func (out *lastProgressOutput) WriteProgress(prog progress.Progress) error { } //nolint:gocyclo -func runBuild(dockerCli command.Cli, options buildOptions) error { +func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions) error { var ( err error buildCtx io.ReadCloser @@ -272,7 +272,7 @@ func runBuild(dockerCli command.Cli, options buildOptions) error { } } - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(ctx) defer cancel() var resolvedTags []*resolvedTag diff --git a/cli/command/image/build_test.go b/cli/command/image/build_test.go index e7ae1aca41..e69df8f261 100644 --- a/cli/command/image/build_test.go +++ b/cli/command/image/build_test.go @@ -48,7 +48,7 @@ func TestRunBuildDockerfileFromStdinWithCompress(t *testing.T) { options.dockerfileName = "-" options.context = dir.Path() options.untrusted = true - assert.NilError(t, runBuild(cli, options)) + assert.NilError(t, runBuild(context.TODO(), cli, options)) expected := []string{fakeBuild.options.Dockerfile, ".dockerignore", "foo"} assert.DeepEqual(t, expected, fakeBuild.filenames(t)) @@ -75,7 +75,7 @@ func TestRunBuildResetsUidAndGidInContext(t *testing.T) { options := newBuildOptions() options.context = dir.Path() options.untrusted = true - assert.NilError(t, runBuild(cli, options)) + assert.NilError(t, runBuild(context.TODO(), cli, options)) headers := fakeBuild.headers(t) expected := []*tar.Header{ @@ -110,7 +110,7 @@ COPY data /data options.context = dir.Path() options.dockerfileName = df.Path() options.untrusted = true - assert.NilError(t, runBuild(cli, options)) + assert.NilError(t, runBuild(context.TODO(), cli, options)) expected := []string{fakeBuild.options.Dockerfile, ".dockerignore", "data"} assert.DeepEqual(t, expected, fakeBuild.filenames(t)) @@ -170,7 +170,7 @@ RUN echo hello world options := newBuildOptions() options.context = tmpDir.Join("context-link") options.untrusted = true - assert.NilError(t, runBuild(cli, options)) + assert.NilError(t, runBuild(context.TODO(), cli, options)) assert.DeepEqual(t, fakeBuild.filenames(t), []string{"Dockerfile"}) } diff --git a/cli/command/image/history.go b/cli/command/image/history.go index c302e1bd45..e36b9bc03c 100644 --- a/cli/command/image/history.go +++ b/cli/command/image/history.go @@ -29,7 +29,7 @@ func NewHistoryCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.image = args[0] - return runHistory(dockerCli, opts) + return runHistory(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{ "aliases": "docker image history, docker history", @@ -46,9 +46,7 @@ func NewHistoryCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runHistory(dockerCli command.Cli, opts historyOptions) error { - ctx := context.Background() - +func runHistory(ctx context.Context, dockerCli command.Cli, opts historyOptions) error { history, err := dockerCli.Client().ImageHistory(ctx, opts.image) if err != nil { return err diff --git a/cli/command/image/import.go b/cli/command/image/import.go index 1923eded7a..f7a0af8832 100644 --- a/cli/command/image/import.go +++ b/cli/command/image/import.go @@ -34,7 +34,7 @@ func NewImportCommand(dockerCli command.Cli) *cobra.Command { if len(args) > 1 { options.reference = args[1] } - return runImport(dockerCli, options) + return runImport(cmd.Context(), dockerCli, options) }, Annotations: map[string]string{ "aliases": "docker image import, docker import", @@ -51,7 +51,7 @@ func NewImportCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runImport(dockerCli command.Cli, options importOptions) error { +func runImport(ctx context.Context, dockerCli command.Cli, options importOptions) error { var source types.ImageImportSource switch { case options.source == "-": @@ -78,7 +78,7 @@ func runImport(dockerCli command.Cli, options importOptions) error { } } - responseBody, err := dockerCli.Client().ImageImport(context.Background(), source, options.reference, types.ImageImportOptions{ + responseBody, err := dockerCli.Client().ImageImport(ctx, source, options.reference, types.ImageImportOptions{ Message: options.message, Changes: options.changes.GetAll(), Platform: options.platform, diff --git a/cli/command/image/inspect.go b/cli/command/image/inspect.go index 0f9a918192..b3bd28dd13 100644 --- a/cli/command/image/inspect.go +++ b/cli/command/image/inspect.go @@ -25,7 +25,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.refs = args - return runInspect(dockerCli, opts) + return runInspect(cmd.Context(), dockerCli, opts) }, } @@ -34,10 +34,8 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runInspect(dockerCli command.Cli, opts inspectOptions) error { +func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error { client := dockerCli.Client() - ctx := context.Background() - getRefFunc := func(ref string) (any, []byte, error) { return client.ImageInspectWithRaw(ctx, ref) } diff --git a/cli/command/image/list.go b/cli/command/image/list.go index 2dd062da23..81ce4d914b 100644 --- a/cli/command/image/list.go +++ b/cli/command/image/list.go @@ -35,7 +35,7 @@ func NewImagesCommand(dockerCli command.Cli) *cobra.Command { if len(args) > 0 { options.matchName = args[0] } - return runImages(dockerCli, options) + return runImages(cmd.Context(), dockerCli, options) }, Annotations: map[string]string{ "category-top": "7", @@ -62,9 +62,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { return &cmd } -func runImages(dockerCli command.Cli, options imagesOptions) error { - ctx := context.Background() - +func runImages(ctx context.Context, dockerCli command.Cli, options imagesOptions) error { filters := options.filter.Value() if options.matchName != "" { filters.Add("reference", options.matchName) diff --git a/cli/command/image/load.go b/cli/command/image/load.go index 517610ec09..b11303d90c 100644 --- a/cli/command/image/load.go +++ b/cli/command/image/load.go @@ -27,7 +27,7 @@ func NewLoadCommand(dockerCli command.Cli) *cobra.Command { Short: "Load an image from a tar archive or STDIN", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runLoad(dockerCli, opts) + return runLoad(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{ "aliases": "docker image load, docker load", @@ -43,7 +43,7 @@ func NewLoadCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runLoad(dockerCli command.Cli, opts loadOptions) error { +func runLoad(ctx context.Context, dockerCli command.Cli, opts loadOptions) error { var input io.Reader = dockerCli.In() if opts.input != "" { // We use sequential.Open to use sequential file access on Windows, avoiding @@ -65,7 +65,7 @@ func runLoad(dockerCli command.Cli, opts loadOptions) error { if !dockerCli.Out().IsTerminal() { opts.quiet = true } - response, err := dockerCli.Client().ImageLoad(context.Background(), input, opts.quiet) + response, err := dockerCli.Client().ImageLoad(ctx, input, opts.quiet) if err != nil { return err } diff --git a/cli/command/image/prune.go b/cli/command/image/prune.go index e3bf349910..205a9dedb3 100644 --- a/cli/command/image/prune.go +++ b/cli/command/image/prune.go @@ -29,7 +29,7 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command { Short: "Remove unused images", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - spaceReclaimed, output, err := runPrune(dockerCli, options) + spaceReclaimed, output, err := runPrune(cmd.Context(), dockerCli, options) if err != nil { return err } @@ -58,7 +58,7 @@ Are you sure you want to continue?` Are you sure you want to continue?` ) -func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { +func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { pruneFilters := options.filter.Value().Clone() pruneFilters.Add("dangling", strconv.FormatBool(!options.all)) pruneFilters = command.PruneFilters(dockerCli, pruneFilters) @@ -71,7 +71,7 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint6 return 0, "", nil } - report, err := dockerCli.Client().ImagesPrune(context.Background(), pruneFilters) + report, err := dockerCli.Client().ImagesPrune(ctx, pruneFilters) if err != nil { return 0, "", err } @@ -99,6 +99,6 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint6 // RunPrune calls the Image Prune API // This returns the amount of space reclaimed and a detailed output string -func RunPrune(dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) { - return runPrune(dockerCli, pruneOptions{force: true, all: all, filter: filter}) +func RunPrune(ctx context.Context, dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) { + return runPrune(ctx, dockerCli, pruneOptions{force: true, all: all, filter: filter}) } diff --git a/cli/command/image/pull.go b/cli/command/image/pull.go index b602619d9a..9ec9771e28 100644 --- a/cli/command/image/pull.go +++ b/cli/command/image/pull.go @@ -33,7 +33,7 @@ func NewPullCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.remote = args[0] - return RunPull(dockerCli, opts) + return RunPull(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{ "category-top": "5", @@ -54,7 +54,7 @@ func NewPullCommand(dockerCli command.Cli) *cobra.Command { } // RunPull performs a pull against the engine based on the specified options -func RunPull(dockerCLI command.Cli, opts PullOptions) error { +func RunPull(ctx context.Context, dockerCLI command.Cli, opts PullOptions) error { distributionRef, err := reference.ParseNormalizedNamed(opts.remote) switch { case err != nil: @@ -68,7 +68,6 @@ func RunPull(dockerCLI command.Cli, opts PullOptions) error { } } - ctx := context.Background() imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, AuthResolver(dockerCLI), distributionRef.String()) if err != nil { return err diff --git a/cli/command/image/push.go b/cli/command/image/push.go index dc323b6718..98b9f24da7 100644 --- a/cli/command/image/push.go +++ b/cli/command/image/push.go @@ -35,7 +35,7 @@ func NewPushCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.remote = args[0] - return RunPush(dockerCli, opts) + return RunPush(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{ "category-top": "6", @@ -53,7 +53,7 @@ func NewPushCommand(dockerCli command.Cli) *cobra.Command { } // RunPush performs a push against the engine based on the specified options -func RunPush(dockerCli command.Cli, opts pushOptions) error { +func RunPush(ctx context.Context, dockerCli command.Cli, opts pushOptions) error { ref, err := reference.ParseNormalizedNamed(opts.remote) switch { case err != nil: @@ -73,8 +73,6 @@ func RunPush(dockerCli command.Cli, opts pushOptions) error { return err } - ctx := context.Background() - // Resolve the Auth config relevant for this server authConfig := command.ResolveAuthConfig(dockerCli.ConfigFile(), repoInfo.Index) encodedAuth, err := registrytypes.EncodeAuthConfig(authConfig) diff --git a/cli/command/image/remove.go b/cli/command/image/remove.go index 82eca7988b..4f18c41cb0 100644 --- a/cli/command/image/remove.go +++ b/cli/command/image/remove.go @@ -27,7 +27,7 @@ func NewRemoveCommand(dockerCli command.Cli) *cobra.Command { Short: "Remove one or more images", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runRemove(dockerCli, opts, args) + return runRemove(cmd.Context(), dockerCli, opts, args) }, Annotations: map[string]string{ "aliases": "docker image rm, docker image remove, docker rmi", @@ -49,9 +49,8 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { return &cmd } -func runRemove(dockerCli command.Cli, opts removeOptions, images []string) error { +func runRemove(ctx context.Context, dockerCli command.Cli, opts removeOptions, images []string) error { client := dockerCli.Client() - ctx := context.Background() options := types.ImageRemoveOptions{ Force: opts.force, diff --git a/cli/command/image/save.go b/cli/command/image/save.go index 8063c0e785..40cdf68ee1 100644 --- a/cli/command/image/save.go +++ b/cli/command/image/save.go @@ -26,7 +26,7 @@ func NewSaveCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.images = args - return RunSave(dockerCli, opts) + return RunSave(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{ "aliases": "docker image save, docker save", @@ -42,7 +42,7 @@ func NewSaveCommand(dockerCli command.Cli) *cobra.Command { } // RunSave performs a save against the engine based on the specified options -func RunSave(dockerCli command.Cli, opts saveOptions) error { +func RunSave(ctx context.Context, dockerCli command.Cli, opts saveOptions) error { if opts.output == "" && dockerCli.Out().IsTerminal() { return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect") } @@ -51,7 +51,7 @@ func RunSave(dockerCli command.Cli, opts saveOptions) error { return errors.Wrap(err, "failed to save image") } - responseBody, err := dockerCli.Client().ImageSave(context.Background(), opts.images) + responseBody, err := dockerCli.Client().ImageSave(ctx, opts.images) if err != nil { return err } diff --git a/cli/command/image/tag.go b/cli/command/image/tag.go index f63b328b5b..29da7f3753 100644 --- a/cli/command/image/tag.go +++ b/cli/command/image/tag.go @@ -25,7 +25,7 @@ func NewTagCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { opts.image = args[0] opts.name = args[1] - return runTag(dockerCli, opts) + return runTag(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{ "aliases": "docker image tag, docker tag", @@ -39,8 +39,6 @@ func NewTagCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runTag(dockerCli command.Cli, opts tagOptions) error { - ctx := context.Background() - +func runTag(ctx context.Context, dockerCli command.Cli, opts tagOptions) error { return dockerCli.Client().ImageTag(ctx, opts.image, opts.name) } diff --git a/cli/command/manifest/create_list.go b/cli/command/manifest/create_list.go index f2e54dcff6..ac78b14f62 100644 --- a/cli/command/manifest/create_list.go +++ b/cli/command/manifest/create_list.go @@ -25,7 +25,7 @@ func newCreateListCommand(dockerCli command.Cli) *cobra.Command { Short: "Create a local manifest list for annotating and pushing to a registry", Args: cli.RequiresMinArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - return createManifestList(dockerCli, args, opts) + return createManifestList(cmd.Context(), dockerCli, args, opts) }, } @@ -35,7 +35,7 @@ func newCreateListCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func createManifestList(dockerCli command.Cli, args []string, opts createOpts) error { +func createManifestList(ctx context.Context, dockerCli command.Cli, args []string, opts createOpts) error { newRef := args[0] targetRef, err := normalizeReference(newRef) if err != nil { @@ -58,7 +58,6 @@ func createManifestList(dockerCli command.Cli, args []string, opts createOpts) e return errors.Errorf("refusing to amend an existing manifest list with no --amend flag") } - ctx := context.Background() // Now create the local manifest list transaction by looking up the manifest schemas // for the constituent images: manifests := args[1:] diff --git a/cli/command/manifest/inspect.go b/cli/command/manifest/inspect.go index 565dbda49f..75acb8b604 100644 --- a/cli/command/manifest/inspect.go +++ b/cli/command/manifest/inspect.go @@ -39,7 +39,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { opts.list = args[0] opts.ref = args[1] } - return runInspect(dockerCli, opts) + return runInspect(cmd.Context(), dockerCli, opts) }, } @@ -49,7 +49,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runInspect(dockerCli command.Cli, opts inspectOptions) error { +func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error { namedRef, err := normalizeReference(opts.ref) if err != nil { return err @@ -76,7 +76,6 @@ func runInspect(dockerCli command.Cli, opts inspectOptions) error { } // Next try a remote manifest - ctx := context.Background() registryClient := dockerCli.RegistryClient(opts.insecure) imageManifest, err := registryClient.GetManifest(ctx, namedRef) if err == nil { diff --git a/cli/command/manifest/push.go b/cli/command/manifest/push.go index 303f124b4e..29fcffe30f 100644 --- a/cli/command/manifest/push.go +++ b/cli/command/manifest/push.go @@ -53,7 +53,7 @@ func newPushListCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.target = args[0] - return runPush(dockerCli, opts) + return runPush(cmd.Context(), dockerCli, opts) }, } @@ -63,7 +63,7 @@ func newPushListCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runPush(dockerCli command.Cli, opts pushOpts) error { +func runPush(ctx context.Context, dockerCli command.Cli, opts pushOpts) error { targetRef, err := normalizeReference(opts.target) if err != nil { return err @@ -82,7 +82,6 @@ func runPush(dockerCli command.Cli, opts pushOpts) error { return err } - ctx := context.Background() if err := pushList(ctx, dockerCli, req); err != nil { return err } diff --git a/cli/command/manifest/rm.go b/cli/command/manifest/rm.go index 380dc59c20..2e2dc04624 100644 --- a/cli/command/manifest/rm.go +++ b/cli/command/manifest/rm.go @@ -1,6 +1,7 @@ package manifest import ( + "context" "strings" "github.com/docker/cli/cli" @@ -15,14 +16,14 @@ func newRmManifestListCommand(dockerCli command.Cli) *cobra.Command { Short: "Delete one or more manifest lists from local storage", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runRm(dockerCli, args) + return runRm(cmd.Context(), dockerCli, args) }, } return cmd } -func runRm(dockerCli command.Cli, targets []string) error { +func runRm(_ context.Context, dockerCli command.Cli, targets []string) error { var errs []string for _, target := range targets { targetRef, refErr := normalizeReference(target) diff --git a/cli/command/network/connect.go b/cli/command/network/connect.go index 872608c1b1..6ffb9b8dcf 100644 --- a/cli/command/network/connect.go +++ b/cli/command/network/connect.go @@ -36,7 +36,7 @@ func newConnectCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { options.network = args[0] options.container = args[1] - return runConnect(dockerCli, options) + return runConnect(cmd.Context(), dockerCli, options) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) == 0 { @@ -57,7 +57,7 @@ func newConnectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runConnect(dockerCli command.Cli, options connectOptions) error { +func runConnect(ctx context.Context, dockerCli command.Cli, options connectOptions) error { client := dockerCli.Client() driverOpts, err := convertDriverOpt(options.driverOpts) @@ -75,7 +75,7 @@ func runConnect(dockerCli command.Cli, options connectOptions) error { DriverOpts: driverOpts, } - return client.NetworkConnect(context.Background(), options.network, options.container, epConfig) + return client.NetworkConnect(ctx, options.network, options.container, epConfig) } func convertDriverOpt(options []string) (map[string]string, error) { diff --git a/cli/command/network/create.go b/cli/command/network/create.go index 7b71b6181f..b2a841835a 100644 --- a/cli/command/network/create.go +++ b/cli/command/network/create.go @@ -51,7 +51,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { options.name = args[0] - return runCreate(dockerCli, options) + return runCreate(cmd.Context(), dockerCli, options) }, ValidArgsFunction: completion.NoComplete, } @@ -84,7 +84,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runCreate(dockerCli command.Cli, options createOptions) error { +func runCreate(ctx context.Context, dockerCli command.Cli, options createOptions) error { client := dockerCli.Client() ipamCfg, err := consolidateIpam(options.ipamSubnet, options.ipamIPRange, options.ipamGateway, options.ipamAux.GetAll()) @@ -98,7 +98,7 @@ func runCreate(dockerCli command.Cli, options createOptions) error { Network: options.configFrom, } } - resp, err := client.NetworkCreate(context.Background(), options.name, types.NetworkCreate{ + resp, err := client.NetworkCreate(ctx, options.name, types.NetworkCreate{ Driver: options.driver, Options: options.driverOpts.GetAll(), IPAM: &network.IPAM{ diff --git a/cli/command/network/disconnect.go b/cli/command/network/disconnect.go index 11f03b9254..abed538f66 100644 --- a/cli/command/network/disconnect.go +++ b/cli/command/network/disconnect.go @@ -26,7 +26,7 @@ func newDisconnectCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { opts.network = args[0] opts.container = args[1] - return runDisconnect(dockerCli, opts) + return runDisconnect(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if len(args) == 0 { @@ -43,10 +43,10 @@ func newDisconnectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runDisconnect(dockerCli command.Cli, opts disconnectOptions) error { +func runDisconnect(ctx context.Context, dockerCli command.Cli, opts disconnectOptions) error { client := dockerCli.Client() - return client.NetworkDisconnect(context.Background(), opts.network, opts.container, opts.force) + return client.NetworkDisconnect(ctx, opts.network, opts.container, opts.force) } func isConnected(network string) func(types.Container) bool { diff --git a/cli/command/network/inspect.go b/cli/command/network/inspect.go index 621b14a41d..c4d87bb58e 100644 --- a/cli/command/network/inspect.go +++ b/cli/command/network/inspect.go @@ -27,7 +27,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.names = args - return runInspect(dockerCli, opts) + return runInspect(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: completion.NetworkNames(dockerCli), } @@ -38,11 +38,9 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runInspect(dockerCli command.Cli, opts inspectOptions) error { +func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error { client := dockerCli.Client() - ctx := context.Background() - getNetFunc := func(name string) (any, []byte, error) { return client.NetworkInspectWithRaw(ctx, name, types.NetworkInspectOptions{Verbose: opts.verbose}) } diff --git a/cli/command/network/list.go b/cli/command/network/list.go index 903b561ac9..8bbc0a1002 100644 --- a/cli/command/network/list.go +++ b/cli/command/network/list.go @@ -31,7 +31,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { Short: "List networks", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runList(dockerCli, options) + return runList(cmd.Context(), dockerCli, options) }, ValidArgsFunction: completion.NoComplete, } @@ -45,10 +45,10 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runList(dockerCli command.Cli, options listOptions) error { +func runList(ctx context.Context, dockerCli command.Cli, options listOptions) error { client := dockerCli.Client() listOptions := types.NetworkListOptions{Filters: options.filter.Value()} - networkResources, err := client.NetworkList(context.Background(), listOptions) + networkResources, err := client.NetworkList(ctx, listOptions) if err != nil { return err } diff --git a/cli/command/network/prune.go b/cli/command/network/prune.go index 460a5b5646..f097878ac8 100644 --- a/cli/command/network/prune.go +++ b/cli/command/network/prune.go @@ -24,7 +24,7 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command { Short: "Remove all unused networks", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - output, err := runPrune(dockerCli, options) + output, err := runPrune(cmd.Context(), dockerCli, options) if err != nil { return err } @@ -46,14 +46,14 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command { const warning = `WARNING! This will remove all custom networks not used by at least one container. Are you sure you want to continue?` -func runPrune(dockerCli command.Cli, options pruneOptions) (output string, err error) { +func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) (output string, err error) { pruneFilters := command.PruneFilters(dockerCli, options.filter.Value()) if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) { return "", nil } - report, err := dockerCli.Client().NetworksPrune(context.Background(), pruneFilters) + report, err := dockerCli.Client().NetworksPrune(ctx, pruneFilters) if err != nil { return "", err } @@ -70,7 +70,7 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (output string, err e // RunPrune calls the Network Prune API // This returns the amount of space reclaimed and a detailed output string -func RunPrune(dockerCli command.Cli, _ bool, filter opts.FilterOpt) (uint64, string, error) { - output, err := runPrune(dockerCli, pruneOptions{force: true, filter: filter}) +func RunPrune(ctx context.Context, dockerCli command.Cli, _ bool, filter opts.FilterOpt) (uint64, string, error) { + output, err := runPrune(ctx, dockerCli, pruneOptions{force: true, filter: filter}) return 0, output, err } diff --git a/cli/command/network/remove.go b/cli/command/network/remove.go index ee96fd614c..cefd06c065 100644 --- a/cli/command/network/remove.go +++ b/cli/command/network/remove.go @@ -25,7 +25,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { Short: "Remove one or more networks", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runRemove(dockerCli, args, &opts) + return runRemove(cmd.Context(), dockerCli, args, &opts) }, ValidArgsFunction: completion.NetworkNames(dockerCli), } @@ -40,9 +40,9 @@ const ingressWarning = "WARNING! Before removing the routing-mesh network, " + "Otherwise, removal may not be effective and functionality of newly create " + "ingress networks will be impaired.\nAre you sure you want to continue?" -func runRemove(dockerCli command.Cli, networks []string, opts *removeOptions) error { +func runRemove(ctx context.Context, dockerCli command.Cli, networks []string, opts *removeOptions) error { client := dockerCli.Client() - ctx := context.Background() + status := 0 for _, name := range networks { diff --git a/cli/command/node/demote.go b/cli/command/node/demote.go index 5250dfc0be..ea914bb094 100644 --- a/cli/command/node/demote.go +++ b/cli/command/node/demote.go @@ -1,6 +1,7 @@ package node import ( + "context" "fmt" "github.com/docker/cli/cli" @@ -15,12 +16,12 @@ func newDemoteCommand(dockerCli command.Cli) *cobra.Command { Short: "Demote one or more nodes from manager in the swarm", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runDemote(dockerCli, args) + return runDemote(cmd.Context(), dockerCli, args) }, } } -func runDemote(dockerCli command.Cli, nodes []string) error { +func runDemote(ctx context.Context, dockerCli command.Cli, nodes []string) error { demote := func(node *swarm.Node) error { if node.Spec.Role == swarm.NodeRoleWorker { fmt.Fprintf(dockerCli.Out(), "Node %s is already a worker.\n", node.ID) @@ -32,5 +33,5 @@ func runDemote(dockerCli command.Cli, nodes []string) error { success := func(nodeID string) { fmt.Fprintf(dockerCli.Out(), "Manager %s demoted in the swarm.\n", nodeID) } - return updateNodes(dockerCli, nodes, demote, success) + return updateNodes(ctx, dockerCli, nodes, demote, success) } diff --git a/cli/command/node/inspect.go b/cli/command/node/inspect.go index 4073bc995e..acb3da97b9 100644 --- a/cli/command/node/inspect.go +++ b/cli/command/node/inspect.go @@ -27,7 +27,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.nodeIds = args - return runInspect(dockerCli, opts) + return runInspect(cmd.Context(), dockerCli, opts) }, } @@ -37,9 +37,8 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runInspect(dockerCli command.Cli, opts inspectOptions) error { +func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error { client := dockerCli.Client() - ctx := context.Background() if opts.pretty { opts.format = "pretty" diff --git a/cli/command/node/list.go b/cli/command/node/list.go index e942789a1b..f64b8174ff 100644 --- a/cli/command/node/list.go +++ b/cli/command/node/list.go @@ -31,7 +31,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { Short: "List nodes in the swarm", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runList(dockerCli, options) + return runList(cmd.Context(), dockerCli, options) }, ValidArgsFunction: completion.NoComplete, } @@ -43,9 +43,8 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runList(dockerCli command.Cli, options listOptions) error { +func runList(ctx context.Context, dockerCli command.Cli, options listOptions) error { client := dockerCli.Client() - ctx := context.Background() nodes, err := client.NodeList( ctx, diff --git a/cli/command/node/promote.go b/cli/command/node/promote.go index 4612cc13ff..c9d45e9cda 100644 --- a/cli/command/node/promote.go +++ b/cli/command/node/promote.go @@ -1,6 +1,7 @@ package node import ( + "context" "fmt" "github.com/docker/cli/cli" @@ -15,12 +16,12 @@ func newPromoteCommand(dockerCli command.Cli) *cobra.Command { Short: "Promote one or more nodes to manager in the swarm", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runPromote(dockerCli, args) + return runPromote(cmd.Context(), dockerCli, args) }, } } -func runPromote(dockerCli command.Cli, nodes []string) error { +func runPromote(ctx context.Context, dockerCli command.Cli, nodes []string) error { promote := func(node *swarm.Node) error { if node.Spec.Role == swarm.NodeRoleManager { fmt.Fprintf(dockerCli.Out(), "Node %s is already a manager.\n", node.ID) @@ -32,5 +33,5 @@ func runPromote(dockerCli command.Cli, nodes []string) error { success := func(nodeID string) { fmt.Fprintf(dockerCli.Out(), "Node %s promoted to a manager in the swarm.\n", nodeID) } - return updateNodes(dockerCli, nodes, promote, success) + return updateNodes(ctx, dockerCli, nodes, promote, success) } diff --git a/cli/command/node/ps.go b/cli/command/node/ps.go index 28f90a387d..207ecff575 100644 --- a/cli/command/node/ps.go +++ b/cli/command/node/ps.go @@ -39,7 +39,7 @@ func newPsCommand(dockerCli command.Cli) *cobra.Command { options.nodeIDs = args } - return runPs(dockerCli, options) + return runPs(cmd.Context(), dockerCli, options) }, ValidArgsFunction: completion.NoComplete, } @@ -53,9 +53,8 @@ func newPsCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runPs(dockerCli command.Cli, options psOptions) error { +func runPs(ctx context.Context, dockerCli command.Cli, options psOptions) error { client := dockerCli.Client() - ctx := context.Background() var ( errs []string diff --git a/cli/command/node/remove.go b/cli/command/node/remove.go index 65e3cdc30a..fedf34dec4 100644 --- a/cli/command/node/remove.go +++ b/cli/command/node/remove.go @@ -25,7 +25,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { Short: "Remove one or more nodes from the swarm", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runRemove(dockerCli, args, opts) + return runRemove(cmd.Context(), dockerCli, args, opts) }, } flags := cmd.Flags() @@ -33,9 +33,8 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runRemove(dockerCli command.Cli, args []string, opts removeOptions) error { +func runRemove(ctx context.Context, dockerCli command.Cli, args []string, opts removeOptions) error { client := dockerCli.Client() - ctx := context.Background() var errs []string diff --git a/cli/command/node/update.go b/cli/command/node/update.go index 2353172080..2083aeaf5d 100644 --- a/cli/command/node/update.go +++ b/cli/command/node/update.go @@ -23,7 +23,7 @@ func newUpdateCommand(dockerCli command.Cli) *cobra.Command { Short: "Update a node", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runUpdate(dockerCli, cmd.Flags(), args[0]) + return runUpdate(cmd.Context(), dockerCli, cmd.Flags(), args[0]) }, } @@ -36,16 +36,15 @@ func newUpdateCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runUpdate(dockerCli command.Cli, flags *pflag.FlagSet, nodeID string) error { +func runUpdate(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, nodeID string) error { success := func(_ string) { fmt.Fprintln(dockerCli.Out(), nodeID) } - return updateNodes(dockerCli, []string{nodeID}, mergeNodeUpdate(flags), success) + return updateNodes(ctx, dockerCli, []string{nodeID}, mergeNodeUpdate(flags), success) } -func updateNodes(dockerCli command.Cli, nodes []string, mergeNode func(node *swarm.Node) error, success func(nodeID string)) error { +func updateNodes(ctx context.Context, dockerCli command.Cli, nodes []string, mergeNode func(node *swarm.Node) error, success func(nodeID string)) error { client := dockerCli.Client() - ctx := context.Background() for _, nodeID := range nodes { node, _, err := client.NodeInspectWithRaw(ctx, nodeID) diff --git a/cli/command/plugin/create.go b/cli/command/plugin/create.go index 937b1000e3..3b23734ae5 100644 --- a/cli/command/plugin/create.go +++ b/cli/command/plugin/create.go @@ -74,7 +74,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { options.repoName = args[0] options.context = args[1] - return runCreate(dockerCli, options) + return runCreate(cmd.Context(), dockerCli, options) }, ValidArgsFunction: completion.NoComplete, } @@ -86,7 +86,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runCreate(dockerCli command.Cli, options pluginCreateOptions) error { +func runCreate(ctx context.Context, dockerCli command.Cli, options pluginCreateOptions) error { var ( createCtx io.ReadCloser err error @@ -119,8 +119,6 @@ func runCreate(dockerCli command.Cli, options pluginCreateOptions) error { return err } - ctx := context.Background() - createOptions := types.PluginCreateOptions{RepoName: options.repoName} if err = dockerCli.Client().PluginCreate(ctx, createCtx, createOptions); err != nil { return err diff --git a/cli/command/plugin/disable.go b/cli/command/plugin/disable.go index 014d86b2b8..084b50365d 100644 --- a/cli/command/plugin/disable.go +++ b/cli/command/plugin/disable.go @@ -18,7 +18,7 @@ func newDisableCommand(dockerCli command.Cli) *cobra.Command { Short: "Disable a plugin", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runDisable(dockerCli, args[0], force) + return runDisable(cmd.Context(), dockerCli, args[0], force) }, } @@ -27,8 +27,8 @@ func newDisableCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runDisable(dockerCli command.Cli, name string, force bool) error { - if err := dockerCli.Client().PluginDisable(context.Background(), name, types.PluginDisableOptions{Force: force}); err != nil { +func runDisable(ctx context.Context, dockerCli command.Cli, name string, force bool) error { + if err := dockerCli.Client().PluginDisable(ctx, name, types.PluginDisableOptions{Force: force}); err != nil { return err } fmt.Fprintln(dockerCli.Out(), name) diff --git a/cli/command/plugin/enable.go b/cli/command/plugin/enable.go index 19df1e7bd2..e1724fd50c 100644 --- a/cli/command/plugin/enable.go +++ b/cli/command/plugin/enable.go @@ -25,7 +25,7 @@ func newEnableCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.name = args[0] - return runEnable(dockerCli, &opts) + return runEnable(cmd.Context(), dockerCli, &opts) }, } @@ -34,13 +34,13 @@ func newEnableCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runEnable(dockerCli command.Cli, opts *enableOpts) error { +func runEnable(ctx context.Context, dockerCli command.Cli, opts *enableOpts) error { name := opts.name if opts.timeout < 0 { return errors.Errorf("negative timeout %d is invalid", opts.timeout) } - if err := dockerCli.Client().PluginEnable(context.Background(), name, types.PluginEnableOptions{Timeout: opts.timeout}); err != nil { + if err := dockerCli.Client().PluginEnable(ctx, name, types.PluginEnableOptions{Timeout: opts.timeout}); err != nil { return err } fmt.Fprintln(dockerCli.Out(), name) diff --git a/cli/command/plugin/inspect.go b/cli/command/plugin/inspect.go index 08085792a5..5ef03fa8c8 100644 --- a/cli/command/plugin/inspect.go +++ b/cli/command/plugin/inspect.go @@ -24,7 +24,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.pluginNames = args - return runInspect(dockerCli, opts) + return runInspect(cmd.Context(), dockerCli, opts) }, } @@ -33,9 +33,8 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runInspect(dockerCli command.Cli, opts inspectOptions) error { +func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error { client := dockerCli.Client() - ctx := context.Background() getRef := func(ref string) (any, []byte, error) { return client.PluginInspectWithRaw(ctx, ref) } diff --git a/cli/command/plugin/install.go b/cli/command/plugin/install.go index c4f689ec3f..beea9af86d 100644 --- a/cli/command/plugin/install.go +++ b/cli/command/plugin/install.go @@ -44,7 +44,7 @@ func newInstallCommand(dockerCli command.Cli) *cobra.Command { if len(args) > 1 { options.args = args[1:] } - return runInstall(dockerCli, options) + return runInstall(cmd.Context(), dockerCli, options) }, } @@ -104,7 +104,7 @@ func buildPullConfig(ctx context.Context, dockerCli command.Cli, opts pluginOpti return options, nil } -func runInstall(dockerCli command.Cli, opts pluginOptions) error { +func runInstall(ctx context.Context, dockerCli command.Cli, opts pluginOptions) error { var localName string if opts.localName != "" { aref, err := reference.ParseNormalizedNamed(opts.localName) @@ -117,7 +117,6 @@ func runInstall(dockerCli command.Cli, opts pluginOptions) error { localName = reference.FamiliarString(reference.TagNameOnly(aref)) } - ctx := context.Background() options, err := buildPullConfig(ctx, dockerCli, opts, "plugin install") if err != nil { return err diff --git a/cli/command/plugin/list.go b/cli/command/plugin/list.go index 5f4344f9f6..0c7234a2c3 100644 --- a/cli/command/plugin/list.go +++ b/cli/command/plugin/list.go @@ -30,7 +30,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { Aliases: []string{"list"}, Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runList(dockerCli, options) + return runList(cmd.Context(), dockerCli, options) }, ValidArgsFunction: completion.NoComplete, } @@ -45,8 +45,8 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runList(dockerCli command.Cli, options listOptions) error { - plugins, err := dockerCli.Client().PluginList(context.Background(), options.filter.Value()) +func runList(ctx context.Context, dockerCli command.Cli, options listOptions) error { + plugins, err := dockerCli.Client().PluginList(ctx, options.filter.Value()) if err != nil { return err } diff --git a/cli/command/plugin/push.go b/cli/command/plugin/push.go index 80b05c500b..7f8b5dcca4 100644 --- a/cli/command/plugin/push.go +++ b/cli/command/plugin/push.go @@ -27,7 +27,7 @@ func newPushCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.name = args[0] - return runPush(dockerCli, opts) + return runPush(cmd.Context(), dockerCli, opts) }, } @@ -38,7 +38,7 @@ func newPushCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runPush(dockerCli command.Cli, opts pushOptions) error { +func runPush(ctx context.Context, dockerCli command.Cli, opts pushOptions) error { named, err := reference.ParseNormalizedNamed(opts.name) if err != nil { return err @@ -49,8 +49,6 @@ func runPush(dockerCli command.Cli, opts pushOptions) error { named = reference.TagNameOnly(named) - ctx := context.Background() - repoInfo, err := registry.ParseRepositoryInfo(named) if err != nil { return err diff --git a/cli/command/plugin/remove.go b/cli/command/plugin/remove.go index a2092bd76b..2614cab3ac 100644 --- a/cli/command/plugin/remove.go +++ b/cli/command/plugin/remove.go @@ -26,7 +26,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.plugins = args - return runRemove(dockerCli, &opts) + return runRemove(cmd.Context(), dockerCli, &opts) }, } @@ -35,9 +35,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runRemove(dockerCli command.Cli, opts *rmOptions) error { - ctx := context.Background() - +func runRemove(ctx context.Context, dockerCli command.Cli, opts *rmOptions) error { var errs cli.Errors for _, name := range opts.plugins { if err := dockerCli.Client().PluginRemove(ctx, name, types.PluginRemoveOptions{Force: opts.force}); err != nil { diff --git a/cli/command/plugin/set.go b/cli/command/plugin/set.go index 724fdebfd5..64442097b3 100644 --- a/cli/command/plugin/set.go +++ b/cli/command/plugin/set.go @@ -1,8 +1,6 @@ package plugin import ( - "context" - "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" @@ -14,7 +12,7 @@ func newSetCommand(dockerCli command.Cli) *cobra.Command { Short: "Change settings for a plugin", Args: cli.RequiresMinArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - return dockerCli.Client().PluginSet(context.Background(), args[0], args[1:]) + return dockerCli.Client().PluginSet(cmd.Context(), args[0], args[1:]) }, } diff --git a/cli/command/plugin/upgrade.go b/cli/command/plugin/upgrade.go index 32859e9f4d..5134f3642d 100644 --- a/cli/command/plugin/upgrade.go +++ b/cli/command/plugin/upgrade.go @@ -24,7 +24,7 @@ func newUpgradeCommand(dockerCli command.Cli) *cobra.Command { if len(args) == 2 { options.remote = args[1] } - return runUpgrade(dockerCli, options) + return runUpgrade(cmd.Context(), dockerCli, options) }, Annotations: map[string]string{"version": "1.26"}, } @@ -35,8 +35,7 @@ func newUpgradeCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runUpgrade(dockerCli command.Cli, opts pluginOptions) error { - ctx := context.Background() +func runUpgrade(ctx context.Context, dockerCli command.Cli, opts pluginOptions) error { p, _, err := dockerCli.Client().PluginInspectWithRaw(ctx, opts.localName) if err != nil { return errors.Errorf("error reading plugin data: %v", err) diff --git a/cli/command/registry/login.go b/cli/command/registry/login.go index 6098c1863e..3a52203e1f 100644 --- a/cli/command/registry/login.go +++ b/cli/command/registry/login.go @@ -43,7 +43,7 @@ func NewLoginCommand(dockerCli command.Cli) *cobra.Command { if len(args) > 0 { opts.serverAddress = args[0] } - return runLogin(dockerCli, opts) + return runLogin(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{ "category-top": "8", @@ -100,8 +100,7 @@ func verifyloginOptions(dockerCli command.Cli, opts *loginOptions) error { return nil } -func runLogin(dockerCli command.Cli, opts loginOptions) error { //nolint:gocyclo - ctx := context.Background() +func runLogin(ctx context.Context, dockerCli command.Cli, opts loginOptions) error { //nolint:gocyclo clnt := dockerCli.Client() if err := verifyloginOptions(dockerCli, &opts); err != nil { return err diff --git a/cli/command/registry/login_test.go b/cli/command/registry/login_test.go index ddbba746d2..acdb7a93f6 100644 --- a/cli/command/registry/login_test.go +++ b/cli/command/registry/login_test.go @@ -171,7 +171,7 @@ func TestRunLogin(t *testing.T) { cred := *tc.inputStoredCred assert.NilError(t, configfile.GetCredentialsStore(cred.ServerAddress).Store(cred)) } - loginErr := runLogin(cli, tc.inputLoginOption) + loginErr := runLogin(context.Background(), cli, tc.inputLoginOption) if tc.expectedErr != "" { assert.Error(t, loginErr, tc.expectedErr) return diff --git a/cli/command/registry/logout.go b/cli/command/registry/logout.go index 1799e5410a..6f47327cdf 100644 --- a/cli/command/registry/logout.go +++ b/cli/command/registry/logout.go @@ -1,6 +1,7 @@ package registry import ( + "context" "fmt" "github.com/docker/cli/cli" @@ -21,7 +22,7 @@ func NewLogoutCommand(dockerCli command.Cli) *cobra.Command { if len(args) > 0 { serverAddress = args[0] } - return runLogout(dockerCli, serverAddress) + return runLogout(cmd.Context(), dockerCli, serverAddress) }, Annotations: map[string]string{ "category-top": "9", @@ -32,7 +33,7 @@ func NewLogoutCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runLogout(dockerCli command.Cli, serverAddress string) error { +func runLogout(_ context.Context, dockerCli command.Cli, serverAddress string) error { var isDefaultRegistry bool if serverAddress == "" { diff --git a/cli/command/registry/search.go b/cli/command/registry/search.go index c2f78dfce1..0f22c79ee0 100644 --- a/cli/command/registry/search.go +++ b/cli/command/registry/search.go @@ -32,7 +32,7 @@ func NewSearchCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { options.term = args[0] - return runSearch(dockerCli, options) + return runSearch(cmd.Context(), dockerCli, options) }, Annotations: map[string]string{ "category-top": "10", @@ -49,7 +49,7 @@ func NewSearchCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runSearch(dockerCli command.Cli, options searchOptions) error { +func runSearch(ctx context.Context, dockerCli command.Cli, options searchOptions) error { if options.filter.Value().Contains("is-automated") { _, _ = fmt.Fprintln(dockerCli.Err(), `WARNING: the "is-automated" filter is deprecated, and searching for "is-automated=true" will not yield any results in future.`) } @@ -64,7 +64,6 @@ func runSearch(dockerCli command.Cli, options searchOptions) error { return err } - ctx := context.Background() requestPrivilege := command.RegistryAuthenticationPrivilegedFunc(dockerCli, indexInfo, "search") results, err := dockerCli.Client().ImageSearch(ctx, options.term, types.ImageSearchOptions{ RegistryAuth: encodedAuth, diff --git a/cli/command/secret/create.go b/cli/command/secret/create.go index 3f656ec3ee..706e92c3d1 100644 --- a/cli/command/secret/create.go +++ b/cli/command/secret/create.go @@ -36,7 +36,7 @@ func newSecretCreateCommand(dockerCli command.Cli) *cobra.Command { if len(args) == 2 { options.file = args[1] } - return runSecretCreate(dockerCli, options) + return runSecretCreate(cmd.Context(), dockerCli, options) }, } flags := cmd.Flags() @@ -49,9 +49,8 @@ func newSecretCreateCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runSecretCreate(dockerCli command.Cli, options createOptions) error { +func runSecretCreate(ctx context.Context, dockerCli command.Cli, options createOptions) error { client := dockerCli.Client() - ctx := context.Background() if options.driver != "" && options.file != "" { return errors.Errorf("When using secret driver secret data must be empty") diff --git a/cli/command/secret/inspect.go b/cli/command/secret/inspect.go index a3e6e10724..1210567f15 100644 --- a/cli/command/secret/inspect.go +++ b/cli/command/secret/inspect.go @@ -26,7 +26,7 @@ func newSecretInspectCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.names = args - return runSecretInspect(dockerCli, opts) + return runSecretInspect(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return completeNames(dockerCli)(cmd, args, toComplete) @@ -38,9 +38,8 @@ func newSecretInspectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runSecretInspect(dockerCli command.Cli, opts inspectOptions) error { +func runSecretInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error { client := dockerCli.Client() - ctx := context.Background() if opts.pretty { opts.format = "pretty" diff --git a/cli/command/secret/ls.go b/cli/command/secret/ls.go index 6d8693875c..11a5620518 100644 --- a/cli/command/secret/ls.go +++ b/cli/command/secret/ls.go @@ -29,7 +29,7 @@ func newSecretListCommand(dockerCli command.Cli) *cobra.Command { Short: "List secrets", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runSecretList(dockerCli, options) + return runSecretList(cmd.Context(), dockerCli, options) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return completeNames(dockerCli)(cmd, args, toComplete) @@ -44,9 +44,8 @@ func newSecretListCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runSecretList(dockerCli command.Cli, options listOptions) error { +func runSecretList(ctx context.Context, dockerCli command.Cli, options listOptions) error { client := dockerCli.Client() - ctx := context.Background() secrets, err := client.SecretList(ctx, types.SecretListOptions{Filters: options.filter.Value()}) if err != nil { diff --git a/cli/command/secret/remove.go b/cli/command/secret/remove.go index b22dd76d78..e51d03d345 100644 --- a/cli/command/secret/remove.go +++ b/cli/command/secret/remove.go @@ -25,7 +25,7 @@ func newSecretRemoveCommand(dockerCli command.Cli) *cobra.Command { opts := removeOptions{ names: args, } - return runSecretRemove(dockerCli, opts) + return runSecretRemove(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return completeNames(dockerCli)(cmd, args, toComplete) @@ -33,9 +33,8 @@ func newSecretRemoveCommand(dockerCli command.Cli) *cobra.Command { } } -func runSecretRemove(dockerCli command.Cli, opts removeOptions) error { +func runSecretRemove(ctx context.Context, dockerCli command.Cli, opts removeOptions) error { client := dockerCli.Client() - ctx := context.Background() var errs []string diff --git a/cli/command/service/create.go b/cli/command/service/create.go index d5b8fec087..31dc3a565a 100644 --- a/cli/command/service/create.go +++ b/cli/command/service/create.go @@ -28,7 +28,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command { if len(args) > 1 { opts.args = args[1:] } - return runCreate(dockerCli, cmd.Flags(), opts) + return runCreate(cmd.Context(), dockerCli, cmd.Flags(), opts) }, ValidArgsFunction: completion.NoComplete, } @@ -76,12 +76,10 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runCreate(dockerCli command.Cli, flags *pflag.FlagSet, opts *serviceOptions) error { +func runCreate(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, opts *serviceOptions) error { apiClient := dockerCli.Client() createOpts := types.ServiceCreateOptions{} - ctx := context.Background() - service, err := opts.ToService(ctx, apiClient, flags) if err != nil { return err @@ -94,14 +92,14 @@ func runCreate(dockerCli command.Cli, flags *pflag.FlagSet, opts *serviceOptions specifiedSecrets := opts.secrets.Value() if len(specifiedSecrets) > 0 { // parse and validate secrets - secrets, err := ParseSecrets(apiClient, specifiedSecrets) + secrets, err := ParseSecrets(ctx, apiClient, specifiedSecrets) if err != nil { return err } service.TaskTemplate.ContainerSpec.Secrets = secrets } - if err := setConfigs(apiClient, &service, opts); err != nil { + if err := setConfigs(ctx, apiClient, &service, opts); err != nil { return err } @@ -145,7 +143,7 @@ func runCreate(dockerCli command.Cli, flags *pflag.FlagSet, opts *serviceOptions // setConfigs does double duty: it both sets the ConfigReferences of the // service, and it sets the service CredentialSpec. This is because there is an // interplay between the CredentialSpec and the Config it depends on. -func setConfigs(apiClient client.ConfigAPIClient, service *swarm.ServiceSpec, opts *serviceOptions) error { +func setConfigs(ctx context.Context, apiClient client.ConfigAPIClient, service *swarm.ServiceSpec, opts *serviceOptions) error { specifiedConfigs := opts.configs.Value() // if the user has requested to use a Config, for the CredentialSpec add it // to the specifiedConfigs as a RuntimeTarget. @@ -157,7 +155,7 @@ func setConfigs(apiClient client.ConfigAPIClient, service *swarm.ServiceSpec, op } if len(specifiedConfigs) > 0 { // parse and validate configs - configs, err := ParseConfigs(apiClient, specifiedConfigs) + configs, err := ParseConfigs(ctx, apiClient, specifiedConfigs) if err != nil { return err } diff --git a/cli/command/service/create_test.go b/cli/command/service/create_test.go index 84ee6022ba..e37af4bbf6 100644 --- a/cli/command/service/create_test.go +++ b/cli/command/service/create_test.go @@ -96,8 +96,10 @@ func TestSetConfigsWithCredSpecAndConfigs(t *testing.T) { }, nil } + ctx := context.Background() + // now call setConfigs - err := setConfigs(fakeClient, service, opts) + err := setConfigs(ctx, fakeClient, service, opts) // verify no error is returned assert.NilError(t, err) @@ -166,7 +168,8 @@ func TestSetConfigsOnlyCredSpec(t *testing.T) { } // now call setConfigs - err := setConfigs(fakeClient, service, opts) + ctx := context.Background() + err := setConfigs(ctx, fakeClient, service, opts) // verify no error is returned assert.NilError(t, err) @@ -216,7 +219,8 @@ func TestSetConfigsOnlyConfigs(t *testing.T) { } // now call setConfigs - err := setConfigs(fakeClient, service, opts) + ctx := context.Background() + err := setConfigs(ctx, fakeClient, service, opts) // verify no error is returned assert.NilError(t, err) @@ -262,7 +266,8 @@ func TestSetConfigsNoConfigs(t *testing.T) { return nil, nil } - err := setConfigs(fakeClient, service, opts) + ctx := context.Background() + err := setConfigs(ctx, fakeClient, service, opts) assert.NilError(t, err) // ensure that the value of the credentialspec has not changed diff --git a/cli/command/service/inspect.go b/cli/command/service/inspect.go index ac76c70dbc..bb6ba54c9a 100644 --- a/cli/command/service/inspect.go +++ b/cli/command/service/inspect.go @@ -33,7 +33,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { if opts.pretty && len(opts.format) > 0 { return errors.Errorf("--format is incompatible with human friendly format") } - return runInspect(dockerCli, opts) + return runInspect(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return CompletionFn(dockerCli)(cmd, args, toComplete) @@ -46,9 +46,8 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runInspect(dockerCli command.Cli, opts inspectOptions) error { +func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error { client := dockerCli.Client() - ctx := context.Background() if opts.pretty { opts.format = "pretty" diff --git a/cli/command/service/list.go b/cli/command/service/list.go index 444b894779..b67b0d130d 100644 --- a/cli/command/service/list.go +++ b/cli/command/service/list.go @@ -31,7 +31,7 @@ func newListCommand(dockerCLI command.Cli) *cobra.Command { Short: "List services", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runList(dockerCLI, options) + return runList(cmd.Context(), dockerCLI, options) }, ValidArgsFunction: completion.NoComplete, } @@ -44,10 +44,9 @@ func newListCommand(dockerCLI command.Cli) *cobra.Command { return cmd } -func runList(dockerCLI command.Cli, options listOptions) error { +func runList(ctx context.Context, dockerCLI command.Cli, options listOptions) error { var ( apiClient = dockerCLI.Client() - ctx = context.Background() err error ) diff --git a/cli/command/service/logs.go b/cli/command/service/logs.go index cb3471244a..e31f992fb4 100644 --- a/cli/command/service/logs.go +++ b/cli/command/service/logs.go @@ -47,7 +47,7 @@ func newLogsCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.target = args[0] - return runLogs(dockerCli, &opts) + return runLogs(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{"version": "1.29"}, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { @@ -72,9 +72,7 @@ func newLogsCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runLogs(dockerCli command.Cli, opts *logsOptions) error { - ctx := context.Background() - +func runLogs(ctx context.Context, dockerCli command.Cli, opts *logsOptions) error { apiClient := dockerCli.Client() var ( diff --git a/cli/command/service/parse.go b/cli/command/service/parse.go index 4a1e2ed17b..239be18810 100644 --- a/cli/command/service/parse.go +++ b/cli/command/service/parse.go @@ -12,13 +12,12 @@ import ( // ParseSecrets retrieves the secrets with the requested names and fills // secret IDs into the secret references. -func ParseSecrets(apiClient client.SecretAPIClient, requestedSecrets []*swarmtypes.SecretReference) ([]*swarmtypes.SecretReference, error) { +func ParseSecrets(ctx context.Context, apiClient client.SecretAPIClient, requestedSecrets []*swarmtypes.SecretReference) ([]*swarmtypes.SecretReference, error) { if len(requestedSecrets) == 0 { return []*swarmtypes.SecretReference{}, nil } secretRefs := make(map[string]*swarmtypes.SecretReference) - ctx := context.Background() for _, secret := range requestedSecrets { if _, exists := secretRefs[secret.File.Name]; exists { @@ -65,7 +64,7 @@ func ParseSecrets(apiClient client.SecretAPIClient, requestedSecrets []*swarmtyp // ParseConfigs retrieves the configs from the requested names and converts // them to config references to use with the spec -func ParseConfigs(apiClient client.ConfigAPIClient, requestedConfigs []*swarmtypes.ConfigReference) ([]*swarmtypes.ConfigReference, error) { +func ParseConfigs(ctx context.Context, apiClient client.ConfigAPIClient, requestedConfigs []*swarmtypes.ConfigReference) ([]*swarmtypes.ConfigReference, error) { if len(requestedConfigs) == 0 { return []*swarmtypes.ConfigReference{}, nil } @@ -83,7 +82,6 @@ func ParseConfigs(apiClient client.ConfigAPIClient, requestedConfigs []*swarmtyp // it is only needed to be referenced once. configRefs := make(map[string]*swarmtypes.ConfigReference) runtimeRefs := make(map[string]*swarmtypes.ConfigReference) - ctx := context.Background() for _, config := range requestedConfigs { // copy the config, so we don't mutate the args diff --git a/cli/command/service/ps.go b/cli/command/service/ps.go index 8f1fed2891..126d9ace2f 100644 --- a/cli/command/service/ps.go +++ b/cli/command/service/ps.go @@ -35,7 +35,7 @@ func newPsCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { options.services = args - return runPS(dockerCli, options) + return runPS(cmd.Context(), dockerCli, options) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return CompletionFn(dockerCli)(cmd, args, toComplete) @@ -51,9 +51,8 @@ func newPsCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runPS(dockerCli command.Cli, options psOptions) error { +func runPS(ctx context.Context, dockerCli command.Cli, options psOptions) error { apiClient := dockerCli.Client() - ctx := context.Background() filter, notfound, err := createFilter(ctx, apiClient, options) if err != nil { diff --git a/cli/command/service/ps_test.go b/cli/command/service/ps_test.go index a17f4061be..470c4b09dc 100644 --- a/cli/command/service/ps_test.go +++ b/cli/command/service/ps_test.go @@ -89,7 +89,9 @@ func TestRunPSWarnsOnNotFound(t *testing.T) { filter: opts.NewFilterOpt(), format: "{{.ID}}", } - err := runPS(cli, options) + + ctx := context.Background() + err := runPS(ctx, cli, options) assert.Error(t, err, "no such service: bar") } @@ -104,7 +106,8 @@ func TestRunPSQuiet(t *testing.T) { } cli := test.NewFakeCli(client) - err := runPS(cli, psOptions{services: []string{"foo"}, quiet: true, filter: opts.NewFilterOpt()}) + ctx := context.Background() + err := runPS(ctx, cli, psOptions{services: []string{"foo"}, quiet: true, filter: opts.NewFilterOpt()}) assert.NilError(t, err) assert.Check(t, is.Equal("sxabyp0obqokwekpun4rjo0b3\n", cli.OutBuffer().String())) } diff --git a/cli/command/service/remove.go b/cli/command/service/remove.go index c1b5863fed..c6e938e13b 100644 --- a/cli/command/service/remove.go +++ b/cli/command/service/remove.go @@ -18,7 +18,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { Short: "Remove one or more services", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runRemove(dockerCli, args) + return runRemove(cmd.Context(), dockerCli, args) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return CompletionFn(dockerCli)(cmd, args, toComplete) @@ -29,11 +29,9 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runRemove(dockerCli command.Cli, sids []string) error { +func runRemove(ctx context.Context, dockerCli command.Cli, sids []string) error { client := dockerCli.Client() - ctx := context.Background() - var errs []string for _, sid := range sids { err := client.ServiceRemove(ctx, sid) diff --git a/cli/command/service/rollback.go b/cli/command/service/rollback.go index 5b9a863e20..fb963d1355 100644 --- a/cli/command/service/rollback.go +++ b/cli/command/service/rollback.go @@ -19,7 +19,7 @@ func newRollbackCommand(dockerCli command.Cli) *cobra.Command { Short: "Revert changes to a service's configuration", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runRollback(dockerCli, options, args[0]) + return runRollback(cmd.Context(), dockerCli, options, args[0]) }, Annotations: map[string]string{"version": "1.31"}, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { @@ -34,9 +34,8 @@ func newRollbackCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runRollback(dockerCli command.Cli, options *serviceOptions, serviceID string) error { +func runRollback(ctx context.Context, dockerCli command.Cli, options *serviceOptions, serviceID string) error { apiClient := dockerCli.Client() - ctx := context.Background() service, _, err := apiClient.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{}) if err != nil { diff --git a/cli/command/service/scale.go b/cli/command/service/scale.go index 4e6efd84cc..0f5b62ca16 100644 --- a/cli/command/service/scale.go +++ b/cli/command/service/scale.go @@ -26,7 +26,7 @@ func newScaleCommand(dockerCli command.Cli) *cobra.Command { Short: "Scale one or multiple replicated services", Args: scaleArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runScale(dockerCli, options, args) + return runScale(cmd.Context(), dockerCli, options, args) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return CompletionFn(dockerCli)(cmd, args, toComplete) @@ -56,10 +56,9 @@ func scaleArgs(cmd *cobra.Command, args []string) error { return nil } -func runScale(dockerCli command.Cli, options *scaleOptions, args []string) error { +func runScale(ctx context.Context, dockerCli command.Cli, options *scaleOptions, args []string) error { var errs []string var serviceIDs []string - ctx := context.Background() for _, arg := range args { serviceID, scaleStr, _ := strings.Cut(arg, "=") diff --git a/cli/command/service/update.go b/cli/command/service/update.go index ac3eb88ca8..f4e7357b1c 100644 --- a/cli/command/service/update.go +++ b/cli/command/service/update.go @@ -31,7 +31,7 @@ func newUpdateCommand(dockerCli command.Cli) *cobra.Command { Short: "Update a service", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runUpdate(dockerCli, cmd.Flags(), options, args[0]) + return runUpdate(cmd.Context(), dockerCli, cmd.Flags(), options, args[0]) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return CompletionFn(dockerCli)(cmd, args, toComplete) @@ -127,9 +127,8 @@ func newListOptsVarWithValidator(validator opts.ValidatorFctType) *opts.ListOpts } //nolint:gocyclo -func runUpdate(dockerCli command.Cli, flags *pflag.FlagSet, options *serviceOptions, serviceID string) error { +func runUpdate(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, options *serviceOptions, serviceID string) error { apiClient := dockerCli.Client() - ctx := context.Background() service, _, err := apiClient.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{}) if err != nil { @@ -195,14 +194,14 @@ func runUpdate(dockerCli command.Cli, flags *pflag.FlagSet, options *serviceOpti } } - updatedSecrets, err := getUpdatedSecrets(apiClient, flags, spec.TaskTemplate.ContainerSpec.Secrets) + updatedSecrets, err := getUpdatedSecrets(ctx, apiClient, flags, spec.TaskTemplate.ContainerSpec.Secrets) if err != nil { return err } spec.TaskTemplate.ContainerSpec.Secrets = updatedSecrets - updatedConfigs, err := getUpdatedConfigs(apiClient, flags, spec.TaskTemplate.ContainerSpec) + updatedConfigs, err := getUpdatedConfigs(ctx, apiClient, flags, spec.TaskTemplate.ContainerSpec) if err != nil { return err } @@ -763,7 +762,7 @@ func updateEnvironment(flags *pflag.FlagSet, field *[]string) { } } -func getUpdatedSecrets(apiClient client.SecretAPIClient, flags *pflag.FlagSet, secrets []*swarm.SecretReference) ([]*swarm.SecretReference, error) { +func getUpdatedSecrets(ctx context.Context, apiClient client.SecretAPIClient, flags *pflag.FlagSet, secrets []*swarm.SecretReference) ([]*swarm.SecretReference, error) { newSecrets := []*swarm.SecretReference{} toRemove := buildToRemoveSet(flags, flagSecretRemove) @@ -776,7 +775,7 @@ func getUpdatedSecrets(apiClient client.SecretAPIClient, flags *pflag.FlagSet, s if flags.Changed(flagSecretAdd) { values := flags.Lookup(flagSecretAdd).Value.(*opts.SecretOpt).Value() - addSecrets, err := ParseSecrets(apiClient, values) + addSecrets, err := ParseSecrets(ctx, apiClient, values) if err != nil { return nil, err } @@ -786,7 +785,7 @@ func getUpdatedSecrets(apiClient client.SecretAPIClient, flags *pflag.FlagSet, s return newSecrets, nil } -func getUpdatedConfigs(apiClient client.ConfigAPIClient, flags *pflag.FlagSet, spec *swarm.ContainerSpec) ([]*swarm.ConfigReference, error) { +func getUpdatedConfigs(ctx context.Context, apiClient client.ConfigAPIClient, flags *pflag.FlagSet, spec *swarm.ContainerSpec) ([]*swarm.ConfigReference, error) { var ( // credSpecConfigName stores the name of the config specified by the // credential-spec flag. if a Runtime target Config with this name is @@ -835,7 +834,7 @@ func getUpdatedConfigs(apiClient client.ConfigAPIClient, flags *pflag.FlagSet, s } if len(resolveConfigs) > 0 { - addConfigs, err := ParseConfigs(apiClient, resolveConfigs) + addConfigs, err := ParseConfigs(ctx, apiClient, resolveConfigs) if err != nil { return nil, err } diff --git a/cli/command/service/update_test.go b/cli/command/service/update_test.go index db884b84fb..127c01a857 100644 --- a/cli/command/service/update_test.go +++ b/cli/command/service/update_test.go @@ -554,7 +554,8 @@ func TestUpdateSecretUpdateInPlace(t *testing.T) { }, } - updatedSecrets, err := getUpdatedSecrets(apiClient, flags, secrets) + ctx := context.Background() + updatedSecrets, err := getUpdatedSecrets(ctx, apiClient, flags, secrets) assert.NilError(t, err) assert.Assert(t, is.Len(updatedSecrets, 1)) @@ -1231,7 +1232,8 @@ func TestUpdateGetUpdatedConfigs(t *testing.T) { }, } - finalConfigs, err := getUpdatedConfigs(fakeClient, flags, containerSpec) + ctx := context.Background() + finalConfigs, err := getUpdatedConfigs(ctx, fakeClient, flags, containerSpec) assert.NilError(t, err) // ensure that the finalConfigs consists of all of the expected diff --git a/cli/command/stack/cmd.go b/cli/command/stack/cmd.go index ff55262bf3..bf4dc79955 100644 --- a/cli/command/stack/cmd.go +++ b/cli/command/stack/cmd.go @@ -48,7 +48,7 @@ func NewStackCommand(dockerCli command.Cli) *cobra.Command { // completeNames offers completion for swarm stacks func completeNames(dockerCli command.Cli) completion.ValidArgsFn { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - list, err := swarm.GetStacks(dockerCli) + list, err := swarm.GetStacks(cmd.Context(), dockerCli) if err != nil { return nil, cobra.ShellCompDirectiveError } diff --git a/cli/command/stack/deploy.go b/cli/command/stack/deploy.go index 83447ff1e4..8238e4b464 100644 --- a/cli/command/stack/deploy.go +++ b/cli/command/stack/deploy.go @@ -26,7 +26,7 @@ func newDeployCommand(dockerCli command.Cli) *cobra.Command { if err != nil { return err } - return swarm.RunDeploy(dockerCli, opts, config) + return swarm.RunDeploy(cmd.Context(), dockerCli, opts, config) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return completeNames(dockerCli)(cmd, args, toComplete) diff --git a/cli/command/stack/list.go b/cli/command/stack/list.go index fc5b03d651..d737b8771e 100644 --- a/cli/command/stack/list.go +++ b/cli/command/stack/list.go @@ -1,6 +1,7 @@ package stack import ( + "context" "sort" "github.com/docker/cli/cli" @@ -23,7 +24,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { Short: "List stacks", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return RunList(dockerCli, opts) + return RunList(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: completion.NoComplete, } @@ -34,8 +35,8 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { } // RunList performs a stack list against the specified swarm cluster -func RunList(dockerCli command.Cli, opts options.List) error { - ss, err := swarm.GetStacks(dockerCli) +func RunList(ctx context.Context, dockerCli command.Cli, opts options.List) error { + ss, err := swarm.GetStacks(ctx, dockerCli) if err != nil { return err } diff --git a/cli/command/stack/ps.go b/cli/command/stack/ps.go index 570da21cd8..8a91cc75f8 100644 --- a/cli/command/stack/ps.go +++ b/cli/command/stack/ps.go @@ -22,7 +22,7 @@ func newPsCommand(dockerCli command.Cli) *cobra.Command { if err := validateStackName(opts.Namespace); err != nil { return err } - return swarm.RunPS(dockerCli, opts) + return swarm.RunPS(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return completeNames(dockerCli)(cmd, args, toComplete) diff --git a/cli/command/stack/remove.go b/cli/command/stack/remove.go index 7981b6fe88..0018624bce 100644 --- a/cli/command/stack/remove.go +++ b/cli/command/stack/remove.go @@ -21,7 +21,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { if err := validateStackNames(opts.Namespaces); err != nil { return err } - return swarm.RunRemove(dockerCli, opts) + return swarm.RunRemove(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return completeNames(dockerCli)(cmd, args, toComplete) diff --git a/cli/command/stack/services.go b/cli/command/stack/services.go index fdfd5eece3..2638c985b0 100644 --- a/cli/command/stack/services.go +++ b/cli/command/stack/services.go @@ -1,6 +1,7 @@ package stack import ( + "context" "fmt" "sort" @@ -29,7 +30,7 @@ func newServicesCommand(dockerCli command.Cli) *cobra.Command { if err := validateStackName(opts.Namespace); err != nil { return err } - return RunServices(dockerCli, opts) + return RunServices(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return completeNames(dockerCli)(cmd, args, toComplete) @@ -43,8 +44,8 @@ func newServicesCommand(dockerCli command.Cli) *cobra.Command { } // RunServices performs a stack services against the specified swarm cluster -func RunServices(dockerCli command.Cli, opts options.Services) error { - services, err := swarm.GetServices(dockerCli, opts) +func RunServices(ctx context.Context, dockerCli command.Cli, opts options.Services) error { + services, err := swarm.GetServices(ctx, dockerCli, opts) if err != nil { return err } diff --git a/cli/command/stack/swarm/deploy.go b/cli/command/stack/swarm/deploy.go index df5f300026..c6159dc21a 100644 --- a/cli/command/stack/swarm/deploy.go +++ b/cli/command/stack/swarm/deploy.go @@ -22,9 +22,7 @@ const ( ) // RunDeploy is the swarm implementation of docker stack deploy -func RunDeploy(dockerCli command.Cli, opts options.Deploy, cfg *composetypes.Config) error { - ctx := context.Background() - +func RunDeploy(ctx context.Context, dockerCli command.Cli, opts options.Deploy, cfg *composetypes.Config) error { if err := validateResolveImageFlag(&opts); err != nil { return err } diff --git a/cli/command/stack/swarm/deploy_composefile.go b/cli/command/stack/swarm/deploy_composefile.go index 2d8a46639c..73810aad8f 100644 --- a/cli/command/stack/swarm/deploy_composefile.go +++ b/cli/command/stack/swarm/deploy_composefile.go @@ -56,7 +56,7 @@ func deployCompose(ctx context.Context, dockerCli command.Cli, opts options.Depl return err } - services, err := convert.Services(namespace, config, dockerCli.Client()) + services, err := convert.Services(ctx, namespace, config, dockerCli.Client()) if err != nil { return err } diff --git a/cli/command/stack/swarm/list.go b/cli/command/stack/swarm/list.go index 42fd7f414e..983ea5e201 100644 --- a/cli/command/stack/swarm/list.go +++ b/cli/command/stack/swarm/list.go @@ -11,9 +11,9 @@ import ( ) // GetStacks lists the swarm stacks. -func GetStacks(dockerCli command.Cli) ([]*formatter.Stack, error) { +func GetStacks(ctx context.Context, dockerCli command.Cli) ([]*formatter.Stack, error) { services, err := dockerCli.Client().ServiceList( - context.Background(), + ctx, types.ServiceListOptions{Filters: getAllStacksFilter()}) if err != nil { return nil, err diff --git a/cli/command/stack/swarm/ps.go b/cli/command/stack/swarm/ps.go index 5b28a39e73..fe2839b065 100644 --- a/cli/command/stack/swarm/ps.go +++ b/cli/command/stack/swarm/ps.go @@ -12,10 +12,9 @@ import ( ) // RunPS is the swarm implementation of docker stack ps -func RunPS(dockerCli command.Cli, opts options.PS) error { +func RunPS(ctx context.Context, dockerCli command.Cli, opts options.PS) error { filter := getStackFilterFromOpt(opts.Namespace, opts.Filter) - ctx := context.Background() client := dockerCli.Client() tasks, err := client.TaskList(ctx, types.TaskListOptions{Filters: filter}) if err != nil { diff --git a/cli/command/stack/swarm/remove.go b/cli/command/stack/swarm/remove.go index 4dedef12f3..6dc49a1ce7 100644 --- a/cli/command/stack/swarm/remove.go +++ b/cli/command/stack/swarm/remove.go @@ -15,9 +15,8 @@ import ( ) // RunRemove is the swarm implementation of docker stack remove -func RunRemove(dockerCli command.Cli, opts options.Remove) error { +func RunRemove(ctx context.Context, dockerCli command.Cli, opts options.Remove) error { client := dockerCli.Client() - ctx := context.Background() var errs []string for _, namespace := range opts.Namespaces { diff --git a/cli/command/stack/swarm/services.go b/cli/command/stack/swarm/services.go index 3c24bf72dd..dc4f8c87c4 100644 --- a/cli/command/stack/swarm/services.go +++ b/cli/command/stack/swarm/services.go @@ -11,10 +11,9 @@ import ( ) // GetServices is the swarm implementation of listing stack services -func GetServices(dockerCli command.Cli, opts options.Services) ([]swarm.Service, error) { +func GetServices(ctx context.Context, dockerCli command.Cli, opts options.Services) ([]swarm.Service, error) { var ( err error - ctx = context.Background() client = dockerCli.Client() ) diff --git a/cli/command/swarm/ca.go b/cli/command/swarm/ca.go index 8793a1c9be..25c235a450 100644 --- a/cli/command/swarm/ca.go +++ b/cli/command/swarm/ca.go @@ -34,7 +34,7 @@ func newCACommand(dockerCli command.Cli) *cobra.Command { Short: "Display and rotate the root CA", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runCA(dockerCli, cmd.Flags(), opts) + return runCA(cmd.Context(), dockerCli, cmd.Flags(), opts) }, Annotations: map[string]string{ "version": "1.30", @@ -54,9 +54,8 @@ func newCACommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runCA(dockerCli command.Cli, flags *pflag.FlagSet, opts caOptions) error { +func runCA(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, opts caOptions) error { client := dockerCli.Client() - ctx := context.Background() swarmInspect, err := client.SwarmInspect(ctx) if err != nil { diff --git a/cli/command/swarm/init.go b/cli/command/swarm/init.go index 1325779099..8612a5f8f1 100644 --- a/cli/command/swarm/init.go +++ b/cli/command/swarm/init.go @@ -38,7 +38,7 @@ func newInitCommand(dockerCli command.Cli) *cobra.Command { Short: "Initialize a swarm", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runInit(dockerCli, cmd.Flags(), opts) + return runInit(cmd.Context(), dockerCli, cmd.Flags(), opts) }, Annotations: map[string]string{ "version": "1.24", @@ -65,9 +65,8 @@ func newInitCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runInit(dockerCli command.Cli, flags *pflag.FlagSet, opts initOptions) error { +func runInit(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, opts initOptions) error { client := dockerCli.Client() - ctx := context.Background() defaultAddrPool := make([]string, 0, len(opts.defaultAddrPools)) for _, p := range opts.defaultAddrPools { diff --git a/cli/command/swarm/join.go b/cli/command/swarm/join.go index d36efbdb76..3e497e7f1f 100644 --- a/cli/command/swarm/join.go +++ b/cli/command/swarm/join.go @@ -34,7 +34,7 @@ func newJoinCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.remote = args[0] - return runJoin(dockerCli, cmd.Flags(), opts) + return runJoin(cmd.Context(), dockerCli, cmd.Flags(), opts) }, Annotations: map[string]string{ "version": "1.24", @@ -52,9 +52,8 @@ func newJoinCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runJoin(dockerCli command.Cli, flags *pflag.FlagSet, opts joinOptions) error { +func runJoin(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, opts joinOptions) error { client := dockerCli.Client() - ctx := context.Background() req := swarm.JoinRequest{ JoinToken: opts.token, diff --git a/cli/command/swarm/join_token.go b/cli/command/swarm/join_token.go index afd64d55ab..de0611700a 100644 --- a/cli/command/swarm/join_token.go +++ b/cli/command/swarm/join_token.go @@ -26,7 +26,7 @@ func newJoinTokenCommand(dockerCli command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.role = args[0] - return runJoinToken(dockerCli, opts) + return runJoinToken(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{ "version": "1.24", @@ -41,7 +41,7 @@ func newJoinTokenCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runJoinToken(dockerCli command.Cli, opts joinTokenOptions) error { +func runJoinToken(ctx context.Context, dockerCli command.Cli, opts joinTokenOptions) error { worker := opts.role == "worker" manager := opts.role == "manager" @@ -50,7 +50,6 @@ func runJoinToken(dockerCli command.Cli, opts joinTokenOptions) error { } client := dockerCli.Client() - ctx := context.Background() if opts.rotate { flags := swarm.UpdateFlags{ diff --git a/cli/command/swarm/leave.go b/cli/command/swarm/leave.go index 586e59aa94..9d73852158 100644 --- a/cli/command/swarm/leave.go +++ b/cli/command/swarm/leave.go @@ -22,7 +22,7 @@ func newLeaveCommand(dockerCli command.Cli) *cobra.Command { Short: "Leave the swarm", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runLeave(dockerCli, opts) + return runLeave(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{ "version": "1.24", @@ -36,9 +36,8 @@ func newLeaveCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runLeave(dockerCli command.Cli, opts leaveOptions) error { +func runLeave(ctx context.Context, dockerCli command.Cli, opts leaveOptions) error { client := dockerCli.Client() - ctx := context.Background() if err := client.SwarmLeave(ctx, opts.force); err != nil { return err diff --git a/cli/command/swarm/unlock.go b/cli/command/swarm/unlock.go index 12db5d884b..ad727e073d 100644 --- a/cli/command/swarm/unlock.go +++ b/cli/command/swarm/unlock.go @@ -23,7 +23,7 @@ func newUnlockCommand(dockerCli command.Cli) *cobra.Command { Short: "Unlock swarm", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runUnlock(dockerCli) + return runUnlock(cmd.Context(), dockerCli) }, Annotations: map[string]string{ "version": "1.24", @@ -35,9 +35,8 @@ func newUnlockCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runUnlock(dockerCli command.Cli) error { +func runUnlock(ctx context.Context, dockerCli command.Cli) error { client := dockerCli.Client() - ctx := context.Background() // First see if the node is actually part of a swarm, and if it is actually locked first. // If it's in any other state than locked, don't ask for the key. diff --git a/cli/command/swarm/unlock_key.go b/cli/command/swarm/unlock_key.go index b3e051a18a..dfd467eacd 100644 --- a/cli/command/swarm/unlock_key.go +++ b/cli/command/swarm/unlock_key.go @@ -26,7 +26,7 @@ func newUnlockKeyCommand(dockerCli command.Cli) *cobra.Command { Short: "Manage the unlock key", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runUnlockKey(dockerCli, opts) + return runUnlockKey(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{ "version": "1.24", @@ -42,9 +42,8 @@ func newUnlockKeyCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runUnlockKey(dockerCli command.Cli, opts unlockKeyOptions) error { +func runUnlockKey(ctx context.Context, dockerCli command.Cli, opts unlockKeyOptions) error { client := dockerCli.Client() - ctx := context.Background() if opts.rotate { flags := swarm.UpdateFlags{RotateManagerUnlockKey: true} diff --git a/cli/command/swarm/update.go b/cli/command/swarm/update.go index dc72fc744e..50ddc17b1a 100644 --- a/cli/command/swarm/update.go +++ b/cli/command/swarm/update.go @@ -21,7 +21,7 @@ func newUpdateCommand(dockerCli command.Cli) *cobra.Command { Short: "Update the swarm", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runUpdate(dockerCli, cmd.Flags(), opts) + return runUpdate(cmd.Context(), dockerCli, cmd.Flags(), opts) }, PreRunE: func(cmd *cobra.Command, args []string) error { if cmd.Flags().NFlag() == 0 { @@ -41,9 +41,8 @@ func newUpdateCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runUpdate(dockerCli command.Cli, flags *pflag.FlagSet, opts swarmOptions) error { +func runUpdate(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, opts swarmOptions) error { client := dockerCli.Client() - ctx := context.Background() var updateFlags swarm.UpdateFlags diff --git a/cli/command/system/df.go b/cli/command/system/df.go index 150e0d0e0b..f6a98a0367 100644 --- a/cli/command/system/df.go +++ b/cli/command/system/df.go @@ -26,7 +26,7 @@ func newDiskUsageCommand(dockerCli command.Cli) *cobra.Command { Short: "Show docker disk usage", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runDiskUsage(dockerCli, opts) + return runDiskUsage(cmd.Context(), dockerCli, opts) }, Annotations: map[string]string{"version": "1.25"}, ValidArgsFunction: completion.NoComplete, @@ -40,9 +40,9 @@ func newDiskUsageCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runDiskUsage(dockerCli command.Cli, opts diskUsageOptions) error { +func runDiskUsage(ctx context.Context, dockerCli command.Cli, opts diskUsageOptions) error { // TODO expose types.DiskUsageOptions.Types as flag on the command-line and/or as separate commands (docker container df / docker container usage) - du, err := dockerCli.Client().DiskUsage(context.Background(), types.DiskUsageOptions{}) + du, err := dockerCli.Client().DiskUsage(ctx, types.DiskUsageOptions{}) if err != nil { return err } diff --git a/cli/command/system/dial_stdio.go b/cli/command/system/dial_stdio.go index 6bfef787a6..d4193ce8af 100644 --- a/cli/command/system/dial_stdio.go +++ b/cli/command/system/dial_stdio.go @@ -21,16 +21,17 @@ func newDialStdioCommand(dockerCli command.Cli) *cobra.Command { Args: cli.NoArgs, Hidden: true, RunE: func(cmd *cobra.Command, args []string) error { - return runDialStdio(dockerCli) + return runDialStdio(cmd.Context(), dockerCli) }, ValidArgsFunction: completion.NoComplete, } return cmd } -func runDialStdio(dockerCli command.Cli) error { - ctx, cancel := context.WithCancel(context.Background()) +func runDialStdio(ctx context.Context, dockerCli command.Cli) error { + ctx, cancel := context.WithCancel(ctx) defer cancel() + dialer := dockerCli.Client().Dialer() conn, err := dialer(ctx) if err != nil { diff --git a/cli/command/system/events.go b/cli/command/system/events.go index d018b4d083..ea6444d910 100644 --- a/cli/command/system/events.go +++ b/cli/command/system/events.go @@ -37,7 +37,7 @@ func NewEventsCommand(dockerCli command.Cli) *cobra.Command { Short: "Get real time events from the server", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runEvents(dockerCli, &options) + return runEvents(cmd.Context(), dockerCli, &options) }, Annotations: map[string]string{ "aliases": "docker system events, docker events", @@ -54,7 +54,7 @@ func NewEventsCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runEvents(dockerCli command.Cli, options *eventsOptions) error { +func runEvents(ctx context.Context, dockerCli command.Cli, options *eventsOptions) error { tmpl, err := makeTemplate(options.format) if err != nil { return cli.StatusError{ @@ -62,7 +62,7 @@ func runEvents(dockerCli command.Cli, options *eventsOptions) error { Status: "Error parsing format: " + err.Error(), } } - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(ctx) evts, errs := dockerCli.Client().Events(ctx, types.EventsOptions{ Since: options.since, Until: options.until, diff --git a/cli/command/system/info.go b/cli/command/system/info.go index d560c058ee..4088972057 100644 --- a/cli/command/system/info.go +++ b/cli/command/system/info.go @@ -64,7 +64,7 @@ func NewInfoCommand(dockerCli command.Cli) *cobra.Command { Short: "Display system-wide information", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runInfo(cmd, dockerCli, &opts) + return runInfo(cmd.Context(), cmd, dockerCli, &opts) }, Annotations: map[string]string{ "category-top": "12", @@ -77,7 +77,7 @@ func NewInfoCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runInfo(cmd *cobra.Command, dockerCli command.Cli, opts *infoOptions) error { +func runInfo(ctx context.Context, cmd *cobra.Command, dockerCli command.Cli, opts *infoOptions) error { info := dockerInfo{ ClientInfo: &clientInfo{ // Don't pass a dockerCLI to newClientVersion(), because we currently @@ -95,7 +95,6 @@ func runInfo(cmd *cobra.Command, dockerCli command.Cli, opts *infoOptions) error } if needsServerInfo(opts.format, info) { - ctx := context.Background() if dinfo, err := dockerCli.Client().Info(ctx); err == nil { info.Info = &dinfo } else { diff --git a/cli/command/system/inspect.go b/cli/command/system/inspect.go index a5e79c625f..4c136af8ad 100644 --- a/cli/command/system/inspect.go +++ b/cli/command/system/inspect.go @@ -32,7 +32,7 @@ func NewInspectCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.ids = args - return runInspect(dockerCli, opts) + return runInspect(cmd.Context(), dockerCli, opts) }, } @@ -44,11 +44,11 @@ func NewInspectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runInspect(dockerCli command.Cli, opts inspectOptions) error { +func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error { var elementSearcher inspect.GetRefFunc switch opts.inspectType { case "", "container", "image", "node", "network", "service", "volume", "task", "plugin", "secret": - elementSearcher = inspectAll(context.Background(), dockerCli, opts.size, opts.inspectType) + elementSearcher = inspectAll(ctx, dockerCli, opts.size, opts.inspectType) default: return errors.Errorf("%q is not a valid value for --type", opts.inspectType) } diff --git a/cli/command/system/prune.go b/cli/command/system/prune.go index fdc3ffc3f0..d91c450bf6 100644 --- a/cli/command/system/prune.go +++ b/cli/command/system/prune.go @@ -2,6 +2,7 @@ package system import ( "bytes" + "context" "fmt" "sort" "text/template" @@ -39,7 +40,7 @@ func newPruneCommand(dockerCli command.Cli) *cobra.Command { Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { options.pruneBuildCache = versions.GreaterThanOrEqualTo(dockerCli.Client().ClientVersion(), "1.31") - return runPrune(dockerCli, options) + return runPrune(cmd.Context(), dockerCli, options) }, Annotations: map[string]string{"version": "1.25"}, ValidArgsFunction: completion.NoComplete, @@ -68,7 +69,7 @@ const confirmationTemplate = `WARNING! This will remove: {{end}} Are you sure you want to continue?` -func runPrune(dockerCli command.Cli, options pruneOptions) error { +func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) error { // TODO version this once "until" filter is supported for volumes if options.pruneVolumes && options.filter.Value().Contains("until") { return fmt.Errorf(`ERROR: The "until" filter is not supported with "--volumes"`) @@ -76,7 +77,7 @@ func runPrune(dockerCli command.Cli, options pruneOptions) error { if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), confirmationMessage(dockerCli, options)) { return nil } - pruneFuncs := []func(dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error){ + pruneFuncs := []func(ctx context.Context, dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error){ container.RunPrune, network.RunPrune, } @@ -90,7 +91,7 @@ func runPrune(dockerCli command.Cli, options pruneOptions) error { var spaceReclaimed uint64 for _, pruneFn := range pruneFuncs { - spc, output, err := pruneFn(dockerCli, options.all, options.filter) + spc, output, err := pruneFn(ctx, dockerCli, options.all, options.filter) if err != nil { return err } diff --git a/cli/command/system/version.go b/cli/command/system/version.go index 4cb34a0273..f25446b06d 100644 --- a/cli/command/system/version.go +++ b/cli/command/system/version.go @@ -116,7 +116,7 @@ func NewVersionCommand(dockerCli command.Cli) *cobra.Command { Short: "Show the Docker version information", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runVersion(dockerCli, &opts) + return runVersion(cmd.Context(), dockerCli, &opts) }, Annotations: map[string]string{ "category-top": "10", @@ -144,7 +144,7 @@ func arch() string { return arch } -func runVersion(dockerCli command.Cli, opts *versionOptions) error { +func runVersion(ctx context.Context, dockerCli command.Cli, opts *versionOptions) error { var err error tmpl, err := newVersionTemplate(opts.format) if err != nil { @@ -156,7 +156,7 @@ func runVersion(dockerCli command.Cli, opts *versionOptions) error { vd := versionInfo{ Client: newClientVersion(dockerCli.CurrentContext(), dockerCli), } - sv, err := dockerCli.Client().ServerVersion(context.Background()) + sv, err := dockerCli.Client().ServerVersion(ctx) if err == nil { vd.Server = &sv foundEngine := false diff --git a/cli/command/trust/common.go b/cli/command/trust/common.go index a62852297b..1248bb487e 100644 --- a/cli/command/trust/common.go +++ b/cli/command/trust/common.go @@ -51,8 +51,7 @@ type trustKey struct { // lookupTrustInfo returns processed signature and role information about a notary repository. // This information is to be pretty printed or serialized into a machine-readable format. -func lookupTrustInfo(cli command.Cli, remote string) ([]trustTagRow, []client.RoleWithSignatures, []data.Role, error) { - ctx := context.Background() +func lookupTrustInfo(ctx context.Context, cli command.Cli, remote string) ([]trustTagRow, []client.RoleWithSignatures, []data.Role, error) { imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, image.AuthResolver(cli), remote) if err != nil { return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, err diff --git a/cli/command/trust/inspect.go b/cli/command/trust/inspect.go index b2040d2838..81994d085e 100644 --- a/cli/command/trust/inspect.go +++ b/cli/command/trust/inspect.go @@ -1,6 +1,7 @@ package trust import ( + "context" "encoding/json" "fmt" "sort" @@ -28,7 +29,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { options.remotes = args - return runInspect(dockerCli, options) + return runInspect(cmd.Context(), dockerCli, options) }, } @@ -38,12 +39,12 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runInspect(dockerCLI command.Cli, opts inspectOptions) error { +func runInspect(ctx context.Context, dockerCLI command.Cli, opts inspectOptions) error { if opts.prettyPrint { var err error for index, remote := range opts.remotes { - if err = prettyPrintTrustInfo(dockerCLI, remote); err != nil { + if err = prettyPrintTrustInfo(ctx, dockerCLI, remote); err != nil { return err } @@ -57,14 +58,14 @@ func runInspect(dockerCLI command.Cli, opts inspectOptions) error { } getRefFunc := func(ref string) (any, []byte, error) { - i, err := getRepoTrustInfo(dockerCLI, ref) + i, err := getRepoTrustInfo(ctx, dockerCLI, ref) return nil, i, err } return inspect.Inspect(dockerCLI.Out(), opts.remotes, "", getRefFunc) } -func getRepoTrustInfo(dockerCLI command.Cli, remote string) ([]byte, error) { - signatureRows, adminRolesWithSigs, delegationRoles, err := lookupTrustInfo(dockerCLI, remote) +func getRepoTrustInfo(ctx context.Context, dockerCLI command.Cli, remote string) ([]byte, error) { + signatureRows, adminRolesWithSigs, delegationRoles, err := lookupTrustInfo(ctx, dockerCLI, remote) if err != nil { return []byte{}, err } diff --git a/cli/command/trust/inspect_pretty.go b/cli/command/trust/inspect_pretty.go index 0407549b44..f0e16006ba 100644 --- a/cli/command/trust/inspect_pretty.go +++ b/cli/command/trust/inspect_pretty.go @@ -1,6 +1,7 @@ package trust import ( + "context" "fmt" "io" "sort" @@ -11,8 +12,8 @@ import ( "github.com/theupdateframework/notary/client" ) -func prettyPrintTrustInfo(cli command.Cli, remote string) error { - signatureRows, adminRolesWithSigs, delegationRoles, err := lookupTrustInfo(cli, remote) +func prettyPrintTrustInfo(ctx context.Context, cli command.Cli, remote string) error { + signatureRows, adminRolesWithSigs, delegationRoles, err := lookupTrustInfo(ctx, cli, remote) if err != nil { return err } diff --git a/cli/command/trust/revoke.go b/cli/command/trust/revoke.go index f36dff190a..0c52aaeebd 100644 --- a/cli/command/trust/revoke.go +++ b/cli/command/trust/revoke.go @@ -26,7 +26,7 @@ func newRevokeCommand(dockerCLI command.Cli) *cobra.Command { Short: "Remove trust for an image", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return revokeTrust(dockerCLI, args[0], options) + return revokeTrust(cmd.Context(), dockerCLI, args[0], options) }, } flags := cmd.Flags() @@ -34,8 +34,7 @@ func newRevokeCommand(dockerCLI command.Cli) *cobra.Command { return cmd } -func revokeTrust(dockerCLI command.Cli, remote string, options revokeOptions) error { - ctx := context.Background() +func revokeTrust(ctx context.Context, dockerCLI command.Cli, remote string, options revokeOptions) error { imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, image.AuthResolver(dockerCLI), remote) if err != nil { return err diff --git a/cli/command/trust/sign.go b/cli/command/trust/sign.go index 1ac45a1acc..72cfc2d103 100644 --- a/cli/command/trust/sign.go +++ b/cli/command/trust/sign.go @@ -34,7 +34,7 @@ func newSignCommand(dockerCLI command.Cli) *cobra.Command { Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { options.imageName = args[0] - return runSignImage(dockerCLI, options) + return runSignImage(cmd.Context(), dockerCLI, options) }, } flags := cmd.Flags() @@ -42,9 +42,8 @@ func newSignCommand(dockerCLI command.Cli) *cobra.Command { return cmd } -func runSignImage(dockerCLI command.Cli, options signOptions) error { +func runSignImage(ctx context.Context, dockerCLI command.Cli, options signOptions) error { imageName := options.imageName - ctx := context.Background() imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, image.AuthResolver(dockerCLI), imageName) if err != nil { return err diff --git a/cli/command/trust/signer_add.go b/cli/command/trust/signer_add.go index e840970790..db6bcd7c34 100644 --- a/cli/command/trust/signer_add.go +++ b/cli/command/trust/signer_add.go @@ -36,7 +36,7 @@ func newSignerAddCommand(dockerCLI command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { options.signer = args[0] options.repos = args[1:] - return addSigner(dockerCLI, options) + return addSigner(cmd.Context(), dockerCLI, options) }, } flags := cmd.Flags() @@ -47,7 +47,7 @@ func newSignerAddCommand(dockerCLI command.Cli) *cobra.Command { var validSignerName = regexp.MustCompile(`^[a-z0-9][a-z0-9\_\-]*$`).MatchString -func addSigner(dockerCLI command.Cli, options signerAddOptions) error { +func addSigner(ctx context.Context, dockerCLI command.Cli, options signerAddOptions) error { signerName := options.signer if !validSignerName(signerName) { return fmt.Errorf("signer name \"%s\" must start with lowercase alphanumeric characters and can include \"-\" or \"_\" after the first character", signerName) @@ -66,7 +66,7 @@ func addSigner(dockerCLI command.Cli, options signerAddOptions) error { var errRepos []string for _, repoName := range options.repos { fmt.Fprintf(dockerCLI.Out(), "Adding signer \"%s\" to %s...\n", signerName, repoName) - if err := addSignerToRepo(dockerCLI, signerName, repoName, signerPubKeys); err != nil { + if err := addSignerToRepo(ctx, dockerCLI, signerName, repoName, signerPubKeys); err != nil { fmt.Fprintln(dockerCLI.Err(), err.Error()+"\n") errRepos = append(errRepos, repoName) } else { @@ -79,8 +79,7 @@ func addSigner(dockerCLI command.Cli, options signerAddOptions) error { return nil } -func addSignerToRepo(dockerCLI command.Cli, signerName string, repoName string, signerPubKeys []data.PublicKey) error { - ctx := context.Background() +func addSignerToRepo(ctx context.Context, dockerCLI command.Cli, signerName string, repoName string, signerPubKeys []data.PublicKey) error { imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, image.AuthResolver(dockerCLI), repoName) if err != nil { return err diff --git a/cli/command/trust/signer_remove.go b/cli/command/trust/signer_remove.go index 226c39de04..bef3d3b271 100644 --- a/cli/command/trust/signer_remove.go +++ b/cli/command/trust/signer_remove.go @@ -31,7 +31,7 @@ func newSignerRemoveCommand(dockerCli command.Cli) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { options.signer = args[0] options.repos = args[1:] - return removeSigner(dockerCli, options) + return removeSigner(cmd.Context(), dockerCli, options) }, } flags := cmd.Flags() @@ -39,11 +39,11 @@ func newSignerRemoveCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func removeSigner(dockerCLI command.Cli, options signerRemoveOptions) error { +func removeSigner(ctx context.Context, dockerCLI command.Cli, options signerRemoveOptions) error { var errRepos []string for _, repo := range options.repos { fmt.Fprintf(dockerCLI.Out(), "Removing signer \"%s\" from %s...\n", options.signer, repo) - if _, err := removeSingleSigner(dockerCLI, repo, options.signer, options.forceYes); err != nil { + if _, err := removeSingleSigner(ctx, dockerCLI, repo, options.signer, options.forceYes); err != nil { fmt.Fprintln(dockerCLI.Err(), err.Error()+"\n") errRepos = append(errRepos, repo) } @@ -78,8 +78,7 @@ func isLastSignerForReleases(roleWithSig data.Role, allRoles []client.RoleWithSi // removeSingleSigner attempts to remove a single signer and returns whether signer removal happened. // The signer not being removed doesn't necessarily raise an error e.g. user choosing "No" when prompted for confirmation. -func removeSingleSigner(dockerCLI command.Cli, repoName, signerName string, forceYes bool) (bool, error) { - ctx := context.Background() +func removeSingleSigner(ctx context.Context, dockerCLI command.Cli, repoName, signerName string, forceYes bool) (bool, error) { imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, image.AuthResolver(dockerCLI), repoName) if err != nil { return false, err diff --git a/cli/command/trust/signer_remove_test.go b/cli/command/trust/signer_remove_test.go index 204c115c21..05fa679715 100644 --- a/cli/command/trust/signer_remove_test.go +++ b/cli/command/trust/signer_remove_test.go @@ -1,6 +1,7 @@ package trust import ( + "context" "io" "testing" @@ -70,11 +71,12 @@ func TestTrustSignerRemoveErrors(t *testing.T) { func TestRemoveSingleSigner(t *testing.T) { cli := test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(notaryfake.GetLoadedNotaryRepository) - removed, err := removeSingleSigner(cli, "signed-repo", "test", true) + ctx := context.Background() + removed, err := removeSingleSigner(ctx, cli, "signed-repo", "test", true) assert.Error(t, err, "no signer test for repository signed-repo") assert.Equal(t, removed, false, "No signer should be removed") - removed, err = removeSingleSigner(cli, "signed-repo", "releases", true) + removed, err = removeSingleSigner(ctx, cli, "signed-repo", "releases", true) assert.Error(t, err, "releases is a reserved keyword and cannot be removed") assert.Equal(t, removed, false, "No signer should be removed") } @@ -82,7 +84,8 @@ func TestRemoveSingleSigner(t *testing.T) { func TestRemoveMultipleSigners(t *testing.T) { cli := test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(notaryfake.GetLoadedNotaryRepository) - err := removeSigner(cli, signerRemoveOptions{signer: "test", repos: []string{"signed-repo", "signed-repo"}, forceYes: true}) + ctx := context.Background() + err := removeSigner(ctx, cli, signerRemoveOptions{signer: "test", repos: []string{"signed-repo", "signed-repo"}, forceYes: true}) assert.Error(t, err, "error removing signer from: signed-repo, signed-repo") assert.Check(t, is.Contains(cli.ErrBuffer().String(), "no signer test for repository signed-repo")) @@ -91,9 +94,10 @@ func TestRemoveMultipleSigners(t *testing.T) { func TestRemoveLastSignerWarning(t *testing.T) { cli := test.NewFakeCli(&fakeClient{}) + ctx := context.Background() cli.SetNotaryClient(notaryfake.GetLoadedNotaryRepository) - err := removeSigner(cli, signerRemoveOptions{signer: "alice", repos: []string{"signed-repo"}, forceYes: false}) + err := removeSigner(ctx, cli, signerRemoveOptions{signer: "alice", repos: []string{"signed-repo"}, forceYes: false}) assert.NilError(t, err) assert.Check(t, is.Contains(cli.OutBuffer().String(), "The signer \"alice\" signed the last released version of signed-repo. "+ diff --git a/cli/command/volume/create.go b/cli/command/volume/create.go index 1884949c69..15e1627cbb 100644 --- a/cli/command/volume/create.go +++ b/cli/command/volume/create.go @@ -57,7 +57,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command { options.name = args[0] } options.cluster = hasClusterVolumeOptionSet(cmd.Flags()) - return runCreate(dockerCli, options) + return runCreate(cmd.Context(), dockerCli, options) }, ValidArgsFunction: completion.NoComplete, } @@ -112,7 +112,7 @@ func hasClusterVolumeOptionSet(flags *pflag.FlagSet) bool { flags.Changed("limit-bytes") || flags.Changed("required-bytes") } -func runCreate(dockerCli command.Cli, options createOptions) error { +func runCreate(ctx context.Context, dockerCli command.Cli, options createOptions) error { volOpts := volume.CreateOptions{ Driver: options.driver, DriverOpts: options.driverOpts.GetAll(), @@ -194,7 +194,7 @@ func runCreate(dockerCli command.Cli, options createOptions) error { volOpts.ClusterVolumeSpec.AccessibilityRequirements = topology } - vol, err := dockerCli.Client().VolumeCreate(context.Background(), volOpts) + vol, err := dockerCli.Client().VolumeCreate(ctx, volOpts) if err != nil { return err } diff --git a/cli/command/volume/inspect.go b/cli/command/volume/inspect.go index 6cff6b6178..5319fdbed9 100644 --- a/cli/command/volume/inspect.go +++ b/cli/command/volume/inspect.go @@ -25,7 +25,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.names = args - return runInspect(dockerCli, opts) + return runInspect(cmd.Context(), dockerCli, opts) }, ValidArgsFunction: completion.VolumeNames(dockerCli), } @@ -35,11 +35,9 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runInspect(dockerCli command.Cli, opts inspectOptions) error { +func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error { client := dockerCli.Client() - ctx := context.Background() - getVolFunc := func(name string) (any, []byte, error) { i, err := client.VolumeInspect(ctx, name) return i, nil, err diff --git a/cli/command/volume/list.go b/cli/command/volume/list.go index fa1c1ceb97..e51bfe5e1c 100644 --- a/cli/command/volume/list.go +++ b/cli/command/volume/list.go @@ -35,7 +35,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { Short: "List volumes", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runList(dockerCli, options) + return runList(cmd.Context(), dockerCli, options) }, ValidArgsFunction: completion.NoComplete, } @@ -51,9 +51,9 @@ func newListCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runList(dockerCli command.Cli, options listOptions) error { +func runList(ctx context.Context, dockerCli command.Cli, options listOptions) error { client := dockerCli.Client() - volumes, err := client.VolumeList(context.Background(), volume.ListOptions{Filters: options.filter.Value()}) + volumes, err := client.VolumeList(ctx, volume.ListOptions{Filters: options.filter.Value()}) if err != nil { return err } diff --git a/cli/command/volume/prune.go b/cli/command/volume/prune.go index d4ed935da9..f86cf56f9c 100644 --- a/cli/command/volume/prune.go +++ b/cli/command/volume/prune.go @@ -30,7 +30,7 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command { Short: "Remove unused local volumes", Args: cli.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - spaceReclaimed, output, err := runPrune(dockerCli, options) + spaceReclaimed, output, err := runPrune(cmd.Context(), dockerCli, options) if err != nil { return err } @@ -60,7 +60,7 @@ Are you sure you want to continue?` Are you sure you want to continue?` ) -func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { +func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { pruneFilters := command.PruneFilters(dockerCli, options.filter.Value()) warning := unusedVolumesWarning @@ -80,7 +80,7 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint6 return 0, "", nil } - report, err := dockerCli.Client().VolumesPrune(context.Background(), pruneFilters) + report, err := dockerCli.Client().VolumesPrune(ctx, pruneFilters) if err != nil { return 0, "", err } @@ -98,6 +98,6 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint6 // RunPrune calls the Volume Prune API // This returns the amount of space reclaimed and a detailed output string -func RunPrune(dockerCli command.Cli, _ bool, filter opts.FilterOpt) (uint64, string, error) { - return runPrune(dockerCli, pruneOptions{force: true, filter: filter}) +func RunPrune(ctx context.Context, dockerCli command.Cli, _ bool, filter opts.FilterOpt) (uint64, string, error) { + return runPrune(ctx, dockerCli, pruneOptions{force: true, filter: filter}) } diff --git a/cli/command/volume/remove.go b/cli/command/volume/remove.go index a2abb5947c..df3dfe79a0 100644 --- a/cli/command/volume/remove.go +++ b/cli/command/volume/remove.go @@ -30,7 +30,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.volumes = args - return runRemove(dockerCli, &opts) + return runRemove(cmd.Context(), dockerCli, &opts) }, ValidArgsFunction: completion.VolumeNames(dockerCli), } @@ -41,9 +41,8 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runRemove(dockerCli command.Cli, opts *removeOptions) error { +func runRemove(ctx context.Context, dockerCli command.Cli, opts *removeOptions) error { client := dockerCli.Client() - ctx := context.Background() var errs []string diff --git a/cli/command/volume/update.go b/cli/command/volume/update.go index 26e0e4ba2f..c04c2ff8f5 100644 --- a/cli/command/volume/update.go +++ b/cli/command/volume/update.go @@ -20,7 +20,7 @@ func newUpdateCommand(dockerCli command.Cli) *cobra.Command { Short: "Update a volume (cluster volumes only)", Args: cli.RequiresMaxArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runUpdate(dockerCli, args[0], availability, cmd.Flags()) + return runUpdate(cmd.Context(), dockerCli, args[0], availability, cmd.Flags()) }, Annotations: map[string]string{ "version": "1.42", @@ -37,13 +37,12 @@ func newUpdateCommand(dockerCli command.Cli) *cobra.Command { return cmd } -func runUpdate(dockerCli command.Cli, volumeID, availability string, flags *pflag.FlagSet) error { +func runUpdate(ctx context.Context, dockerCli command.Cli, volumeID, availability string, flags *pflag.FlagSet) error { // TODO(dperny): For this earliest version, the only thing that can be // updated is Availability, which is necessary because to delete a cluster // volume, the availability must first be set to "drain" apiClient := dockerCli.Client() - ctx := context.Background() vol, _, err := apiClient.VolumeInspectWithRaw(ctx, volumeID) if err != nil { diff --git a/cli/compose/convert/service.go b/cli/compose/convert/service.go index ab18204cd4..708c5a7d20 100644 --- a/cli/compose/convert/service.go +++ b/cli/compose/convert/service.go @@ -1,6 +1,7 @@ package convert import ( + "context" "os" "sort" "strings" @@ -25,17 +26,18 @@ const ( // Services from compose-file types to engine API types func Services( + ctx context.Context, namespace Namespace, config *composetypes.Config, apiClient client.CommonAPIClient, ) (map[string]swarm.ServiceSpec, error) { result := make(map[string]swarm.ServiceSpec) for _, service := range config.Services { - secrets, err := convertServiceSecrets(apiClient, namespace, service.Secrets, config.Secrets) + secrets, err := convertServiceSecrets(ctx, apiClient, namespace, service.Secrets, config.Secrets) if err != nil { return nil, errors.Wrapf(err, "service %s", service.Name) } - configs, err := convertServiceConfigObjs(apiClient, namespace, service, config.Configs) + configs, err := convertServiceConfigObjs(ctx, apiClient, namespace, service, config.Configs) if err != nil { return nil, errors.Wrapf(err, "service %s", service.Name) } @@ -240,6 +242,7 @@ func convertServiceNetworks( // TODO: fix secrets API so that SecretAPIClient is not required here func convertServiceSecrets( + ctx context.Context, apiClient client.SecretAPIClient, namespace Namespace, secrets []composetypes.ServiceSecretConfig, @@ -267,7 +270,7 @@ func convertServiceSecrets( }) } - secrs, err := servicecli.ParseSecrets(apiClient, refs) + secrs, err := servicecli.ParseSecrets(ctx, apiClient, refs) if err != nil { return nil, err } @@ -284,6 +287,7 @@ func convertServiceSecrets( // // TODO: fix configs API so that ConfigsAPIClient is not required here func convertServiceConfigObjs( + ctx context.Context, apiClient client.ConfigAPIClient, namespace Namespace, service composetypes.ServiceConfig, @@ -342,7 +346,7 @@ func convertServiceConfigObjs( }) } - confs, err := servicecli.ParseConfigs(apiClient, refs) + confs, err := servicecli.ParseConfigs(ctx, apiClient, refs) if err != nil { return nil, err } diff --git a/cli/compose/convert/service_test.go b/cli/compose/convert/service_test.go index e5064973a4..3cf2ee9e03 100644 --- a/cli/compose/convert/service_test.go +++ b/cli/compose/convert/service_test.go @@ -507,7 +507,8 @@ func TestConvertServiceSecrets(t *testing.T) { }, nil }, } - refs, err := convertServiceSecrets(apiClient, namespace, secrets, secretSpecs) + ctx := context.Background() + refs, err := convertServiceSecrets(ctx, apiClient, namespace, secrets, secretSpecs) assert.NilError(t, err) expected := []*swarm.SecretReference{ { @@ -566,7 +567,8 @@ func TestConvertServiceConfigs(t *testing.T) { }, nil }, } - refs, err := convertServiceConfigObjs(apiClient, namespace, service, configSpecs) + ctx := context.Background() + refs, err := convertServiceConfigObjs(ctx, apiClient, namespace, service, configSpecs) assert.NilError(t, err) expected := []*swarm.ConfigReference{ { diff --git a/e2e/cli-plugins/plugins/nopersistentprerun/main.go b/e2e/cli-plugins/plugins/nopersistentprerun/main.go index 375d26bc68..5f07bf7e01 100644 --- a/e2e/cli-plugins/plugins/nopersistentprerun/main.go +++ b/e2e/cli-plugins/plugins/nopersistentprerun/main.go @@ -1,7 +1,6 @@ package main import ( - "context" "fmt" "github.com/docker/cli/cli-plugins/manager" @@ -18,7 +17,7 @@ func main() { // PersistentPreRunE: Not specified, we need to test that it works in the absence of an explicit call RunE: func(cmd *cobra.Command, args []string) error { cli := dockerCli.Client() - ping, err := cli.Ping(context.Background()) + ping, err := cli.Ping(cmd.Context()) if err != nil { return err }