Skip to content

Commit 33d1477

Browse files
aledbfclaude
andcommitted
fix(cli): report a failed --remove-existing-container removal
up ignored the error removing the existing container and went on. The reference fails up with "An error occurred setting up the container." and the message "Command failed: <docker> rm -f <id>" (with the container ID for a Compose configuration), exit 1. The removal is now logged as the reference's start/stop pair, "Removing Existing Container" ("Removing existing container." for Compose), instead of an info line. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent cf21a9c commit 33d1477

2 files changed

Lines changed: 111 additions & 2 deletions

File tree

‎internal/cli/up.go‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -321,8 +321,9 @@ func runUp(ctx context.Context, out Output, opts *upOpts) error {
321321

322322
existingIDs, _ := engine.ListContainers(ctx, true, idLabels)
323323
if len(existingIDs) > 0 && opts.removeExisting {
324-
logger.Write(fmt.Sprintf("Removing existing container %s...", existingIDs[0]), log.LevelInfo)
325-
_ = engine.RemoveContainer(ctx, existingIDs[0])
324+
if err := removeExistingContainer(ctx, engine, logger, cfg, opts.dockerPath, existingIDs[0]); err != nil {
325+
return writeErrorJSON(out, coreerrors.ToErrorOutput(err))
326+
}
326327
existingIDs = nil
327328
}
328329

@@ -1046,6 +1047,42 @@ func hookRemoteEnv(probed map[string]string, remoteEnvs []string, cfgRemoteEnv m
10461047
return append(env, secrets...)
10471048
}
10481049

1050+
type containerRemover interface {
1051+
RemoveContainer(ctx context.Context, id string) error
1052+
}
1053+
1054+
type containerRemoveError struct {
1055+
dockerPath string
1056+
id string
1057+
err error
1058+
}
1059+
1060+
func (e *containerRemoveError) Error() string {
1061+
return fmt.Sprintf("Command failed: %s rm -f %s", e.dockerPath, e.id)
1062+
}
1063+
1064+
func (e *containerRemoveError) Unwrap() error { return e.err }
1065+
1066+
func removeExistingContainer(ctx context.Context, engine containerRemover, logger log.Logger, cfg *config.DevContainer, dockerPath, id string) error {
1067+
text := "Removing Existing Container"
1068+
if cfg.IsComposeConfig() {
1069+
text = "Removing existing container."
1070+
}
1071+
start := logger.Start(text)
1072+
if err := engine.RemoveContainer(ctx, id); err != nil {
1073+
removeErr := &coreerrors.ContainerError{
1074+
Description: "An error occurred setting up the container.",
1075+
OriginalError: &containerRemoveError{dockerPath: cmp.Or(dockerPath, "docker"), id: id, err: err},
1076+
}
1077+
if cfg.IsComposeConfig() {
1078+
removeErr.ContainerID = id
1079+
}
1080+
return removeErr
1081+
}
1082+
logger.Stop(text, start)
1083+
return nil
1084+
}
1085+
10491086
func hookContainerError(hookErr error, containerID, fallback string) *coreerrors.ContainerError {
10501087
he, ok := errors.AsType[*lifecycle.HookError](hookErr)
10511088
if !ok {

‎internal/cli/up_held_test.go‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
2424

2525
"github.com/devcontainers/cli/internal/config"
26+
coreerrors "github.com/devcontainers/cli/internal/errors"
2627
"github.com/devcontainers/cli/internal/docker"
2728
"github.com/devcontainers/cli/internal/imagemeta"
2829
"github.com/devcontainers/cli/internal/lifecycle"
@@ -656,3 +657,74 @@ func TestUpFeatureBuildOptionsCarryTheContainerEnv(t *testing.T) {
656657
t.Errorf("ContainerEnv = %v, want the config's %v", got, cfg.ContainerEnv)
657658
}
658659
}
660+
661+
type fakeRemover struct {
662+
removed []string
663+
err error
664+
}
665+
666+
func (f *fakeRemover) RemoveContainer(_ context.Context, id string) error {
667+
f.removed = append(f.removed, id)
668+
return f.err
669+
}
670+
671+
func TestRemoveExistingContainer(t *testing.T) {
672+
daemonErr := errors.New("removal of container abc is already in progress")
673+
image := &config.DevContainer{}
674+
compose := &config.DevContainer{DockerComposeFile: config.StringOrStrings{"docker-compose.yml"}}
675+
for _, tc := range []struct {
676+
name string
677+
cfg *config.DevContainer
678+
dockerPath string
679+
removeErr error
680+
wantEvents []string
681+
wantErr *coreerrors.ErrorOutput
682+
}{
683+
{"image config", image, "", nil, []string{"start:Removing Existing Container", "stop:Removing Existing Container"}, nil},
684+
{"compose config", compose, "", nil, []string{"start:Removing existing container.", "stop:Removing existing container."}, nil},
685+
{"image config fails", image, "", daemonErr, []string{"start:Removing Existing Container"}, &coreerrors.ErrorOutput{
686+
Outcome: "error", Message: "Command failed: docker rm -f abc", Description: "An error occurred setting up the container.",
687+
}},
688+
{"compose config fails", compose, "/usr/bin/podman", daemonErr, []string{"start:Removing existing container."}, &coreerrors.ErrorOutput{
689+
Outcome: "error", Message: "Command failed: /usr/bin/podman rm -f abc", Description: "An error occurred setting up the container.", ContainerID: "abc",
690+
}},
691+
} {
692+
t.Run(tc.name, func(t *testing.T) {
693+
var logged bytes.Buffer
694+
logger := log.New(log.Options{Writer: &logged, Format: "json", Level: log.LevelTrace})
695+
engine := &fakeRemover{err: tc.removeErr}
696+
697+
err := removeExistingContainer(context.Background(), engine, logger, tc.cfg, tc.dockerPath, "abc")
698+
699+
if !slices.Equal(engine.removed, []string{"abc"}) {
700+
t.Errorf("removed %q, want [abc]", engine.removed)
701+
}
702+
var events []string
703+
for line := range strings.Lines(logged.String()) {
704+
var e log.Event
705+
if err := json.Unmarshal([]byte(line), &e); err != nil {
706+
t.Fatalf("log line %q: %v", line, err)
707+
}
708+
events = append(events, e.Type+":"+e.Text)
709+
}
710+
if !slices.Equal(events, tc.wantEvents) {
711+
t.Errorf("events = %q, want %q", events, tc.wantEvents)
712+
}
713+
if tc.wantErr == nil {
714+
if err != nil {
715+
t.Fatalf("err = %v, want nil", err)
716+
}
717+
return
718+
}
719+
if err == nil {
720+
t.Fatal("err = nil, want the removal failure")
721+
}
722+
if got := coreerrors.ToErrorOutput(err); !reflect.DeepEqual(got, *tc.wantErr) {
723+
t.Errorf("error output = %+v, want %+v", got, *tc.wantErr)
724+
}
725+
if !errors.Is(err, daemonErr) {
726+
t.Errorf("err = %v, want it to wrap the daemon error", err)
727+
}
728+
})
729+
}
730+
}

0 commit comments

Comments
 (0)