Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cli: deprecate cli.StatusError direct field usage #5666

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions cli-plugins/plugin/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/connhelper"
"github.com/docker/cli/cli/debug"
"github.com/docker/cli/internal"
"github.com/docker/docker/client"
"github.com/spf13/cobra"
"go.opentelemetry.io/otel"
Expand Down Expand Up @@ -93,14 +94,11 @@ func Run(makeCmd func(command.Cli) *cobra.Command, meta manager.Metadata) {
plugin := makeCmd(dockerCli)

if err := RunPlugin(dockerCli, plugin, meta); err != nil {
var stErr cli.StatusError
var stErr internal.StatusError
if errors.As(err, &stErr) {
_, _ = fmt.Fprintln(dockerCli.Err(), stErr)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you make StatusError internal, a CLI plugin won't be able to create such an error, and control the exit code

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm, as an interface it would force the plugin to implement their own error type and not rely on the struct. 🤔 - I'm wondering though if this is what we should do since plugins are essentially being forced to use the struct directly which to me seems bad as it makes it more difficult for the CLI to make any changes in the longer term and even more difficult knowing what contracts we actually have that we should respect.

The main case was to change the cli.StatusError{}.Status field to be of type error instead of type string. The reason being we want to be able to use errors.Is to match children of this error which is impossible with a string type for Status.

The second reason is to convert this to an interface so that third parties don't depend on this error type directly in their code. We are going to break third parties by changing cli.StatusError{}.Status -> cli.StatusError{}.Cause in any case so I took the opportunity to try and do it in one go instead of having to go through multiple such breaking changes in the future.

package main

import (
	"errors"
	"fmt"
)

type StatusError struct {
	Status error
	Code   int
}

func (s StatusError) Error() string {
	return s.Status.Error()
}

// NEED this to get the child
func (s StatusError) Unwrap() error {
	return s.Status
}

type barError struct{}

func (b barError) Error() string {
	return "I am bar error"
}

func bar() error {
	return barError{}
}

func foo() error {
	err := bar()
	return StatusError{
		Status: fmt.Errorf("I am wrapping this error: %w", err),
		Code:   125,
	}
}

func main() {
	err := foo()
	if errors.Is(err, barError{}) {
		fmt.Printf("Is bar error: %s\n", err)
	}
}

https://go.dev/play/p/eQi-908JZhR

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just add a new Cause attribute to StatusError and implement Unwrap() error ? Doing so you can use errors.Is as long as cause has been set, which would have lower impact - as this change requires major changes anyway

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes this option can be pursued which would make things easier in the near term.

My goal was to try to create a clear boundary for third parties to use instead - whilst we get to do a major release (v28). Since we didn't clearly define what "internal" code is in the past, we now have this situation where changing the CLI code can come with a lot of unknown pitfalls.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess you could say I'm trying to kill two birds with one stone.

  1. match child error types
  2. reduce technical debt

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

understood, but impact is huge for our ecosystem.
keeping code clean is easier when you have no users.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I'll update the code. Perhaps we could do a slow transition to an exported interface?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ndeloof i pushed some changes in a separate commit, let me know what you think

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my preference goes for #5778, as lower impact and simplest solution for the need

// StatusError should only be used for errors, and all errors should
// have a non-zero exit status, so never exit with 0
if stErr.StatusCode == 0 { // FIXME(thaJeztah): this should never be used with a zero status-code. Check if we do this anywhere.
stErr.StatusCode = 1
}
_, _ = fmt.Fprintln(dockerCli.Err(), stErr)
os.Exit(stErr.StatusCode)
}
_, _ = fmt.Fprintln(dockerCli.Err(), err)
Expand Down
5 changes: 3 additions & 2 deletions cli/cobra.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
pluginmanager "github.com/docker/cli/cli-plugins/manager"
"github.com/docker/cli/cli/command"
cliflags "github.com/docker/cli/cli/flags"
"github.com/docker/cli/internal"
"github.com/docker/docker/pkg/homedir"
"github.com/docker/docker/registry"
"github.com/fvbommel/sortorder"
Expand Down Expand Up @@ -92,8 +93,8 @@ func FlagErrorFunc(cmd *cobra.Command, err error) error {
return nil
}

return StatusError{
Status: fmt.Sprintf("%s\n\nUsage: %s\n\nRun '%s --help' for more information", err, cmd.UseLine(), cmd.CommandPath()),
return internal.StatusError{
Cause: fmt.Errorf("%w\n\nUsage: %s\n\nRun '%s --help' for more information", err, cmd.UseLine(), cmd.CommandPath()),
StatusCode: 125,
}
}
Expand Down
3 changes: 2 additions & 1 deletion cli/command/config/inspect.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/formatter"
flagsHelper "github.com/docker/cli/cli/flags"
"github.com/docker/cli/internal"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -67,7 +68,7 @@ func RunConfigInspect(ctx context.Context, dockerCli command.Cli, opts InspectOp
}

if err := InspectFormatWrite(configCtx, opts.Names, getRef); err != nil {
return cli.StatusError{StatusCode: 1, Status: err.Error()}
return internal.StatusError{StatusCode: 1, Cause: err}
}
return nil
}
3 changes: 2 additions & 1 deletion cli/command/container/attach.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/internal"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/moby/sys/signal"
Expand Down Expand Up @@ -161,7 +162,7 @@ func getExitStatus(errC <-chan error, resultC <-chan container.WaitResponse) err
return errors.New(result.Error.Message)
}
if result.StatusCode != 0 {
return cli.StatusError{StatusCode: int(result.StatusCode)}
return internal.StatusError{StatusCode: int(result.StatusCode)}
}
case err := <-errC:
return err
Expand Down
4 changes: 2 additions & 2 deletions cli/command/container/attach_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"io"
"testing"

"github.com/docker/cli/cli"
"github.com/docker/cli/internal"
"github.com/docker/cli/internal/test"
"github.com/docker/docker/api/types/container"
"github.com/pkg/errors"
Expand Down Expand Up @@ -110,7 +110,7 @@ func TestGetExitStatus(t *testing.T) {
result: &container.WaitResponse{
StatusCode: 15,
},
expectedError: cli.StatusError{StatusCode: 15},
expectedError: internal.StatusError{StatusCode: 15},
},
}

Expand Down
13 changes: 7 additions & 6 deletions cli/command/container/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/docker/cli/cli/command/image"
"github.com/docker/cli/cli/internal/jsonstream"
"github.com/docker/cli/cli/streams"
"github.com/docker/cli/internal"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types/container"
imagetypes "github.com/docker/docker/api/types/image"
Expand Down Expand Up @@ -92,8 +93,8 @@ func NewCreateCommand(dockerCli command.Cli) *cobra.Command {

func runCreate(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, options *createOptions, copts *containerOptions) error {
if err := validatePullOpt(options.pull); err != nil {
return cli.StatusError{
Status: withHelp(err, "create").Error(),
return internal.StatusError{
Cause: withHelp(err, "create"),
StatusCode: 125,
}
}
Expand All @@ -109,14 +110,14 @@ func runCreate(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet,
copts.env = *opts.NewListOptsRef(&newEnv, nil)
containerCfg, err := parse(flags, copts, dockerCli.ServerInfo().OSType)
if err != nil {
return cli.StatusError{
Status: withHelp(err, "create").Error(),
return internal.StatusError{
Cause: withHelp(err, "create"),
StatusCode: 125,
}
}
if err = validateAPIVersion(containerCfg, dockerCli.Client().ClientVersion()); err != nil {
return cli.StatusError{
Status: withHelp(err, "create").Error(),
return internal.StatusError{
Cause: withHelp(err, "create"),
StatusCode: 125,
}
}
Expand Down
4 changes: 2 additions & 2 deletions cli/command/container/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (
"strings"
"testing"

"github.com/docker/cli/cli"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/internal"
"github.com/docker/cli/internal/test"
"github.com/docker/cli/internal/test/notary"
"github.com/docker/docker/api/types/container"
Expand Down Expand Up @@ -185,7 +185,7 @@ func TestCreateContainerImagePullPolicyInvalid(t *testing.T) {
&containerOptions{},
)

statusErr := cli.StatusError{}
var statusErr internal.StatusError
assert.Check(t, errors.As(err, &statusErr))
assert.Check(t, is.Equal(statusErr.StatusCode, 125))
assert.Check(t, is.ErrorContains(err, tc.ExpectedErrMsg))
Expand Down
5 changes: 3 additions & 2 deletions cli/command/container/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/internal"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
Expand Down Expand Up @@ -206,11 +207,11 @@ func getExecExitStatus(ctx context.Context, apiClient client.ContainerAPIClient,
if !client.IsErrConnectionFailed(err) {
return err
}
return cli.StatusError{StatusCode: -1}
return internal.StatusError{StatusCode: -1}
}
status := resp.ExitCode
if status != 0 {
return cli.StatusError{StatusCode: status}
return internal.StatusError{StatusCode: status}
}
return nil
}
Expand Down
4 changes: 2 additions & 2 deletions cli/command/container/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import (
"os"
"testing"

"github.com/docker/cli/cli"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/internal"
"github.com/docker/cli/internal/test"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types"
Expand Down Expand Up @@ -231,7 +231,7 @@ func TestGetExecExitStatus(t *testing.T) {
},
{
exitCode: 15,
expectedError: cli.StatusError{StatusCode: 15},
expectedError: internal.StatusError{StatusCode: 15},
},
}

Expand Down
31 changes: 16 additions & 15 deletions cli/command/container/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/internal"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types/container"
"github.com/moby/sys/signal"
Expand Down Expand Up @@ -84,8 +85,8 @@ func NewRunCommand(dockerCli command.Cli) *cobra.Command {

func runRun(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, ropts *runOptions, copts *containerOptions) error {
if err := validatePullOpt(ropts.pull); err != nil {
return cli.StatusError{
Status: withHelp(err, "run").Error(),
return internal.StatusError{
Cause: withHelp(err, "run"),
StatusCode: 125,
}
}
Expand All @@ -102,14 +103,14 @@ func runRun(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, ro
containerCfg, err := parse(flags, copts, dockerCli.ServerInfo().OSType)
// just in case the parse does not exit
if err != nil {
return cli.StatusError{
Status: withHelp(err, "run").Error(),
return internal.StatusError{
Cause: withHelp(err, "run"),
StatusCode: 125,
}
}
if err = validateAPIVersion(containerCfg, dockerCli.CurrentVersion()); err != nil {
return cli.StatusError{
Status: withHelp(err, "run").Error(),
return internal.StatusError{
Cause: withHelp(err, "run"),
StatusCode: 125,
}
}
Expand Down Expand Up @@ -241,15 +242,15 @@ func runContainer(ctx context.Context, dockerCli command.Cli, runOpts *runOption
}
status := <-statusChan
if status != 0 {
return cli.StatusError{StatusCode: status}
return internal.StatusError{StatusCode: status}
}
case status := <-statusChan:
// notify hijackedIOStreamer that we're exiting and wait
// so that the terminal can be restored.
cancelFun()
<-errCh
if status != 0 {
return cli.StatusError{StatusCode: status}
return internal.StatusError{StatusCode: status}
}
}

Expand Down Expand Up @@ -311,7 +312,7 @@ func withHelp(err error, commandName string) error {

// toStatusError attempts to detect specific error-conditions to assign
// an appropriate exit-code for situations where the problem originates
// from the container. It returns [cli.StatusError] with the original
// from the container. It returns [internal.StatusError] with the original
// error message and the Status field set as follows:
//
// - 125: for generic failures sent back from the daemon
Expand All @@ -323,21 +324,21 @@ func toStatusError(err error) error {
errMsg := err.Error()

if strings.Contains(errMsg, "executable file not found") || strings.Contains(errMsg, "no such file or directory") || strings.Contains(errMsg, "system cannot find the file specified") {
return cli.StatusError{
Status: withHelp(err, "run").Error(),
return internal.StatusError{
Cause: withHelp(err, "run"),
StatusCode: 127,
}
}

if strings.Contains(errMsg, syscall.EACCES.Error()) || strings.Contains(errMsg, syscall.EISDIR.Error()) {
return cli.StatusError{
Status: withHelp(err, "run").Error(),
return internal.StatusError{
Cause: withHelp(err, "run"),
StatusCode: 126,
}
}

return cli.StatusError{
Status: withHelp(err, "run").Error(),
return internal.StatusError{
Cause: withHelp(err, "run"),
StatusCode: 125,
}
}
18 changes: 9 additions & 9 deletions cli/command/container/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import (
"time"

"github.com/creack/pty"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/streams"
"github.com/docker/cli/internal"
"github.com/docker/cli/internal/test"
"github.com/docker/cli/internal/test/notary"
"github.com/docker/docker/api/types"
Expand Down Expand Up @@ -131,7 +131,7 @@ func TestRunAttach(t *testing.T) {

select {
case cmdErr := <-cmdErrC:
assert.Equal(t, cmdErr, cli.StatusError{
assert.Equal(t, cmdErr, internal.StatusError{
StatusCode: 33,
})
case <-time.After(2 * time.Second):
Expand Down Expand Up @@ -213,7 +213,7 @@ func TestRunAttachTermination(t *testing.T) {

select {
case cmdErr := <-cmdErrC:
assert.Equal(t, cmdErr, cli.StatusError{
assert.Equal(t, cmdErr, internal.StatusError{
StatusCode: 130,
})
case <-time.After(2 * time.Second):
Expand Down Expand Up @@ -289,10 +289,10 @@ func TestRunPullTermination(t *testing.T) {

select {
case cmdErr := <-cmdErrC:
assert.Equal(t, cmdErr, cli.StatusError{
StatusCode: 125,
Status: "docker: context canceled\n\nRun 'docker run --help' for more information",
})
assert.ErrorIs(t, cmdErr, context.Canceled)
v, ok := cmdErr.(internal.StatusError)
assert.Check(t, ok)
assert.Check(t, is.Equal(v.StatusCode, 125))
case <-time.After(10 * time.Second):
t.Fatal("cmd did not return before the timeout")
}
Expand Down Expand Up @@ -342,7 +342,7 @@ func TestRunCommandWithContentTrustErrors(t *testing.T) {
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
err := cmd.Execute()
statusErr := cli.StatusError{}
statusErr := internal.StatusError{}
assert.Check(t, errors.As(err, &statusErr))
assert.Check(t, is.Equal(statusErr.StatusCode, 125))
assert.Check(t, is.ErrorContains(err, tc.expectedError))
Expand Down Expand Up @@ -375,7 +375,7 @@ func TestRunContainerImagePullPolicyInvalid(t *testing.T) {
&containerOptions{},
)

statusErr := cli.StatusError{}
statusErr := internal.StatusError{}
assert.Check(t, errors.As(err, &statusErr))
assert.Check(t, is.Equal(statusErr.StatusCode, 125))
assert.Check(t, is.ErrorContains(err, tc.ExpectedErrMsg))
Expand Down
3 changes: 2 additions & 1 deletion cli/command/container/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/internal"
"github.com/docker/docker/api/types/container"
"github.com/moby/sys/signal"
"github.com/moby/term"
Expand Down Expand Up @@ -172,7 +173,7 @@ func RunStart(ctx context.Context, dockerCli command.Cli, opts *StartOptions) er
}

if status := <-statusChan; status != 0 {
return cli.StatusError{StatusCode: status}
return internal.StatusError{StatusCode: status}
}
return nil
case opts.Checkpoint != "":
Expand Down
3 changes: 2 additions & 1 deletion cli/command/image/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/docker/cli/cli/command/image/build"
"github.com/docker/cli/cli/internal/jsonstream"
"github.com/docker/cli/cli/streams"
"github.com/docker/cli/internal"
"github.com/docker/cli/opts"
"github.com/docker/docker/api"
"github.com/docker/docker/api/types"
Expand Down Expand Up @@ -372,7 +373,7 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions)
if options.quiet {
fmt.Fprintf(dockerCli.Err(), "%s%s", progBuff, buildBuff)
}
return cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
return internal.StatusError{Cause: jerr, StatusCode: jerr.Code}
}
return err
}
Expand Down
Loading
Loading