create.go 48 KB

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