create.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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, project.Name)
  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(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. Runtime: service.Runtime,
  338. LogConfig: logConfig,
  339. GroupAdd: service.GroupAdd,
  340. }
  341. return &containerConfig, &hostConfig, networkConfig, nil
  342. }
  343. // copy/pasted from https://github.com/docker/cli/blob/9de1b162f/cli/command/container/opts.go#L673-L697 + RelativePath
  344. // TODO find so way to share this code with docker/cli
  345. func parseSecurityOpts(p *types.Project, securityOpts []string) ([]string, error) {
  346. for key, opt := range securityOpts {
  347. con := strings.SplitN(opt, "=", 2)
  348. if len(con) == 1 && con[0] != "no-new-privileges" {
  349. if strings.Contains(opt, ":") {
  350. con = strings.SplitN(opt, ":", 2)
  351. } else {
  352. return securityOpts, errors.Errorf("Invalid security-opt: %q", opt)
  353. }
  354. }
  355. if con[0] == "seccomp" && con[1] != "unconfined" {
  356. f, err := ioutil.ReadFile(p.RelativePath(con[1]))
  357. if err != nil {
  358. return securityOpts, errors.Errorf("opening seccomp profile (%s) failed: %v", con[1], err)
  359. }
  360. b := bytes.NewBuffer(nil)
  361. if err := json.Compact(b, f); err != nil {
  362. return securityOpts, errors.Errorf("compacting json for seccomp profile (%s) failed: %v", con[1], err)
  363. }
  364. securityOpts[key] = fmt.Sprintf("seccomp=%s", b.Bytes())
  365. }
  366. }
  367. return securityOpts, nil
  368. }
  369. func (s *composeService) prepareLabels(service types.ServiceConfig, number int) (map[string]string, error) {
  370. labels := map[string]string{}
  371. for k, v := range service.Labels {
  372. labels[k] = v
  373. }
  374. for k, v := range service.CustomLabels {
  375. labels[k] = v
  376. }
  377. hash, err := ServiceHash(service)
  378. if err != nil {
  379. return nil, err
  380. }
  381. labels[api.ConfigHashLabel] = hash
  382. labels[api.ContainerNumberLabel] = strconv.Itoa(number)
  383. var dependencies []string
  384. for s, d := range service.DependsOn {
  385. dependencies = append(dependencies, s+":"+d.Condition)
  386. }
  387. labels[api.DependenciesLabel] = strings.Join(dependencies, ",")
  388. return labels, nil
  389. }
  390. func getDefaultNetworkMode(project *types.Project, service types.ServiceConfig) string {
  391. if len(project.Networks) == 0 {
  392. return "none"
  393. }
  394. if len(service.Networks) > 0 {
  395. name := service.NetworksByPriority()[0]
  396. return project.Networks[name].Name
  397. }
  398. return project.Networks["default"].Name
  399. }
  400. func getRestartPolicy(service types.ServiceConfig) container.RestartPolicy {
  401. var restart container.RestartPolicy
  402. if service.Restart != "" {
  403. split := strings.Split(service.Restart, ":")
  404. var attempts int
  405. if len(split) > 1 {
  406. attempts, _ = strconv.Atoi(split[1])
  407. }
  408. restart = container.RestartPolicy{
  409. Name: split[0],
  410. MaximumRetryCount: attempts,
  411. }
  412. }
  413. if service.Deploy != nil && service.Deploy.RestartPolicy != nil {
  414. policy := *service.Deploy.RestartPolicy
  415. var attempts int
  416. if policy.MaxAttempts != nil {
  417. attempts = int(*policy.MaxAttempts)
  418. }
  419. restart = container.RestartPolicy{
  420. Name: policy.Condition,
  421. MaximumRetryCount: attempts,
  422. }
  423. }
  424. return restart
  425. }
  426. func getDeployResources(s types.ServiceConfig) container.Resources {
  427. var swappiness *int64
  428. if s.MemSwappiness != 0 {
  429. val := int64(s.MemSwappiness)
  430. swappiness = &val
  431. }
  432. resources := container.Resources{
  433. CgroupParent: s.CgroupParent,
  434. Memory: int64(s.MemLimit),
  435. MemorySwap: int64(s.MemSwapLimit),
  436. MemorySwappiness: swappiness,
  437. MemoryReservation: int64(s.MemReservation),
  438. OomKillDisable: &s.OomKillDisable,
  439. CPUCount: s.CPUCount,
  440. CPUPeriod: s.CPUPeriod,
  441. CPUQuota: s.CPUQuota,
  442. CPURealtimePeriod: s.CPURTPeriod,
  443. CPURealtimeRuntime: s.CPURTRuntime,
  444. CPUShares: s.CPUShares,
  445. CPUPercent: int64(s.CPUS * 100),
  446. CpusetCpus: s.CPUSet,
  447. }
  448. if s.PidsLimit != 0 {
  449. resources.PidsLimit = &s.PidsLimit
  450. }
  451. setBlkio(s.BlkioConfig, &resources)
  452. if s.Deploy != nil {
  453. setLimits(s.Deploy.Resources.Limits, &resources)
  454. setReservations(s.Deploy.Resources.Reservations, &resources)
  455. }
  456. for _, device := range s.Devices {
  457. // FIXME should use docker/cli parseDevice, unfortunately private
  458. src := ""
  459. dst := ""
  460. permissions := "rwm"
  461. arr := strings.Split(device, ":")
  462. switch len(arr) {
  463. case 3:
  464. permissions = arr[2]
  465. fallthrough
  466. case 2:
  467. dst = arr[1]
  468. fallthrough
  469. case 1:
  470. src = arr[0]
  471. }
  472. if dst == "" {
  473. dst = src
  474. }
  475. resources.Devices = append(resources.Devices, container.DeviceMapping{
  476. PathOnHost: src,
  477. PathInContainer: dst,
  478. CgroupPermissions: permissions,
  479. })
  480. }
  481. for name, u := range s.Ulimits {
  482. soft := u.Single
  483. if u.Soft != 0 {
  484. soft = u.Soft
  485. }
  486. hard := u.Single
  487. if u.Hard != 0 {
  488. hard = u.Hard
  489. }
  490. resources.Ulimits = append(resources.Ulimits, &units.Ulimit{
  491. Name: name,
  492. Hard: int64(hard),
  493. Soft: int64(soft),
  494. })
  495. }
  496. return resources
  497. }
  498. func setReservations(reservations *types.Resource, resources *container.Resources) {
  499. if reservations == nil {
  500. return
  501. }
  502. for _, device := range reservations.Devices {
  503. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  504. Capabilities: [][]string{device.Capabilities},
  505. Count: int(device.Count),
  506. DeviceIDs: device.IDs,
  507. Driver: device.Driver,
  508. })
  509. }
  510. }
  511. func setLimits(limits *types.Resource, resources *container.Resources) {
  512. if limits == nil {
  513. return
  514. }
  515. if limits.MemoryBytes != 0 {
  516. resources.Memory = int64(limits.MemoryBytes)
  517. }
  518. if limits.NanoCPUs != "" {
  519. i, _ := strconv.ParseInt(limits.NanoCPUs, 10, 64)
  520. resources.NanoCPUs = i
  521. }
  522. }
  523. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  524. if blkio == nil {
  525. return
  526. }
  527. resources.BlkioWeight = blkio.Weight
  528. for _, b := range blkio.WeightDevice {
  529. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  530. Path: b.Path,
  531. Weight: b.Weight,
  532. })
  533. }
  534. for _, b := range blkio.DeviceReadBps {
  535. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  536. Path: b.Path,
  537. Rate: b.Rate,
  538. })
  539. }
  540. for _, b := range blkio.DeviceReadIOps {
  541. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  542. Path: b.Path,
  543. Rate: b.Rate,
  544. })
  545. }
  546. for _, b := range blkio.DeviceWriteBps {
  547. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  548. Path: b.Path,
  549. Rate: b.Rate,
  550. })
  551. }
  552. for _, b := range blkio.DeviceWriteIOps {
  553. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  554. Path: b.Path,
  555. Rate: b.Rate,
  556. })
  557. }
  558. }
  559. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  560. ports := nat.PortSet{}
  561. for _, s := range s.Expose {
  562. p := nat.Port(s)
  563. ports[p] = struct{}{}
  564. }
  565. for _, p := range s.Ports {
  566. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  567. ports[p] = struct{}{}
  568. }
  569. return ports
  570. }
  571. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  572. bindings := nat.PortMap{}
  573. for _, port := range s.Ports {
  574. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  575. binding := nat.PortBinding{
  576. HostIP: port.HostIP,
  577. HostPort: port.Published,
  578. }
  579. bindings[p] = append(bindings[p], binding)
  580. }
  581. return bindings
  582. }
  583. func getVolumesFrom(project *types.Project, volumesFrom []string) ([]string, []string, error) {
  584. var volumes = []string{}
  585. var services = []string{}
  586. // parse volumes_from
  587. if len(volumesFrom) == 0 {
  588. return volumes, services, nil
  589. }
  590. for _, vol := range volumesFrom {
  591. spec := strings.Split(vol, ":")
  592. if len(spec) == 0 {
  593. continue
  594. }
  595. if spec[0] == "container" {
  596. volumes = append(volumes, strings.Join(spec[1:], ":"))
  597. continue
  598. }
  599. serviceName := spec[0]
  600. services = append(services, serviceName)
  601. service, err := project.GetService(serviceName)
  602. if err != nil {
  603. return nil, nil, err
  604. }
  605. firstContainer := getContainerName(project.Name, service, 1)
  606. v := fmt.Sprintf("container:%s", firstContainer)
  607. if len(spec) > 2 {
  608. v = fmt.Sprintf("container:%s:%s", firstContainer, strings.Join(spec[1:], ":"))
  609. }
  610. volumes = append(volumes, v)
  611. }
  612. return volumes, services, nil
  613. }
  614. func getDependentServiceFromMode(mode string) string {
  615. if strings.HasPrefix(mode, types.NetworkModeServicePrefix) {
  616. return mode[len(types.NetworkModeServicePrefix):]
  617. }
  618. return ""
  619. }
  620. func (s *composeService) buildContainerVolumes(ctx context.Context, p types.Project, service types.ServiceConfig,
  621. inherit *moby.Container) (map[string]struct{}, []string, []mount.Mount, error) {
  622. var mounts = []mount.Mount{}
  623. image := getImageName(service, p.Name)
  624. imgInspect, _, err := s.apiClient.ImageInspectWithRaw(ctx, image)
  625. if err != nil {
  626. return nil, nil, nil, err
  627. }
  628. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  629. if err != nil {
  630. return nil, nil, nil, err
  631. }
  632. volumeMounts := map[string]struct{}{}
  633. binds := []string{}
  634. MOUNTS:
  635. for _, m := range mountOptions {
  636. volumeMounts[m.Target] = struct{}{}
  637. // `Bind` API is used when host path need to be created if missing, `Mount` is preferred otherwise
  638. if m.Type == mount.TypeBind || m.Type == mount.TypeNamedPipe {
  639. for _, v := range service.Volumes {
  640. if v.Target == m.Target && v.Bind != nil && v.Bind.CreateHostPath {
  641. binds = append(binds, fmt.Sprintf("%s:%s:%s", m.Source, m.Target, getBindMode(v.Bind, m.ReadOnly)))
  642. continue MOUNTS
  643. }
  644. }
  645. }
  646. mounts = append(mounts, m)
  647. }
  648. return volumeMounts, binds, mounts, nil
  649. }
  650. func getBindMode(bind *types.ServiceVolumeBind, readOnly bool) string {
  651. mode := "rw"
  652. if readOnly {
  653. mode = "ro"
  654. }
  655. switch bind.SELinux {
  656. case types.SELinuxShared:
  657. mode += ",z"
  658. case types.SELinuxPrivate:
  659. mode += ",Z"
  660. }
  661. return mode
  662. }
  663. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  664. var mounts = map[string]mount.Mount{}
  665. if inherit != nil {
  666. for _, m := range inherit.Mounts {
  667. if m.Type == "tmpfs" {
  668. continue
  669. }
  670. src := m.Source
  671. if m.Type == "volume" {
  672. src = m.Name
  673. }
  674. m.Destination = path.Clean(m.Destination)
  675. if img.Config != nil {
  676. if _, ok := img.Config.Volumes[m.Destination]; ok {
  677. // inherit previous container's anonymous volume
  678. mounts[m.Destination] = mount.Mount{
  679. Type: m.Type,
  680. Source: src,
  681. Target: m.Destination,
  682. ReadOnly: !m.RW,
  683. }
  684. }
  685. }
  686. volumes := []types.ServiceVolumeConfig{}
  687. for _, v := range s.Volumes {
  688. if v.Target != m.Destination || v.Source != "" {
  689. volumes = append(volumes, v)
  690. continue
  691. }
  692. // inherit previous container's anonymous volume
  693. mounts[m.Destination] = mount.Mount{
  694. Type: m.Type,
  695. Source: src,
  696. Target: m.Destination,
  697. ReadOnly: !m.RW,
  698. }
  699. }
  700. s.Volumes = volumes
  701. }
  702. }
  703. mounts, err := fillBindMounts(p, s, mounts)
  704. if err != nil {
  705. return nil, err
  706. }
  707. values := make([]mount.Mount, 0, len(mounts))
  708. for _, v := range mounts {
  709. values = append(values, v)
  710. }
  711. return values, nil
  712. }
  713. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  714. for _, v := range s.Volumes {
  715. bindMount, err := buildMount(p, v)
  716. if err != nil {
  717. return nil, err
  718. }
  719. m[bindMount.Target] = bindMount
  720. }
  721. secrets, err := buildContainerSecretMounts(p, s)
  722. if err != nil {
  723. return nil, err
  724. }
  725. for _, s := range secrets {
  726. if _, found := m[s.Target]; found {
  727. continue
  728. }
  729. m[s.Target] = s
  730. }
  731. configs, err := buildContainerConfigMounts(p, s)
  732. if err != nil {
  733. return nil, err
  734. }
  735. for _, c := range configs {
  736. if _, found := m[c.Target]; found {
  737. continue
  738. }
  739. m[c.Target] = c
  740. }
  741. return m, nil
  742. }
  743. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  744. var mounts = map[string]mount.Mount{}
  745. configsBaseDir := "/"
  746. for _, config := range s.Configs {
  747. target := config.Target
  748. if config.Target == "" {
  749. target = configsBaseDir + config.Source
  750. } else if !isUnixAbs(config.Target) {
  751. target = configsBaseDir + config.Target
  752. }
  753. definedConfig := p.Configs[config.Source]
  754. if definedConfig.External.External {
  755. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  756. }
  757. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  758. Type: types.VolumeTypeBind,
  759. Source: definedConfig.File,
  760. Target: target,
  761. ReadOnly: true,
  762. })
  763. if err != nil {
  764. return nil, err
  765. }
  766. mounts[target] = bindMount
  767. }
  768. values := make([]mount.Mount, 0, len(mounts))
  769. for _, v := range mounts {
  770. values = append(values, v)
  771. }
  772. return values, nil
  773. }
  774. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  775. var mounts = map[string]mount.Mount{}
  776. secretsDir := "/run/secrets/"
  777. for _, secret := range s.Secrets {
  778. target := secret.Target
  779. if secret.Target == "" {
  780. target = secretsDir + secret.Source
  781. } else if !isUnixAbs(secret.Target) {
  782. target = secretsDir + secret.Target
  783. }
  784. definedSecret := p.Secrets[secret.Source]
  785. if definedSecret.External.External {
  786. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  787. }
  788. mount, err := buildMount(p, types.ServiceVolumeConfig{
  789. Type: types.VolumeTypeBind,
  790. Source: definedSecret.File,
  791. Target: target,
  792. ReadOnly: true,
  793. })
  794. if err != nil {
  795. return nil, err
  796. }
  797. mounts[target] = mount
  798. }
  799. values := make([]mount.Mount, 0, len(mounts))
  800. for _, v := range mounts {
  801. values = append(values, v)
  802. }
  803. return values, nil
  804. }
  805. func isUnixAbs(path string) bool {
  806. return strings.HasPrefix(path, "/")
  807. }
  808. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  809. source := volume.Source
  810. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  811. // do not replace these with filepath.Abs(source) that will include a default drive.
  812. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  813. // volume source has already been prefixed with workdir if required, by compose-go project loader
  814. var err error
  815. source, err = filepath.Abs(source)
  816. if err != nil {
  817. return mount.Mount{}, err
  818. }
  819. }
  820. if volume.Type == types.VolumeTypeVolume {
  821. if volume.Source != "" {
  822. pVolume, ok := project.Volumes[volume.Source]
  823. if ok {
  824. source = pVolume.Name
  825. }
  826. }
  827. }
  828. bind, vol, tmpfs := buildMountOptions(volume)
  829. volume.Target = path.Clean(volume.Target)
  830. return mount.Mount{
  831. Type: mount.Type(volume.Type),
  832. Source: source,
  833. Target: volume.Target,
  834. ReadOnly: volume.ReadOnly,
  835. Consistency: mount.Consistency(volume.Consistency),
  836. BindOptions: bind,
  837. VolumeOptions: vol,
  838. TmpfsOptions: tmpfs,
  839. }, nil
  840. }
  841. func buildMountOptions(volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  842. switch volume.Type {
  843. case "bind":
  844. if volume.Volume != nil {
  845. logrus.Warnf("mount of type `bind` should not define `volume` option")
  846. }
  847. if volume.Tmpfs != nil {
  848. logrus.Warnf("mount of type `tmpfs` should not define `tmpfs` option")
  849. }
  850. return buildBindOption(volume.Bind), nil, nil
  851. case "volume":
  852. if volume.Bind != nil {
  853. logrus.Warnf("mount of type `volume` should not define `bind` option")
  854. }
  855. if volume.Tmpfs != nil {
  856. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  857. }
  858. return nil, buildVolumeOptions(volume.Volume), nil
  859. case "tmpfs":
  860. if volume.Bind != nil {
  861. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  862. }
  863. if volume.Volume != nil {
  864. logrus.Warnf("mount of type `tmpfs` should not define `volume` option")
  865. }
  866. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  867. }
  868. return nil, nil, nil
  869. }
  870. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  871. if bind == nil {
  872. return nil
  873. }
  874. return &mount.BindOptions{
  875. Propagation: mount.Propagation(bind.Propagation),
  876. // NonRecursive: false, FIXME missing from model ?
  877. }
  878. }
  879. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  880. if vol == nil {
  881. return nil
  882. }
  883. return &mount.VolumeOptions{
  884. NoCopy: vol.NoCopy,
  885. // Labels: , // FIXME missing from model ?
  886. // DriverConfig: , // FIXME missing from model ?
  887. }
  888. }
  889. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  890. if tmpfs == nil {
  891. return nil
  892. }
  893. return &mount.TmpfsOptions{
  894. SizeBytes: int64(tmpfs.Size),
  895. // Mode: , // FIXME missing from model ?
  896. }
  897. }
  898. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  899. aliases := []string{s.Name}
  900. if c != nil {
  901. aliases = append(aliases, c.Aliases...)
  902. }
  903. return aliases
  904. }
  905. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  906. _, err := s.apiClient.NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  907. if err != nil {
  908. if errdefs.IsNotFound(err) {
  909. if n.External.External {
  910. if n.Driver == "overlay" {
  911. // Swarm nodes do not register overlay networks that were
  912. // created on a different node unless they're in use.
  913. // Here we assume `driver` is relevant for a network we don't manage
  914. // which is a non-sense, but this is our legacy ¯\(ツ)/¯
  915. // networkAttach will later fail anyway if network actually doesn't exists
  916. return nil
  917. }
  918. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  919. }
  920. var ipam *network.IPAM
  921. if n.Ipam.Config != nil {
  922. var config []network.IPAMConfig
  923. for _, pool := range n.Ipam.Config {
  924. config = append(config, network.IPAMConfig{
  925. Subnet: pool.Subnet,
  926. IPRange: pool.IPRange,
  927. Gateway: pool.Gateway,
  928. AuxAddress: pool.AuxiliaryAddresses,
  929. })
  930. }
  931. ipam = &network.IPAM{
  932. Driver: n.Ipam.Driver,
  933. Config: config,
  934. }
  935. }
  936. createOpts := moby.NetworkCreate{
  937. // TODO NameSpace Labels
  938. Labels: n.Labels,
  939. Driver: n.Driver,
  940. Options: n.DriverOpts,
  941. Internal: n.Internal,
  942. Attachable: n.Attachable,
  943. IPAM: ipam,
  944. EnableIPv6: n.EnableIPv6,
  945. }
  946. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  947. createOpts.IPAM = &network.IPAM{}
  948. }
  949. if n.Ipam.Driver != "" {
  950. createOpts.IPAM.Driver = n.Ipam.Driver
  951. }
  952. for _, ipamConfig := range n.Ipam.Config {
  953. config := network.IPAMConfig{
  954. Subnet: ipamConfig.Subnet,
  955. }
  956. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  957. }
  958. networkEventName := fmt.Sprintf("Network %s", n.Name)
  959. w := progress.ContextWriter(ctx)
  960. w.Event(progress.CreatingEvent(networkEventName))
  961. if _, err := s.apiClient.NetworkCreate(ctx, n.Name, createOpts); err != nil {
  962. w.Event(progress.ErrorEvent(networkEventName))
  963. return errors.Wrapf(err, "failed to create network %s", n.Name)
  964. }
  965. w.Event(progress.CreatedEvent(networkEventName))
  966. return nil
  967. }
  968. return err
  969. }
  970. return nil
  971. }
  972. func (s *composeService) removeNetwork(ctx context.Context, networkID string, networkName string) error {
  973. w := progress.ContextWriter(ctx)
  974. eventName := fmt.Sprintf("Network %s", networkName)
  975. w.Event(progress.RemovingEvent(eventName))
  976. if err := s.apiClient.NetworkRemove(ctx, networkID); err != nil {
  977. w.Event(progress.ErrorEvent(eventName))
  978. return errors.Wrapf(err, fmt.Sprintf("failed to remove network %s", networkID))
  979. }
  980. w.Event(progress.RemovedEvent(eventName))
  981. return nil
  982. }
  983. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig, project string) error {
  984. inspected, err := s.apiClient.VolumeInspect(ctx, volume.Name)
  985. if err != nil {
  986. if !errdefs.IsNotFound(err) {
  987. return err
  988. }
  989. if volume.External.External {
  990. return fmt.Errorf("external volume %q not found", volume.Name)
  991. }
  992. err := s.createVolume(ctx, volume)
  993. return err
  994. }
  995. if volume.External.External {
  996. return nil
  997. }
  998. // Volume exists with name, but let's double-check this is the expected one
  999. p, ok := inspected.Labels[api.ProjectLabel]
  1000. if !ok {
  1001. logrus.Warnf("volume %q already exists but was not created by Docker Compose. Use `external: true` to use an existing volume", volume.Name)
  1002. }
  1003. if ok && p != project {
  1004. logrus.Warnf("volume %q already exists but was not created for project %q. Use `external: true` to use an existing volume", volume.Name, p)
  1005. }
  1006. return nil
  1007. }
  1008. func (s *composeService) createVolume(ctx context.Context, volume types.VolumeConfig) error {
  1009. eventName := fmt.Sprintf("Volume %q", volume.Name)
  1010. w := progress.ContextWriter(ctx)
  1011. w.Event(progress.CreatingEvent(eventName))
  1012. _, err := s.apiClient.VolumeCreate(ctx, volume_api.VolumeCreateBody{
  1013. Labels: volume.Labels,
  1014. Name: volume.Name,
  1015. Driver: volume.Driver,
  1016. DriverOpts: volume.DriverOpts,
  1017. })
  1018. if err != nil {
  1019. w.Event(progress.ErrorEvent(eventName))
  1020. return err
  1021. }
  1022. w.Event(progress.CreatedEvent(eventName))
  1023. return nil
  1024. }