create.go 30 KB

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