diff options
Diffstat (limited to 'pkg/adapter/containers.go')
-rw-r--r-- | pkg/adapter/containers.go | 90 |
1 files changed, 90 insertions, 0 deletions
diff --git a/pkg/adapter/containers.go b/pkg/adapter/containers.go index 9f5fc7e65..9ec897a60 100644 --- a/pkg/adapter/containers.go +++ b/pkg/adapter/containers.go @@ -786,3 +786,93 @@ func (r *LocalRuntime) Top(cli *cliconfig.TopValues) ([]string, error) { } return container.Top(descriptors) } + +// Prune removes stopped containers +func (r *LocalRuntime) Prune(ctx context.Context, maxWorkers int, force bool) ([]string, map[string]error, error) { + var ( + ok = []string{} + failures = map[string]error{} + err error + ) + + logrus.Debugf("Setting maximum rm workers to %d", maxWorkers) + + filter := func(c *libpod.Container) bool { + state, err := c.State() + if err != nil { + logrus.Error(err) + return false + } + if c.PodID() != "" { + return false + } + if state == libpod.ContainerStateStopped || state == libpod.ContainerStateExited { + return true + } + return false + } + delContainers, err := r.Runtime.GetContainers(filter) + if err != nil { + return ok, failures, err + } + if len(delContainers) < 1 { + return ok, failures, err + } + pool := shared.NewPool("prune", maxWorkers, len(delContainers)) + for _, c := range delContainers { + ctr := c + pool.Add(shared.Job{ + ID: ctr.ID(), + Fn: func() error { + err := r.Runtime.RemoveContainer(ctx, ctr, force, false) + if err != nil { + logrus.Debugf("Failed to prune container %s: %s", ctr.ID(), err.Error()) + } + return err + }, + }) + } + return pool.Run() +} + +// CleanupContainers any leftovers bits of stopped containers +func (r *LocalRuntime) CleanupContainers(ctx context.Context, cli *cliconfig.CleanupValues) ([]string, map[string]error, error) { + var ( + ok = []string{} + failures = map[string]error{} + ) + + ctrs, err := shortcuts.GetContainersByContext(cli.All, cli.Latest, cli.InputArgs, r.Runtime) + if err != nil { + return ok, failures, err + } + + for _, ctr := range ctrs { + if cli.Remove { + err = removeContainer(ctx, ctr, r) + } else { + err = cleanupContainer(ctx, ctr, r) + } + + if err == nil { + ok = append(ok, ctr.ID()) + } else { + failures[ctr.ID()] = err + } + } + return ok, failures, nil +} + +func removeContainer(ctx context.Context, ctr *libpod.Container, runtime *LocalRuntime) error { + if err := runtime.RemoveContainer(ctx, ctr, false, true); err != nil { + return errors.Wrapf(err, "failed to cleanup and remove container %v", ctr.ID()) + } + return nil +} + +func cleanupContainer(ctx context.Context, ctr *libpod.Container, runtime *LocalRuntime) error { + if err := ctr.Cleanup(ctx); err != nil { + return errors.Wrapf(err, "failed to cleanup container %v", ctr.ID()) + } + return nil +} |