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. DeviceCgroupRules: s.DeviceCgroupRules,
  448. }
  449. if s.PidsLimit != 0 {
  450. resources.PidsLimit = &s.PidsLimit
  451. }
  452. setBlkio(s.BlkioConfig, &resources)
  453. if s.Deploy != nil {
  454. setLimits(s.Deploy.Resources.Limits, &resources)
  455. setReservations(s.Deploy.Resources.Reservations, &resources)
  456. }
  457. for _, device := range s.Devices {
  458. // FIXME should use docker/cli parseDevice, unfortunately private
  459. src := ""
  460. dst := ""
  461. permissions := "rwm"
  462. arr := strings.Split(device, ":")
  463. switch len(arr) {
  464. case 3:
  465. permissions = arr[2]
  466. fallthrough
  467. case 2:
  468. dst = arr[1]
  469. fallthrough
  470. case 1:
  471. src = arr[0]
  472. }
  473. if dst == "" {
  474. dst = src
  475. }
  476. resources.Devices = append(resources.Devices, container.DeviceMapping{
  477. PathOnHost: src,
  478. PathInContainer: dst,
  479. CgroupPermissions: permissions,
  480. })
  481. }
  482. for name, u := range s.Ulimits {
  483. soft := u.Single
  484. if u.Soft != 0 {
  485. soft = u.Soft
  486. }
  487. hard := u.Single
  488. if u.Hard != 0 {
  489. hard = u.Hard
  490. }
  491. resources.Ulimits = append(resources.Ulimits, &units.Ulimit{
  492. Name: name,
  493. Hard: int64(hard),
  494. Soft: int64(soft),
  495. })
  496. }
  497. return resources
  498. }
  499. func setReservations(reservations *types.Resource, resources *container.Resources) {
  500. if reservations == nil {
  501. return
  502. }
  503. for _, device := range reservations.Devices {
  504. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  505. Capabilities: [][]string{device.Capabilities},
  506. Count: int(device.Count),
  507. DeviceIDs: device.IDs,
  508. Driver: device.Driver,
  509. })
  510. }
  511. }
  512. func setLimits(limits *types.Resource, resources *container.Resources) {
  513. if limits == nil {
  514. return
  515. }
  516. if limits.MemoryBytes != 0 {
  517. resources.Memory = int64(limits.MemoryBytes)
  518. }
  519. if limits.NanoCPUs != "" {
  520. i, _ := strconv.ParseInt(limits.NanoCPUs, 10, 64)
  521. resources.NanoCPUs = i
  522. }
  523. }
  524. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  525. if blkio == nil {
  526. return
  527. }
  528. resources.BlkioWeight = blkio.Weight
  529. for _, b := range blkio.WeightDevice {
  530. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  531. Path: b.Path,
  532. Weight: b.Weight,
  533. })
  534. }
  535. for _, b := range blkio.DeviceReadBps {
  536. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  537. Path: b.Path,
  538. Rate: b.Rate,
  539. })
  540. }
  541. for _, b := range blkio.DeviceReadIOps {
  542. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  543. Path: b.Path,
  544. Rate: b.Rate,
  545. })
  546. }
  547. for _, b := range blkio.DeviceWriteBps {
  548. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  549. Path: b.Path,
  550. Rate: b.Rate,
  551. })
  552. }
  553. for _, b := range blkio.DeviceWriteIOps {
  554. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  555. Path: b.Path,
  556. Rate: b.Rate,
  557. })
  558. }
  559. }
  560. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  561. ports := nat.PortSet{}
  562. for _, s := range s.Expose {
  563. p := nat.Port(s)
  564. ports[p] = struct{}{}
  565. }
  566. for _, p := range s.Ports {
  567. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  568. ports[p] = struct{}{}
  569. }
  570. return ports
  571. }
  572. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  573. bindings := nat.PortMap{}
  574. for _, port := range s.Ports {
  575. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  576. binding := nat.PortBinding{
  577. HostIP: port.HostIP,
  578. HostPort: port.Published,
  579. }
  580. bindings[p] = append(bindings[p], binding)
  581. }
  582. return bindings
  583. }
  584. func getVolumesFrom(project *types.Project, volumesFrom []string) ([]string, []string, error) {
  585. var volumes = []string{}
  586. var services = []string{}
  587. // parse volumes_from
  588. if len(volumesFrom) == 0 {
  589. return volumes, services, nil
  590. }
  591. for _, vol := range volumesFrom {
  592. spec := strings.Split(vol, ":")
  593. if len(spec) == 0 {
  594. continue
  595. }
  596. if spec[0] == "container" {
  597. volumes = append(volumes, strings.Join(spec[1:], ":"))
  598. continue
  599. }
  600. serviceName := spec[0]
  601. services = append(services, serviceName)
  602. service, err := project.GetService(serviceName)
  603. if err != nil {
  604. return nil, nil, err
  605. }
  606. firstContainer := getContainerName(project.Name, service, 1)
  607. v := fmt.Sprintf("container:%s", firstContainer)
  608. if len(spec) > 2 {
  609. v = fmt.Sprintf("container:%s:%s", firstContainer, strings.Join(spec[1:], ":"))
  610. }
  611. volumes = append(volumes, v)
  612. }
  613. return volumes, services, nil
  614. }
  615. func getDependentServiceFromMode(mode string) string {
  616. if strings.HasPrefix(mode, types.NetworkModeServicePrefix) {
  617. return mode[len(types.NetworkModeServicePrefix):]
  618. }
  619. return ""
  620. }
  621. func (s *composeService) buildContainerVolumes(ctx context.Context, p types.Project, service types.ServiceConfig,
  622. inherit *moby.Container) (map[string]struct{}, []string, []mount.Mount, error) {
  623. var mounts = []mount.Mount{}
  624. image := getImageName(service, p.Name)
  625. imgInspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, image)
  626. if err != nil {
  627. return nil, nil, nil, err
  628. }
  629. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  630. if err != nil {
  631. return nil, nil, nil, err
  632. }
  633. volumeMounts := map[string]struct{}{}
  634. binds := []string{}
  635. MOUNTS:
  636. for _, m := range mountOptions {
  637. volumeMounts[m.Target] = struct{}{}
  638. // `Bind` API is used when host path need to be created if missing, `Mount` is preferred otherwise
  639. if m.Type == mount.TypeBind || m.Type == mount.TypeNamedPipe {
  640. for _, v := range service.Volumes {
  641. if v.Target == m.Target && v.Bind != nil && v.Bind.CreateHostPath {
  642. binds = append(binds, fmt.Sprintf("%s:%s:%s", m.Source, m.Target, getBindMode(v.Bind, m.ReadOnly)))
  643. continue MOUNTS
  644. }
  645. }
  646. }
  647. mounts = append(mounts, m)
  648. }
  649. return volumeMounts, binds, mounts, nil
  650. }
  651. func getBindMode(bind *types.ServiceVolumeBind, readOnly bool) string {
  652. mode := "rw"
  653. if readOnly {
  654. mode = "ro"
  655. }
  656. switch bind.SELinux {
  657. case types.SELinuxShared:
  658. mode += ",z"
  659. case types.SELinuxPrivate:
  660. mode += ",Z"
  661. }
  662. return mode
  663. }
  664. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  665. var mounts = map[string]mount.Mount{}
  666. if inherit != nil {
  667. for _, m := range inherit.Mounts {
  668. if m.Type == "tmpfs" {
  669. continue
  670. }
  671. src := m.Source
  672. if m.Type == "volume" {
  673. src = m.Name
  674. }
  675. m.Destination = path.Clean(m.Destination)
  676. if img.Config != nil {
  677. if _, ok := img.Config.Volumes[m.Destination]; ok {
  678. // inherit previous container's anonymous volume
  679. mounts[m.Destination] = mount.Mount{
  680. Type: m.Type,
  681. Source: src,
  682. Target: m.Destination,
  683. ReadOnly: !m.RW,
  684. }
  685. }
  686. }
  687. volumes := []types.ServiceVolumeConfig{}
  688. for _, v := range s.Volumes {
  689. if v.Target != m.Destination || v.Source != "" {
  690. volumes = append(volumes, v)
  691. continue
  692. }
  693. // inherit previous container's anonymous volume
  694. mounts[m.Destination] = mount.Mount{
  695. Type: m.Type,
  696. Source: src,
  697. Target: m.Destination,
  698. ReadOnly: !m.RW,
  699. }
  700. }
  701. s.Volumes = volumes
  702. }
  703. }
  704. mounts, err := fillBindMounts(p, s, mounts)
  705. if err != nil {
  706. return nil, err
  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 fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  715. for _, v := range s.Volumes {
  716. bindMount, err := buildMount(p, v)
  717. if err != nil {
  718. return nil, err
  719. }
  720. m[bindMount.Target] = bindMount
  721. }
  722. secrets, err := buildContainerSecretMounts(p, s)
  723. if err != nil {
  724. return nil, err
  725. }
  726. for _, s := range secrets {
  727. if _, found := m[s.Target]; found {
  728. continue
  729. }
  730. m[s.Target] = s
  731. }
  732. configs, err := buildContainerConfigMounts(p, s)
  733. if err != nil {
  734. return nil, err
  735. }
  736. for _, c := range configs {
  737. if _, found := m[c.Target]; found {
  738. continue
  739. }
  740. m[c.Target] = c
  741. }
  742. return m, nil
  743. }
  744. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  745. var mounts = map[string]mount.Mount{}
  746. configsBaseDir := "/"
  747. for _, config := range s.Configs {
  748. target := config.Target
  749. if config.Target == "" {
  750. target = configsBaseDir + config.Source
  751. } else if !isUnixAbs(config.Target) {
  752. target = configsBaseDir + config.Target
  753. }
  754. definedConfig := p.Configs[config.Source]
  755. if definedConfig.External.External {
  756. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  757. }
  758. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  759. Type: types.VolumeTypeBind,
  760. Source: definedConfig.File,
  761. Target: target,
  762. ReadOnly: true,
  763. })
  764. if err != nil {
  765. return nil, err
  766. }
  767. mounts[target] = bindMount
  768. }
  769. values := make([]mount.Mount, 0, len(mounts))
  770. for _, v := range mounts {
  771. values = append(values, v)
  772. }
  773. return values, nil
  774. }
  775. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  776. var mounts = map[string]mount.Mount{}
  777. secretsDir := "/run/secrets/"
  778. for _, secret := range s.Secrets {
  779. target := secret.Target
  780. if secret.Target == "" {
  781. target = secretsDir + secret.Source
  782. } else if !isUnixAbs(secret.Target) {
  783. target = secretsDir + secret.Target
  784. }
  785. definedSecret := p.Secrets[secret.Source]
  786. if definedSecret.External.External {
  787. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  788. }
  789. mount, err := buildMount(p, types.ServiceVolumeConfig{
  790. Type: types.VolumeTypeBind,
  791. Source: definedSecret.File,
  792. Target: target,
  793. ReadOnly: true,
  794. })
  795. if err != nil {
  796. return nil, err
  797. }
  798. mounts[target] = mount
  799. }
  800. values := make([]mount.Mount, 0, len(mounts))
  801. for _, v := range mounts {
  802. values = append(values, v)
  803. }
  804. return values, nil
  805. }
  806. func isUnixAbs(path string) bool {
  807. return strings.HasPrefix(path, "/")
  808. }
  809. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  810. source := volume.Source
  811. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  812. // do not replace these with filepath.Abs(source) that will include a default drive.
  813. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  814. // volume source has already been prefixed with workdir if required, by compose-go project loader
  815. var err error
  816. source, err = filepath.Abs(source)
  817. if err != nil {
  818. return mount.Mount{}, err
  819. }
  820. }
  821. if volume.Type == types.VolumeTypeVolume {
  822. if volume.Source != "" {
  823. pVolume, ok := project.Volumes[volume.Source]
  824. if ok {
  825. source = pVolume.Name
  826. }
  827. }
  828. }
  829. bind, vol, tmpfs := buildMountOptions(volume)
  830. volume.Target = path.Clean(volume.Target)
  831. return mount.Mount{
  832. Type: mount.Type(volume.Type),
  833. Source: source,
  834. Target: volume.Target,
  835. ReadOnly: volume.ReadOnly,
  836. Consistency: mount.Consistency(volume.Consistency),
  837. BindOptions: bind,
  838. VolumeOptions: vol,
  839. TmpfsOptions: tmpfs,
  840. }, nil
  841. }
  842. func buildMountOptions(volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  843. switch volume.Type {
  844. case "bind":
  845. if volume.Volume != nil {
  846. logrus.Warnf("mount of type `bind` should not define `volume` option")
  847. }
  848. if volume.Tmpfs != nil {
  849. logrus.Warnf("mount of type `tmpfs` should not define `tmpfs` option")
  850. }
  851. return buildBindOption(volume.Bind), nil, nil
  852. case "volume":
  853. if volume.Bind != nil {
  854. logrus.Warnf("mount of type `volume` should not define `bind` option")
  855. }
  856. if volume.Tmpfs != nil {
  857. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  858. }
  859. return nil, buildVolumeOptions(volume.Volume), nil
  860. case "tmpfs":
  861. if volume.Bind != nil {
  862. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  863. }
  864. if volume.Volume != nil {
  865. logrus.Warnf("mount of type `tmpfs` should not define `volume` option")
  866. }
  867. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  868. }
  869. return nil, nil, nil
  870. }
  871. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  872. if bind == nil {
  873. return nil
  874. }
  875. return &mount.BindOptions{
  876. Propagation: mount.Propagation(bind.Propagation),
  877. // NonRecursive: false, FIXME missing from model ?
  878. }
  879. }
  880. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  881. if vol == nil {
  882. return nil
  883. }
  884. return &mount.VolumeOptions{
  885. NoCopy: vol.NoCopy,
  886. // Labels: , // FIXME missing from model ?
  887. // DriverConfig: , // FIXME missing from model ?
  888. }
  889. }
  890. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  891. if tmpfs == nil {
  892. return nil
  893. }
  894. return &mount.TmpfsOptions{
  895. SizeBytes: int64(tmpfs.Size),
  896. // Mode: , // FIXME missing from model ?
  897. }
  898. }
  899. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  900. aliases := []string{s.Name}
  901. if c != nil {
  902. aliases = append(aliases, c.Aliases...)
  903. }
  904. return aliases
  905. }
  906. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  907. _, err := s.apiClient().NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  908. if err != nil {
  909. if errdefs.IsNotFound(err) {
  910. if n.External.External {
  911. if n.Driver == "overlay" {
  912. // Swarm nodes do not register overlay networks that were
  913. // created on a different node unless they're in use.
  914. // Here we assume `driver` is relevant for a network we don't manage
  915. // which is a non-sense, but this is our legacy ¯\(ツ)/¯
  916. // networkAttach will later fail anyway if network actually doesn't exists
  917. return nil
  918. }
  919. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  920. }
  921. var ipam *network.IPAM
  922. if n.Ipam.Config != nil {
  923. var config []network.IPAMConfig
  924. for _, pool := range n.Ipam.Config {
  925. config = append(config, network.IPAMConfig{
  926. Subnet: pool.Subnet,
  927. IPRange: pool.IPRange,
  928. Gateway: pool.Gateway,
  929. AuxAddress: pool.AuxiliaryAddresses,
  930. })
  931. }
  932. ipam = &network.IPAM{
  933. Driver: n.Ipam.Driver,
  934. Config: config,
  935. }
  936. }
  937. createOpts := moby.NetworkCreate{
  938. // TODO NameSpace Labels
  939. Labels: n.Labels,
  940. Driver: n.Driver,
  941. Options: n.DriverOpts,
  942. Internal: n.Internal,
  943. Attachable: n.Attachable,
  944. IPAM: ipam,
  945. EnableIPv6: n.EnableIPv6,
  946. }
  947. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  948. createOpts.IPAM = &network.IPAM{}
  949. }
  950. if n.Ipam.Driver != "" {
  951. createOpts.IPAM.Driver = n.Ipam.Driver
  952. }
  953. for _, ipamConfig := range n.Ipam.Config {
  954. config := network.IPAMConfig{
  955. Subnet: ipamConfig.Subnet,
  956. }
  957. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  958. }
  959. networkEventName := fmt.Sprintf("Network %s", n.Name)
  960. w := progress.ContextWriter(ctx)
  961. w.Event(progress.CreatingEvent(networkEventName))
  962. if _, err := s.apiClient().NetworkCreate(ctx, n.Name, createOpts); err != nil {
  963. w.Event(progress.ErrorEvent(networkEventName))
  964. return errors.Wrapf(err, "failed to create network %s", n.Name)
  965. }
  966. w.Event(progress.CreatedEvent(networkEventName))
  967. return nil
  968. }
  969. return err
  970. }
  971. return nil
  972. }
  973. func (s *composeService) removeNetwork(ctx context.Context, network string, w progress.Writer) error {
  974. eventName := fmt.Sprintf("Network %s", network)
  975. w.Event(progress.RemovingEvent(eventName))
  976. if err := s.apiClient().NetworkRemove(ctx, network); err != nil {
  977. w.Event(progress.ErrorEvent(eventName))
  978. return errors.Wrapf(err, fmt.Sprintf("failed to remove network %s", network))
  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. }