create.go 9.2 KB

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