github.com/sams1990/dockerrepo@v17.12.1-ce-rc2+incompatible/daemon/restart.go (about)

     1  package daemon
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/docker/docker/container"
     7  	"github.com/sirupsen/logrus"
     8  )
     9  
    10  // ContainerRestart stops and starts a container. It attempts to
    11  // gracefully stop the container within the given timeout, forcefully
    12  // stopping it if the timeout is exceeded. If given a negative
    13  // timeout, ContainerRestart will wait forever until a graceful
    14  // stop. Returns an error if the container cannot be found, or if
    15  // there is an underlying error at any stage of the restart.
    16  func (daemon *Daemon) ContainerRestart(name string, seconds *int) error {
    17  	container, err := daemon.GetContainer(name)
    18  	if err != nil {
    19  		return err
    20  	}
    21  	if seconds == nil {
    22  		stopTimeout := container.StopTimeout()
    23  		seconds = &stopTimeout
    24  	}
    25  	if err := daemon.containerRestart(container, *seconds); err != nil {
    26  		return fmt.Errorf("Cannot restart container %s: %v", name, err)
    27  	}
    28  	return nil
    29  
    30  }
    31  
    32  // containerRestart attempts to gracefully stop and then start the
    33  // container. When stopping, wait for the given duration in seconds to
    34  // gracefully stop, before forcefully terminating the container. If
    35  // given a negative duration, wait forever for a graceful stop.
    36  func (daemon *Daemon) containerRestart(container *container.Container, seconds int) error {
    37  	// Avoid unnecessarily unmounting and then directly mounting
    38  	// the container when the container stops and then starts
    39  	// again
    40  	if err := daemon.Mount(container); err == nil {
    41  		defer daemon.Unmount(container)
    42  	}
    43  
    44  	if container.IsRunning() {
    45  		// set AutoRemove flag to false before stop so the container won't be
    46  		// removed during restart process
    47  		autoRemove := container.HostConfig.AutoRemove
    48  
    49  		container.HostConfig.AutoRemove = false
    50  		err := daemon.containerStop(container, seconds)
    51  		// restore AutoRemove irrespective of whether the stop worked or not
    52  		container.HostConfig.AutoRemove = autoRemove
    53  		// containerStop will write HostConfig to disk, we shall restore AutoRemove
    54  		// in disk too
    55  		if toDiskErr := daemon.checkpointAndSave(container); toDiskErr != nil {
    56  			logrus.Errorf("Write container to disk error: %v", toDiskErr)
    57  		}
    58  
    59  		if err != nil {
    60  			return err
    61  		}
    62  	}
    63  
    64  	if err := daemon.containerStart(container, "", "", true); err != nil {
    65  		return err
    66  	}
    67  
    68  	daemon.LogContainerEvent(container, "restart")
    69  	return nil
    70  }