1
0

create.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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 _, s := range s.Expose {
  478. p := nat.Port(s)
  479. ports[p] = struct{}{}
  480. }
  481. for _, p := range s.Ports {
  482. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  483. ports[p] = struct{}{}
  484. }
  485. return ports
  486. }
  487. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  488. bindings := nat.PortMap{}
  489. for _, port := range s.Ports {
  490. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  491. bind := bindings[p]
  492. binding := nat.PortBinding{
  493. HostIP: port.HostIP,
  494. }
  495. if port.Published > 0 {
  496. binding.HostPort = fmt.Sprint(port.Published)
  497. }
  498. bind = append(bind, binding)
  499. bindings[p] = bind
  500. }
  501. return bindings
  502. }
  503. func getVolumesFrom(project *types.Project, volumesFrom []string) ([]string, []string, error) {
  504. var volumes = []string{}
  505. var services = []string{}
  506. // parse volumes_from
  507. if len(volumesFrom) == 0 {
  508. return volumes, services, nil
  509. }
  510. for _, vol := range volumesFrom {
  511. spec := strings.Split(vol, ":")
  512. if len(spec) == 0 {
  513. continue
  514. }
  515. if spec[0] == "container" {
  516. volumes = append(volumes, strings.Join(spec[1:], ":"))
  517. continue
  518. }
  519. serviceName := spec[0]
  520. services = append(services, serviceName)
  521. service, err := project.GetService(serviceName)
  522. if err != nil {
  523. return nil, nil, err
  524. }
  525. firstContainer := getContainerName(project.Name, service, 1)
  526. v := fmt.Sprintf("%s:%s", firstContainer, strings.Join(spec[1:], ":"))
  527. volumes = append(volumes, v)
  528. }
  529. return volumes, services, nil
  530. }
  531. func getDependentServiceFromMode(mode string) string {
  532. if strings.HasPrefix(mode, types.NetworkModeServicePrefix) {
  533. return mode[len(types.NetworkModeServicePrefix):]
  534. }
  535. return ""
  536. }
  537. func (s *composeService) buildContainerVolumes(ctx context.Context, p types.Project, service types.ServiceConfig,
  538. inherit *moby.Container) (map[string]struct{}, []string, []mount.Mount, error) {
  539. var mounts = []mount.Mount{}
  540. image := getImageName(service, p.Name)
  541. imgInspect, _, err := s.apiClient.ImageInspectWithRaw(ctx, image)
  542. if err != nil {
  543. return nil, nil, nil, err
  544. }
  545. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  546. if err != nil {
  547. return nil, nil, nil, err
  548. }
  549. volumeMounts := map[string]struct{}{}
  550. binds := []string{}
  551. MOUNTS:
  552. for _, m := range mountOptions {
  553. volumeMounts[m.Target] = struct{}{}
  554. // `Bind` API is used when host path need to be created if missing, `Mount` is preferred otherwise
  555. if m.Type == mount.TypeBind || m.Type == mount.TypeNamedPipe {
  556. for _, v := range service.Volumes {
  557. if v.Target == m.Target && v.Bind != nil && v.Bind.CreateHostPath {
  558. mode := "rw"
  559. if m.ReadOnly {
  560. mode = "ro"
  561. }
  562. binds = append(binds, fmt.Sprintf("%s:%s:%s", m.Source, m.Target, mode))
  563. continue MOUNTS
  564. }
  565. }
  566. }
  567. mounts = append(mounts, m)
  568. }
  569. return volumeMounts, binds, mounts, nil
  570. }
  571. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  572. var mounts = map[string]mount.Mount{}
  573. if inherit != nil {
  574. for _, m := range inherit.Mounts {
  575. if m.Type == "tmpfs" {
  576. continue
  577. }
  578. src := m.Source
  579. if m.Type == "volume" {
  580. src = m.Name
  581. }
  582. m.Destination = path.Clean(m.Destination)
  583. if img.Config != nil {
  584. if _, ok := img.Config.Volumes[m.Destination]; ok {
  585. // inherit previous container's anonymous volume
  586. mounts[m.Destination] = mount.Mount{
  587. Type: m.Type,
  588. Source: src,
  589. Target: m.Destination,
  590. ReadOnly: !m.RW,
  591. }
  592. }
  593. }
  594. for i, v := range s.Volumes {
  595. if v.Target != m.Destination {
  596. continue
  597. }
  598. if v.Source == "" {
  599. // inherit previous container's anonymous volume
  600. mounts[m.Destination] = mount.Mount{
  601. Type: m.Type,
  602. Source: src,
  603. Target: m.Destination,
  604. ReadOnly: !m.RW,
  605. }
  606. // Avoid mount to be later re-defined
  607. l := len(s.Volumes) - 1
  608. s.Volumes[i] = s.Volumes[l]
  609. s.Volumes = s.Volumes[:l]
  610. }
  611. }
  612. }
  613. }
  614. mounts, err := fillBindMounts(p, s, mounts)
  615. if err != nil {
  616. return nil, err
  617. }
  618. values := make([]mount.Mount, 0, len(mounts))
  619. for _, v := range mounts {
  620. values = append(values, v)
  621. }
  622. return values, nil
  623. }
  624. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  625. for _, v := range s.Volumes {
  626. bindMount, err := buildMount(p, v)
  627. if err != nil {
  628. return nil, err
  629. }
  630. m[bindMount.Target] = bindMount
  631. }
  632. secrets, err := buildContainerSecretMounts(p, s)
  633. if err != nil {
  634. return nil, err
  635. }
  636. for _, s := range secrets {
  637. if _, found := m[s.Target]; found {
  638. continue
  639. }
  640. m[s.Target] = s
  641. }
  642. configs, err := buildContainerConfigMounts(p, s)
  643. if err != nil {
  644. return nil, err
  645. }
  646. for _, c := range configs {
  647. if _, found := m[c.Target]; found {
  648. continue
  649. }
  650. m[c.Target] = c
  651. }
  652. return m, nil
  653. }
  654. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  655. var mounts = map[string]mount.Mount{}
  656. configsBaseDir := "/"
  657. for _, config := range s.Configs {
  658. target := config.Target
  659. if config.Target == "" {
  660. target = configsBaseDir + config.Source
  661. } else if !isUnixAbs(config.Target) {
  662. target = configsBaseDir + config.Target
  663. }
  664. definedConfig := p.Configs[config.Source]
  665. if definedConfig.External.External {
  666. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  667. }
  668. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  669. Type: types.VolumeTypeBind,
  670. Source: definedConfig.File,
  671. Target: target,
  672. ReadOnly: true,
  673. })
  674. if err != nil {
  675. return nil, err
  676. }
  677. mounts[target] = bindMount
  678. }
  679. values := make([]mount.Mount, 0, len(mounts))
  680. for _, v := range mounts {
  681. values = append(values, v)
  682. }
  683. return values, nil
  684. }
  685. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  686. var mounts = map[string]mount.Mount{}
  687. secretsDir := "/run/secrets/"
  688. for _, secret := range s.Secrets {
  689. target := secret.Target
  690. if secret.Target == "" {
  691. target = secretsDir + secret.Source
  692. } else if !isUnixAbs(secret.Target) {
  693. target = secretsDir + secret.Target
  694. }
  695. definedSecret := p.Secrets[secret.Source]
  696. if definedSecret.External.External {
  697. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  698. }
  699. mount, err := buildMount(p, types.ServiceVolumeConfig{
  700. Type: types.VolumeTypeBind,
  701. Source: definedSecret.File,
  702. Target: target,
  703. ReadOnly: true,
  704. })
  705. if err != nil {
  706. return nil, err
  707. }
  708. mounts[target] = mount
  709. }
  710. values := make([]mount.Mount, 0, len(mounts))
  711. for _, v := range mounts {
  712. values = append(values, v)
  713. }
  714. return values, nil
  715. }
  716. func isUnixAbs(path string) bool {
  717. return strings.HasPrefix(path, "/")
  718. }
  719. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  720. source := volume.Source
  721. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  722. // do not replace these with filepath.Abs(source) that will include a default drive.
  723. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  724. // volume source has already been prefixed with workdir if required, by compose-go project loader
  725. var err error
  726. source, err = filepath.Abs(source)
  727. if err != nil {
  728. return mount.Mount{}, err
  729. }
  730. }
  731. if volume.Type == types.VolumeTypeVolume {
  732. if volume.Source != "" {
  733. pVolume, ok := project.Volumes[volume.Source]
  734. if ok {
  735. source = pVolume.Name
  736. }
  737. }
  738. }
  739. bind, vol, tmpfs := buildMountOptions(volume)
  740. volume.Target = path.Clean(volume.Target)
  741. return mount.Mount{
  742. Type: mount.Type(volume.Type),
  743. Source: source,
  744. Target: volume.Target,
  745. ReadOnly: volume.ReadOnly,
  746. Consistency: mount.Consistency(volume.Consistency),
  747. BindOptions: bind,
  748. VolumeOptions: vol,
  749. TmpfsOptions: tmpfs,
  750. }, nil
  751. }
  752. func buildMountOptions(volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  753. switch volume.Type {
  754. case "bind":
  755. if volume.Volume != nil {
  756. logrus.Warnf("mount of type `bind` should not define `volume` option")
  757. }
  758. if volume.Tmpfs != nil {
  759. logrus.Warnf("mount of type `tmpfs` should not define `tmpfs` option")
  760. }
  761. return buildBindOption(volume.Bind), nil, nil
  762. case "volume":
  763. if volume.Bind != nil {
  764. logrus.Warnf("mount of type `volume` should not define `bind` option")
  765. }
  766. if volume.Tmpfs != nil {
  767. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  768. }
  769. return nil, buildVolumeOptions(volume.Volume), nil
  770. case "tmpfs":
  771. if volume.Bind != nil {
  772. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  773. }
  774. if volume.Tmpfs != nil {
  775. logrus.Warnf("mount of type `tmpfs` should not define `volumeZ` option")
  776. }
  777. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  778. }
  779. return nil, nil, nil
  780. }
  781. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  782. if bind == nil {
  783. return nil
  784. }
  785. return &mount.BindOptions{
  786. Propagation: mount.Propagation(bind.Propagation),
  787. // NonRecursive: false, FIXME missing from model ?
  788. }
  789. }
  790. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  791. if vol == nil {
  792. return nil
  793. }
  794. return &mount.VolumeOptions{
  795. NoCopy: vol.NoCopy,
  796. // Labels: , // FIXME missing from model ?
  797. // DriverConfig: , // FIXME missing from model ?
  798. }
  799. }
  800. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  801. if tmpfs == nil {
  802. return nil
  803. }
  804. return &mount.TmpfsOptions{
  805. SizeBytes: tmpfs.Size,
  806. // Mode: , // FIXME missing from model ?
  807. }
  808. }
  809. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  810. aliases := []string{s.Name}
  811. if c != nil {
  812. aliases = append(aliases, c.Aliases...)
  813. }
  814. return aliases
  815. }
  816. func getNetworksForService(s types.ServiceConfig) map[string]*types.ServiceNetworkConfig {
  817. if len(s.Networks) > 0 {
  818. return s.Networks
  819. }
  820. if s.NetworkMode != "" {
  821. return nil
  822. }
  823. return map[string]*types.ServiceNetworkConfig{"default": nil}
  824. }
  825. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  826. _, err := s.apiClient.NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  827. if err != nil {
  828. if errdefs.IsNotFound(err) {
  829. if n.External.External {
  830. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  831. }
  832. var ipam *network.IPAM
  833. if n.Ipam.Config != nil {
  834. var config []network.IPAMConfig
  835. for _, pool := range n.Ipam.Config {
  836. config = append(config, network.IPAMConfig{
  837. Subnet: pool.Subnet,
  838. IPRange: pool.IPRange,
  839. Gateway: pool.Gateway,
  840. AuxAddress: pool.AuxiliaryAddresses,
  841. })
  842. }
  843. ipam = &network.IPAM{
  844. Driver: n.Ipam.Driver,
  845. Config: config,
  846. }
  847. }
  848. createOpts := moby.NetworkCreate{
  849. // TODO NameSpace Labels
  850. Labels: n.Labels,
  851. Driver: n.Driver,
  852. Options: n.DriverOpts,
  853. Internal: n.Internal,
  854. Attachable: n.Attachable,
  855. IPAM: ipam,
  856. }
  857. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  858. createOpts.IPAM = &network.IPAM{}
  859. }
  860. if n.Ipam.Driver != "" {
  861. createOpts.IPAM.Driver = n.Ipam.Driver
  862. }
  863. for _, ipamConfig := range n.Ipam.Config {
  864. config := network.IPAMConfig{
  865. Subnet: ipamConfig.Subnet,
  866. }
  867. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  868. }
  869. networkEventName := fmt.Sprintf("Network %s", n.Name)
  870. w := progress.ContextWriter(ctx)
  871. w.Event(progress.CreatingEvent(networkEventName))
  872. if _, err := s.apiClient.NetworkCreate(ctx, n.Name, createOpts); err != nil {
  873. w.Event(progress.ErrorEvent(networkEventName))
  874. return errors.Wrapf(err, "failed to create network %s", n.Name)
  875. }
  876. w.Event(progress.CreatedEvent(networkEventName))
  877. return nil
  878. }
  879. return err
  880. }
  881. return nil
  882. }
  883. func (s *composeService) removeNetwork(ctx context.Context, networkID string, networkName string) error {
  884. w := progress.ContextWriter(ctx)
  885. eventName := fmt.Sprintf("Network %s", networkName)
  886. w.Event(progress.RemovingEvent(eventName))
  887. if err := s.apiClient.NetworkRemove(ctx, networkID); err != nil {
  888. w.Event(progress.ErrorEvent(eventName))
  889. return errors.Wrapf(err, fmt.Sprintf("failed to remove network %s", networkID))
  890. }
  891. w.Event(progress.RemovedEvent(eventName))
  892. return nil
  893. }
  894. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig) error {
  895. // TODO could identify volume by label vs name
  896. _, err := s.apiClient.VolumeInspect(ctx, volume.Name)
  897. if err != nil {
  898. if !errdefs.IsNotFound(err) {
  899. return err
  900. }
  901. eventName := fmt.Sprintf("Volume %q", volume.Name)
  902. w := progress.ContextWriter(ctx)
  903. w.Event(progress.CreatingEvent(eventName))
  904. _, err := s.apiClient.VolumeCreate(ctx, volume_api.VolumeCreateBody{
  905. Labels: volume.Labels,
  906. Name: volume.Name,
  907. Driver: volume.Driver,
  908. DriverOpts: volume.DriverOpts,
  909. })
  910. if err != nil {
  911. w.Event(progress.ErrorEvent(eventName))
  912. return err
  913. }
  914. w.Event(progress.CreatedEvent(eventName))
  915. }
  916. return nil
  917. }