github.com/containers/libpod@v1.9.4-0.20220419124438-4284fd425507/cmd/podman/cleanup.go (about)

     1  //+build !remoteclient
     2  
     3  package main
     4  
     5  import (
     6  	"github.com/containers/libpod/cmd/podman/cliconfig"
     7  	"github.com/containers/libpod/pkg/adapter"
     8  	"github.com/pkg/errors"
     9  	"github.com/spf13/cobra"
    10  )
    11  
    12  var (
    13  	cleanupCommand     cliconfig.CleanupValues
    14  	cleanupDescription = `
    15     podman container cleanup
    16  
    17     Cleans up mount points and network stacks on one or more containers from the host. The container name or ID can be used. This command is used internally when running containers, but can also be used if container cleanup has failed when a container exits.
    18  `
    19  	_cleanupCommand = &cobra.Command{
    20  		Use:   "cleanup [flags] CONTAINER [CONTAINER...]",
    21  		Short: "Cleanup network and mountpoints of one or more containers",
    22  		Long:  cleanupDescription,
    23  		RunE: func(cmd *cobra.Command, args []string) error {
    24  			cleanupCommand.InputArgs = args
    25  			cleanupCommand.GlobalFlags = MainGlobalOpts
    26  			cleanupCommand.Remote = remoteclient
    27  			return cleanupCmd(&cleanupCommand)
    28  		},
    29  		Args: func(cmd *cobra.Command, args []string) error {
    30  			return checkAllLatestAndCIDFile(cmd, args, false, false)
    31  		},
    32  		Example: `podman container cleanup --latest
    33    podman container cleanup ctrID1 ctrID2 ctrID3
    34    podman container cleanup --all`,
    35  	}
    36  )
    37  
    38  func init() {
    39  	cleanupCommand.Command = _cleanupCommand
    40  	cleanupCommand.SetHelpTemplate(HelpTemplate())
    41  	cleanupCommand.SetUsageTemplate(UsageTemplate())
    42  	flags := cleanupCommand.Flags()
    43  
    44  	flags.BoolVarP(&cleanupCommand.All, "all", "a", false, "Cleans up all containers")
    45  	flags.BoolVarP(&cleanupCommand.Latest, "latest", "l", false, "Act on the latest container podman is aware of")
    46  	flags.BoolVar(&cleanupCommand.Remove, "rm", false, "After cleanup, remove the container entirely")
    47  	flags.BoolVar(&cleanupCommand.RemoveImage, "rmi", false, "After cleanup, remove the image entirely")
    48  	markFlagHiddenForRemoteClient("latest", flags)
    49  }
    50  
    51  func cleanupCmd(c *cliconfig.CleanupValues) error {
    52  	runtime, err := adapter.GetRuntime(getContext(), &c.PodmanCommand)
    53  	if err != nil {
    54  		return errors.Wrapf(err, "could not get runtime")
    55  	}
    56  	defer runtime.DeferredShutdown(false)
    57  
    58  	ok, failures, err := runtime.CleanupContainers(getContext(), c)
    59  	if err != nil {
    60  		return err
    61  	}
    62  
    63  	return printCmdResults(ok, failures)
    64  }