create.go 11 KB

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