create.go 41 KB

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