create.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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. "errors"
  19. "fmt"
  20. "os"
  21. "path"
  22. "path/filepath"
  23. "strconv"
  24. "strings"
  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/filters"
  29. "github.com/docker/docker/api/types/mount"
  30. "github.com/docker/docker/api/types/network"
  31. "github.com/docker/docker/api/types/strslice"
  32. "github.com/docker/docker/api/types/versions"
  33. volume_api "github.com/docker/docker/api/types/volume"
  34. "github.com/docker/docker/errdefs"
  35. "github.com/docker/go-connections/nat"
  36. "github.com/docker/go-units"
  37. "github.com/sirupsen/logrus"
  38. "github.com/compose-spec/compose-go/v2/types"
  39. "github.com/docker/compose/v2/pkg/api"
  40. "github.com/docker/compose/v2/pkg/progress"
  41. "github.com/docker/compose/v2/pkg/utils"
  42. )
  43. type createOptions struct {
  44. AutoRemove bool
  45. AttachStdin bool
  46. UseNetworkAliases bool
  47. Labels types.Labels
  48. }
  49. type createConfigs struct {
  50. Container *container.Config
  51. Host *container.HostConfig
  52. Network *network.NetworkingConfig
  53. Links []string
  54. }
  55. func (s *composeService) Create(ctx context.Context, project *types.Project, createOpts api.CreateOptions) error {
  56. return progress.RunWithTitle(ctx, func(ctx context.Context) error {
  57. return s.create(ctx, project, createOpts)
  58. }, s.stdinfo(), "Creating")
  59. }
  60. func (s *composeService) create(ctx context.Context, project *types.Project, options api.CreateOptions) error {
  61. if len(options.Services) == 0 {
  62. options.Services = project.ServiceNames()
  63. }
  64. var observedState Containers
  65. observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true)
  66. if err != nil {
  67. return err
  68. }
  69. err = s.ensureImagesExists(ctx, project, options.Build, options.QuietPull)
  70. if err != nil {
  71. return err
  72. }
  73. prepareNetworks(project)
  74. if err := s.ensureNetworks(ctx, project.Networks); err != nil {
  75. return err
  76. }
  77. if err := s.ensureProjectVolumes(ctx, project); err != nil {
  78. return err
  79. }
  80. allServiceNames := append(project.ServiceNames(), project.DisabledServiceNames()...)
  81. orphans := observedState.filter(isNotService(allServiceNames...))
  82. if len(orphans) > 0 && !options.IgnoreOrphans {
  83. if options.RemoveOrphans {
  84. err := s.removeContainers(ctx, orphans, nil, false)
  85. if err != nil {
  86. return err
  87. }
  88. } else {
  89. logrus.Warnf("Found orphan containers (%s) for this project. If "+
  90. "you removed or renamed this service in your compose "+
  91. "file, you can run this command with the "+
  92. "--remove-orphans flag to clean it up.", orphans.names())
  93. }
  94. }
  95. return newConvergence(options.Services, observedState, s).apply(ctx, project, options)
  96. }
  97. func prepareNetworks(project *types.Project) {
  98. for k, network := range project.Networks {
  99. network.Labels = network.Labels.Add(api.NetworkLabel, k)
  100. network.Labels = network.Labels.Add(api.ProjectLabel, project.Name)
  101. network.Labels = network.Labels.Add(api.VersionLabel, api.ComposeVersion)
  102. project.Networks[k] = network
  103. }
  104. }
  105. func (s *composeService) ensureNetworks(ctx context.Context, networks types.Networks) error {
  106. for i, network := range networks {
  107. err := s.ensureNetwork(ctx, &network)
  108. if err != nil {
  109. return err
  110. }
  111. networks[i] = network
  112. }
  113. return nil
  114. }
  115. func (s *composeService) ensureProjectVolumes(ctx context.Context, project *types.Project) error {
  116. for k, volume := range project.Volumes {
  117. volume.Labels = volume.Labels.Add(api.VolumeLabel, k)
  118. volume.Labels = volume.Labels.Add(api.ProjectLabel, project.Name)
  119. volume.Labels = volume.Labels.Add(api.VersionLabel, api.ComposeVersion)
  120. err := s.ensureVolume(ctx, volume, project.Name)
  121. if err != nil {
  122. return err
  123. }
  124. }
  125. return nil
  126. }
  127. func (s *composeService) getCreateConfigs(ctx context.Context,
  128. p *types.Project,
  129. service types.ServiceConfig,
  130. number int,
  131. inherit *moby.Container,
  132. opts createOptions,
  133. ) (createConfigs, error) {
  134. labels, err := s.prepareLabels(opts.Labels, service, number)
  135. if err != nil {
  136. return createConfigs{}, err
  137. }
  138. var (
  139. runCmd strslice.StrSlice
  140. entrypoint strslice.StrSlice
  141. )
  142. if service.Command != nil {
  143. runCmd = strslice.StrSlice(service.Command)
  144. }
  145. if service.Entrypoint != nil {
  146. entrypoint = strslice.StrSlice(service.Entrypoint)
  147. }
  148. var (
  149. tty = service.Tty
  150. stdinOpen = service.StdinOpen
  151. )
  152. proxyConfig := types.MappingWithEquals(s.configFile().ParseProxyConfig(s.apiClient().DaemonHost(), nil))
  153. env := proxyConfig.OverrideBy(service.Environment)
  154. var mainNwName string
  155. var mainNw *types.ServiceNetworkConfig
  156. if len(service.Networks) > 0 {
  157. mainNwName = service.NetworksByPriority()[0]
  158. mainNw = service.Networks[mainNwName]
  159. }
  160. macAddress, err := s.prepareContainerMACAddress(ctx, service, mainNw, mainNwName)
  161. if err != nil {
  162. return createConfigs{}, err
  163. }
  164. healthcheck, err := s.ToMobyHealthCheck(ctx, service.HealthCheck)
  165. if err != nil {
  166. return createConfigs{}, err
  167. }
  168. var containerConfig = container.Config{
  169. Hostname: service.Hostname,
  170. Domainname: service.DomainName,
  171. User: service.User,
  172. ExposedPorts: buildContainerPorts(service),
  173. Tty: tty,
  174. OpenStdin: stdinOpen,
  175. StdinOnce: opts.AttachStdin && stdinOpen,
  176. AttachStdin: opts.AttachStdin,
  177. AttachStderr: true,
  178. AttachStdout: true,
  179. Cmd: runCmd,
  180. Image: api.GetImageNameOrDefault(service, p.Name),
  181. WorkingDir: service.WorkingDir,
  182. Entrypoint: entrypoint,
  183. NetworkDisabled: service.NetworkMode == "disabled",
  184. MacAddress: macAddress,
  185. Labels: labels,
  186. StopSignal: service.StopSignal,
  187. Env: ToMobyEnv(env),
  188. Healthcheck: healthcheck,
  189. StopTimeout: ToSeconds(service.StopGracePeriod),
  190. } // VOLUMES/MOUNTS/FILESYSTEMS
  191. tmpfs := map[string]string{}
  192. for _, t := range service.Tmpfs {
  193. if arr := strings.SplitN(t, ":", 2); len(arr) > 1 {
  194. tmpfs[arr[0]] = arr[1]
  195. } else {
  196. tmpfs[arr[0]] = ""
  197. }
  198. }
  199. binds, mounts, err := s.buildContainerVolumes(ctx, *p, service, inherit)
  200. if err != nil {
  201. return createConfigs{}, err
  202. }
  203. // NETWORKING
  204. links, err := s.getLinks(ctx, p.Name, service, number)
  205. if err != nil {
  206. return createConfigs{}, err
  207. }
  208. networkMode, networkingConfig := defaultNetworkSettings(p, service, number, links, opts.UseNetworkAliases)
  209. portBindings := buildContainerPortBindingOptions(service)
  210. // MISC
  211. resources := getDeployResources(service)
  212. var logConfig container.LogConfig
  213. if service.Logging != nil {
  214. logConfig = container.LogConfig{
  215. Type: service.Logging.Driver,
  216. Config: service.Logging.Options,
  217. }
  218. }
  219. securityOpts, unconfined, err := parseSecurityOpts(p, service.SecurityOpt)
  220. if err != nil {
  221. return createConfigs{}, err
  222. }
  223. hostConfig := container.HostConfig{
  224. AutoRemove: opts.AutoRemove,
  225. Binds: binds,
  226. Mounts: mounts,
  227. CapAdd: strslice.StrSlice(service.CapAdd),
  228. CapDrop: strslice.StrSlice(service.CapDrop),
  229. NetworkMode: networkMode,
  230. Init: service.Init,
  231. IpcMode: container.IpcMode(service.Ipc),
  232. CgroupnsMode: container.CgroupnsMode(service.Cgroup),
  233. ReadonlyRootfs: service.ReadOnly,
  234. RestartPolicy: getRestartPolicy(service),
  235. ShmSize: int64(service.ShmSize),
  236. Sysctls: service.Sysctls,
  237. PortBindings: portBindings,
  238. Resources: resources,
  239. VolumeDriver: service.VolumeDriver,
  240. VolumesFrom: service.VolumesFrom,
  241. DNS: service.DNS,
  242. DNSSearch: service.DNSSearch,
  243. DNSOptions: service.DNSOpts,
  244. ExtraHosts: service.ExtraHosts.AsList(":"),
  245. SecurityOpt: securityOpts,
  246. UsernsMode: container.UsernsMode(service.UserNSMode),
  247. UTSMode: container.UTSMode(service.Uts),
  248. Privileged: service.Privileged,
  249. PidMode: container.PidMode(service.Pid),
  250. Tmpfs: tmpfs,
  251. Isolation: container.Isolation(service.Isolation),
  252. Runtime: service.Runtime,
  253. LogConfig: logConfig,
  254. GroupAdd: service.GroupAdd,
  255. Links: links,
  256. OomScoreAdj: int(service.OomScoreAdj),
  257. }
  258. if unconfined {
  259. hostConfig.MaskedPaths = []string{}
  260. hostConfig.ReadonlyPaths = []string{}
  261. }
  262. cfgs := createConfigs{
  263. Container: &containerConfig,
  264. Host: &hostConfig,
  265. Network: networkingConfig,
  266. Links: links,
  267. }
  268. return cfgs, nil
  269. }
  270. // prepareContainerMACAddress handles the service-level mac_address field and the newer mac_address field added to service
  271. // network config. This newer field is only compatible with the Engine API v1.44 (and onwards), and this API version
  272. // also deprecates the container-wide mac_address field. Thus, this method will validate service config and mutate the
  273. // passed mainNw to provide backward-compatibility whenever possible.
  274. //
  275. // It returns the container-wide MAC address, but this value will be kept empty for newer API versions.
  276. func (s *composeService) prepareContainerMACAddress(ctx context.Context, service types.ServiceConfig, mainNw *types.ServiceNetworkConfig, nwName string) (string, error) {
  277. version, err := s.RuntimeVersion(ctx)
  278. if err != nil {
  279. return "", err
  280. }
  281. // Engine API 1.44 added support for endpoint-specific MAC address and now returns a warning when a MAC address is
  282. // set in container.Config. Thus, we have to jump through a number of hoops:
  283. //
  284. // 1. Top-level mac_address and main endpoint's MAC address should be the same ;
  285. // 2. If supported by the API, top-level mac_address should be migrated to the main endpoint and container.Config
  286. // should be kept empty ;
  287. // 3. Otherwise, the endpoint mac_address should be set in container.Config and no other endpoint-specific
  288. // mac_address can be specified. If that's the case, use top-level mac_address ;
  289. //
  290. // After that, if an endpoint mac_address is set, it's either user-defined or migrated by the code below, so
  291. // there's no need to check for API version in defaultNetworkSettings.
  292. macAddress := service.MacAddress
  293. if macAddress != "" && mainNw != nil && mainNw.MacAddress != "" && mainNw.MacAddress != macAddress {
  294. return "", fmt.Errorf("the service-level mac_address should have the same value as network %s", nwName)
  295. }
  296. if versions.GreaterThanOrEqualTo(version, "1.44") {
  297. if mainNw != nil && mainNw.MacAddress == "" {
  298. mainNw.MacAddress = macAddress
  299. }
  300. macAddress = ""
  301. } else if len(service.Networks) > 0 {
  302. var withMacAddress []string
  303. for nwName, nw := range service.Networks {
  304. if nw != nil && nw.MacAddress != "" {
  305. withMacAddress = append(withMacAddress, nwName)
  306. }
  307. }
  308. if len(withMacAddress) > 1 {
  309. return "", fmt.Errorf("a MAC address is specified for multiple networks (%s), but this feature requires Docker Engine 1.44 or later (currently: %s)", strings.Join(withMacAddress, ", "), version)
  310. }
  311. if mainNw != nil {
  312. macAddress = mainNw.MacAddress
  313. }
  314. }
  315. return macAddress, nil
  316. }
  317. func getAliases(project *types.Project, service types.ServiceConfig, serviceIndex int, networkKey string, useNetworkAliases bool) []string {
  318. aliases := []string{getContainerName(project.Name, service, serviceIndex)}
  319. if useNetworkAliases {
  320. aliases = append(aliases, service.Name)
  321. if cfg := service.Networks[networkKey]; cfg != nil {
  322. aliases = append(aliases, cfg.Aliases...)
  323. }
  324. }
  325. return aliases
  326. }
  327. func createEndpointSettings(p *types.Project, service types.ServiceConfig, serviceIndex int, networkKey string, links []string, useNetworkAliases bool) *network.EndpointSettings {
  328. config := service.Networks[networkKey]
  329. var ipam *network.EndpointIPAMConfig
  330. var (
  331. ipv4Address string
  332. ipv6Address string
  333. macAddress string
  334. )
  335. if config != nil {
  336. ipv4Address = config.Ipv4Address
  337. ipv6Address = config.Ipv6Address
  338. ipam = &network.EndpointIPAMConfig{
  339. IPv4Address: ipv4Address,
  340. IPv6Address: ipv6Address,
  341. LinkLocalIPs: config.LinkLocalIPs,
  342. }
  343. macAddress = config.MacAddress
  344. }
  345. return &network.EndpointSettings{
  346. Aliases: getAliases(p, service, serviceIndex, networkKey, useNetworkAliases),
  347. Links: links,
  348. IPAddress: ipv4Address,
  349. IPv6Gateway: ipv6Address,
  350. IPAMConfig: ipam,
  351. MacAddress: macAddress,
  352. }
  353. }
  354. // copy/pasted from https://github.com/docker/cli/blob/9de1b162f/cli/command/container/opts.go#L673-L697 + RelativePath
  355. // TODO find so way to share this code with docker/cli
  356. func parseSecurityOpts(p *types.Project, securityOpts []string) ([]string, bool, error) {
  357. var (
  358. unconfined bool
  359. parsed []string
  360. )
  361. for _, opt := range securityOpts {
  362. if opt == "systempaths=unconfined" {
  363. unconfined = true
  364. continue
  365. }
  366. con := strings.SplitN(opt, "=", 2)
  367. if len(con) == 1 && con[0] != "no-new-privileges" {
  368. if strings.Contains(opt, ":") {
  369. con = strings.SplitN(opt, ":", 2)
  370. } else {
  371. return securityOpts, false, fmt.Errorf("Invalid security-opt: %q", opt)
  372. }
  373. }
  374. if con[0] == "seccomp" && con[1] != "unconfined" {
  375. f, err := os.ReadFile(p.RelativePath(con[1]))
  376. if err != nil {
  377. return securityOpts, false, fmt.Errorf("opening seccomp profile (%s) failed: %w", con[1], err)
  378. }
  379. b := bytes.NewBuffer(nil)
  380. if err := json.Compact(b, f); err != nil {
  381. return securityOpts, false, fmt.Errorf("compacting json for seccomp profile (%s) failed: %w", con[1], err)
  382. }
  383. parsed = append(parsed, fmt.Sprintf("seccomp=%s", b.Bytes()))
  384. } else {
  385. parsed = append(parsed, opt)
  386. }
  387. }
  388. return parsed, unconfined, nil
  389. }
  390. func (s *composeService) prepareLabels(labels types.Labels, service types.ServiceConfig, number int) (map[string]string, error) {
  391. hash, err := ServiceHash(service)
  392. if err != nil {
  393. return nil, err
  394. }
  395. labels[api.ConfigHashLabel] = hash
  396. labels[api.ContainerNumberLabel] = strconv.Itoa(number)
  397. var dependencies []string
  398. for s, d := range service.DependsOn {
  399. dependencies = append(dependencies, fmt.Sprintf("%s:%s:%t", s, d.Condition, d.Restart))
  400. }
  401. labels[api.DependenciesLabel] = strings.Join(dependencies, ",")
  402. return labels, nil
  403. }
  404. // defaultNetworkSettings determines the container.NetworkMode and corresponding network.NetworkingConfig (nil if not applicable).
  405. func defaultNetworkSettings(
  406. project *types.Project,
  407. service types.ServiceConfig,
  408. serviceIndex int,
  409. links []string,
  410. useNetworkAliases bool,
  411. ) (container.NetworkMode, *network.NetworkingConfig) {
  412. if service.NetworkMode != "" {
  413. return container.NetworkMode(service.NetworkMode), nil
  414. }
  415. if len(project.Networks) == 0 {
  416. return "none", nil
  417. }
  418. var networkKey string
  419. if len(service.Networks) > 0 {
  420. networkKey = service.NetworksByPriority()[0]
  421. } else {
  422. networkKey = "default"
  423. }
  424. mobyNetworkName := project.Networks[networkKey].Name
  425. epSettings := createEndpointSettings(project, service, serviceIndex, networkKey, links, useNetworkAliases)
  426. networkConfig := &network.NetworkingConfig{
  427. EndpointsConfig: map[string]*network.EndpointSettings{
  428. mobyNetworkName: epSettings,
  429. },
  430. }
  431. // From the Engine API docs:
  432. // > Supported standard values are: bridge, host, none, and container:<name|id>.
  433. // > Any other value is taken as a custom network's name to which this container should connect to.
  434. return container.NetworkMode(mobyNetworkName), networkConfig
  435. }
  436. func getRestartPolicy(service types.ServiceConfig) container.RestartPolicy {
  437. var restart container.RestartPolicy
  438. if service.Restart != "" {
  439. split := strings.Split(service.Restart, ":")
  440. var attempts int
  441. if len(split) > 1 {
  442. attempts, _ = strconv.Atoi(split[1])
  443. }
  444. restart = container.RestartPolicy{
  445. Name: mapRestartPolicyCondition(split[0]),
  446. MaximumRetryCount: attempts,
  447. }
  448. }
  449. if service.Deploy != nil && service.Deploy.RestartPolicy != nil {
  450. policy := *service.Deploy.RestartPolicy
  451. var attempts int
  452. if policy.MaxAttempts != nil {
  453. attempts = int(*policy.MaxAttempts)
  454. }
  455. restart = container.RestartPolicy{
  456. Name: mapRestartPolicyCondition(policy.Condition),
  457. MaximumRetryCount: attempts,
  458. }
  459. }
  460. return restart
  461. }
  462. func mapRestartPolicyCondition(condition string) container.RestartPolicyMode {
  463. // map definitions of deploy.restart_policy to engine definitions
  464. switch condition {
  465. case "none", "no":
  466. return container.RestartPolicyDisabled
  467. case "on-failure":
  468. return container.RestartPolicyOnFailure
  469. case "unless-stopped":
  470. return container.RestartPolicyUnlessStopped
  471. case "any", "always":
  472. return container.RestartPolicyAlways
  473. default:
  474. return container.RestartPolicyMode(condition)
  475. }
  476. }
  477. func getDeployResources(s types.ServiceConfig) container.Resources {
  478. var swappiness *int64
  479. if s.MemSwappiness != 0 {
  480. val := int64(s.MemSwappiness)
  481. swappiness = &val
  482. }
  483. resources := container.Resources{
  484. CgroupParent: s.CgroupParent,
  485. Memory: int64(s.MemLimit),
  486. MemorySwap: int64(s.MemSwapLimit),
  487. MemorySwappiness: swappiness,
  488. MemoryReservation: int64(s.MemReservation),
  489. OomKillDisable: &s.OomKillDisable,
  490. CPUCount: s.CPUCount,
  491. CPUPeriod: s.CPUPeriod,
  492. CPUQuota: s.CPUQuota,
  493. CPURealtimePeriod: s.CPURTPeriod,
  494. CPURealtimeRuntime: s.CPURTRuntime,
  495. CPUShares: s.CPUShares,
  496. NanoCPUs: int64(s.CPUS * 1e9),
  497. CPUPercent: int64(s.CPUPercent * 100),
  498. CpusetCpus: s.CPUSet,
  499. DeviceCgroupRules: s.DeviceCgroupRules,
  500. }
  501. if s.PidsLimit != 0 {
  502. resources.PidsLimit = &s.PidsLimit
  503. }
  504. setBlkio(s.BlkioConfig, &resources)
  505. if s.Deploy != nil {
  506. setLimits(s.Deploy.Resources.Limits, &resources)
  507. setReservations(s.Deploy.Resources.Reservations, &resources)
  508. }
  509. for _, device := range s.Devices {
  510. // FIXME should use docker/cli parseDevice, unfortunately private
  511. src := ""
  512. dst := ""
  513. permissions := "rwm"
  514. arr := strings.Split(device, ":")
  515. switch len(arr) {
  516. case 3:
  517. permissions = arr[2]
  518. fallthrough
  519. case 2:
  520. dst = arr[1]
  521. fallthrough
  522. case 1:
  523. src = arr[0]
  524. }
  525. if dst == "" {
  526. dst = src
  527. }
  528. resources.Devices = append(resources.Devices, container.DeviceMapping{
  529. PathOnHost: src,
  530. PathInContainer: dst,
  531. CgroupPermissions: permissions,
  532. })
  533. }
  534. ulimits := toUlimits(s.Ulimits)
  535. resources.Ulimits = ulimits
  536. return resources
  537. }
  538. func toUlimits(m map[string]*types.UlimitsConfig) []*units.Ulimit {
  539. var ulimits []*units.Ulimit
  540. for name, u := range m {
  541. soft := u.Single
  542. if u.Soft != 0 {
  543. soft = u.Soft
  544. }
  545. hard := u.Single
  546. if u.Hard != 0 {
  547. hard = u.Hard
  548. }
  549. ulimits = append(ulimits, &units.Ulimit{
  550. Name: name,
  551. Hard: int64(hard),
  552. Soft: int64(soft),
  553. })
  554. }
  555. return ulimits
  556. }
  557. func setReservations(reservations *types.Resource, resources *container.Resources) {
  558. if reservations == nil {
  559. return
  560. }
  561. // Cpu reservation is a swarm option and PIDs is only a limit
  562. // So we only need to map memory reservation and devices
  563. if reservations.MemoryBytes != 0 {
  564. resources.MemoryReservation = int64(reservations.MemoryBytes)
  565. }
  566. for _, device := range reservations.Devices {
  567. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  568. Capabilities: [][]string{device.Capabilities},
  569. Count: int(device.Count),
  570. DeviceIDs: device.IDs,
  571. Driver: device.Driver,
  572. })
  573. }
  574. }
  575. func setLimits(limits *types.Resource, resources *container.Resources) {
  576. if limits == nil {
  577. return
  578. }
  579. if limits.MemoryBytes != 0 {
  580. resources.Memory = int64(limits.MemoryBytes)
  581. }
  582. if limits.NanoCPUs != "" {
  583. if f, err := strconv.ParseFloat(limits.NanoCPUs, 64); err == nil {
  584. resources.NanoCPUs = int64(f * 1e9)
  585. }
  586. }
  587. if limits.Pids > 0 {
  588. resources.PidsLimit = &limits.Pids
  589. }
  590. }
  591. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  592. if blkio == nil {
  593. return
  594. }
  595. resources.BlkioWeight = blkio.Weight
  596. for _, b := range blkio.WeightDevice {
  597. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  598. Path: b.Path,
  599. Weight: b.Weight,
  600. })
  601. }
  602. for _, b := range blkio.DeviceReadBps {
  603. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  604. Path: b.Path,
  605. Rate: uint64(b.Rate),
  606. })
  607. }
  608. for _, b := range blkio.DeviceReadIOps {
  609. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  610. Path: b.Path,
  611. Rate: uint64(b.Rate),
  612. })
  613. }
  614. for _, b := range blkio.DeviceWriteBps {
  615. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  616. Path: b.Path,
  617. Rate: uint64(b.Rate),
  618. })
  619. }
  620. for _, b := range blkio.DeviceWriteIOps {
  621. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  622. Path: b.Path,
  623. Rate: uint64(b.Rate),
  624. })
  625. }
  626. }
  627. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  628. ports := nat.PortSet{}
  629. for _, s := range s.Expose {
  630. p := nat.Port(s)
  631. ports[p] = struct{}{}
  632. }
  633. for _, p := range s.Ports {
  634. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  635. ports[p] = struct{}{}
  636. }
  637. return ports
  638. }
  639. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  640. bindings := nat.PortMap{}
  641. for _, port := range s.Ports {
  642. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  643. binding := nat.PortBinding{
  644. HostIP: port.HostIP,
  645. HostPort: port.Published,
  646. }
  647. bindings[p] = append(bindings[p], binding)
  648. }
  649. return bindings
  650. }
  651. func getDependentServiceFromMode(mode string) string {
  652. if strings.HasPrefix(
  653. mode,
  654. types.NetworkModeServicePrefix,
  655. ) {
  656. return mode[len(types.NetworkModeServicePrefix):]
  657. }
  658. return ""
  659. }
  660. func (s *composeService) buildContainerVolumes(
  661. ctx context.Context,
  662. p types.Project,
  663. service types.ServiceConfig,
  664. inherit *moby.Container,
  665. ) ([]string, []mount.Mount, error) {
  666. var mounts []mount.Mount
  667. var binds []string
  668. image := api.GetImageNameOrDefault(service, p.Name)
  669. imgInspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, image)
  670. if err != nil {
  671. return nil, nil, err
  672. }
  673. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  674. if err != nil {
  675. return nil, nil, err
  676. }
  677. MOUNTS:
  678. for _, m := range mountOptions {
  679. if m.Type == mount.TypeNamedPipe {
  680. mounts = append(mounts, m)
  681. continue
  682. }
  683. if m.Type == mount.TypeBind {
  684. // `Mount` is preferred but does not offer option to created host path if missing
  685. // so `Bind` API is used here with raw volume string
  686. // see https://github.com/moby/moby/issues/43483
  687. for _, v := range service.Volumes {
  688. if v.Target == m.Target {
  689. switch {
  690. case string(m.Type) != v.Type:
  691. v.Source = m.Source
  692. fallthrough
  693. case v.Bind != nil && v.Bind.CreateHostPath:
  694. binds = append(binds, v.String())
  695. continue MOUNTS
  696. }
  697. }
  698. }
  699. }
  700. mounts = append(mounts, m)
  701. }
  702. return binds, mounts, nil
  703. }
  704. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  705. var mounts = map[string]mount.Mount{}
  706. if inherit != nil {
  707. for _, m := range inherit.Mounts {
  708. if m.Type == "tmpfs" {
  709. continue
  710. }
  711. src := m.Source
  712. if m.Type == "volume" {
  713. src = m.Name
  714. }
  715. m.Destination = path.Clean(m.Destination)
  716. if img.Config != nil {
  717. if _, ok := img.Config.Volumes[m.Destination]; ok {
  718. // inherit previous container's anonymous volume
  719. mounts[m.Destination] = mount.Mount{
  720. Type: m.Type,
  721. Source: src,
  722. Target: m.Destination,
  723. ReadOnly: !m.RW,
  724. }
  725. }
  726. }
  727. volumes := []types.ServiceVolumeConfig{}
  728. for _, v := range s.Volumes {
  729. if v.Target != m.Destination || v.Source != "" {
  730. volumes = append(volumes, v)
  731. continue
  732. }
  733. // inherit previous container's anonymous volume
  734. mounts[m.Destination] = mount.Mount{
  735. Type: m.Type,
  736. Source: src,
  737. Target: m.Destination,
  738. ReadOnly: !m.RW,
  739. }
  740. }
  741. s.Volumes = volumes
  742. }
  743. }
  744. mounts, err := fillBindMounts(p, s, mounts)
  745. if err != nil {
  746. return nil, err
  747. }
  748. values := make([]mount.Mount, 0, len(mounts))
  749. for _, v := range mounts {
  750. values = append(values, v)
  751. }
  752. return values, nil
  753. }
  754. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  755. for _, v := range s.Volumes {
  756. bindMount, err := buildMount(p, v)
  757. if err != nil {
  758. return nil, err
  759. }
  760. m[bindMount.Target] = bindMount
  761. }
  762. secrets, err := buildContainerSecretMounts(p, s)
  763. if err != nil {
  764. return nil, err
  765. }
  766. for _, s := range secrets {
  767. if _, found := m[s.Target]; found {
  768. continue
  769. }
  770. m[s.Target] = s
  771. }
  772. configs, err := buildContainerConfigMounts(p, s)
  773. if err != nil {
  774. return nil, err
  775. }
  776. for _, c := range configs {
  777. if _, found := m[c.Target]; found {
  778. continue
  779. }
  780. m[c.Target] = c
  781. }
  782. return m, nil
  783. }
  784. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  785. var mounts = map[string]mount.Mount{}
  786. configsBaseDir := "/"
  787. for _, config := range s.Configs {
  788. target := config.Target
  789. if config.Target == "" {
  790. target = configsBaseDir + config.Source
  791. } else if !isAbsTarget(config.Target) {
  792. target = configsBaseDir + config.Target
  793. }
  794. if config.UID != "" || config.GID != "" || config.Mode != nil {
  795. logrus.Warn("config `uid`, `gid` and `mode` are not supported, they will be ignored")
  796. }
  797. definedConfig := p.Configs[config.Source]
  798. if definedConfig.External {
  799. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  800. }
  801. if definedConfig.Driver != "" {
  802. return nil, errors.New("Docker Compose does not support configs.*.driver")
  803. }
  804. if definedConfig.TemplateDriver != "" {
  805. return nil, errors.New("Docker Compose does not support configs.*.template_driver")
  806. }
  807. if definedConfig.Environment != "" || definedConfig.Content != "" {
  808. continue
  809. }
  810. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  811. Type: types.VolumeTypeBind,
  812. Source: definedConfig.File,
  813. Target: target,
  814. ReadOnly: true,
  815. })
  816. if err != nil {
  817. return nil, err
  818. }
  819. mounts[target] = bindMount
  820. }
  821. values := make([]mount.Mount, 0, len(mounts))
  822. for _, v := range mounts {
  823. values = append(values, v)
  824. }
  825. return values, nil
  826. }
  827. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  828. var mounts = map[string]mount.Mount{}
  829. secretsDir := "/run/secrets/"
  830. for _, secret := range s.Secrets {
  831. target := secret.Target
  832. if secret.Target == "" {
  833. target = secretsDir + secret.Source
  834. } else if !isAbsTarget(secret.Target) {
  835. target = secretsDir + secret.Target
  836. }
  837. if secret.UID != "" || secret.GID != "" || secret.Mode != nil {
  838. logrus.Warn("secrets `uid`, `gid` and `mode` are not supported, they will be ignored")
  839. }
  840. definedSecret := p.Secrets[secret.Source]
  841. if definedSecret.External {
  842. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  843. }
  844. if definedSecret.Driver != "" {
  845. return nil, errors.New("Docker Compose does not support secrets.*.driver")
  846. }
  847. if definedSecret.TemplateDriver != "" {
  848. return nil, errors.New("Docker Compose does not support secrets.*.template_driver")
  849. }
  850. if definedSecret.Environment != "" {
  851. continue
  852. }
  853. mnt, err := buildMount(p, types.ServiceVolumeConfig{
  854. Type: types.VolumeTypeBind,
  855. Source: definedSecret.File,
  856. Target: target,
  857. ReadOnly: true,
  858. })
  859. if err != nil {
  860. return nil, err
  861. }
  862. mounts[target] = mnt
  863. }
  864. values := make([]mount.Mount, 0, len(mounts))
  865. for _, v := range mounts {
  866. values = append(values, v)
  867. }
  868. return values, nil
  869. }
  870. func isAbsTarget(p string) bool {
  871. return isUnixAbs(p) || isWindowsAbs(p)
  872. }
  873. func isUnixAbs(p string) bool {
  874. return strings.HasPrefix(p, "/")
  875. }
  876. func isWindowsAbs(p string) bool {
  877. if strings.HasPrefix(p, "\\\\") {
  878. return true
  879. }
  880. if len(p) > 2 && p[1] == ':' {
  881. return p[2] == '\\'
  882. }
  883. return false
  884. }
  885. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  886. source := volume.Source
  887. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  888. // do not replace these with filepath.Abs(source) that will include a default drive.
  889. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  890. // volume source has already been prefixed with workdir if required, by compose-go project loader
  891. var err error
  892. source, err = filepath.Abs(source)
  893. if err != nil {
  894. return mount.Mount{}, err
  895. }
  896. }
  897. if volume.Type == types.VolumeTypeVolume {
  898. if volume.Source != "" {
  899. pVolume, ok := project.Volumes[volume.Source]
  900. if ok {
  901. source = pVolume.Name
  902. }
  903. }
  904. }
  905. bind, vol, tmpfs := buildMountOptions(project, volume)
  906. volume.Target = path.Clean(volume.Target)
  907. if bind != nil {
  908. volume.Type = types.VolumeTypeBind
  909. }
  910. return mount.Mount{
  911. Type: mount.Type(volume.Type),
  912. Source: source,
  913. Target: volume.Target,
  914. ReadOnly: volume.ReadOnly,
  915. Consistency: mount.Consistency(volume.Consistency),
  916. BindOptions: bind,
  917. VolumeOptions: vol,
  918. TmpfsOptions: tmpfs,
  919. }, nil
  920. }
  921. func buildMountOptions(project types.Project, volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  922. switch volume.Type {
  923. case "bind":
  924. if volume.Volume != nil {
  925. logrus.Warnf("mount of type `bind` should not define `volume` option")
  926. }
  927. if volume.Tmpfs != nil {
  928. logrus.Warnf("mount of type `bind` should not define `tmpfs` option")
  929. }
  930. return buildBindOption(volume.Bind), nil, nil
  931. case "volume":
  932. if volume.Bind != nil {
  933. logrus.Warnf("mount of type `volume` should not define `bind` option")
  934. }
  935. if volume.Tmpfs != nil {
  936. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  937. }
  938. if v, ok := project.Volumes[volume.Source]; ok && v.DriverOpts["o"] == types.VolumeTypeBind {
  939. return buildBindOption(&types.ServiceVolumeBind{
  940. CreateHostPath: true,
  941. }), nil, nil
  942. }
  943. return nil, buildVolumeOptions(volume.Volume), nil
  944. case "tmpfs":
  945. if volume.Bind != nil {
  946. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  947. }
  948. if volume.Volume != nil {
  949. logrus.Warnf("mount of type `tmpfs` should not define `volume` option")
  950. }
  951. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  952. }
  953. return nil, nil, nil
  954. }
  955. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  956. if bind == nil {
  957. return nil
  958. }
  959. return &mount.BindOptions{
  960. Propagation: mount.Propagation(bind.Propagation),
  961. // NonRecursive: false, FIXME missing from model ?
  962. }
  963. }
  964. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  965. if vol == nil {
  966. return nil
  967. }
  968. return &mount.VolumeOptions{
  969. NoCopy: vol.NoCopy,
  970. // Labels: , // FIXME missing from model ?
  971. // DriverConfig: , // FIXME missing from model ?
  972. }
  973. }
  974. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  975. if tmpfs == nil {
  976. return nil
  977. }
  978. return &mount.TmpfsOptions{
  979. SizeBytes: int64(tmpfs.Size),
  980. Mode: os.FileMode(tmpfs.Mode),
  981. }
  982. }
  983. func (s *composeService) ensureNetwork(ctx context.Context, n *types.NetworkConfig) error {
  984. if n.External {
  985. return s.resolveExternalNetwork(ctx, n)
  986. }
  987. err := s.resolveOrCreateNetwork(ctx, n)
  988. if errdefs.IsConflict(err) {
  989. // Maybe another execution of `docker compose up|run` created same network
  990. // let's retry once
  991. return s.resolveOrCreateNetwork(ctx, n)
  992. }
  993. return err
  994. }
  995. func (s *composeService) resolveOrCreateNetwork(ctx context.Context, n *types.NetworkConfig) error { //nolint:gocyclo
  996. expectedNetworkLabel := n.Labels[api.NetworkLabel]
  997. expectedProjectLabel := n.Labels[api.ProjectLabel]
  998. // First, try to find a unique network matching by name or ID
  999. inspect, err := s.apiClient().NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  1000. if err == nil {
  1001. // NetworkInspect will match on ID prefix, so double check we get the expected one
  1002. // as looking for network named `db` we could erroneously matched network ID `db9086999caf`
  1003. if inspect.Name == n.Name || inspect.ID == n.Name {
  1004. p, ok := inspect.Labels[api.ProjectLabel]
  1005. if !ok {
  1006. logrus.Warnf("a network with name %s exists but was not created by compose.\n"+
  1007. "Set `external: true` to use an existing network", n.Name)
  1008. } else if p != expectedProjectLabel {
  1009. logrus.Warnf("a network with name %s exists but was not created for project %q.\n"+
  1010. "Set `external: true` to use an existing network", n.Name, expectedProjectLabel)
  1011. }
  1012. if inspect.Labels[api.NetworkLabel] != expectedNetworkLabel {
  1013. return fmt.Errorf("network %s was found but has incorrect label %s set to %q", n.Name, api.NetworkLabel, inspect.Labels[api.NetworkLabel])
  1014. }
  1015. return nil
  1016. }
  1017. }
  1018. // ignore other errors. Typically, an ambiguous request by name results in some generic `invalidParameter` error
  1019. // Either not found, or name is ambiguous - use NetworkList to list by name
  1020. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  1021. Filters: filters.NewArgs(filters.Arg("name", n.Name)),
  1022. })
  1023. if err != nil {
  1024. return err
  1025. }
  1026. // NetworkList Matches all or part of a network name, so we have to filter for a strict match
  1027. networks = utils.Filter(networks, func(net moby.NetworkResource) bool {
  1028. return net.Name == n.Name
  1029. })
  1030. for _, net := range networks {
  1031. if net.Labels[api.ProjectLabel] == expectedProjectLabel &&
  1032. net.Labels[api.NetworkLabel] == expectedNetworkLabel {
  1033. return nil
  1034. }
  1035. }
  1036. // we could have set NetworkList with a projectFilter and networkFilter but not doing so allows to catch this
  1037. // scenario were a network with same name exists but doesn't have label, and use of `CheckDuplicate: true`
  1038. // prevents to create another one.
  1039. if len(networks) > 0 {
  1040. logrus.Warnf("a network with name %s exists but was not created by compose.\n"+
  1041. "Set `external: true` to use an existing network", n.Name)
  1042. return nil
  1043. }
  1044. var ipam *network.IPAM
  1045. if n.Ipam.Config != nil {
  1046. var config []network.IPAMConfig
  1047. for _, pool := range n.Ipam.Config {
  1048. config = append(config, network.IPAMConfig{
  1049. Subnet: pool.Subnet,
  1050. IPRange: pool.IPRange,
  1051. Gateway: pool.Gateway,
  1052. AuxAddress: pool.AuxiliaryAddresses,
  1053. })
  1054. }
  1055. ipam = &network.IPAM{
  1056. Driver: n.Ipam.Driver,
  1057. Config: config,
  1058. }
  1059. }
  1060. createOpts := moby.NetworkCreate{
  1061. CheckDuplicate: true,
  1062. Labels: n.Labels,
  1063. Driver: n.Driver,
  1064. Options: n.DriverOpts,
  1065. Internal: n.Internal,
  1066. Attachable: n.Attachable,
  1067. IPAM: ipam,
  1068. EnableIPv6: n.EnableIPv6,
  1069. }
  1070. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  1071. createOpts.IPAM = &network.IPAM{}
  1072. }
  1073. if n.Ipam.Driver != "" {
  1074. createOpts.IPAM.Driver = n.Ipam.Driver
  1075. }
  1076. for _, ipamConfig := range n.Ipam.Config {
  1077. config := network.IPAMConfig{
  1078. Subnet: ipamConfig.Subnet,
  1079. IPRange: ipamConfig.IPRange,
  1080. Gateway: ipamConfig.Gateway,
  1081. AuxAddress: ipamConfig.AuxiliaryAddresses,
  1082. }
  1083. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  1084. }
  1085. networkEventName := fmt.Sprintf("Network %s", n.Name)
  1086. w := progress.ContextWriter(ctx)
  1087. w.Event(progress.CreatingEvent(networkEventName))
  1088. _, err = s.apiClient().NetworkCreate(ctx, n.Name, createOpts)
  1089. if err != nil {
  1090. w.Event(progress.ErrorEvent(networkEventName))
  1091. return fmt.Errorf("failed to create network %s: %w", n.Name, err)
  1092. }
  1093. w.Event(progress.CreatedEvent(networkEventName))
  1094. return nil
  1095. }
  1096. func (s *composeService) resolveExternalNetwork(ctx context.Context, n *types.NetworkConfig) error {
  1097. // NetworkInspect will match on ID prefix, so NetworkList with a name
  1098. // filter is used to look for an exact match to prevent e.g. a network
  1099. // named `db` from getting erroneously matched to a network with an ID
  1100. // like `db9086999caf`
  1101. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  1102. Filters: filters.NewArgs(filters.Arg("name", n.Name)),
  1103. })
  1104. if err != nil {
  1105. return err
  1106. }
  1107. if len(networks) == 0 {
  1108. // in this instance, n.Name is really an ID
  1109. sn, err := s.apiClient().NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  1110. if err != nil {
  1111. return err
  1112. }
  1113. networks = append(networks, sn)
  1114. }
  1115. // NetworkList API doesn't return the exact name match, so we can retrieve more than one network with a request
  1116. networks = utils.Filter(networks, func(net moby.NetworkResource) bool {
  1117. // later in this function, the name is changed the to ID.
  1118. // this function is called during the rebuild stage of `compose watch`.
  1119. // we still require just one network back, but we need to run the search on the ID
  1120. return net.Name == n.Name || net.ID == n.Name
  1121. })
  1122. switch len(networks) {
  1123. case 1:
  1124. n.Name = networks[0].ID
  1125. return nil
  1126. case 0:
  1127. if n.Driver == "overlay" {
  1128. // Swarm nodes do not register overlay networks that were
  1129. // created on a different node unless they're in use.
  1130. // Here we assume `driver` is relevant for a network we don't manage
  1131. // which is a non-sense, but this is our legacy ¯\(ツ)/¯
  1132. // networkAttach will later fail anyway if network actually doesn't exists
  1133. enabled, err := s.isSWarmEnabled(ctx)
  1134. if err != nil {
  1135. return err
  1136. }
  1137. if enabled {
  1138. return nil
  1139. }
  1140. }
  1141. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  1142. default:
  1143. return fmt.Errorf("multiple networks with name %q were found. Use network ID as `name` to avoid ambiguity", n.Name)
  1144. }
  1145. }
  1146. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig, project string) error {
  1147. inspected, err := s.apiClient().VolumeInspect(ctx, volume.Name)
  1148. if err != nil {
  1149. if !errdefs.IsNotFound(err) {
  1150. return err
  1151. }
  1152. if volume.External {
  1153. return fmt.Errorf("external volume %q not found", volume.Name)
  1154. }
  1155. err := s.createVolume(ctx, volume)
  1156. return err
  1157. }
  1158. if volume.External {
  1159. return nil
  1160. }
  1161. // Volume exists with name, but let's double-check this is the expected one
  1162. p, ok := inspected.Labels[api.ProjectLabel]
  1163. if !ok {
  1164. logrus.Warnf("volume %q already exists but was not created by Docker Compose. Use `external: true` to use an existing volume", volume.Name)
  1165. }
  1166. if ok && p != project {
  1167. logrus.Warnf("volume %q already exists but was created for project %q (expected %q). Use `external: true` to use an existing volume", volume.Name, p, project)
  1168. }
  1169. return nil
  1170. }
  1171. func (s *composeService) createVolume(ctx context.Context, volume types.VolumeConfig) error {
  1172. eventName := fmt.Sprintf("Volume %q", volume.Name)
  1173. w := progress.ContextWriter(ctx)
  1174. w.Event(progress.CreatingEvent(eventName))
  1175. _, err := s.apiClient().VolumeCreate(ctx, volume_api.CreateOptions{
  1176. Labels: volume.Labels,
  1177. Name: volume.Name,
  1178. Driver: volume.Driver,
  1179. DriverOpts: volume.DriverOpts,
  1180. })
  1181. if err != nil {
  1182. w.Event(progress.ErrorEvent(eventName))
  1183. return err
  1184. }
  1185. w.Event(progress.CreatedEvent(eventName))
  1186. return nil
  1187. }