create.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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"
  18. "path/filepath"
  19. "strconv"
  20. "strings"
  21. "github.com/compose-spec/compose-go/types"
  22. moby "github.com/docker/docker/api/types"
  23. "github.com/docker/docker/api/types/blkiodev"
  24. "github.com/docker/docker/api/types/container"
  25. "github.com/docker/docker/api/types/mount"
  26. "github.com/docker/docker/api/types/network"
  27. "github.com/docker/docker/api/types/strslice"
  28. volume_api "github.com/docker/docker/api/types/volume"
  29. "github.com/docker/docker/errdefs"
  30. "github.com/docker/go-connections/nat"
  31. "github.com/docker/go-units"
  32. "github.com/pkg/errors"
  33. "github.com/sirupsen/logrus"
  34. "github.com/docker/compose-cli/pkg/api"
  35. "github.com/docker/compose-cli/pkg/progress"
  36. "github.com/docker/compose-cli/pkg/utils"
  37. )
  38. func (s *composeService) Create(ctx context.Context, project *types.Project, options api.CreateOptions) error {
  39. return progress.Run(ctx, func(ctx context.Context) error {
  40. return s.create(ctx, project, options)
  41. })
  42. }
  43. func (s *composeService) create(ctx context.Context, project *types.Project, options api.CreateOptions) error {
  44. if len(options.Services) == 0 {
  45. options.Services = project.ServiceNames()
  46. }
  47. var observedState Containers
  48. observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true)
  49. if err != nil {
  50. return err
  51. }
  52. err = s.ensureImagesExists(ctx, project, observedState, options.QuietPull)
  53. if err != nil {
  54. return err
  55. }
  56. prepareNetworks(project)
  57. err = prepareVolumes(project)
  58. if err != nil {
  59. return err
  60. }
  61. if err := s.ensureNetworks(ctx, project.Networks); err != nil {
  62. return err
  63. }
  64. if err := s.ensureProjectVolumes(ctx, project); err != nil {
  65. return err
  66. }
  67. allServices := project.AllServices()
  68. allServiceNames := []string{}
  69. for _, service := range allServices {
  70. allServiceNames = append(allServiceNames, service.Name)
  71. }
  72. orphans := observedState.filter(isNotService(allServiceNames...))
  73. if len(orphans) > 0 {
  74. if options.RemoveOrphans {
  75. w := progress.ContextWriter(ctx)
  76. err := s.removeContainers(ctx, w, orphans, nil, false)
  77. if err != nil {
  78. return err
  79. }
  80. } else {
  81. logrus.Warnf("Found orphan containers (%s) for this project. If "+
  82. "you removed or renamed this service in your compose "+
  83. "file, you can run this command with the "+
  84. "--remove-orphans flag to clean it up.", orphans.names())
  85. }
  86. }
  87. prepareServicesDependsOn(project)
  88. return newConvergence(options.Services, observedState, s).apply(ctx, project, options)
  89. }
  90. func prepareVolumes(p *types.Project) error {
  91. for i := range p.Services {
  92. volumesFrom, dependServices, err := getVolumesFrom(p, p.Services[i].VolumesFrom)
  93. if err != nil {
  94. return err
  95. }
  96. p.Services[i].VolumesFrom = volumesFrom
  97. if len(dependServices) > 0 {
  98. if p.Services[i].DependsOn == nil {
  99. p.Services[i].DependsOn = make(types.DependsOnConfig, len(dependServices))
  100. }
  101. for _, service := range p.Services {
  102. if utils.StringContains(dependServices, service.Name) {
  103. p.Services[i].DependsOn[service.Name] = types.ServiceDependency{
  104. Condition: types.ServiceConditionStarted,
  105. }
  106. }
  107. }
  108. }
  109. }
  110. return nil
  111. }
  112. func prepareNetworks(project *types.Project) {
  113. for k, network := range project.Networks {
  114. network.Labels = network.Labels.Add(api.NetworkLabel, k)
  115. network.Labels = network.Labels.Add(api.ProjectLabel, project.Name)
  116. network.Labels = network.Labels.Add(api.VersionLabel, api.ComposeVersion)
  117. project.Networks[k] = network
  118. }
  119. }
  120. func prepareServicesDependsOn(p *types.Project) {
  121. outLoop:
  122. for i := range p.Services {
  123. networkDependency := getDependentServiceFromMode(p.Services[i].NetworkMode)
  124. ipcDependency := getDependentServiceFromMode(p.Services[i].Ipc)
  125. pidDependency := getDependentServiceFromMode(p.Services[i].Pid)
  126. if networkDependency == "" && ipcDependency == "" && pidDependency == "" {
  127. continue
  128. }
  129. if p.Services[i].DependsOn == nil {
  130. p.Services[i].DependsOn = make(types.DependsOnConfig)
  131. }
  132. for _, service := range p.Services {
  133. if service.Name == networkDependency || service.Name == ipcDependency || service.Name == pidDependency {
  134. p.Services[i].DependsOn[service.Name] = types.ServiceDependency{
  135. Condition: types.ServiceConditionStarted,
  136. }
  137. continue outLoop
  138. }
  139. }
  140. }
  141. }
  142. func (s *composeService) ensureNetworks(ctx context.Context, networks types.Networks) error {
  143. for _, network := range networks {
  144. err := s.ensureNetwork(ctx, network)
  145. if err != nil {
  146. return err
  147. }
  148. }
  149. return nil
  150. }
  151. func (s *composeService) ensureProjectVolumes(ctx context.Context, project *types.Project) error {
  152. for k, volume := range project.Volumes {
  153. volume.Labels = volume.Labels.Add(api.VolumeLabel, k)
  154. volume.Labels = volume.Labels.Add(api.ProjectLabel, project.Name)
  155. volume.Labels = volume.Labels.Add(api.VersionLabel, api.ComposeVersion)
  156. err := s.ensureVolume(ctx, volume)
  157. if err != nil {
  158. return err
  159. }
  160. }
  161. return nil
  162. }
  163. func getImageName(service types.ServiceConfig, projectName string) string {
  164. imageName := service.Image
  165. if imageName == "" {
  166. imageName = projectName + "_" + service.Name
  167. }
  168. return imageName
  169. }
  170. func (s *composeService) getCreateOptions(ctx context.Context, p *types.Project, service types.ServiceConfig, number int, inherit *moby.Container,
  171. autoRemove bool) (*container.Config, *container.HostConfig, *network.NetworkingConfig, error) {
  172. hash, err := ServiceHash(service)
  173. if err != nil {
  174. return nil, nil, nil, err
  175. }
  176. labels := map[string]string{}
  177. for k, v := range service.Labels {
  178. labels[k] = v
  179. }
  180. labels[api.ProjectLabel] = p.Name
  181. labels[api.ServiceLabel] = service.Name
  182. labels[api.VersionLabel] = api.ComposeVersion
  183. if _, ok := service.Labels[api.OneoffLabel]; !ok {
  184. labels[api.OneoffLabel] = "False"
  185. }
  186. labels[api.ConfigHashLabel] = hash
  187. labels[api.WorkingDirLabel] = p.WorkingDir
  188. labels[api.ConfigFilesLabel] = strings.Join(p.ComposeFiles, ",")
  189. labels[api.ContainerNumberLabel] = strconv.Itoa(number)
  190. var (
  191. runCmd strslice.StrSlice
  192. entrypoint strslice.StrSlice
  193. )
  194. if len(service.Command) > 0 {
  195. runCmd = strslice.StrSlice(service.Command)
  196. }
  197. if len(service.Entrypoint) > 0 {
  198. entrypoint = strslice.StrSlice(service.Entrypoint)
  199. }
  200. var (
  201. tty = service.Tty
  202. stdinOpen = service.StdinOpen
  203. attachStdin = false
  204. )
  205. volumeMounts, binds, mounts, err := s.buildContainerVolumes(ctx, *p, service, inherit)
  206. if err != nil {
  207. return nil, nil, nil, err
  208. }
  209. containerConfig := container.Config{
  210. Hostname: service.Hostname,
  211. Domainname: service.DomainName,
  212. User: service.User,
  213. ExposedPorts: buildContainerPorts(service),
  214. Tty: tty,
  215. OpenStdin: stdinOpen,
  216. StdinOnce: attachStdin && stdinOpen,
  217. AttachStdin: attachStdin,
  218. AttachStderr: true,
  219. AttachStdout: true,
  220. Cmd: runCmd,
  221. Image: getImageName(service, p.Name),
  222. WorkingDir: service.WorkingDir,
  223. Entrypoint: entrypoint,
  224. NetworkDisabled: service.NetworkMode == "disabled",
  225. MacAddress: service.MacAddress,
  226. Labels: labels,
  227. StopSignal: service.StopSignal,
  228. Env: ToMobyEnv(service.Environment),
  229. Healthcheck: ToMobyHealthCheck(service.HealthCheck),
  230. Volumes: volumeMounts,
  231. StopTimeout: ToSeconds(service.StopGracePeriod),
  232. }
  233. portBindings := buildContainerPortBindingOptions(service)
  234. resources := getDeployResources(service)
  235. if service.NetworkMode == "" {
  236. service.NetworkMode = getDefaultNetworkMode(p, service)
  237. }
  238. var networkConfig *network.NetworkingConfig
  239. for _, id := range service.NetworksByPriority() {
  240. net := p.Networks[id]
  241. config := service.Networks[id]
  242. var ipam *network.EndpointIPAMConfig
  243. var (
  244. ipv4Address string
  245. ipv6Address string
  246. )
  247. if config != nil {
  248. ipv4Address = config.Ipv4Address
  249. ipv6Address = config.Ipv6Address
  250. ipam = &network.EndpointIPAMConfig{
  251. IPv4Address: ipv4Address,
  252. IPv6Address: ipv6Address,
  253. }
  254. }
  255. networkConfig = &network.NetworkingConfig{
  256. EndpointsConfig: map[string]*network.EndpointSettings{
  257. net.Name: {
  258. Aliases: getAliases(service, config),
  259. IPAddress: ipv4Address,
  260. IPv6Gateway: ipv6Address,
  261. IPAMConfig: ipam,
  262. },
  263. },
  264. }
  265. break //nolint:staticcheck
  266. }
  267. tmpfs := map[string]string{}
  268. for _, t := range service.Tmpfs {
  269. if arr := strings.SplitN(t, ":", 2); len(arr) > 1 {
  270. tmpfs[arr[0]] = arr[1]
  271. } else {
  272. tmpfs[arr[0]] = ""
  273. }
  274. }
  275. var logConfig container.LogConfig
  276. if service.Logging != nil {
  277. logConfig = container.LogConfig{
  278. Type: service.Logging.Driver,
  279. Config: service.Logging.Options,
  280. }
  281. }
  282. hostConfig := container.HostConfig{
  283. AutoRemove: autoRemove,
  284. Binds: binds,
  285. Mounts: mounts,
  286. CapAdd: strslice.StrSlice(service.CapAdd),
  287. CapDrop: strslice.StrSlice(service.CapDrop),
  288. NetworkMode: container.NetworkMode(service.NetworkMode),
  289. Init: service.Init,
  290. IpcMode: container.IpcMode(service.Ipc),
  291. ReadonlyRootfs: service.ReadOnly,
  292. RestartPolicy: getRestartPolicy(service),
  293. ShmSize: int64(service.ShmSize),
  294. Sysctls: service.Sysctls,
  295. PortBindings: portBindings,
  296. Resources: resources,
  297. VolumeDriver: service.VolumeDriver,
  298. VolumesFrom: service.VolumesFrom,
  299. DNS: service.DNS,
  300. DNSSearch: service.DNSSearch,
  301. DNSOptions: service.DNSOpts,
  302. ExtraHosts: service.ExtraHosts,
  303. SecurityOpt: service.SecurityOpt,
  304. UsernsMode: container.UsernsMode(service.UserNSMode),
  305. Privileged: service.Privileged,
  306. PidMode: container.PidMode(service.Pid),
  307. Tmpfs: tmpfs,
  308. Isolation: container.Isolation(service.Isolation),
  309. LogConfig: logConfig,
  310. }
  311. return &containerConfig, &hostConfig, networkConfig, nil
  312. }
  313. func getDefaultNetworkMode(project *types.Project, service types.ServiceConfig) string {
  314. mode := "none"
  315. if len(project.Networks) > 0 {
  316. for name := range getNetworksForService(service) {
  317. mode = project.Networks[name].Name
  318. break
  319. }
  320. }
  321. return mode
  322. }
  323. func getRestartPolicy(service types.ServiceConfig) container.RestartPolicy {
  324. var restart container.RestartPolicy
  325. if service.Restart != "" {
  326. split := strings.Split(service.Restart, ":")
  327. var attempts int
  328. if len(split) > 1 {
  329. attempts, _ = strconv.Atoi(split[1])
  330. }
  331. restart = container.RestartPolicy{
  332. Name: split[0],
  333. MaximumRetryCount: attempts,
  334. }
  335. }
  336. if service.Deploy != nil && service.Deploy.RestartPolicy != nil {
  337. policy := *service.Deploy.RestartPolicy
  338. var attempts int
  339. if policy.MaxAttempts != nil {
  340. attempts = int(*policy.MaxAttempts)
  341. }
  342. restart = container.RestartPolicy{
  343. Name: policy.Condition,
  344. MaximumRetryCount: attempts,
  345. }
  346. }
  347. return restart
  348. }
  349. func getDeployResources(s types.ServiceConfig) container.Resources {
  350. var swappiness *int64
  351. if s.MemSwappiness != 0 {
  352. val := int64(s.MemSwappiness)
  353. swappiness = &val
  354. }
  355. resources := container.Resources{
  356. CgroupParent: s.CgroupParent,
  357. Memory: int64(s.MemLimit),
  358. MemorySwap: int64(s.MemSwapLimit),
  359. MemorySwappiness: swappiness,
  360. MemoryReservation: int64(s.MemReservation),
  361. CPUCount: s.CPUCount,
  362. CPUPeriod: s.CPUPeriod,
  363. CPUQuota: s.CPUQuota,
  364. CPURealtimePeriod: s.CPURTPeriod,
  365. CPURealtimeRuntime: s.CPURTRuntime,
  366. CPUShares: s.CPUShares,
  367. CPUPercent: int64(s.CPUS * 100),
  368. CpusetCpus: s.CPUSet,
  369. }
  370. setBlkio(s.BlkioConfig, &resources)
  371. if s.Deploy != nil {
  372. setLimits(s.Deploy.Resources.Limits, &resources)
  373. setReservations(s.Deploy.Resources.Reservations, &resources)
  374. }
  375. for _, device := range s.Devices {
  376. // FIXME should use docker/cli parseDevice, unfortunately private
  377. src := ""
  378. dst := ""
  379. permissions := "rwm"
  380. arr := strings.Split(device, ":")
  381. switch len(arr) {
  382. case 3:
  383. permissions = arr[2]
  384. fallthrough
  385. case 2:
  386. dst = arr[1]
  387. fallthrough
  388. case 1:
  389. src = arr[0]
  390. }
  391. resources.Devices = append(resources.Devices, container.DeviceMapping{
  392. PathOnHost: src,
  393. PathInContainer: dst,
  394. CgroupPermissions: permissions,
  395. })
  396. }
  397. for name, u := range s.Ulimits {
  398. soft := u.Single
  399. if u.Soft != 0 {
  400. soft = u.Soft
  401. }
  402. hard := u.Single
  403. if u.Hard != 0 {
  404. hard = u.Hard
  405. }
  406. resources.Ulimits = append(resources.Ulimits, &units.Ulimit{
  407. Name: name,
  408. Hard: int64(hard),
  409. Soft: int64(soft),
  410. })
  411. }
  412. return resources
  413. }
  414. func setReservations(reservations *types.Resource, resources *container.Resources) {
  415. if reservations == nil {
  416. return
  417. }
  418. for _, device := range reservations.Devices {
  419. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  420. Capabilities: [][]string{device.Capabilities},
  421. Count: int(device.Count),
  422. DeviceIDs: device.IDs,
  423. Driver: device.Driver,
  424. })
  425. }
  426. }
  427. func setLimits(limits *types.Resource, resources *container.Resources) {
  428. if limits == nil {
  429. return
  430. }
  431. if limits.MemoryBytes != 0 {
  432. resources.Memory = int64(limits.MemoryBytes)
  433. }
  434. if limits.NanoCPUs != "" {
  435. i, _ := strconv.ParseInt(limits.NanoCPUs, 10, 64)
  436. resources.NanoCPUs = i
  437. }
  438. }
  439. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  440. if blkio == nil {
  441. return
  442. }
  443. resources.BlkioWeight = blkio.Weight
  444. for _, b := range blkio.WeightDevice {
  445. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  446. Path: b.Path,
  447. Weight: b.Weight,
  448. })
  449. }
  450. for _, b := range blkio.DeviceReadBps {
  451. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  452. Path: b.Path,
  453. Rate: b.Rate,
  454. })
  455. }
  456. for _, b := range blkio.DeviceReadIOps {
  457. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  458. Path: b.Path,
  459. Rate: b.Rate,
  460. })
  461. }
  462. for _, b := range blkio.DeviceWriteBps {
  463. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  464. Path: b.Path,
  465. Rate: b.Rate,
  466. })
  467. }
  468. for _, b := range blkio.DeviceWriteIOps {
  469. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  470. Path: b.Path,
  471. Rate: b.Rate,
  472. })
  473. }
  474. }
  475. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  476. ports := nat.PortSet{}
  477. for _, p := range s.Ports {
  478. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  479. ports[p] = struct{}{}
  480. }
  481. return ports
  482. }
  483. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  484. bindings := nat.PortMap{}
  485. for _, port := range s.Ports {
  486. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  487. bind := bindings[p]
  488. binding := nat.PortBinding{
  489. HostIP: port.HostIP,
  490. }
  491. if port.Published > 0 {
  492. binding.HostPort = fmt.Sprint(port.Published)
  493. }
  494. bind = append(bind, binding)
  495. bindings[p] = bind
  496. }
  497. return bindings
  498. }
  499. func getVolumesFrom(project *types.Project, volumesFrom []string) ([]string, []string, error) {
  500. var volumes = []string{}
  501. var services = []string{}
  502. // parse volumes_from
  503. if len(volumesFrom) == 0 {
  504. return volumes, services, nil
  505. }
  506. for _, vol := range volumesFrom {
  507. spec := strings.Split(vol, ":")
  508. if len(spec) == 0 {
  509. continue
  510. }
  511. if spec[0] == "container" {
  512. volumes = append(volumes, strings.Join(spec[1:], ":"))
  513. continue
  514. }
  515. serviceName := spec[0]
  516. services = append(services, serviceName)
  517. service, err := project.GetService(serviceName)
  518. if err != nil {
  519. return nil, nil, err
  520. }
  521. firstContainer := getContainerName(project.Name, service, 1)
  522. v := fmt.Sprintf("%s:%s", firstContainer, strings.Join(spec[1:], ":"))
  523. volumes = append(volumes, v)
  524. }
  525. return volumes, services, nil
  526. }
  527. func getDependentServiceFromMode(mode string) string {
  528. if strings.HasPrefix(mode, types.NetworkModeServicePrefix) {
  529. return mode[len(types.NetworkModeServicePrefix):]
  530. }
  531. return ""
  532. }
  533. func (s *composeService) buildContainerVolumes(ctx context.Context, p types.Project, service types.ServiceConfig,
  534. inherit *moby.Container) (map[string]struct{}, []string, []mount.Mount, error) {
  535. var mounts = []mount.Mount{}
  536. image := getImageName(service, p.Name)
  537. imgInspect, _, err := s.apiClient.ImageInspectWithRaw(ctx, image)
  538. if err != nil {
  539. return nil, nil, nil, err
  540. }
  541. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  542. if err != nil {
  543. return nil, nil, nil, err
  544. }
  545. volumeMounts := map[string]struct{}{}
  546. binds := []string{}
  547. MOUNTS:
  548. for _, m := range mountOptions {
  549. volumeMounts[m.Target] = struct{}{}
  550. // `Bind` API is used when host path need to be created if missing, `Mount` is preferred otherwise
  551. if m.Type == mount.TypeBind || m.Type == mount.TypeNamedPipe {
  552. for _, v := range service.Volumes {
  553. if v.Target == m.Target && v.Bind != nil && v.Bind.CreateHostPath {
  554. mode := "rw"
  555. if m.ReadOnly {
  556. mode = "ro"
  557. }
  558. binds = append(binds, fmt.Sprintf("%s:%s:%s", m.Source, m.Target, mode))
  559. continue MOUNTS
  560. }
  561. }
  562. }
  563. mounts = append(mounts, m)
  564. }
  565. return volumeMounts, binds, mounts, nil
  566. }
  567. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  568. var mounts = map[string]mount.Mount{}
  569. if inherit != nil {
  570. for _, m := range inherit.Mounts {
  571. if m.Type == "tmpfs" {
  572. continue
  573. }
  574. src := m.Source
  575. if m.Type == "volume" {
  576. src = m.Name
  577. }
  578. m.Destination = path.Clean(m.Destination)
  579. if img.Config != nil {
  580. if _, ok := img.Config.Volumes[m.Destination]; ok {
  581. // inherit previous container's anonymous volume
  582. mounts[m.Destination] = mount.Mount{
  583. Type: m.Type,
  584. Source: src,
  585. Target: m.Destination,
  586. ReadOnly: !m.RW,
  587. }
  588. }
  589. }
  590. for i, v := range s.Volumes {
  591. if v.Target != m.Destination {
  592. continue
  593. }
  594. if v.Source == "" {
  595. // inherit previous container's anonymous volume
  596. mounts[m.Destination] = mount.Mount{
  597. Type: m.Type,
  598. Source: src,
  599. Target: m.Destination,
  600. ReadOnly: !m.RW,
  601. }
  602. // Avoid mount to be later re-defined
  603. l := len(s.Volumes) - 1
  604. s.Volumes[i] = s.Volumes[l]
  605. s.Volumes = s.Volumes[:l]
  606. }
  607. }
  608. }
  609. }
  610. mounts, err := fillBindMounts(p, s, mounts)
  611. if err != nil {
  612. return nil, err
  613. }
  614. values := make([]mount.Mount, 0, len(mounts))
  615. for _, v := range mounts {
  616. values = append(values, v)
  617. }
  618. return values, nil
  619. }
  620. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  621. for _, v := range s.Volumes {
  622. bindMount, err := buildMount(p, v)
  623. if err != nil {
  624. return nil, err
  625. }
  626. m[bindMount.Target] = bindMount
  627. }
  628. secrets, err := buildContainerSecretMounts(p, s)
  629. if err != nil {
  630. return nil, err
  631. }
  632. for _, s := range secrets {
  633. if _, found := m[s.Target]; found {
  634. continue
  635. }
  636. m[s.Target] = s
  637. }
  638. configs, err := buildContainerConfigMounts(p, s)
  639. if err != nil {
  640. return nil, err
  641. }
  642. for _, c := range configs {
  643. if _, found := m[c.Target]; found {
  644. continue
  645. }
  646. m[c.Target] = c
  647. }
  648. return m, nil
  649. }
  650. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  651. var mounts = map[string]mount.Mount{}
  652. configsBaseDir := "/"
  653. for _, config := range s.Configs {
  654. target := config.Target
  655. if config.Target == "" {
  656. target = configsBaseDir + config.Source
  657. } else if !isUnixAbs(config.Target) {
  658. target = configsBaseDir + config.Target
  659. }
  660. definedConfig := p.Configs[config.Source]
  661. if definedConfig.External.External {
  662. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  663. }
  664. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  665. Type: types.VolumeTypeBind,
  666. Source: definedConfig.File,
  667. Target: target,
  668. ReadOnly: true,
  669. })
  670. if err != nil {
  671. return nil, err
  672. }
  673. mounts[target] = bindMount
  674. }
  675. values := make([]mount.Mount, 0, len(mounts))
  676. for _, v := range mounts {
  677. values = append(values, v)
  678. }
  679. return values, nil
  680. }
  681. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  682. var mounts = map[string]mount.Mount{}
  683. secretsDir := "/run/secrets/"
  684. for _, secret := range s.Secrets {
  685. target := secret.Target
  686. if secret.Target == "" {
  687. target = secretsDir + secret.Source
  688. } else if !isUnixAbs(secret.Target) {
  689. target = secretsDir + secret.Target
  690. }
  691. definedSecret := p.Secrets[secret.Source]
  692. if definedSecret.External.External {
  693. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  694. }
  695. mount, err := buildMount(p, types.ServiceVolumeConfig{
  696. Type: types.VolumeTypeBind,
  697. Source: definedSecret.File,
  698. Target: target,
  699. ReadOnly: true,
  700. })
  701. if err != nil {
  702. return nil, err
  703. }
  704. mounts[target] = mount
  705. }
  706. values := make([]mount.Mount, 0, len(mounts))
  707. for _, v := range mounts {
  708. values = append(values, v)
  709. }
  710. return values, nil
  711. }
  712. func isUnixAbs(path string) bool {
  713. return strings.HasPrefix(path, "/")
  714. }
  715. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  716. source := volume.Source
  717. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  718. // do not replace these with filepath.Abs(source) that will include a default drive.
  719. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  720. // volume source has already been prefixed with workdir if required, by compose-go project loader
  721. var err error
  722. source, err = filepath.Abs(source)
  723. if err != nil {
  724. return mount.Mount{}, err
  725. }
  726. }
  727. if volume.Type == types.VolumeTypeVolume {
  728. if volume.Source != "" {
  729. pVolume, ok := project.Volumes[volume.Source]
  730. if ok {
  731. source = pVolume.Name
  732. }
  733. }
  734. }
  735. bind, vol, tmpfs := buildMountOptions(volume)
  736. volume.Target = path.Clean(volume.Target)
  737. return mount.Mount{
  738. Type: mount.Type(volume.Type),
  739. Source: source,
  740. Target: volume.Target,
  741. ReadOnly: volume.ReadOnly,
  742. Consistency: mount.Consistency(volume.Consistency),
  743. BindOptions: bind,
  744. VolumeOptions: vol,
  745. TmpfsOptions: tmpfs,
  746. }, nil
  747. }
  748. func buildMountOptions(volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  749. switch volume.Type {
  750. case "bind":
  751. if volume.Volume != nil {
  752. logrus.Warnf("mount of type `bind` should not define `volume` option")
  753. }
  754. if volume.Tmpfs != nil {
  755. logrus.Warnf("mount of type `tmpfs` should not define `tmpfs` option")
  756. }
  757. return buildBindOption(volume.Bind), nil, nil
  758. case "volume":
  759. if volume.Bind != nil {
  760. logrus.Warnf("mount of type `volume` should not define `bind` option")
  761. }
  762. if volume.Tmpfs != nil {
  763. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  764. }
  765. return nil, buildVolumeOptions(volume.Volume), nil
  766. case "tmpfs":
  767. if volume.Bind != nil {
  768. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  769. }
  770. if volume.Tmpfs != nil {
  771. logrus.Warnf("mount of type `tmpfs` should not define `volumeZ` option")
  772. }
  773. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  774. }
  775. return nil, nil, nil
  776. }
  777. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  778. if bind == nil {
  779. return nil
  780. }
  781. return &mount.BindOptions{
  782. Propagation: mount.Propagation(bind.Propagation),
  783. // NonRecursive: false, FIXME missing from model ?
  784. }
  785. }
  786. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  787. if vol == nil {
  788. return nil
  789. }
  790. return &mount.VolumeOptions{
  791. NoCopy: vol.NoCopy,
  792. // Labels: , // FIXME missing from model ?
  793. // DriverConfig: , // FIXME missing from model ?
  794. }
  795. }
  796. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  797. if tmpfs == nil {
  798. return nil
  799. }
  800. return &mount.TmpfsOptions{
  801. SizeBytes: tmpfs.Size,
  802. // Mode: , // FIXME missing from model ?
  803. }
  804. }
  805. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  806. aliases := []string{s.Name}
  807. if c != nil {
  808. aliases = append(aliases, c.Aliases...)
  809. }
  810. return aliases
  811. }
  812. func getNetworksForService(s types.ServiceConfig) map[string]*types.ServiceNetworkConfig {
  813. if len(s.Networks) > 0 {
  814. return s.Networks
  815. }
  816. if s.NetworkMode != "" {
  817. return nil
  818. }
  819. return map[string]*types.ServiceNetworkConfig{"default": nil}
  820. }
  821. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  822. _, err := s.apiClient.NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  823. if err != nil {
  824. if errdefs.IsNotFound(err) {
  825. if n.External.External {
  826. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  827. }
  828. var ipam *network.IPAM
  829. if n.Ipam.Config != nil {
  830. var config []network.IPAMConfig
  831. for _, pool := range n.Ipam.Config {
  832. config = append(config, network.IPAMConfig{
  833. Subnet: pool.Subnet,
  834. IPRange: pool.IPRange,
  835. Gateway: pool.Gateway,
  836. AuxAddress: pool.AuxiliaryAddresses,
  837. })
  838. }
  839. ipam = &network.IPAM{
  840. Driver: n.Ipam.Driver,
  841. Config: config,
  842. }
  843. }
  844. createOpts := moby.NetworkCreate{
  845. // TODO NameSpace Labels
  846. Labels: n.Labels,
  847. Driver: n.Driver,
  848. Options: n.DriverOpts,
  849. Internal: n.Internal,
  850. Attachable: n.Attachable,
  851. IPAM: ipam,
  852. }
  853. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  854. createOpts.IPAM = &network.IPAM{}
  855. }
  856. if n.Ipam.Driver != "" {
  857. createOpts.IPAM.Driver = n.Ipam.Driver
  858. }
  859. for _, ipamConfig := range n.Ipam.Config {
  860. config := network.IPAMConfig{
  861. Subnet: ipamConfig.Subnet,
  862. }
  863. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  864. }
  865. networkEventName := fmt.Sprintf("Network %s", n.Name)
  866. w := progress.ContextWriter(ctx)
  867. w.Event(progress.CreatingEvent(networkEventName))
  868. if _, err := s.apiClient.NetworkCreate(ctx, n.Name, createOpts); err != nil {
  869. w.Event(progress.ErrorEvent(networkEventName))
  870. return errors.Wrapf(err, "failed to create network %s", n.Name)
  871. }
  872. w.Event(progress.CreatedEvent(networkEventName))
  873. return nil
  874. }
  875. return err
  876. }
  877. return nil
  878. }
  879. func (s *composeService) removeNetwork(ctx context.Context, networkID string, networkName string) error {
  880. w := progress.ContextWriter(ctx)
  881. eventName := fmt.Sprintf("Network %s", networkName)
  882. w.Event(progress.RemovingEvent(eventName))
  883. if err := s.apiClient.NetworkRemove(ctx, networkID); err != nil {
  884. w.Event(progress.ErrorEvent(eventName))
  885. return errors.Wrapf(err, fmt.Sprintf("failed to remove network %s", networkID))
  886. }
  887. w.Event(progress.RemovedEvent(eventName))
  888. return nil
  889. }
  890. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig) error {
  891. // TODO could identify volume by label vs name
  892. _, err := s.apiClient.VolumeInspect(ctx, volume.Name)
  893. if err != nil {
  894. if !errdefs.IsNotFound(err) {
  895. return err
  896. }
  897. eventName := fmt.Sprintf("Volume %q", volume.Name)
  898. w := progress.ContextWriter(ctx)
  899. w.Event(progress.CreatingEvent(eventName))
  900. _, err := s.apiClient.VolumeCreate(ctx, volume_api.VolumeCreateBody{
  901. Labels: volume.Labels,
  902. Name: volume.Name,
  903. Driver: volume.Driver,
  904. DriverOpts: volume.DriverOpts,
  905. })
  906. if err != nil {
  907. w.Event(progress.ErrorEvent(eventName))
  908. return err
  909. }
  910. w.Event(progress.CreatedEvent(eventName))
  911. }
  912. return nil
  913. }