create.go 11 KB

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