rm pod with podman run if ctr creation failed

Currently, if the container creation failed with
either run or create and you've used --pod with new:
the pod would be created nonetheless. This change ensures
the pod just created is also cleaned up in case
of container creation failure

Fixes #21228

Signed-off-by: danishprakash <danish.prakash@suse.com>
This commit is contained in:
danishprakash
2024-01-16 20:02:03 +05:30
parent 9fed92ba89
commit 1c88b12204
3 changed files with 42 additions and 0 deletions

View File

@ -180,6 +180,13 @@ func create(cmd *cobra.Command, args []string) error {
report, err := registry.ContainerEngine().ContainerCreate(registry.GetContext(), s)
if err != nil {
// if pod was created as part of run
// remove it in case ctr creation fails
if err := rmPodIfNecessary(cmd, s); err != nil {
if !errors.Is(err, define.ErrNoSuchPod) {
logrus.Error(err.Error())
}
}
return err
}
@ -385,6 +392,18 @@ func PullImage(imageName string, cliVals *entities.ContainerCreateOptions) (stri
return imageName, nil
}
func rmPodIfNecessary(cmd *cobra.Command, s *specgen.SpecGenerator) error {
if !strings.HasPrefix(cmd.Flag("pod").Value.String(), "new:") {
return nil
}
// errcheck not necessary since
// pod creation would've failed
podName := strings.Replace(s.Pod, "new:", "", 1)
_, err := registry.ContainerEngine().PodRm(context.Background(), []string{podName}, entities.PodRmOptions{})
return err
}
// createPodIfNecessary automatically creates a pod when requested. if the pod name
// has the form new:ID, the pod ID is created and the name in the spec generator is replaced
// with ID.

View File

@ -228,6 +228,13 @@ func run(cmd *cobra.Command, args []string) error {
registry.SetExitCode(report.ExitCode)
}
if err != nil {
// if pod was created as part of run
// remove it in case ctr creation fails
if err := rmPodIfNecessary(cmd, s); err != nil {
if !errors.Is(err, define.ErrNoSuchPod) {
logrus.Error(err.Error())
}
}
return err
}

View File

@ -1399,4 +1399,20 @@ search | $IMAGE |
run_podman rm -f -t0 $cid
}
@test "podman run - rm pod if container creation failed with -pod new:" {
run_podman run -d --name foobar $IMAGE hostname
cid=$output
podname=pod$(random_string)
run_podman 125 run --rm --pod "new:$podname" --name foobar $IMAGE hostname
is "$output" ".*creating container storage: the container name \"foobar\" is already in use by"
# pod should've been cleaned up
# if container creation failed
run_podman 1 pod exists $podname
run_podman rm $cid
run_podman rmi $(pause_image)
}
# vim: filetype=sh