create.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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, 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. if err := daemon.Register(container); err != nil {
  129. return nil, err
  130. }
  131. daemon.LogContainerEvent(container, "create")
  132. return container, nil
  133. }
  134. func (daemon *Daemon) generateSecurityOpt(ipcMode containertypes.IpcMode, pidMode containertypes.PidMode, privileged bool) ([]string, error) {
  135. if ipcMode.IsHost() || pidMode.IsHost() || privileged {
  136. return label.DisableSecOpt(), nil
  137. }
  138. var ipcLabel []string
  139. var pidLabel []string
  140. ipcContainer := ipcMode.Container()
  141. pidContainer := pidMode.Container()
  142. if ipcContainer != "" {
  143. c, err := daemon.GetContainer(ipcContainer)
  144. if err != nil {
  145. return nil, err
  146. }
  147. ipcLabel = label.DupSecOpt(c.ProcessLabel)
  148. if pidContainer == "" {
  149. return ipcLabel, err
  150. }
  151. }
  152. if pidContainer != "" {
  153. c, err := daemon.GetContainer(pidContainer)
  154. if err != nil {
  155. return nil, err
  156. }
  157. pidLabel = label.DupSecOpt(c.ProcessLabel)
  158. if ipcContainer == "" {
  159. return pidLabel, err
  160. }
  161. }
  162. if pidLabel != nil && ipcLabel != nil {
  163. for i := 0; i < len(pidLabel); i++ {
  164. if pidLabel[i] != ipcLabel[i] {
  165. return nil, fmt.Errorf("--ipc and --pid containers SELinux labels aren't the same")
  166. }
  167. }
  168. return pidLabel, nil
  169. }
  170. return nil, nil
  171. }
  172. func (daemon *Daemon) setRWLayer(container *container.Container) error {
  173. var layerID layer.ChainID
  174. if container.ImageID != "" {
  175. img, err := daemon.imageStore.Get(container.ImageID)
  176. if err != nil {
  177. return err
  178. }
  179. layerID = img.RootFS.ChainID()
  180. }
  181. rwLayerOpts := &layer.CreateRWLayerOpts{
  182. MountLabel: container.MountLabel,
  183. InitFunc: daemon.getLayerInit(),
  184. StorageOpt: container.HostConfig.StorageOpt,
  185. }
  186. rwLayer, err := daemon.layerStore.CreateRWLayer(container.ID, layerID, rwLayerOpts)
  187. if err != nil {
  188. return err
  189. }
  190. container.RWLayer = rwLayer
  191. return nil
  192. }
  193. // VolumeCreate creates a volume with the specified name, driver, and opts
  194. // This is called directly from the Engine API
  195. func (daemon *Daemon) VolumeCreate(name, driverName string, opts, labels map[string]string) (*types.Volume, error) {
  196. if name == "" {
  197. name = stringid.GenerateNonCryptoID()
  198. }
  199. v, err := daemon.volumes.Create(name, driverName, opts, labels)
  200. if err != nil {
  201. if volumestore.IsNameConflict(err) {
  202. return nil, fmt.Errorf("A volume named %s already exists. Choose a different volume name.", name)
  203. }
  204. return nil, err
  205. }
  206. daemon.LogVolumeEvent(v.Name(), "create", map[string]string{"driver": v.DriverName()})
  207. apiV := volumeToAPIType(v)
  208. apiV.Mountpoint = v.Path()
  209. return apiV, nil
  210. }
  211. func (daemon *Daemon) mergeAndVerifyConfig(config *containertypes.Config, img *image.Image) error {
  212. if img != nil && img.Config != nil {
  213. if err := merge(config, img.Config); err != nil {
  214. return err
  215. }
  216. }
  217. // Reset the Entrypoint if it is [""]
  218. if len(config.Entrypoint) == 1 && config.Entrypoint[0] == "" {
  219. config.Entrypoint = nil
  220. }
  221. if len(config.Entrypoint) == 0 && len(config.Cmd) == 0 {
  222. return fmt.Errorf("No command specified")
  223. }
  224. return nil
  225. }
  226. // Checks if the client set configurations for more than one network while creating a container
  227. // Also checks if the IPAMConfig is valid
  228. func (daemon *Daemon) verifyNetworkingConfig(nwConfig *networktypes.NetworkingConfig) error {
  229. if nwConfig == nil || len(nwConfig.EndpointsConfig) == 0 {
  230. return nil
  231. }
  232. if len(nwConfig.EndpointsConfig) == 1 {
  233. for _, v := range nwConfig.EndpointsConfig {
  234. if v != nil && v.IPAMConfig != nil {
  235. if v.IPAMConfig.IPv4Address != "" && net.ParseIP(v.IPAMConfig.IPv4Address).To4() == nil {
  236. return apierrors.NewBadRequestError(fmt.Errorf("invalid IPv4 address: %s", v.IPAMConfig.IPv4Address))
  237. }
  238. if v.IPAMConfig.IPv6Address != "" {
  239. n := net.ParseIP(v.IPAMConfig.IPv6Address)
  240. // if the address is an invalid network address (ParseIP == nil) or if it is
  241. // an IPv4 address (To4() != nil), then it is an invalid IPv6 address
  242. if n == nil || n.To4() != nil {
  243. return apierrors.NewBadRequestError(fmt.Errorf("invalid IPv6 address: %s", v.IPAMConfig.IPv6Address))
  244. }
  245. }
  246. }
  247. }
  248. return nil
  249. }
  250. l := make([]string, 0, len(nwConfig.EndpointsConfig))
  251. for k := range nwConfig.EndpointsConfig {
  252. l = append(l, k)
  253. }
  254. err := fmt.Errorf("Container cannot be connected to network endpoints: %s", strings.Join(l, ", "))
  255. return apierrors.NewBadRequestError(err)
  256. }