create.go 48 KB

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