restart.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package daemon
  2. import (
  3. "fmt"
  4. "github.com/Sirupsen/logrus"
  5. "github.com/docker/docker/container"
  6. )
  7. // ContainerRestart stops and starts a container. It attempts to
  8. // gracefully stop the container within the given timeout, forcefully
  9. // stopping it if the timeout is exceeded. If given a negative
  10. // timeout, ContainerRestart will wait forever until a graceful
  11. // stop. Returns an error if the container cannot be found, or if
  12. // there is an underlying error at any stage of the restart.
  13. func (daemon *Daemon) ContainerRestart(name string, seconds *int) error {
  14. container, err := daemon.GetContainer(name)
  15. if err != nil {
  16. return err
  17. }
  18. if seconds == nil {
  19. stopTimeout := container.StopTimeout()
  20. seconds = &stopTimeout
  21. }
  22. if err := daemon.containerRestart(container, *seconds); err != nil {
  23. return fmt.Errorf("Cannot restart container %s: %v", name, err)
  24. }
  25. return nil
  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. if container.IsRunning() {
  39. // set AutoRemove flag to false before stop so the container won't be
  40. // removed during restart process
  41. autoRemove := container.HostConfig.AutoRemove
  42. container.HostConfig.AutoRemove = false
  43. err := daemon.containerStop(container, seconds)
  44. // restore AutoRemove irrespective of whether the stop worked or not
  45. container.HostConfig.AutoRemove = autoRemove
  46. // containerStop will write HostConfig to disk, we shall restore AutoRemove
  47. // in disk too
  48. if toDiskErr := container.ToDiskLocking(); toDiskErr != nil {
  49. logrus.Errorf("Write container to disk error: %v", toDiskErr)
  50. }
  51. if err != nil {
  52. return err
  53. }
  54. }
  55. if err := daemon.containerStart(container, "", "", true); err != nil {
  56. return err
  57. }
  58. daemon.LogContainerEvent(container, "restart")
  59. return nil
  60. }