Skip to content

Commit

Permalink
Merge pull request docker#4700 from thaJeztah/wire_up_contexts
Browse files Browse the repository at this point in the history
Plumb contexts through commands
  • Loading branch information
thaJeztah authored Dec 13, 2023
2 parents 2b63b4f + 5400a48 commit ae2b58f
Show file tree
Hide file tree
Showing 146 changed files with 409 additions and 470 deletions.
10 changes: 5 additions & 5 deletions cli/command/builder/prune.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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)

Expand All @@ -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,
Expand All @@ -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})
}
6 changes: 3 additions & 3 deletions cli/command/checkpoint/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand All @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions cli/command/checkpoint/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
Expand All @@ -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 {
Expand Down
6 changes: 3 additions & 3 deletions cli/command/checkpoint/remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
},
}

Expand All @@ -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,
})
Expand Down
13 changes: 10 additions & 3 deletions cli/command/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -441,6 +445,9 @@ func (cli *DockerCli) initialize() error {
return
}
}
if cli.baseCtx == nil {
cli.baseCtx = context.Background()
}
cli.initializeFromClient()
})
return cli.initErr
Expand Down Expand Up @@ -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
}
Expand Down
10 changes: 10 additions & 0 deletions cli/command/cli_options.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package command

import (
"context"
"io"
"os"
"strconv"
Expand Down Expand Up @@ -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 {
Expand Down
5 changes: 2 additions & 3 deletions cli/command/config/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand All @@ -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 != "-" {
Expand Down
5 changes: 2 additions & 3 deletions cli/command/config/inspect.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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"
Expand Down
5 changes: 2 additions & 3 deletions cli/command/config/ls.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand All @@ -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 {
Expand Down
5 changes: 2 additions & 3 deletions cli/command/config/remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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

Expand Down
2 changes: 1 addition & 1 deletion cli/command/container/attach.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
6 changes: 2 additions & 4 deletions cli/command/container/commit.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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,
Expand Down
6 changes: 2 additions & 4 deletions cli/command/container/cp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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)

Expand All @@ -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)
Expand Down
15 changes: 8 additions & 7 deletions cli/command/container/cp_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package container

import (
"context"
"io"
"os"
"runtime"
Expand Down Expand Up @@ -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)
})
}
Expand All @@ -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()))
Expand All @@ -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()))
Expand Down Expand Up @@ -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"))
}

Expand All @@ -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" {
Expand All @@ -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"
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions cli/command/container/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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}
Expand All @@ -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
}
Expand Down
Loading

0 comments on commit ae2b58f

Please sign in to comment.