create.go 39 KB

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