start.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package daemon // import "github.com/docker/docker/daemon"
  2. import (
  3. "context"
  4. "runtime"
  5. "time"
  6. "github.com/docker/docker/api/types"
  7. containertypes "github.com/docker/docker/api/types/container"
  8. "github.com/docker/docker/container"
  9. "github.com/docker/docker/errdefs"
  10. "github.com/docker/docker/libcontainerd"
  11. "github.com/pkg/errors"
  12. "github.com/sirupsen/logrus"
  13. )
  14. // ContainerStart starts a container.
  15. func (daemon *Daemon) ContainerStart(ctx context.Context, name string, hostConfig *containertypes.HostConfig, checkpoint string, checkpointDir string) error {
  16. if checkpoint != "" && !daemon.HasExperimental() {
  17. return errdefs.InvalidParameter(errors.New("checkpoint is only supported in experimental mode"))
  18. }
  19. ctr, err := daemon.GetContainer(name)
  20. if err != nil {
  21. return err
  22. }
  23. validateState := func() error {
  24. ctr.Lock()
  25. defer ctr.Unlock()
  26. if ctr.Paused {
  27. return errdefs.Conflict(errors.New("cannot start a paused container, try unpause instead"))
  28. }
  29. if ctr.Running {
  30. return containerNotModifiedError{running: true}
  31. }
  32. if ctr.RemovalInProgress || ctr.Dead {
  33. return errdefs.Conflict(errors.New("container is marked for removal and cannot be started"))
  34. }
  35. return nil
  36. }
  37. if err := validateState(); err != nil {
  38. return err
  39. }
  40. // Windows does not have the backwards compatibility issue here.
  41. if runtime.GOOS != "windows" {
  42. // This is kept for backward compatibility - hostconfig should be passed when
  43. // creating a container, not during start.
  44. if hostConfig != nil {
  45. logrus.Warn("DEPRECATED: Setting host configuration options when the container starts is deprecated and has been removed in Docker 1.12")
  46. oldNetworkMode := ctr.HostConfig.NetworkMode
  47. if err := daemon.setSecurityOptions(ctr, hostConfig); err != nil {
  48. return errdefs.InvalidParameter(err)
  49. }
  50. if err := daemon.mergeAndVerifyLogConfig(&hostConfig.LogConfig); err != nil {
  51. return errdefs.InvalidParameter(err)
  52. }
  53. if err := daemon.setHostConfig(ctr, hostConfig); err != nil {
  54. return errdefs.InvalidParameter(err)
  55. }
  56. newNetworkMode := ctr.HostConfig.NetworkMode
  57. if string(oldNetworkMode) != string(newNetworkMode) {
  58. // if user has change the network mode on starting, clean up the
  59. // old networks. It is a deprecated feature and has been removed in Docker 1.12
  60. ctr.NetworkSettings.Networks = nil
  61. }
  62. if err := ctr.CheckpointTo(daemon.containersReplica); err != nil {
  63. return errdefs.System(err)
  64. }
  65. ctr.InitDNSHostConfig()
  66. }
  67. } else {
  68. if hostConfig != nil {
  69. return errdefs.InvalidParameter(errors.New("Supplying a hostconfig on start is not supported. It should be supplied on create"))
  70. }
  71. }
  72. // check if hostConfig is in line with the current system settings.
  73. // It may happen cgroups are umounted or the like.
  74. if _, err = daemon.verifyContainerSettings(ctr.HostConfig, nil, false); err != nil {
  75. return errdefs.InvalidParameter(err)
  76. }
  77. // Adapt for old containers in case we have updates in this function and
  78. // old containers never have chance to call the new function in create stage.
  79. if hostConfig != nil {
  80. if err := daemon.adaptContainerSettings(ctr.HostConfig, false); err != nil {
  81. return errdefs.InvalidParameter(err)
  82. }
  83. }
  84. return daemon.containerStart(ctx, ctr, checkpoint, checkpointDir, true)
  85. }
  86. // containerStart prepares the container to run by setting up everything the
  87. // container needs, such as storage and networking, as well as links
  88. // between containers. The container is left waiting for a signal to
  89. // begin running.
  90. func (daemon *Daemon) containerStart(ctx context.Context, container *container.Container, checkpoint string, checkpointDir string, resetRestartManager bool) (retErr error) {
  91. start := time.Now()
  92. container.Lock()
  93. defer container.Unlock()
  94. if resetRestartManager && container.Running { // skip this check if already in restarting step and resetRestartManager==false
  95. return nil
  96. }
  97. if container.RemovalInProgress || container.Dead {
  98. return errdefs.Conflict(errors.New("container is marked for removal and cannot be started"))
  99. }
  100. if checkpointDir != "" {
  101. // TODO(mlaventure): how would we support that?
  102. return errdefs.Forbidden(errors.New("custom checkpointdir is not supported"))
  103. }
  104. // if we encounter an error during start we need to ensure that any other
  105. // setup has been cleaned up properly
  106. defer func() {
  107. if retErr != nil {
  108. container.SetError(retErr)
  109. // if no one else has set it, make sure we don't leave it at zero
  110. if container.ExitCode() == 0 {
  111. container.SetExitCode(exitUnknown)
  112. }
  113. if err := container.CheckpointTo(daemon.containersReplica); err != nil {
  114. logrus.Errorf("%s: failed saving state on start failure: %v", container.ID, err)
  115. }
  116. container.Reset(false)
  117. daemon.Cleanup(container)
  118. // if containers AutoRemove flag is set, remove it after clean up
  119. if container.HostConfig.AutoRemove {
  120. container.Unlock()
  121. if err := daemon.ContainerRm(container.ID, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true}); err != nil {
  122. logrus.Errorf("can't remove container %s: %v", container.ID, err)
  123. }
  124. container.Lock()
  125. }
  126. }
  127. }()
  128. if err := daemon.conditionalMountOnStart(container); err != nil {
  129. return err
  130. }
  131. if err := daemon.initializeNetworking(container); err != nil {
  132. return err
  133. }
  134. spec, err := daemon.createSpec(ctx, container)
  135. if err != nil {
  136. return errdefs.System(err)
  137. }
  138. if resetRestartManager {
  139. container.ResetRestartManager(true)
  140. container.HasBeenManuallyStopped = false
  141. }
  142. if err := daemon.saveAppArmorConfig(container); err != nil {
  143. return err
  144. }
  145. if checkpoint != "" {
  146. checkpointDir, err = getCheckpointDir(checkpointDir, checkpoint, container.Name, container.ID, container.CheckpointDir(), false)
  147. if err != nil {
  148. return err
  149. }
  150. }
  151. shim, createOptions, err := daemon.getLibcontainerdCreateOptions(container)
  152. if err != nil {
  153. return err
  154. }
  155. ctr, err := libcontainerd.ReplaceContainer(ctx, daemon.containerd, container.ID, spec, shim, createOptions)
  156. if err != nil {
  157. return setExitCodeFromError(container.SetExitCode, err)
  158. }
  159. // TODO(mlaventure): we need to specify checkpoint options here
  160. tsk, err := ctr.Start(context.TODO(), // Passing ctx to ctr.Start caused integration tests to be stuck in the cleanup phase
  161. checkpointDir, container.StreamConfig.Stdin() != nil || container.Config.Tty,
  162. container.InitializeStdio)
  163. if err != nil {
  164. if err := ctr.Delete(context.Background()); err != nil {
  165. logrus.WithError(err).WithField("container", container.ID).
  166. Error("failed to delete failed start container")
  167. }
  168. return setExitCodeFromError(container.SetExitCode, err)
  169. }
  170. container.HasBeenManuallyRestarted = false
  171. container.SetRunning(ctr, tsk, true)
  172. container.HasBeenStartedBefore = true
  173. daemon.setStateCounter(container)
  174. daemon.initHealthMonitor(container)
  175. if err := container.CheckpointTo(daemon.containersReplica); err != nil {
  176. logrus.WithError(err).WithField("container", container.ID).
  177. Errorf("failed to store container")
  178. }
  179. daemon.LogContainerEvent(container, "start")
  180. containerActions.WithValues("start").UpdateSince(start)
  181. return nil
  182. }
  183. // Cleanup releases any network resources allocated to the container along with any rules
  184. // around how containers are linked together. It also unmounts the container's root filesystem.
  185. func (daemon *Daemon) Cleanup(container *container.Container) {
  186. // Microsoft HCS containers get in a bad state if host resources are
  187. // released while the container still exists.
  188. if ctr, ok := container.C8dContainer(); ok {
  189. if err := ctr.Delete(context.Background()); err != nil {
  190. logrus.Errorf("%s cleanup: failed to delete container from containerd: %v", container.ID, err)
  191. }
  192. }
  193. daemon.releaseNetwork(container)
  194. if err := container.UnmountIpcMount(); err != nil {
  195. logrus.Warnf("%s cleanup: failed to unmount IPC: %s", container.ID, err)
  196. }
  197. if err := daemon.conditionalUnmountOnCleanup(container); err != nil {
  198. // FIXME: remove once reference counting for graphdrivers has been refactored
  199. // Ensure that all the mounts are gone
  200. if mountid, err := daemon.imageService.GetLayerMountID(container.ID); err == nil {
  201. daemon.cleanupMountsByID(mountid)
  202. }
  203. }
  204. if err := container.UnmountSecrets(); err != nil {
  205. logrus.Warnf("%s cleanup: failed to unmount secrets: %s", container.ID, err)
  206. }
  207. if err := recursiveUnmount(container.Root); err != nil {
  208. logrus.WithError(err).WithField("container", container.ID).Warn("Error while cleaning up container resource mounts.")
  209. }
  210. for _, eConfig := range container.ExecCommands.Commands() {
  211. daemon.unregisterExecCommand(container, eConfig)
  212. }
  213. if container.BaseFS != "" {
  214. if err := container.UnmountVolumes(daemon.LogVolumeEvent); err != nil {
  215. logrus.Warnf("%s cleanup: Failed to umount volumes: %v", container.ID, err)
  216. }
  217. }
  218. container.CancelAttachContext()
  219. }