create.go 12 KB

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