create.go 48 KB

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