create.go 12 KB

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