create.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  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. cdi "tags.cncf.io/container-device-interface/pkg/parser"
  46. )
  47. type createOptions struct {
  48. AutoRemove bool
  49. AttachStdin bool
  50. UseNetworkAliases bool
  51. Labels types.Labels
  52. }
  53. type createConfigs struct {
  54. Container *container.Config
  55. Host *container.HostConfig
  56. Network *network.NetworkingConfig
  57. Links []string
  58. }
  59. func (s *composeService) Create(ctx context.Context, project *types.Project, createOpts api.CreateOptions) error {
  60. return progress.RunWithTitle(ctx, func(ctx context.Context) error {
  61. return s.create(ctx, project, createOpts)
  62. }, s.stdinfo(), "Creating")
  63. }
  64. func (s *composeService) create(ctx context.Context, project *types.Project, options api.CreateOptions) error {
  65. if len(options.Services) == 0 {
  66. options.Services = project.ServiceNames()
  67. }
  68. err := project.CheckContainerNameUnicity()
  69. if err != nil {
  70. return err
  71. }
  72. var observedState Containers
  73. observedState, err = s.getContainers(ctx, project.Name, oneOffInclude, true)
  74. if err != nil {
  75. return err
  76. }
  77. err = s.ensureImagesExists(ctx, project, options.Build, options.QuietPull)
  78. if err != nil {
  79. return err
  80. }
  81. prepareNetworks(project)
  82. if err := s.ensureNetworks(ctx, project.Networks); err != nil {
  83. return err
  84. }
  85. if err := s.ensureProjectVolumes(ctx, project); err != nil {
  86. return err
  87. }
  88. orphans := observedState.filter(isOrphaned(project))
  89. if len(orphans) > 0 && !options.IgnoreOrphans {
  90. if options.RemoveOrphans {
  91. err := s.removeContainers(ctx, orphans, nil, 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 to 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. var cdiDeviceNames []string
  588. for _, device := range s.Devices {
  589. if device.Source == device.Target && cdi.IsQualifiedName(device.Source) {
  590. cdiDeviceNames = append(cdiDeviceNames, device.Source)
  591. continue
  592. }
  593. resources.Devices = append(resources.Devices, container.DeviceMapping{
  594. PathOnHost: device.Source,
  595. PathInContainer: device.Target,
  596. CgroupPermissions: device.Permissions,
  597. })
  598. }
  599. if len(cdiDeviceNames) > 0 {
  600. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  601. Driver: "cdi",
  602. DeviceIDs: cdiDeviceNames,
  603. })
  604. }
  605. for _, gpus := range s.Gpus {
  606. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  607. Driver: gpus.Driver,
  608. Count: int(gpus.Count),
  609. DeviceIDs: gpus.IDs,
  610. Capabilities: [][]string{append(gpus.Capabilities, "gpu")},
  611. Options: gpus.Options,
  612. })
  613. }
  614. ulimits := toUlimits(s.Ulimits)
  615. resources.Ulimits = ulimits
  616. return resources
  617. }
  618. func toUlimits(m map[string]*types.UlimitsConfig) []*container.Ulimit {
  619. var ulimits []*container.Ulimit
  620. for name, u := range m {
  621. soft := u.Single
  622. if u.Soft != 0 {
  623. soft = u.Soft
  624. }
  625. hard := u.Single
  626. if u.Hard != 0 {
  627. hard = u.Hard
  628. }
  629. ulimits = append(ulimits, &container.Ulimit{
  630. Name: name,
  631. Hard: int64(hard),
  632. Soft: int64(soft),
  633. })
  634. }
  635. return ulimits
  636. }
  637. func setReservations(reservations *types.Resource, resources *container.Resources) {
  638. if reservations == nil {
  639. return
  640. }
  641. // Cpu reservation is a swarm option and PIDs is only a limit
  642. // So we only need to map memory reservation and devices
  643. if reservations.MemoryBytes != 0 {
  644. resources.MemoryReservation = int64(reservations.MemoryBytes)
  645. }
  646. for _, device := range reservations.Devices {
  647. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  648. Capabilities: [][]string{device.Capabilities},
  649. Count: int(device.Count),
  650. DeviceIDs: device.IDs,
  651. Driver: device.Driver,
  652. Options: device.Options,
  653. })
  654. }
  655. }
  656. func setLimits(limits *types.Resource, resources *container.Resources) {
  657. if limits == nil {
  658. return
  659. }
  660. if limits.MemoryBytes != 0 {
  661. resources.Memory = int64(limits.MemoryBytes)
  662. }
  663. if limits.NanoCPUs != 0 {
  664. resources.NanoCPUs = int64(limits.NanoCPUs * 1e9)
  665. }
  666. if limits.Pids > 0 {
  667. resources.PidsLimit = &limits.Pids
  668. }
  669. }
  670. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  671. if blkio == nil {
  672. return
  673. }
  674. resources.BlkioWeight = blkio.Weight
  675. for _, b := range blkio.WeightDevice {
  676. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  677. Path: b.Path,
  678. Weight: b.Weight,
  679. })
  680. }
  681. for _, b := range blkio.DeviceReadBps {
  682. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  683. Path: b.Path,
  684. Rate: uint64(b.Rate),
  685. })
  686. }
  687. for _, b := range blkio.DeviceReadIOps {
  688. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  689. Path: b.Path,
  690. Rate: uint64(b.Rate),
  691. })
  692. }
  693. for _, b := range blkio.DeviceWriteBps {
  694. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  695. Path: b.Path,
  696. Rate: uint64(b.Rate),
  697. })
  698. }
  699. for _, b := range blkio.DeviceWriteIOps {
  700. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  701. Path: b.Path,
  702. Rate: uint64(b.Rate),
  703. })
  704. }
  705. }
  706. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  707. ports := nat.PortSet{}
  708. for _, s := range s.Expose {
  709. p := nat.Port(s)
  710. ports[p] = struct{}{}
  711. }
  712. for _, p := range s.Ports {
  713. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  714. ports[p] = struct{}{}
  715. }
  716. return ports
  717. }
  718. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  719. bindings := nat.PortMap{}
  720. for _, port := range s.Ports {
  721. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  722. binding := nat.PortBinding{
  723. HostIP: port.HostIP,
  724. HostPort: port.Published,
  725. }
  726. bindings[p] = append(bindings[p], binding)
  727. }
  728. return bindings
  729. }
  730. func getDependentServiceFromMode(mode string) string {
  731. if strings.HasPrefix(
  732. mode,
  733. types.NetworkModeServicePrefix,
  734. ) {
  735. return mode[len(types.NetworkModeServicePrefix):]
  736. }
  737. return ""
  738. }
  739. func (s *composeService) buildContainerVolumes(
  740. ctx context.Context,
  741. p types.Project,
  742. service types.ServiceConfig,
  743. inherit *moby.Container,
  744. ) ([]string, []mount.Mount, error) {
  745. var mounts []mount.Mount
  746. var binds []string
  747. image := api.GetImageNameOrDefault(service, p.Name)
  748. imgInspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, image)
  749. if err != nil {
  750. return nil, nil, err
  751. }
  752. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  753. if err != nil {
  754. return nil, nil, err
  755. }
  756. MOUNTS:
  757. for _, m := range mountOptions {
  758. if m.Type == mount.TypeNamedPipe {
  759. mounts = append(mounts, m)
  760. continue
  761. }
  762. if m.Type == mount.TypeBind {
  763. // `Mount` is preferred but does not offer option to created host path if missing
  764. // so `Bind` API is used here with raw volume string
  765. // see https://github.com/moby/moby/issues/43483
  766. for _, v := range service.Volumes {
  767. if v.Target == m.Target {
  768. switch {
  769. case string(m.Type) != v.Type:
  770. v.Source = m.Source
  771. fallthrough
  772. case v.Bind != nil && v.Bind.CreateHostPath:
  773. binds = append(binds, v.String())
  774. continue MOUNTS
  775. }
  776. }
  777. }
  778. }
  779. mounts = append(mounts, m)
  780. }
  781. return binds, mounts, nil
  782. }
  783. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  784. var mounts = map[string]mount.Mount{}
  785. if inherit != nil {
  786. for _, m := range inherit.Mounts {
  787. if m.Type == "tmpfs" {
  788. continue
  789. }
  790. src := m.Source
  791. if m.Type == "volume" {
  792. src = m.Name
  793. }
  794. m.Destination = path.Clean(m.Destination)
  795. if img.Config != nil {
  796. if _, ok := img.Config.Volumes[m.Destination]; ok {
  797. // inherit previous container's anonymous volume
  798. mounts[m.Destination] = mount.Mount{
  799. Type: m.Type,
  800. Source: src,
  801. Target: m.Destination,
  802. ReadOnly: !m.RW,
  803. }
  804. }
  805. }
  806. volumes := []types.ServiceVolumeConfig{}
  807. for _, v := range s.Volumes {
  808. if v.Target != m.Destination || v.Source != "" {
  809. volumes = append(volumes, v)
  810. continue
  811. }
  812. // inherit previous container's anonymous volume
  813. mounts[m.Destination] = mount.Mount{
  814. Type: m.Type,
  815. Source: src,
  816. Target: m.Destination,
  817. ReadOnly: !m.RW,
  818. }
  819. }
  820. s.Volumes = volumes
  821. }
  822. }
  823. mounts, err := fillBindMounts(p, s, mounts)
  824. if err != nil {
  825. return nil, err
  826. }
  827. values := make([]mount.Mount, 0, len(mounts))
  828. for _, v := range mounts {
  829. values = append(values, v)
  830. }
  831. return values, nil
  832. }
  833. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  834. for _, v := range s.Volumes {
  835. bindMount, err := buildMount(p, v)
  836. if err != nil {
  837. return nil, err
  838. }
  839. m[bindMount.Target] = bindMount
  840. }
  841. secrets, err := buildContainerSecretMounts(p, s)
  842. if err != nil {
  843. return nil, err
  844. }
  845. for _, s := range secrets {
  846. if _, found := m[s.Target]; found {
  847. continue
  848. }
  849. m[s.Target] = s
  850. }
  851. configs, err := buildContainerConfigMounts(p, s)
  852. if err != nil {
  853. return nil, err
  854. }
  855. for _, c := range configs {
  856. if _, found := m[c.Target]; found {
  857. continue
  858. }
  859. m[c.Target] = c
  860. }
  861. return m, nil
  862. }
  863. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  864. var mounts = map[string]mount.Mount{}
  865. configsBaseDir := "/"
  866. for _, config := range s.Configs {
  867. target := config.Target
  868. if config.Target == "" {
  869. target = configsBaseDir + config.Source
  870. } else if !isAbsTarget(config.Target) {
  871. target = configsBaseDir + config.Target
  872. }
  873. if config.UID != "" || config.GID != "" || config.Mode != nil {
  874. logrus.Warn("config `uid`, `gid` and `mode` are not supported, they will be ignored")
  875. }
  876. definedConfig := p.Configs[config.Source]
  877. if definedConfig.External {
  878. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  879. }
  880. if definedConfig.Driver != "" {
  881. return nil, errors.New("Docker Compose does not support configs.*.driver")
  882. }
  883. if definedConfig.TemplateDriver != "" {
  884. return nil, errors.New("Docker Compose does not support configs.*.template_driver")
  885. }
  886. if definedConfig.Environment != "" || definedConfig.Content != "" {
  887. continue
  888. }
  889. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  890. Type: types.VolumeTypeBind,
  891. Source: definedConfig.File,
  892. Target: target,
  893. ReadOnly: true,
  894. })
  895. if err != nil {
  896. return nil, err
  897. }
  898. mounts[target] = bindMount
  899. }
  900. values := make([]mount.Mount, 0, len(mounts))
  901. for _, v := range mounts {
  902. values = append(values, v)
  903. }
  904. return values, nil
  905. }
  906. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  907. var mounts = map[string]mount.Mount{}
  908. secretsDir := "/run/secrets/"
  909. for _, secret := range s.Secrets {
  910. target := secret.Target
  911. if secret.Target == "" {
  912. target = secretsDir + secret.Source
  913. } else if !isAbsTarget(secret.Target) {
  914. target = secretsDir + secret.Target
  915. }
  916. if secret.UID != "" || secret.GID != "" || secret.Mode != nil {
  917. logrus.Warn("secrets `uid`, `gid` and `mode` are not supported, they will be ignored")
  918. }
  919. definedSecret := p.Secrets[secret.Source]
  920. if definedSecret.External {
  921. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  922. }
  923. if definedSecret.Driver != "" {
  924. return nil, errors.New("Docker Compose does not support secrets.*.driver")
  925. }
  926. if definedSecret.TemplateDriver != "" {
  927. return nil, errors.New("Docker Compose does not support secrets.*.template_driver")
  928. }
  929. if definedSecret.Environment != "" {
  930. continue
  931. }
  932. if _, err := os.Stat(definedSecret.File); os.IsNotExist(err) {
  933. logrus.Warnf("secret file %s does not exist", definedSecret.Name)
  934. }
  935. mnt, err := buildMount(p, types.ServiceVolumeConfig{
  936. Type: types.VolumeTypeBind,
  937. Source: definedSecret.File,
  938. Target: target,
  939. ReadOnly: true,
  940. Bind: &types.ServiceVolumeBind{
  941. CreateHostPath: false,
  942. },
  943. })
  944. if err != nil {
  945. return nil, err
  946. }
  947. mounts[target] = mnt
  948. }
  949. values := make([]mount.Mount, 0, len(mounts))
  950. for _, v := range mounts {
  951. values = append(values, v)
  952. }
  953. return values, nil
  954. }
  955. func isAbsTarget(p string) bool {
  956. return isUnixAbs(p) || isWindowsAbs(p)
  957. }
  958. func isUnixAbs(p string) bool {
  959. return strings.HasPrefix(p, "/")
  960. }
  961. func isWindowsAbs(p string) bool {
  962. if strings.HasPrefix(p, "\\\\") {
  963. return true
  964. }
  965. if len(p) > 2 && p[1] == ':' {
  966. return p[2] == '\\'
  967. }
  968. return false
  969. }
  970. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  971. source := volume.Source
  972. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  973. // do not replace these with filepath.Abs(source) that will include a default drive.
  974. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  975. // volume source has already been prefixed with workdir if required, by compose-go project loader
  976. var err error
  977. source, err = filepath.Abs(source)
  978. if err != nil {
  979. return mount.Mount{}, err
  980. }
  981. }
  982. if volume.Type == types.VolumeTypeVolume {
  983. if volume.Source != "" {
  984. pVolume, ok := project.Volumes[volume.Source]
  985. if ok {
  986. source = pVolume.Name
  987. }
  988. }
  989. }
  990. bind, vol, tmpfs := buildMountOptions(volume)
  991. volume.Target = path.Clean(volume.Target)
  992. if bind != nil {
  993. volume.Type = types.VolumeTypeBind
  994. }
  995. return mount.Mount{
  996. Type: mount.Type(volume.Type),
  997. Source: source,
  998. Target: volume.Target,
  999. ReadOnly: volume.ReadOnly,
  1000. Consistency: mount.Consistency(volume.Consistency),
  1001. BindOptions: bind,
  1002. VolumeOptions: vol,
  1003. TmpfsOptions: tmpfs,
  1004. }, nil
  1005. }
  1006. func buildMountOptions(volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  1007. switch volume.Type {
  1008. case "bind":
  1009. if volume.Volume != nil {
  1010. logrus.Warnf("mount of type `bind` should not define `volume` option")
  1011. }
  1012. if volume.Tmpfs != nil {
  1013. logrus.Warnf("mount of type `bind` should not define `tmpfs` option")
  1014. }
  1015. return buildBindOption(volume.Bind), nil, nil
  1016. case "volume":
  1017. if volume.Bind != nil {
  1018. logrus.Warnf("mount of type `volume` should not define `bind` option")
  1019. }
  1020. if volume.Tmpfs != nil {
  1021. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  1022. }
  1023. return nil, buildVolumeOptions(volume.Volume), nil
  1024. case "tmpfs":
  1025. if volume.Bind != nil {
  1026. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  1027. }
  1028. if volume.Volume != nil {
  1029. logrus.Warnf("mount of type `tmpfs` should not define `volume` option")
  1030. }
  1031. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  1032. }
  1033. return nil, nil, nil
  1034. }
  1035. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  1036. if bind == nil {
  1037. return nil
  1038. }
  1039. return &mount.BindOptions{
  1040. Propagation: mount.Propagation(bind.Propagation),
  1041. // NonRecursive: false, FIXME missing from model ?
  1042. }
  1043. }
  1044. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  1045. if vol == nil {
  1046. return nil
  1047. }
  1048. return &mount.VolumeOptions{
  1049. NoCopy: vol.NoCopy,
  1050. Subpath: vol.Subpath,
  1051. // Labels: , // FIXME missing from model ?
  1052. // DriverConfig: , // FIXME missing from model ?
  1053. }
  1054. }
  1055. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  1056. if tmpfs == nil {
  1057. return nil
  1058. }
  1059. return &mount.TmpfsOptions{
  1060. SizeBytes: int64(tmpfs.Size),
  1061. Mode: os.FileMode(tmpfs.Mode),
  1062. }
  1063. }
  1064. func (s *composeService) ensureNetwork(ctx context.Context, n *types.NetworkConfig) error {
  1065. if n.External {
  1066. return s.resolveExternalNetwork(ctx, n)
  1067. }
  1068. err := s.resolveOrCreateNetwork(ctx, n)
  1069. if errdefs.IsConflict(err) {
  1070. // Maybe another execution of `docker compose up|run` created same network
  1071. // let's retry once
  1072. return s.resolveOrCreateNetwork(ctx, n)
  1073. }
  1074. return err
  1075. }
  1076. func (s *composeService) resolveOrCreateNetwork(ctx context.Context, n *types.NetworkConfig) error { //nolint:gocyclo
  1077. expectedNetworkLabel := n.Labels[api.NetworkLabel]
  1078. expectedProjectLabel := n.Labels[api.ProjectLabel]
  1079. // First, try to find a unique network matching by name or ID
  1080. inspect, err := s.apiClient().NetworkInspect(ctx, n.Name, network.InspectOptions{})
  1081. if err == nil {
  1082. // NetworkInspect will match on ID prefix, so double check we get the expected one
  1083. // as looking for network named `db` we could erroneously match network ID `db9086999caf`
  1084. if inspect.Name == n.Name || inspect.ID == n.Name {
  1085. p, ok := inspect.Labels[api.ProjectLabel]
  1086. if !ok {
  1087. logrus.Warnf("a network with name %s exists but was not created by compose.\n"+
  1088. "Set `external: true` to use an existing network", n.Name)
  1089. } else if p != expectedProjectLabel {
  1090. logrus.Warnf("a network with name %s exists but was not created for project %q.\n"+
  1091. "Set `external: true` to use an existing network", n.Name, expectedProjectLabel)
  1092. }
  1093. if inspect.Labels[api.NetworkLabel] != expectedNetworkLabel {
  1094. return fmt.Errorf("network %s was found but has incorrect label %s set to %q", n.Name, api.NetworkLabel, inspect.Labels[api.NetworkLabel])
  1095. }
  1096. return nil
  1097. }
  1098. }
  1099. // ignore other errors. Typically, an ambiguous request by name results in some generic `invalidParameter` error
  1100. // Either not found, or name is ambiguous - use NetworkList to list by name
  1101. networks, err := s.apiClient().NetworkList(ctx, network.ListOptions{
  1102. Filters: filters.NewArgs(filters.Arg("name", n.Name)),
  1103. })
  1104. if err != nil {
  1105. return err
  1106. }
  1107. // NetworkList Matches all or part of a network name, so we have to filter for a strict match
  1108. networks = utils.Filter(networks, func(net network.Summary) bool {
  1109. return net.Name == n.Name
  1110. })
  1111. for _, net := range networks {
  1112. if net.Labels[api.ProjectLabel] == expectedProjectLabel &&
  1113. net.Labels[api.NetworkLabel] == expectedNetworkLabel {
  1114. return nil
  1115. }
  1116. }
  1117. // we could have set NetworkList with a projectFilter and networkFilter but not doing so allows to catch this
  1118. // scenario were a network with same name exists but doesn't have label, and use of `CheckDuplicate: true`
  1119. // prevents to create another one.
  1120. if len(networks) > 0 {
  1121. logrus.Warnf("a network with name %s exists but was not created by compose.\n"+
  1122. "Set `external: true` to use an existing network", n.Name)
  1123. return nil
  1124. }
  1125. var ipam *network.IPAM
  1126. if n.Ipam.Config != nil {
  1127. var config []network.IPAMConfig
  1128. for _, pool := range n.Ipam.Config {
  1129. config = append(config, network.IPAMConfig{
  1130. Subnet: pool.Subnet,
  1131. IPRange: pool.IPRange,
  1132. Gateway: pool.Gateway,
  1133. AuxAddress: pool.AuxiliaryAddresses,
  1134. })
  1135. }
  1136. ipam = &network.IPAM{
  1137. Driver: n.Ipam.Driver,
  1138. Config: config,
  1139. }
  1140. }
  1141. createOpts := network.CreateOptions{
  1142. Labels: n.Labels,
  1143. Driver: n.Driver,
  1144. Options: n.DriverOpts,
  1145. Internal: n.Internal,
  1146. Attachable: n.Attachable,
  1147. IPAM: ipam,
  1148. EnableIPv6: n.EnableIPv6,
  1149. }
  1150. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  1151. createOpts.IPAM = &network.IPAM{}
  1152. }
  1153. if n.Ipam.Driver != "" {
  1154. createOpts.IPAM.Driver = n.Ipam.Driver
  1155. }
  1156. for _, ipamConfig := range n.Ipam.Config {
  1157. config := network.IPAMConfig{
  1158. Subnet: ipamConfig.Subnet,
  1159. IPRange: ipamConfig.IPRange,
  1160. Gateway: ipamConfig.Gateway,
  1161. AuxAddress: ipamConfig.AuxiliaryAddresses,
  1162. }
  1163. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  1164. }
  1165. networkEventName := fmt.Sprintf("Network %s", n.Name)
  1166. w := progress.ContextWriter(ctx)
  1167. w.Event(progress.CreatingEvent(networkEventName))
  1168. _, err = s.apiClient().NetworkCreate(ctx, n.Name, createOpts)
  1169. if err != nil {
  1170. w.Event(progress.ErrorEvent(networkEventName))
  1171. return fmt.Errorf("failed to create network %s: %w", n.Name, err)
  1172. }
  1173. w.Event(progress.CreatedEvent(networkEventName))
  1174. return nil
  1175. }
  1176. func (s *composeService) resolveExternalNetwork(ctx context.Context, n *types.NetworkConfig) error {
  1177. // NetworkInspect will match on ID prefix, so NetworkList with a name
  1178. // filter is used to look for an exact match to prevent e.g. a network
  1179. // named `db` from getting erroneously matched to a network with an ID
  1180. // like `db9086999caf`
  1181. networks, err := s.apiClient().NetworkList(ctx, network.ListOptions{
  1182. Filters: filters.NewArgs(filters.Arg("name", n.Name)),
  1183. })
  1184. if err != nil {
  1185. return err
  1186. }
  1187. if len(networks) == 0 {
  1188. // in this instance, n.Name is really an ID
  1189. sn, err := s.apiClient().NetworkInspect(ctx, n.Name, network.InspectOptions{})
  1190. if err != nil && !errdefs.IsNotFound(err) {
  1191. return err
  1192. }
  1193. networks = append(networks, sn)
  1194. }
  1195. // NetworkList API doesn't return the exact name match, so we can retrieve more than one network with a request
  1196. networks = utils.Filter(networks, func(net network.Inspect) bool {
  1197. // later in this function, the name is changed the to ID.
  1198. // this function is called during the rebuild stage of `compose watch`.
  1199. // we still require just one network back, but we need to run the search on the ID
  1200. return net.Name == n.Name || net.ID == n.Name
  1201. })
  1202. switch len(networks) {
  1203. case 1:
  1204. n.Name = networks[0].ID
  1205. return nil
  1206. case 0:
  1207. enabled, err := s.isSWarmEnabled(ctx)
  1208. if err != nil {
  1209. return err
  1210. }
  1211. if enabled {
  1212. // Swarm nodes do not register overlay networks that were
  1213. // created on a different node unless they're in use.
  1214. // So we can't preemptively check network exists, but
  1215. // networkAttach will later fail anyway if network actually doesn't exist
  1216. return nil
  1217. }
  1218. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  1219. default:
  1220. return fmt.Errorf("multiple networks with name %q were found. Use network ID as `name` to avoid ambiguity", n.Name)
  1221. }
  1222. }
  1223. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig, project string) error {
  1224. inspected, err := s.apiClient().VolumeInspect(ctx, volume.Name)
  1225. if err != nil {
  1226. if !errdefs.IsNotFound(err) {
  1227. return err
  1228. }
  1229. if volume.External {
  1230. return fmt.Errorf("external volume %q not found", volume.Name)
  1231. }
  1232. err := s.createVolume(ctx, volume)
  1233. return err
  1234. }
  1235. if volume.External {
  1236. return nil
  1237. }
  1238. // Volume exists with name, but let's double-check this is the expected one
  1239. p, ok := inspected.Labels[api.ProjectLabel]
  1240. if !ok {
  1241. logrus.Warnf("volume %q already exists but was not created by Docker Compose. Use `external: true` to use an existing volume", volume.Name)
  1242. }
  1243. if ok && p != project {
  1244. 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)
  1245. }
  1246. return nil
  1247. }
  1248. func (s *composeService) createVolume(ctx context.Context, volume types.VolumeConfig) error {
  1249. eventName := fmt.Sprintf("Volume %q", volume.Name)
  1250. w := progress.ContextWriter(ctx)
  1251. w.Event(progress.CreatingEvent(eventName))
  1252. _, err := s.apiClient().VolumeCreate(ctx, volumetypes.CreateOptions{
  1253. Labels: volume.Labels,
  1254. Name: volume.Name,
  1255. Driver: volume.Driver,
  1256. DriverOpts: volume.DriverOpts,
  1257. })
  1258. if err != nil {
  1259. w.Event(progress.ErrorEvent(eventName))
  1260. return err
  1261. }
  1262. w.Event(progress.CreatedEvent(eventName))
  1263. return nil
  1264. }