create.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package daemon
  2. import (
  3. "fmt"
  4. "net"
  5. "runtime"
  6. "strings"
  7. "time"
  8. "github.com/pkg/errors"
  9. "github.com/Sirupsen/logrus"
  10. apierrors "github.com/docker/docker/api/errors"
  11. "github.com/docker/docker/api/types"
  12. containertypes "github.com/docker/docker/api/types/container"
  13. networktypes "github.com/docker/docker/api/types/network"
  14. "github.com/docker/docker/container"
  15. "github.com/docker/docker/image"
  16. "github.com/docker/docker/layer"
  17. "github.com/docker/docker/pkg/idtools"
  18. "github.com/docker/docker/pkg/stringid"
  19. "github.com/docker/docker/runconfig"
  20. volumestore "github.com/docker/docker/volume/store"
  21. "github.com/opencontainers/runc/libcontainer/label"
  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. if params.Config.Image != "" {
  67. img, err = daemon.GetImage(params.Config.Image)
  68. if err != nil {
  69. return nil, err
  70. }
  71. if runtime.GOOS == "solaris" && img.OS != "solaris " {
  72. return nil, errors.New("Platform on which parent image was created is not Solaris")
  73. }
  74. imgID = img.ID()
  75. }
  76. if err := daemon.mergeAndVerifyConfig(params.Config, img); err != nil {
  77. return nil, err
  78. }
  79. if err := daemon.mergeAndVerifyLogConfig(&params.HostConfig.LogConfig); err != nil {
  80. return nil, err
  81. }
  82. if container, err = daemon.newContainer(params.Name, params.Config, params.HostConfig, imgID, managed); err != nil {
  83. return nil, err
  84. }
  85. defer func() {
  86. if retErr != nil {
  87. if err := daemon.cleanupContainer(container, true, true); err != nil {
  88. logrus.Errorf("failed to cleanup container on create error: %v", err)
  89. }
  90. }
  91. }()
  92. if err := daemon.setSecurityOptions(container, params.HostConfig); err != nil {
  93. return nil, err
  94. }
  95. container.HostConfig.StorageOpt = params.HostConfig.StorageOpt
  96. // Set RWLayer for container after mount labels have been set
  97. if err := daemon.setRWLayer(container); err != nil {
  98. return nil, err
  99. }
  100. rootUID, rootGID, err := idtools.GetRootUIDGID(daemon.uidMaps, daemon.gidMaps)
  101. if err != nil {
  102. return nil, err
  103. }
  104. if err := idtools.MkdirAs(container.Root, 0700, rootUID, rootGID); err != nil {
  105. return nil, err
  106. }
  107. if err := idtools.MkdirAs(container.CheckpointDir(), 0700, rootUID, rootGID); err != nil {
  108. return nil, err
  109. }
  110. if err := daemon.setHostConfig(container, params.HostConfig); err != nil {
  111. return nil, err
  112. }
  113. if err := daemon.createContainerPlatformSpecificSettings(container, params.Config, params.HostConfig); err != nil {
  114. return nil, err
  115. }
  116. var endpointsConfigs map[string]*networktypes.EndpointSettings
  117. if params.NetworkingConfig != nil {
  118. endpointsConfigs = params.NetworkingConfig.EndpointsConfig
  119. }
  120. // Make sure NetworkMode has an acceptable value. We do this to ensure
  121. // backwards API compatibility.
  122. container.HostConfig = runconfig.SetDefaultNetModeIfBlank(container.HostConfig)
  123. daemon.updateContainerNetworkSettings(container, endpointsConfigs)
  124. if err := container.ToDisk(); err != nil {
  125. logrus.Errorf("Error saving new container to disk: %v", err)
  126. return nil, err
  127. }
  128. daemon.Register(container)
  129. daemon.LogContainerEvent(container, "create")
  130. return container, nil
  131. }
  132. func (daemon *Daemon) generateSecurityOpt(ipcMode containertypes.IpcMode, pidMode containertypes.PidMode, privileged bool) ([]string, error) {
  133. if ipcMode.IsHost() || pidMode.IsHost() || privileged {
  134. return label.DisableSecOpt(), nil
  135. }
  136. var ipcLabel []string
  137. var pidLabel []string
  138. ipcContainer := ipcMode.Container()
  139. pidContainer := pidMode.Container()
  140. if ipcContainer != "" {
  141. c, err := daemon.GetContainer(ipcContainer)
  142. if err != nil {
  143. return nil, err
  144. }
  145. ipcLabel = label.DupSecOpt(c.ProcessLabel)
  146. if pidContainer == "" {
  147. return ipcLabel, err
  148. }
  149. }
  150. if pidContainer != "" {
  151. c, err := daemon.GetContainer(pidContainer)
  152. if err != nil {
  153. return nil, err
  154. }
  155. pidLabel = label.DupSecOpt(c.ProcessLabel)
  156. if ipcContainer == "" {
  157. return pidLabel, err
  158. }
  159. }
  160. if pidLabel != nil && ipcLabel != nil {
  161. for i := 0; i < len(pidLabel); i++ {
  162. if pidLabel[i] != ipcLabel[i] {
  163. return nil, fmt.Errorf("--ipc and --pid containers SELinux labels aren't the same")
  164. }
  165. }
  166. return pidLabel, nil
  167. }
  168. return nil, nil
  169. }
  170. func (daemon *Daemon) setRWLayer(container *container.Container) error {
  171. var layerID layer.ChainID
  172. if container.ImageID != "" {
  173. img, err := daemon.imageStore.Get(container.ImageID)
  174. if err != nil {
  175. return err
  176. }
  177. layerID = img.RootFS.ChainID()
  178. }
  179. rwLayerOpts := &layer.CreateRWLayerOpts{
  180. MountLabel: container.MountLabel,
  181. InitFunc: daemon.getLayerInit(),
  182. StorageOpt: container.HostConfig.StorageOpt,
  183. }
  184. rwLayer, err := daemon.layerStore.CreateRWLayer(container.ID, layerID, rwLayerOpts)
  185. if err != nil {
  186. return err
  187. }
  188. container.RWLayer = rwLayer
  189. return nil
  190. }
  191. // VolumeCreate creates a volume with the specified name, driver, and opts
  192. // This is called directly from the Engine API
  193. func (daemon *Daemon) VolumeCreate(name, driverName string, opts, labels map[string]string) (*types.Volume, error) {
  194. if name == "" {
  195. name = stringid.GenerateNonCryptoID()
  196. }
  197. v, err := daemon.volumes.Create(name, driverName, opts, labels)
  198. if err != nil {
  199. if volumestore.IsNameConflict(err) {
  200. return nil, fmt.Errorf("A volume named %s already exists. Choose a different volume name.", name)
  201. }
  202. return nil, err
  203. }
  204. daemon.LogVolumeEvent(v.Name(), "create", map[string]string{"driver": v.DriverName()})
  205. apiV := volumeToAPIType(v)
  206. apiV.Mountpoint = v.Path()
  207. return apiV, nil
  208. }
  209. func (daemon *Daemon) mergeAndVerifyConfig(config *containertypes.Config, img *image.Image) error {
  210. if img != nil && img.Config != nil {
  211. if err := merge(config, img.Config); err != nil {
  212. return err
  213. }
  214. }
  215. // Reset the Entrypoint if it is [""]
  216. if len(config.Entrypoint) == 1 && config.Entrypoint[0] == "" {
  217. config.Entrypoint = nil
  218. }
  219. if len(config.Entrypoint) == 0 && len(config.Cmd) == 0 {
  220. return fmt.Errorf("No command specified")
  221. }
  222. return nil
  223. }
  224. // Checks if the client set configurations for more than one network while creating a container
  225. // Also checks if the IPAMConfig is valid
  226. func (daemon *Daemon) verifyNetworkingConfig(nwConfig *networktypes.NetworkingConfig) error {
  227. if nwConfig == nil || len(nwConfig.EndpointsConfig) == 0 {
  228. return nil
  229. }
  230. if len(nwConfig.EndpointsConfig) == 1 {
  231. for _, v := range nwConfig.EndpointsConfig {
  232. if v != nil && v.IPAMConfig != nil {
  233. if v.IPAMConfig.IPv4Address != "" && net.ParseIP(v.IPAMConfig.IPv4Address).To4() == nil {
  234. return apierrors.NewBadRequestError(fmt.Errorf("invalid IPv4 address: %s", v.IPAMConfig.IPv4Address))
  235. }
  236. if v.IPAMConfig.IPv6Address != "" {
  237. n := net.ParseIP(v.IPAMConfig.IPv6Address)
  238. // if the address is an invalid network address (ParseIP == nil) or if it is
  239. // an IPv4 address (To4() != nil), then it is an invalid IPv6 address
  240. if n == nil || n.To4() != nil {
  241. return apierrors.NewBadRequestError(fmt.Errorf("invalid IPv6 address: %s", v.IPAMConfig.IPv6Address))
  242. }
  243. }
  244. }
  245. }
  246. return nil
  247. }
  248. l := make([]string, 0, len(nwConfig.EndpointsConfig))
  249. for k := range nwConfig.EndpointsConfig {
  250. l = append(l, k)
  251. }
  252. err := fmt.Errorf("Container cannot be connected to network endpoints: %s", strings.Join(l, ", "))
  253. return apierrors.NewBadRequestError(err)
  254. }