restart.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package daemon // import "github.com/docker/docker/daemon"
  2. import (
  3. "context"
  4. "fmt"
  5. containertypes "github.com/docker/docker/api/types/container"
  6. "github.com/docker/docker/container"
  7. )
  8. // ContainerRestart stops and starts a container. It attempts to
  9. // gracefully stop the container within the given timeout, forcefully
  10. // stopping it if the timeout is exceeded. If given a negative
  11. // timeout, ContainerRestart will wait forever until a graceful
  12. // stop. Returns an error if the container cannot be found, or if
  13. // there is an underlying error at any stage of the restart.
  14. func (daemon *Daemon) ContainerRestart(ctx context.Context, name string, options containertypes.StopOptions) error {
  15. ctr, err := daemon.GetContainer(name)
  16. if err != nil {
  17. return err
  18. }
  19. err = daemon.containerRestart(ctx, daemon.config(), ctr, options)
  20. if err != nil {
  21. return fmt.Errorf("Cannot restart container %s: %v", name, err)
  22. }
  23. return nil
  24. }
  25. // containerRestart attempts to gracefully stop and then start the
  26. // container. When stopping, wait for the given duration in seconds to
  27. // gracefully stop, before forcefully terminating the container. If
  28. // given a negative duration, wait forever for a graceful stop.
  29. func (daemon *Daemon) containerRestart(ctx context.Context, daemonCfg *configStore, container *container.Container, options containertypes.StopOptions) error {
  30. // Determine isolation. If not specified in the hostconfig, use daemon default.
  31. actualIsolation := container.HostConfig.Isolation
  32. if containertypes.Isolation.IsDefault(actualIsolation) {
  33. actualIsolation = daemon.defaultIsolation
  34. }
  35. // Avoid unnecessarily unmounting and then directly mounting
  36. // the container when the container stops and then starts
  37. // again. We do not do this for Hyper-V isolated containers
  38. // (implying also on Windows) as the HCS must have exclusive
  39. // access to mount the containers filesystem inside the utility
  40. // VM.
  41. if !containertypes.Isolation.IsHyperV(actualIsolation) {
  42. if err := daemon.Mount(container); err == nil {
  43. defer daemon.Unmount(container)
  44. }
  45. }
  46. if container.IsRunning() {
  47. container.Lock()
  48. container.HasBeenManuallyRestarted = true
  49. container.Unlock()
  50. err := daemon.containerStop(ctx, container, options)
  51. if err != nil {
  52. return err
  53. }
  54. }
  55. if err := daemon.containerStart(ctx, daemonCfg, container, "", "", true); err != nil {
  56. return err
  57. }
  58. daemon.LogContainerEvent(container, "restart")
  59. return nil
  60. }