create.go 28 KB

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