cri-o/lib/stop.go
Sebastien Boeuf 1391c5c2fd crio: Ensure container state is stopped when calling StopContainer()
CRI-O works well with runc when stopping a container because as soon
as the container process returns, it can consider every container
resources such as its rootfs as being freed, and it can proceed
further by unmounting it.

But in case of virtualized runtime such as Clear Containers or Kata
Containers, the same rootfs is being mounted into the VM, usually as
a device being hotplugged. This means the runtime will need to be
triggered after the container process has returned. Particularly,
such runtimes should expect a call into "state" in order to realize
the container process is not running anymore, and it would trigger
the container to be officially stopped, proceeding to the necessary
unmounts.

The way this can be done from CRI-O, without impacting the case of
runc, is to explicitly wait for the container status to be updated
into "stopped" after the container process has returned. This way
CRI-O will call into "state" as long as it cannot see the container
status being updated properly, generating an error after a timeout.

Both PollUpdateStatusStopped() and WaitContainerStateStopped() make
use of go routines in order to support a timeout definition. They
follow the waitContainerStop() approach with chControl.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2018-03-02 14:55:29 -08:00

39 lines
1.2 KiB
Go

package lib
import (
"github.com/kubernetes-incubator/cri-o/oci"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
// ContainerStop stops a running container with a grace period (i.e., timeout).
func (c *ContainerServer) ContainerStop(ctx context.Context, container string, timeout int64) (string, error) {
ctr, err := c.LookupContainer(container)
if err != nil {
return "", errors.Wrapf(err, "failed to find container %s", container)
}
ctrID := ctr.ID()
cStatus := c.runtime.ContainerStatus(ctr)
switch cStatus.Status {
case oci.ContainerStatePaused:
return "", errors.Errorf("cannot stop paused container %s", ctrID)
default:
if cStatus.Status != oci.ContainerStateStopped {
if err := c.runtime.StopContainer(ctx, ctr, timeout); err != nil {
return "", errors.Wrapf(err, "failed to stop container %s", ctrID)
}
if err := c.runtime.WaitContainerStateStopped(ctx, ctr, timeout); err != nil {
return "", errors.Wrapf(err, "failed to get container 'stopped' status %s", ctrID)
}
if err := c.storageRuntimeServer.StopContainer(ctrID); err != nil {
return "", errors.Wrapf(err, "failed to unmount container %s", ctrID)
}
}
}
c.ContainerStateToDisk(ctr)
return ctrID, nil
}