create.go 12 KB

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