create.go 41 KB

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