summaryrefslogtreecommitdiff
path: root/libkpod/remove.go
blob: 529348840258b60f82bf67b0fe95e4a743d31d6e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package libkpod

import (
	"os"
	"path/filepath"

	"github.com/pkg/errors"
	"github.com/projectatomic/libpod/oci"
	"golang.org/x/net/context"
)

// Remove removes a container
func (c *ContainerServer) Remove(ctx context.Context, container string, force bool) (string, error) {
	ctr, err := c.LookupContainer(container)
	if err != nil {
		return "", err
	}
	ctrID := ctr.ID()

	cStatus := c.runtime.ContainerStatus(ctr)
	switch cStatus.Status {
	case oci.ContainerStatePaused:
		return "", errors.Errorf("cannot remove paused container %s", ctrID)
	case oci.ContainerStateCreated, oci.ContainerStateRunning:
		if force {
			_, err = c.ContainerStop(ctx, container, 10)
			if err != nil {
				return "", errors.Wrapf(err, "unable to stop container %s", ctrID)
			}
		} else {
			return "", errors.Errorf("cannot remove running container %s", ctrID)
		}
	}

	if err := c.runtime.DeleteContainer(ctr); err != nil {
		return "", errors.Wrapf(err, "failed to delete container %s", ctrID)
	}
	if err := os.Remove(filepath.Join(c.Config().RuntimeConfig.ContainerExitsDir, ctrID)); err != nil && !os.IsNotExist(err) {
		return "", errors.Wrapf(err, "failed to remove container exit file %s", ctrID)
	}
	c.RemoveContainer(ctr)

	if err := c.storageRuntimeServer.DeleteContainer(ctrID); err != nil {
		return "", errors.Wrapf(err, "failed to delete storage for container %s", ctrID)
	}

	c.ReleaseContainerName(ctr.Name())

	if err := c.ctrIDIndex.Delete(ctrID); err != nil {
		return "", err
	}
	return ctrID, nil
}