create.go 11 KB

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