create.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. package daemon // import "github.com/docker/docker/daemon"
  2. import (
  3. "context"
  4. "fmt"
  5. "runtime"
  6. "strings"
  7. "time"
  8. "github.com/containerd/containerd/platforms"
  9. "github.com/containerd/log"
  10. "github.com/docker/docker/api/types/backend"
  11. containertypes "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/api/types/events"
  13. imagetypes "github.com/docker/docker/api/types/image"
  14. networktypes "github.com/docker/docker/api/types/network"
  15. "github.com/docker/docker/container"
  16. "github.com/docker/docker/daemon/config"
  17. "github.com/docker/docker/daemon/images"
  18. "github.com/docker/docker/errdefs"
  19. "github.com/docker/docker/image"
  20. "github.com/docker/docker/internal/multierror"
  21. "github.com/docker/docker/pkg/idtools"
  22. "github.com/docker/docker/runconfig"
  23. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  24. "github.com/opencontainers/selinux/go-selinux"
  25. archvariant "github.com/tonistiigi/go-archvariant"
  26. )
  27. type createOpts struct {
  28. params backend.ContainerCreateConfig
  29. managed bool
  30. ignoreImagesArgsEscaped bool
  31. }
  32. // CreateManagedContainer creates a container that is managed by a Service
  33. func (daemon *Daemon) CreateManagedContainer(ctx context.Context, params backend.ContainerCreateConfig) (containertypes.CreateResponse, error) {
  34. return daemon.containerCreate(ctx, daemon.config(), createOpts{
  35. params: params,
  36. managed: true,
  37. })
  38. }
  39. // ContainerCreate creates a regular container
  40. func (daemon *Daemon) ContainerCreate(ctx context.Context, params backend.ContainerCreateConfig) (containertypes.CreateResponse, error) {
  41. return daemon.containerCreate(ctx, daemon.config(), createOpts{
  42. params: params,
  43. })
  44. }
  45. // ContainerCreateIgnoreImagesArgsEscaped creates a regular container. This is called from the builder RUN case
  46. // and ensures that we do not take the images ArgsEscaped
  47. func (daemon *Daemon) ContainerCreateIgnoreImagesArgsEscaped(ctx context.Context, params backend.ContainerCreateConfig) (containertypes.CreateResponse, error) {
  48. return daemon.containerCreate(ctx, daemon.config(), createOpts{
  49. params: params,
  50. ignoreImagesArgsEscaped: true,
  51. })
  52. }
  53. func (daemon *Daemon) containerCreate(ctx context.Context, daemonCfg *configStore, opts createOpts) (containertypes.CreateResponse, error) {
  54. start := time.Now()
  55. if opts.params.Config == nil {
  56. return containertypes.CreateResponse{}, errdefs.InvalidParameter(runconfig.ErrEmptyConfig)
  57. }
  58. // Normalize some defaults. Doing this "ad-hoc" here for now, as there's
  59. // only one field to migrate, but we should consider having a better
  60. // location for this (and decide where in the flow would be most appropriate).
  61. //
  62. // TODO(thaJeztah): we should have a more visible, more canonical location for this.
  63. if opts.params.HostConfig != nil && opts.params.HostConfig.RestartPolicy.Name == "" {
  64. // Set the default restart-policy ("none") if no restart-policy was set.
  65. opts.params.HostConfig.RestartPolicy.Name = containertypes.RestartPolicyDisabled
  66. }
  67. warnings, err := daemon.verifyContainerSettings(daemonCfg, opts.params.HostConfig, opts.params.Config, false)
  68. if err != nil {
  69. return containertypes.CreateResponse{Warnings: warnings}, errdefs.InvalidParameter(err)
  70. }
  71. if opts.params.Platform == nil && opts.params.Config.Image != "" {
  72. img, err := daemon.imageService.GetImage(ctx, opts.params.Config.Image, imagetypes.GetImageOpts{Platform: opts.params.Platform})
  73. if err != nil {
  74. return containertypes.CreateResponse{}, err
  75. }
  76. if img != nil {
  77. p := maximumSpec()
  78. imgPlat := ocispec.Platform{
  79. OS: img.OS,
  80. Architecture: img.Architecture,
  81. Variant: img.Variant,
  82. }
  83. if !images.OnlyPlatformWithFallback(p).Match(imgPlat) {
  84. warnings = append(warnings, fmt.Sprintf("The requested image's platform (%s) does not match the detected host platform (%s) and no specific platform was requested", platforms.Format(imgPlat), platforms.Format(p)))
  85. }
  86. }
  87. }
  88. err = daemon.validateNetworkingConfig(opts.params.NetworkingConfig)
  89. if err != nil {
  90. return containertypes.CreateResponse{Warnings: warnings}, errdefs.InvalidParameter(err)
  91. }
  92. if opts.params.HostConfig == nil {
  93. opts.params.HostConfig = &containertypes.HostConfig{}
  94. }
  95. err = daemon.adaptContainerSettings(&daemonCfg.Config, opts.params.HostConfig, opts.params.AdjustCPUShares)
  96. if err != nil {
  97. return containertypes.CreateResponse{Warnings: warnings}, errdefs.InvalidParameter(err)
  98. }
  99. ctr, err := daemon.create(ctx, &daemonCfg.Config, opts)
  100. if err != nil {
  101. return containertypes.CreateResponse{Warnings: warnings}, err
  102. }
  103. containerActions.WithValues("create").UpdateSince(start)
  104. if warnings == nil {
  105. warnings = make([]string, 0) // Create an empty slice to avoid https://github.com/moby/moby/issues/38222
  106. }
  107. return containertypes.CreateResponse{ID: ctr.ID, Warnings: warnings}, nil
  108. }
  109. // Create creates a new container from the given configuration with a given name.
  110. func (daemon *Daemon) create(ctx context.Context, daemonCfg *config.Config, opts createOpts) (retC *container.Container, retErr error) {
  111. var (
  112. ctr *container.Container
  113. img *image.Image
  114. imgManifest *ocispec.Descriptor
  115. imgID image.ID
  116. err error
  117. os = runtime.GOOS
  118. )
  119. if opts.params.Config.Image != "" {
  120. img, err = daemon.imageService.GetImage(ctx, opts.params.Config.Image, imagetypes.GetImageOpts{Platform: opts.params.Platform})
  121. if err != nil {
  122. return nil, err
  123. }
  124. // when using the containerd store, we need to get the actual
  125. // image manifest so we can store it and later deterministically
  126. // resolve the specific image the container is running
  127. if daemon.UsesSnapshotter() {
  128. imgManifest, err = daemon.imageService.GetImageManifest(ctx, opts.params.Config.Image, imagetypes.GetImageOpts{Platform: opts.params.Platform})
  129. if err != nil {
  130. log.G(ctx).WithError(err).Error("failed to find image manifest")
  131. return nil, err
  132. }
  133. }
  134. os = img.OperatingSystem()
  135. imgID = img.ID()
  136. } else if isWindows {
  137. os = "linux" // 'scratch' case.
  138. }
  139. // On WCOW, if are not being invoked by the builder to create this container (where
  140. // ignoreImagesArgEscaped will be true) - if the image already has its arguments escaped,
  141. // ensure that this is replicated across to the created container to avoid double-escaping
  142. // of the arguments/command line when the runtime attempts to run the container.
  143. if os == "windows" && !opts.ignoreImagesArgsEscaped && img != nil && img.RunConfig().ArgsEscaped {
  144. opts.params.Config.ArgsEscaped = true
  145. }
  146. if err := daemon.mergeAndVerifyConfig(opts.params.Config, img); err != nil {
  147. return nil, errdefs.InvalidParameter(err)
  148. }
  149. if err := daemon.mergeAndVerifyLogConfig(&opts.params.HostConfig.LogConfig); err != nil {
  150. return nil, errdefs.InvalidParameter(err)
  151. }
  152. if ctr, err = daemon.newContainer(opts.params.Name, os, opts.params.Config, opts.params.HostConfig, imgID, opts.managed); err != nil {
  153. return nil, err
  154. }
  155. defer func() {
  156. if retErr != nil {
  157. err = daemon.cleanupContainer(ctr, backend.ContainerRmConfig{
  158. ForceRemove: true,
  159. RemoveVolume: true,
  160. })
  161. if err != nil {
  162. log.G(ctx).WithError(err).Error("failed to cleanup container on create error")
  163. }
  164. }
  165. }()
  166. if err := daemon.setSecurityOptions(daemonCfg, ctr, opts.params.HostConfig); err != nil {
  167. return nil, err
  168. }
  169. ctr.HostConfig.StorageOpt = opts.params.HostConfig.StorageOpt
  170. ctr.ImageManifest = imgManifest
  171. if daemon.UsesSnapshotter() {
  172. if err := daemon.imageService.PrepareSnapshot(ctx, ctr.ID, opts.params.Config.Image, opts.params.Platform, setupInitLayer(daemon.idMapping)); err != nil {
  173. return nil, err
  174. }
  175. } else {
  176. // Set RWLayer for container after mount labels have been set
  177. rwLayer, err := daemon.imageService.CreateLayer(ctr, setupInitLayer(daemon.idMapping))
  178. if err != nil {
  179. return nil, errdefs.System(err)
  180. }
  181. ctr.RWLayer = rwLayer
  182. }
  183. current := idtools.CurrentIdentity()
  184. if err := idtools.MkdirAndChown(ctr.Root, 0o710, idtools.Identity{UID: current.UID, GID: daemon.IdentityMapping().RootPair().GID}); err != nil {
  185. return nil, err
  186. }
  187. if err := idtools.MkdirAndChown(ctr.CheckpointDir(), 0o700, current); err != nil {
  188. return nil, err
  189. }
  190. if err := daemon.setHostConfig(ctr, opts.params.HostConfig); err != nil {
  191. return nil, err
  192. }
  193. if err := daemon.createContainerOSSpecificSettings(ctr, opts.params.Config, opts.params.HostConfig); err != nil {
  194. return nil, err
  195. }
  196. var endpointsConfigs map[string]*networktypes.EndpointSettings
  197. if opts.params.NetworkingConfig != nil {
  198. endpointsConfigs = opts.params.NetworkingConfig.EndpointsConfig
  199. }
  200. // Make sure NetworkMode has an acceptable value. We do this to ensure
  201. // backwards API compatibility.
  202. runconfig.SetDefaultNetModeIfBlank(ctr.HostConfig)
  203. daemon.updateContainerNetworkSettings(ctr, endpointsConfigs)
  204. if err := daemon.Register(ctr); err != nil {
  205. return nil, err
  206. }
  207. stateCtr.set(ctr.ID, "stopped")
  208. daemon.LogContainerEvent(ctr, events.ActionCreate)
  209. return ctr, nil
  210. }
  211. func toHostConfigSelinuxLabels(labels []string) []string {
  212. for i, l := range labels {
  213. labels[i] = "label=" + l
  214. }
  215. return labels
  216. }
  217. func (daemon *Daemon) generateSecurityOpt(hostConfig *containertypes.HostConfig) ([]string, error) {
  218. for _, opt := range hostConfig.SecurityOpt {
  219. con := strings.Split(opt, "=")
  220. if con[0] == "label" {
  221. // Caller overrode SecurityOpts
  222. return nil, nil
  223. }
  224. }
  225. ipcMode := hostConfig.IpcMode
  226. pidMode := hostConfig.PidMode
  227. privileged := hostConfig.Privileged
  228. if ipcMode.IsHost() || pidMode.IsHost() || privileged {
  229. return toHostConfigSelinuxLabels(selinux.DisableSecOpt()), nil
  230. }
  231. var ipcLabel []string
  232. var pidLabel []string
  233. ipcContainer := ipcMode.Container()
  234. pidContainer := pidMode.Container()
  235. if ipcContainer != "" {
  236. c, err := daemon.GetContainer(ipcContainer)
  237. if err != nil {
  238. return nil, err
  239. }
  240. ipcLabel, err = selinux.DupSecOpt(c.ProcessLabel)
  241. if err != nil {
  242. return nil, err
  243. }
  244. if pidContainer == "" {
  245. return toHostConfigSelinuxLabels(ipcLabel), err
  246. }
  247. }
  248. if pidContainer != "" {
  249. c, err := daemon.GetContainer(pidContainer)
  250. if err != nil {
  251. return nil, err
  252. }
  253. pidLabel, err = selinux.DupSecOpt(c.ProcessLabel)
  254. if err != nil {
  255. return nil, err
  256. }
  257. if ipcContainer == "" {
  258. return toHostConfigSelinuxLabels(pidLabel), err
  259. }
  260. }
  261. if pidLabel != nil && ipcLabel != nil {
  262. for i := 0; i < len(pidLabel); i++ {
  263. if pidLabel[i] != ipcLabel[i] {
  264. return nil, fmt.Errorf("--ipc and --pid containers SELinux labels aren't the same")
  265. }
  266. }
  267. return toHostConfigSelinuxLabels(pidLabel), nil
  268. }
  269. return nil, nil
  270. }
  271. func (daemon *Daemon) mergeAndVerifyConfig(config *containertypes.Config, img *image.Image) error {
  272. if img != nil && img.Config != nil {
  273. if err := merge(config, img.Config); err != nil {
  274. return err
  275. }
  276. }
  277. // Reset the Entrypoint if it is [""]
  278. if len(config.Entrypoint) == 1 && config.Entrypoint[0] == "" {
  279. config.Entrypoint = nil
  280. }
  281. if len(config.Entrypoint) == 0 && len(config.Cmd) == 0 {
  282. return fmt.Errorf("no command specified")
  283. }
  284. return nil
  285. }
  286. // validateNetworkingConfig checks whether a container's NetworkingConfig is valid.
  287. func (daemon *Daemon) validateNetworkingConfig(nwConfig *networktypes.NetworkingConfig) error {
  288. if nwConfig == nil {
  289. return nil
  290. }
  291. var errs []error
  292. for k, v := range nwConfig.EndpointsConfig {
  293. if v == nil {
  294. errs = append(errs, fmt.Errorf("invalid config for network %s: EndpointsConfig is nil", k))
  295. continue
  296. }
  297. // The referenced network k might not exist when the container is created, so just ignore the error in that case.
  298. nw, _ := daemon.FindNetwork(k)
  299. if err := validateEndpointSettings(nw, k, v); err != nil {
  300. errs = append(errs, fmt.Errorf("invalid config for network %s: %w", k, err))
  301. }
  302. }
  303. if len(errs) > 0 {
  304. return errdefs.InvalidParameter(multierror.Join(errs...))
  305. }
  306. return nil
  307. }
  308. // maximumSpec returns the distribution platform with maximum compatibility for the current node.
  309. func maximumSpec() ocispec.Platform {
  310. p := platforms.DefaultSpec()
  311. if p.Architecture == "amd64" {
  312. p.Variant = archvariant.AMD64Variant()
  313. }
  314. return p
  315. }