github.com/vieux/docker@v0.6.3-0.20161004191708-e097c2a938c7/daemon/restart.go (about)

     1  package daemon
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/Sirupsen/logrus"
     7  	"github.com/docker/docker/container"
     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 err := daemon.containerRestart(container, seconds); err != nil {
    22  		return fmt.Errorf("Cannot restart container %s: %v", name, err)
    23  	}
    24  	return nil
    25  }
    26  
    27  // containerRestart attempts to gracefully stop and then start the
    28  // container. When stopping, wait for the given duration in seconds to
    29  // gracefully stop, before forcefully terminating the container. If
    30  // given a negative duration, wait forever for a graceful stop.
    31  func (daemon *Daemon) containerRestart(container *container.Container, seconds int) error {
    32  	// Avoid unnecessarily unmounting and then directly mounting
    33  	// the container when the container stops and then starts
    34  	// again
    35  	if err := daemon.Mount(container); err == nil {
    36  		defer daemon.Unmount(container)
    37  	}
    38  
    39  	if container.IsRunning() {
    40  		// set AutoRemove flag to false before stop so the container won't be
    41  		// removed during restart process
    42  		autoRemove := container.HostConfig.AutoRemove
    43  
    44  		container.HostConfig.AutoRemove = false
    45  		err := daemon.containerStop(container, seconds)
    46  		// restore AutoRemove irrespective of whether the stop worked or not
    47  		container.HostConfig.AutoRemove = autoRemove
    48  		// containerStop will write HostConfig to disk, we shall restore AutoRemove
    49  		// in disk too
    50  		if toDiskErr := container.ToDiskLocking(); toDiskErr != nil {
    51  			logrus.Errorf("Write container to disk error: %v", toDiskErr)
    52  		}
    53  
    54  		if err != nil {
    55  			return err
    56  		}
    57  	}
    58  
    59  	if err := daemon.containerStart(container, ""); err != nil {
    60  		return err
    61  	}
    62  
    63  	daemon.LogContainerEvent(container, "restart")
    64  	return nil
    65  }