create.go 28 KB

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