start.go 8.3 KB

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