create.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "context"
  16. "fmt"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. "github.com/compose-spec/compose-go/types"
  21. moby "github.com/docker/docker/api/types"
  22. "github.com/docker/docker/api/types/container"
  23. "github.com/docker/docker/api/types/filters"
  24. "github.com/docker/docker/api/types/mount"
  25. "github.com/docker/docker/api/types/network"
  26. "github.com/docker/docker/api/types/strslice"
  27. volume_api "github.com/docker/docker/api/types/volume"
  28. "github.com/docker/docker/errdefs"
  29. "github.com/docker/go-connections/nat"
  30. "github.com/pkg/errors"
  31. "github.com/sirupsen/logrus"
  32. "golang.org/x/sync/errgroup"
  33. "github.com/docker/compose-cli/api/compose"
  34. convert "github.com/docker/compose-cli/local/moby"
  35. "github.com/docker/compose-cli/progress"
  36. )
  37. func (s *composeService) Create(ctx context.Context, project *types.Project, opts compose.CreateOptions) error {
  38. err := s.ensureImagesExists(ctx, project)
  39. if err != nil {
  40. return err
  41. }
  42. if err := s.ensureProjectNetworks(ctx, project); err != nil {
  43. return err
  44. }
  45. if err := s.ensureProjectVolumes(ctx, project); err != nil {
  46. return err
  47. }
  48. var observedState Containers
  49. observedState, err = s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
  50. Filters: filters.NewArgs(
  51. projectFilter(project.Name),
  52. ),
  53. All: true,
  54. })
  55. if err != nil {
  56. return err
  57. }
  58. orphans := observedState.filter(isNotService(project.ServiceNames()...))
  59. if len(orphans) > 0 {
  60. if opts.RemoveOrphans {
  61. eg, _ := errgroup.WithContext(ctx)
  62. w := progress.ContextWriter(ctx)
  63. s.removeContainers(ctx, w, eg, orphans)
  64. if eg.Wait() != nil {
  65. return err
  66. }
  67. } else {
  68. logrus.Warnf("Found orphan containers (%s) for this project. If "+
  69. "you removed or renamed this service in your compose "+
  70. "file, you can run this command with the "+
  71. "--remove-orphans flag to clean it up.", orphans.names())
  72. }
  73. }
  74. return InDependencyOrder(ctx, project, func(c context.Context, service types.ServiceConfig) error {
  75. return s.ensureService(c, observedState, project, service)
  76. })
  77. }
  78. func (s *composeService) ensureProjectNetworks(ctx context.Context, project *types.Project) error {
  79. for k, network := range project.Networks {
  80. if !network.External.External && network.Name != "" {
  81. network.Name = fmt.Sprintf("%s_%s", project.Name, k)
  82. project.Networks[k] = network
  83. }
  84. network.Labels = network.Labels.Add(networkLabel, k)
  85. network.Labels = network.Labels.Add(projectLabel, project.Name)
  86. network.Labels = network.Labels.Add(versionLabel, ComposeVersion)
  87. err := s.ensureNetwork(ctx, network)
  88. if err != nil {
  89. return err
  90. }
  91. }
  92. return nil
  93. }
  94. func (s *composeService) ensureProjectVolumes(ctx context.Context, project *types.Project) error {
  95. for k, volume := range project.Volumes {
  96. if !volume.External.External && volume.Name != "" {
  97. volume.Name = fmt.Sprintf("%s_%s", project.Name, k)
  98. project.Volumes[k] = volume
  99. }
  100. volume.Labels = volume.Labels.Add(volumeLabel, k)
  101. volume.Labels = volume.Labels.Add(projectLabel, project.Name)
  102. volume.Labels = volume.Labels.Add(versionLabel, ComposeVersion)
  103. err := s.ensureVolume(ctx, volume)
  104. if err != nil {
  105. return err
  106. }
  107. }
  108. return nil
  109. }
  110. func getCreateOptions(p *types.Project, s types.ServiceConfig, number int, inherit *moby.Container, autoRemove bool) (*container.Config, *container.HostConfig, *network.NetworkingConfig, error) {
  111. hash, err := jsonHash(s)
  112. if err != nil {
  113. return nil, nil, nil, err
  114. }
  115. labels := map[string]string{}
  116. for k, v := range s.Labels {
  117. labels[k] = v
  118. }
  119. labels[projectLabel] = p.Name
  120. labels[serviceLabel] = s.Name
  121. labels[versionLabel] = ComposeVersion
  122. if _, ok := s.Labels[oneoffLabel]; !ok {
  123. labels[oneoffLabel] = "False"
  124. }
  125. labels[configHashLabel] = hash
  126. labels[workingDirLabel] = p.WorkingDir
  127. labels[configFilesLabel] = strings.Join(p.ComposeFiles, ",")
  128. labels[containerNumberLabel] = strconv.Itoa(number)
  129. var (
  130. runCmd strslice.StrSlice
  131. entrypoint strslice.StrSlice
  132. )
  133. if len(s.Command) > 0 {
  134. runCmd = strslice.StrSlice(s.Command)
  135. }
  136. if len(s.Entrypoint) > 0 {
  137. entrypoint = strslice.StrSlice(s.Entrypoint)
  138. }
  139. image := s.Image
  140. if s.Image == "" {
  141. image = fmt.Sprintf("%s_%s", p.Name, s.Name)
  142. }
  143. var (
  144. tty = s.Tty
  145. stdinOpen = s.StdinOpen
  146. attachStdin = false
  147. )
  148. containerConfig := container.Config{
  149. Hostname: s.Hostname,
  150. Domainname: s.DomainName,
  151. User: s.User,
  152. ExposedPorts: buildContainerPorts(s),
  153. Tty: tty,
  154. OpenStdin: stdinOpen,
  155. StdinOnce: true,
  156. AttachStdin: attachStdin,
  157. AttachStderr: true,
  158. AttachStdout: true,
  159. Cmd: runCmd,
  160. Image: image,
  161. WorkingDir: s.WorkingDir,
  162. Entrypoint: entrypoint,
  163. NetworkDisabled: s.NetworkMode == "disabled",
  164. MacAddress: s.MacAddress,
  165. Labels: labels,
  166. StopSignal: s.StopSignal,
  167. Env: convert.ToMobyEnv(s.Environment),
  168. Healthcheck: convert.ToMobyHealthCheck(s.HealthCheck),
  169. // Volumes: // FIXME unclear to me the overlap with HostConfig.Mounts
  170. StopTimeout: convert.ToSeconds(s.StopGracePeriod),
  171. }
  172. mountOptions, err := buildContainerMountOptions(*p, s, inherit)
  173. if err != nil {
  174. return nil, nil, nil, err
  175. }
  176. bindings := buildContainerBindingOptions(s)
  177. resources := getDeployResources(s)
  178. networkMode := getNetworkMode(p, s)
  179. hostConfig := container.HostConfig{
  180. AutoRemove: autoRemove,
  181. Mounts: mountOptions,
  182. CapAdd: strslice.StrSlice(s.CapAdd),
  183. CapDrop: strslice.StrSlice(s.CapDrop),
  184. NetworkMode: networkMode,
  185. Init: s.Init,
  186. ReadonlyRootfs: s.ReadOnly,
  187. // ShmSize: , TODO
  188. Sysctls: s.Sysctls,
  189. PortBindings: bindings,
  190. Resources: resources,
  191. }
  192. networkConfig := buildDefaultNetworkConfig(s, networkMode)
  193. return &containerConfig, &hostConfig, networkConfig, nil
  194. }
  195. func getDeployResources(s types.ServiceConfig) container.Resources {
  196. resources := container.Resources{}
  197. if s.Deploy == nil {
  198. return resources
  199. }
  200. reservations := s.Deploy.Resources.Reservations
  201. if reservations == nil || len(reservations.Devices) == 0 {
  202. return resources
  203. }
  204. for _, device := range reservations.Devices {
  205. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  206. Capabilities: [][]string{device.Capabilities},
  207. Count: int(device.Count),
  208. DeviceIDs: device.IDs,
  209. Driver: device.Driver,
  210. })
  211. }
  212. return resources
  213. }
  214. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  215. ports := nat.PortSet{}
  216. for _, p := range s.Ports {
  217. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  218. ports[p] = struct{}{}
  219. }
  220. return ports
  221. }
  222. func buildContainerBindingOptions(s types.ServiceConfig) nat.PortMap {
  223. bindings := nat.PortMap{}
  224. for _, port := range s.Ports {
  225. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  226. bind := []nat.PortBinding{}
  227. binding := nat.PortBinding{}
  228. if port.Published > 0 {
  229. binding.HostPort = fmt.Sprint(port.Published)
  230. }
  231. bind = append(bind, binding)
  232. bindings[p] = bind
  233. }
  234. return bindings
  235. }
  236. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, inherit *moby.Container) ([]mount.Mount, error) {
  237. mounts := []mount.Mount{}
  238. var inherited []string
  239. if inherit != nil {
  240. for _, m := range inherit.Mounts {
  241. if m.Type == "tmpfs" {
  242. continue
  243. }
  244. src := m.Source
  245. if m.Type == "volume" {
  246. src = m.Name
  247. }
  248. mounts = append(mounts, mount.Mount{
  249. Type: m.Type,
  250. Source: src,
  251. Target: m.Destination,
  252. ReadOnly: !m.RW,
  253. })
  254. inherited = append(inherited, m.Destination)
  255. }
  256. }
  257. for _, v := range s.Volumes {
  258. if contains(inherited, v.Target) {
  259. continue
  260. }
  261. mount, err := buildMount(p, v)
  262. if err != nil {
  263. return nil, err
  264. }
  265. mounts = append(mounts, mount)
  266. }
  267. return mounts, nil
  268. }
  269. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  270. source := volume.Source
  271. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) {
  272. // volume source has already been prefixed with workdir if required, by compose-go project loader
  273. var err error
  274. source, err = filepath.Abs(source)
  275. if err != nil {
  276. return mount.Mount{}, err
  277. }
  278. }
  279. if volume.Type == types.VolumeTypeVolume {
  280. pVolume, ok := project.Volumes[volume.Source]
  281. if ok {
  282. source = pVolume.Name
  283. }
  284. }
  285. return mount.Mount{
  286. Type: mount.Type(volume.Type),
  287. Source: source,
  288. Target: volume.Target,
  289. ReadOnly: volume.ReadOnly,
  290. Consistency: mount.Consistency(volume.Consistency),
  291. BindOptions: buildBindOption(volume.Bind),
  292. VolumeOptions: buildVolumeOptions(volume.Volume),
  293. TmpfsOptions: buildTmpfsOptions(volume.Tmpfs),
  294. }, nil
  295. }
  296. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  297. if bind == nil {
  298. return nil
  299. }
  300. return &mount.BindOptions{
  301. Propagation: mount.Propagation(bind.Propagation),
  302. // NonRecursive: false, FIXME missing from model ?
  303. }
  304. }
  305. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  306. if vol == nil {
  307. return nil
  308. }
  309. return &mount.VolumeOptions{
  310. NoCopy: vol.NoCopy,
  311. // Labels: , // FIXME missing from model ?
  312. // DriverConfig: , // FIXME missing from model ?
  313. }
  314. }
  315. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  316. if tmpfs == nil {
  317. return nil
  318. }
  319. return &mount.TmpfsOptions{
  320. SizeBytes: tmpfs.Size,
  321. // Mode: , // FIXME missing from model ?
  322. }
  323. }
  324. func buildDefaultNetworkConfig(s types.ServiceConfig, networkMode container.NetworkMode) *network.NetworkingConfig {
  325. config := map[string]*network.EndpointSettings{}
  326. net := string(networkMode)
  327. config[net] = &network.EndpointSettings{
  328. Aliases: getAliases(s, s.Networks[net]),
  329. }
  330. return &network.NetworkingConfig{
  331. EndpointsConfig: config,
  332. }
  333. }
  334. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  335. aliases := []string{s.Name}
  336. if c != nil {
  337. aliases = append(aliases, c.Aliases...)
  338. }
  339. return aliases
  340. }
  341. func getNetworkMode(p *types.Project, service types.ServiceConfig) container.NetworkMode {
  342. mode := service.NetworkMode
  343. if mode == "" {
  344. if len(p.Networks) > 0 {
  345. for name := range getNetworksForService(service) {
  346. return container.NetworkMode(p.Networks[name].Name)
  347. }
  348. }
  349. return container.NetworkMode("none")
  350. }
  351. // FIXME incomplete implementation
  352. if strings.HasPrefix(mode, "service:") {
  353. panic("Not yet implemented")
  354. }
  355. if strings.HasPrefix(mode, "container:") {
  356. panic("Not yet implemented")
  357. }
  358. return container.NetworkMode(mode)
  359. }
  360. func getNetworksForService(s types.ServiceConfig) map[string]*types.ServiceNetworkConfig {
  361. if len(s.Networks) > 0 {
  362. return s.Networks
  363. }
  364. return map[string]*types.ServiceNetworkConfig{"default": nil}
  365. }
  366. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  367. _, err := s.apiClient.NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  368. if err != nil {
  369. if errdefs.IsNotFound(err) {
  370. if n.External.External {
  371. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  372. }
  373. createOpts := moby.NetworkCreate{
  374. // TODO NameSpace Labels
  375. Labels: n.Labels,
  376. Driver: n.Driver,
  377. Options: n.DriverOpts,
  378. Internal: n.Internal,
  379. Attachable: n.Attachable,
  380. }
  381. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  382. createOpts.IPAM = &network.IPAM{}
  383. }
  384. if n.Ipam.Driver != "" {
  385. createOpts.IPAM.Driver = n.Ipam.Driver
  386. }
  387. for _, ipamConfig := range n.Ipam.Config {
  388. config := network.IPAMConfig{
  389. Subnet: ipamConfig.Subnet,
  390. }
  391. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  392. }
  393. networkEventName := fmt.Sprintf("Network %q", n.Name)
  394. w := progress.ContextWriter(ctx)
  395. w.Event(progress.CreatingEvent(networkEventName))
  396. if _, err := s.apiClient.NetworkCreate(ctx, n.Name, createOpts); err != nil {
  397. w.Event(progress.ErrorEvent(networkEventName))
  398. return errors.Wrapf(err, "failed to create network %s", n.Name)
  399. }
  400. w.Event(progress.CreatedEvent(networkEventName))
  401. return nil
  402. }
  403. return err
  404. }
  405. return nil
  406. }
  407. func (s *composeService) ensureNetworkDown(ctx context.Context, networkID string, networkName string) error {
  408. w := progress.ContextWriter(ctx)
  409. eventName := fmt.Sprintf("Network %q", networkName)
  410. w.Event(progress.RemovingEvent(eventName))
  411. if err := s.apiClient.NetworkRemove(ctx, networkID); err != nil {
  412. w.Event(progress.ErrorEvent(eventName))
  413. return errors.Wrapf(err, fmt.Sprintf("failed to create network %s", networkID))
  414. }
  415. w.Event(progress.RemovedEvent(eventName))
  416. return nil
  417. }
  418. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig) error {
  419. // TODO could identify volume by label vs name
  420. _, err := s.apiClient.VolumeInspect(ctx, volume.Name)
  421. if err != nil {
  422. if !errdefs.IsNotFound(err) {
  423. return err
  424. }
  425. eventName := fmt.Sprintf("Volume %q", volume.Name)
  426. w := progress.ContextWriter(ctx)
  427. w.Event(progress.CreatingEvent(eventName))
  428. // TODO we miss support for driver_opts and labels
  429. _, err := s.apiClient.VolumeCreate(ctx, volume_api.VolumeCreateBody{
  430. Labels: volume.Labels,
  431. Name: volume.Name,
  432. Driver: volume.Driver,
  433. DriverOpts: volume.DriverOpts,
  434. })
  435. if err != nil {
  436. w.Event(progress.ErrorEvent(eventName))
  437. return err
  438. }
  439. w.Event(progress.CreatedEvent(eventName))
  440. }
  441. return nil
  442. }