create.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. package daemon
  2. import (
  3. "fmt"
  4. "net"
  5. "runtime"
  6. "strings"
  7. "time"
  8. "github.com/pkg/errors"
  9. apierrors "github.com/docker/docker/api/errors"
  10. "github.com/docker/docker/api/types"
  11. containertypes "github.com/docker/docker/api/types/container"
  12. networktypes "github.com/docker/docker/api/types/network"
  13. "github.com/docker/docker/container"
  14. "github.com/docker/docker/image"
  15. "github.com/docker/docker/layer"
  16. "github.com/docker/docker/pkg/idtools"
  17. "github.com/docker/docker/pkg/stringid"
  18. "github.com/docker/docker/pkg/system"
  19. "github.com/docker/docker/runconfig"
  20. "github.com/opencontainers/selinux/go-selinux/label"
  21. "github.com/sirupsen/logrus"
  22. )
  23. // CreateManagedContainer creates a container that is managed by a Service
  24. func (daemon *Daemon) CreateManagedContainer(params types.ContainerCreateConfig) (containertypes.ContainerCreateCreatedBody, error) {
  25. return daemon.containerCreate(params, true)
  26. }
  27. // ContainerCreate creates a regular container
  28. func (daemon *Daemon) ContainerCreate(params types.ContainerCreateConfig) (containertypes.ContainerCreateCreatedBody, error) {
  29. return daemon.containerCreate(params, false)
  30. }
  31. func (daemon *Daemon) containerCreate(params types.ContainerCreateConfig, managed bool) (containertypes.ContainerCreateCreatedBody, error) {
  32. start := time.Now()
  33. if params.Config == nil {
  34. return containertypes.ContainerCreateCreatedBody{}, fmt.Errorf("Config cannot be empty in order to create a container")
  35. }
  36. warnings, err := daemon.verifyContainerSettings(params.HostConfig, params.Config, false)
  37. if err != nil {
  38. return containertypes.ContainerCreateCreatedBody{Warnings: warnings}, err
  39. }
  40. err = daemon.verifyNetworkingConfig(params.NetworkingConfig)
  41. if err != nil {
  42. return containertypes.ContainerCreateCreatedBody{Warnings: warnings}, err
  43. }
  44. if params.HostConfig == nil {
  45. params.HostConfig = &containertypes.HostConfig{}
  46. }
  47. err = daemon.adaptContainerSettings(params.HostConfig, params.AdjustCPUShares)
  48. if err != nil {
  49. return containertypes.ContainerCreateCreatedBody{Warnings: warnings}, err
  50. }
  51. container, err := daemon.create(params, managed)
  52. if err != nil {
  53. return containertypes.ContainerCreateCreatedBody{Warnings: warnings}, daemon.imageNotExistToErrcode(err)
  54. }
  55. containerActions.WithValues("create").UpdateSince(start)
  56. return containertypes.ContainerCreateCreatedBody{ID: container.ID, Warnings: warnings}, nil
  57. }
  58. // Create creates a new container from the given configuration with a given name.
  59. func (daemon *Daemon) create(params types.ContainerCreateConfig, managed bool) (retC *container.Container, retErr error) {
  60. var (
  61. container *container.Container
  62. img *image.Image
  63. imgID image.ID
  64. err error
  65. )
  66. // TODO: @jhowardmsft LCOW support - at a later point, can remove the hard-coding
  67. // to force the platform to be linux.
  68. // Default the platform if not supplied
  69. if params.Platform == "" {
  70. params.Platform = runtime.GOOS
  71. }
  72. if system.LCOWSupported() {
  73. params.Platform = "linux"
  74. }
  75. if params.Config.Image != "" {
  76. img, err = daemon.GetImage(params.Config.Image)
  77. if err != nil {
  78. return nil, err
  79. }
  80. if runtime.GOOS == "solaris" && img.OS != "solaris " {
  81. return nil, errors.New("platform on which parent image was created is not Solaris")
  82. }
  83. imgID = img.ID()
  84. if runtime.GOOS == "windows" && img.OS == "linux" && !system.LCOWSupported() {
  85. return nil, errors.New("platform on which parent image was created is not Windows")
  86. }
  87. }
  88. // Make sure the platform requested matches the image
  89. if img != nil {
  90. if params.Platform != img.Platform() {
  91. // Ignore this in LCOW mode. @jhowardmsft TODO - This will need revisiting later.
  92. if !system.LCOWSupported() {
  93. return nil, fmt.Errorf("cannot create a %s container from a %s image", params.Platform, img.Platform())
  94. }
  95. }
  96. }
  97. if err := daemon.mergeAndVerifyConfig(params.Config, img); err != nil {
  98. return nil, err
  99. }
  100. if err := daemon.mergeAndVerifyLogConfig(&params.HostConfig.LogConfig); err != nil {
  101. return nil, err
  102. }
  103. if container, err = daemon.newContainer(params.Name, params.Platform, params.Config, params.HostConfig, imgID, managed); err != nil {
  104. return nil, err
  105. }
  106. defer func() {
  107. if retErr != nil {
  108. if err := daemon.cleanupContainer(container, true, true); err != nil {
  109. logrus.Errorf("failed to cleanup container on create error: %v", err)
  110. }
  111. }
  112. }()
  113. if err := daemon.setSecurityOptions(container, params.HostConfig); err != nil {
  114. return nil, err
  115. }
  116. container.HostConfig.StorageOpt = params.HostConfig.StorageOpt
  117. // Fixes: https://github.com/moby/moby/issues/34074 and
  118. // https://github.com/docker/for-win/issues/999.
  119. // Merge the daemon's storage options if they aren't already present. We only
  120. // do this on Windows as there's no effective sandbox size limit other than
  121. // physical on Linux.
  122. if runtime.GOOS == "windows" {
  123. if container.HostConfig.StorageOpt == nil {
  124. container.HostConfig.StorageOpt = make(map[string]string)
  125. }
  126. for _, v := range daemon.configStore.GraphOptions {
  127. opt := strings.SplitN(v, "=", 2)
  128. if _, ok := container.HostConfig.StorageOpt[opt[0]]; !ok {
  129. container.HostConfig.StorageOpt[opt[0]] = opt[1]
  130. }
  131. }
  132. }
  133. // Set RWLayer for container after mount labels have been set
  134. if err := daemon.setRWLayer(container); err != nil {
  135. return nil, err
  136. }
  137. rootIDs := daemon.idMappings.RootPair()
  138. if err := idtools.MkdirAndChown(container.Root, 0700, rootIDs); err != nil {
  139. return nil, err
  140. }
  141. if err := idtools.MkdirAndChown(container.CheckpointDir(), 0700, rootIDs); err != nil {
  142. return nil, err
  143. }
  144. if err := daemon.setHostConfig(container, params.HostConfig); err != nil {
  145. return nil, err
  146. }
  147. if err := daemon.createContainerPlatformSpecificSettings(container, params.Config, params.HostConfig); err != nil {
  148. return nil, err
  149. }
  150. var endpointsConfigs map[string]*networktypes.EndpointSettings
  151. if params.NetworkingConfig != nil {
  152. endpointsConfigs = params.NetworkingConfig.EndpointsConfig
  153. }
  154. // Make sure NetworkMode has an acceptable value. We do this to ensure
  155. // backwards API compatibility.
  156. runconfig.SetDefaultNetModeIfBlank(container.HostConfig)
  157. daemon.updateContainerNetworkSettings(container, endpointsConfigs)
  158. if err := daemon.Register(container); err != nil {
  159. return nil, err
  160. }
  161. stateCtr.set(container.ID, "stopped")
  162. daemon.LogContainerEvent(container, "create")
  163. return container, nil
  164. }
  165. func toHostConfigSelinuxLabels(labels []string) []string {
  166. for i, l := range labels {
  167. labels[i] = "label=" + l
  168. }
  169. return labels
  170. }
  171. func (daemon *Daemon) generateSecurityOpt(hostConfig *containertypes.HostConfig) ([]string, error) {
  172. for _, opt := range hostConfig.SecurityOpt {
  173. con := strings.Split(opt, "=")
  174. if con[0] == "label" {
  175. // Caller overrode SecurityOpts
  176. return nil, nil
  177. }
  178. }
  179. ipcMode := hostConfig.IpcMode
  180. pidMode := hostConfig.PidMode
  181. privileged := hostConfig.Privileged
  182. if ipcMode.IsHost() || pidMode.IsHost() || privileged {
  183. return toHostConfigSelinuxLabels(label.DisableSecOpt()), nil
  184. }
  185. var ipcLabel []string
  186. var pidLabel []string
  187. ipcContainer := ipcMode.Container()
  188. pidContainer := pidMode.Container()
  189. if ipcContainer != "" {
  190. c, err := daemon.GetContainer(ipcContainer)
  191. if err != nil {
  192. return nil, err
  193. }
  194. ipcLabel = label.DupSecOpt(c.ProcessLabel)
  195. if pidContainer == "" {
  196. return toHostConfigSelinuxLabels(ipcLabel), err
  197. }
  198. }
  199. if pidContainer != "" {
  200. c, err := daemon.GetContainer(pidContainer)
  201. if err != nil {
  202. return nil, err
  203. }
  204. pidLabel = label.DupSecOpt(c.ProcessLabel)
  205. if ipcContainer == "" {
  206. return toHostConfigSelinuxLabels(pidLabel), err
  207. }
  208. }
  209. if pidLabel != nil && ipcLabel != nil {
  210. for i := 0; i < len(pidLabel); i++ {
  211. if pidLabel[i] != ipcLabel[i] {
  212. return nil, fmt.Errorf("--ipc and --pid containers SELinux labels aren't the same")
  213. }
  214. }
  215. return toHostConfigSelinuxLabels(pidLabel), nil
  216. }
  217. return nil, nil
  218. }
  219. func (daemon *Daemon) setRWLayer(container *container.Container) error {
  220. var layerID layer.ChainID
  221. if container.ImageID != "" {
  222. img, err := daemon.stores[container.Platform].imageStore.Get(container.ImageID)
  223. if err != nil {
  224. return err
  225. }
  226. layerID = img.RootFS.ChainID()
  227. }
  228. rwLayerOpts := &layer.CreateRWLayerOpts{
  229. MountLabel: container.MountLabel,
  230. InitFunc: daemon.getLayerInit(),
  231. StorageOpt: container.HostConfig.StorageOpt,
  232. }
  233. rwLayer, err := daemon.stores[container.Platform].layerStore.CreateRWLayer(container.ID, layerID, rwLayerOpts)
  234. if err != nil {
  235. return err
  236. }
  237. container.RWLayer = rwLayer
  238. return nil
  239. }
  240. // VolumeCreate creates a volume with the specified name, driver, and opts
  241. // This is called directly from the Engine API
  242. func (daemon *Daemon) VolumeCreate(name, driverName string, opts, labels map[string]string) (*types.Volume, error) {
  243. if name == "" {
  244. name = stringid.GenerateNonCryptoID()
  245. }
  246. v, err := daemon.volumes.Create(name, driverName, opts, labels)
  247. if err != nil {
  248. return nil, err
  249. }
  250. daemon.LogVolumeEvent(v.Name(), "create", map[string]string{"driver": v.DriverName()})
  251. apiV := volumeToAPIType(v)
  252. apiV.Mountpoint = v.Path()
  253. return apiV, nil
  254. }
  255. func (daemon *Daemon) mergeAndVerifyConfig(config *containertypes.Config, img *image.Image) error {
  256. if img != nil && img.Config != nil {
  257. if err := merge(config, img.Config); err != nil {
  258. return err
  259. }
  260. }
  261. // Reset the Entrypoint if it is [""]
  262. if len(config.Entrypoint) == 1 && config.Entrypoint[0] == "" {
  263. config.Entrypoint = nil
  264. }
  265. if len(config.Entrypoint) == 0 && len(config.Cmd) == 0 {
  266. return fmt.Errorf("No command specified")
  267. }
  268. return nil
  269. }
  270. // Checks if the client set configurations for more than one network while creating a container
  271. // Also checks if the IPAMConfig is valid
  272. func (daemon *Daemon) verifyNetworkingConfig(nwConfig *networktypes.NetworkingConfig) error {
  273. if nwConfig == nil || len(nwConfig.EndpointsConfig) == 0 {
  274. return nil
  275. }
  276. if len(nwConfig.EndpointsConfig) == 1 {
  277. for _, v := range nwConfig.EndpointsConfig {
  278. if v != nil && v.IPAMConfig != nil {
  279. if v.IPAMConfig.IPv4Address != "" && net.ParseIP(v.IPAMConfig.IPv4Address).To4() == nil {
  280. return apierrors.NewBadRequestError(fmt.Errorf("invalid IPv4 address: %s", v.IPAMConfig.IPv4Address))
  281. }
  282. if v.IPAMConfig.IPv6Address != "" {
  283. n := net.ParseIP(v.IPAMConfig.IPv6Address)
  284. // if the address is an invalid network address (ParseIP == nil) or if it is
  285. // an IPv4 address (To4() != nil), then it is an invalid IPv6 address
  286. if n == nil || n.To4() != nil {
  287. return apierrors.NewBadRequestError(fmt.Errorf("invalid IPv6 address: %s", v.IPAMConfig.IPv6Address))
  288. }
  289. }
  290. }
  291. }
  292. return nil
  293. }
  294. l := make([]string, 0, len(nwConfig.EndpointsConfig))
  295. for k := range nwConfig.EndpointsConfig {
  296. l = append(l, k)
  297. }
  298. err := fmt.Errorf("Container cannot be connected to network endpoints: %s", strings.Join(l, ", "))
  299. return apierrors.NewBadRequestError(err)
  300. }