create.go 41 KB

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