create.go 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  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. driverOpts types.Options
  398. )
  399. if config != nil {
  400. ipv4Address = config.Ipv4Address
  401. ipv6Address = config.Ipv6Address
  402. ipam = &network.EndpointIPAMConfig{
  403. IPv4Address: ipv4Address,
  404. IPv6Address: ipv6Address,
  405. LinkLocalIPs: config.LinkLocalIPs,
  406. }
  407. macAddress = config.MacAddress
  408. driverOpts = config.DriverOpts
  409. }
  410. return &network.EndpointSettings{
  411. Aliases: getAliases(p, service, serviceIndex, networkKey, useNetworkAliases),
  412. Links: links,
  413. IPAddress: ipv4Address,
  414. IPv6Gateway: ipv6Address,
  415. IPAMConfig: ipam,
  416. MacAddress: macAddress,
  417. DriverOpts: driverOpts,
  418. }
  419. }
  420. // copy/pasted from https://github.com/docker/cli/blob/9de1b162f/cli/command/container/opts.go#L673-L697 + RelativePath
  421. // TODO find so way to share this code with docker/cli
  422. func parseSecurityOpts(p *types.Project, securityOpts []string) ([]string, bool, error) {
  423. var (
  424. unconfined bool
  425. parsed []string
  426. )
  427. for _, opt := range securityOpts {
  428. if opt == "systempaths=unconfined" {
  429. unconfined = true
  430. continue
  431. }
  432. con := strings.SplitN(opt, "=", 2)
  433. if len(con) == 1 && con[0] != "no-new-privileges" {
  434. if strings.Contains(opt, ":") {
  435. con = strings.SplitN(opt, ":", 2)
  436. } else {
  437. return securityOpts, false, fmt.Errorf("Invalid security-opt: %q", opt)
  438. }
  439. }
  440. if con[0] == "seccomp" && con[1] != "unconfined" {
  441. f, err := os.ReadFile(p.RelativePath(con[1]))
  442. if err != nil {
  443. return securityOpts, false, fmt.Errorf("opening seccomp profile (%s) failed: %w", con[1], err)
  444. }
  445. b := bytes.NewBuffer(nil)
  446. if err := json.Compact(b, f); err != nil {
  447. return securityOpts, false, fmt.Errorf("compacting json for seccomp profile (%s) failed: %w", con[1], err)
  448. }
  449. parsed = append(parsed, fmt.Sprintf("seccomp=%s", b.Bytes()))
  450. } else {
  451. parsed = append(parsed, opt)
  452. }
  453. }
  454. return parsed, unconfined, nil
  455. }
  456. func (s *composeService) prepareLabels(labels types.Labels, service types.ServiceConfig, number int) (map[string]string, error) {
  457. hash, err := ServiceHash(service)
  458. if err != nil {
  459. return nil, err
  460. }
  461. labels[api.ConfigHashLabel] = hash
  462. labels[api.ContainerNumberLabel] = strconv.Itoa(number)
  463. var dependencies []string
  464. for s, d := range service.DependsOn {
  465. dependencies = append(dependencies, fmt.Sprintf("%s:%s:%t", s, d.Condition, d.Restart))
  466. }
  467. labels[api.DependenciesLabel] = strings.Join(dependencies, ",")
  468. return labels, nil
  469. }
  470. // defaultNetworkSettings determines the container.NetworkMode and corresponding network.NetworkingConfig (nil if not applicable).
  471. func defaultNetworkSettings(
  472. project *types.Project,
  473. service types.ServiceConfig,
  474. serviceIndex int,
  475. links []string,
  476. useNetworkAliases bool,
  477. version string,
  478. ) (container.NetworkMode, *network.NetworkingConfig) {
  479. if service.NetworkMode != "" {
  480. return container.NetworkMode(service.NetworkMode), nil
  481. }
  482. if len(project.Networks) == 0 {
  483. return "none", nil
  484. }
  485. var primaryNetworkKey string
  486. if len(service.Networks) > 0 {
  487. primaryNetworkKey = service.NetworksByPriority()[0]
  488. } else {
  489. primaryNetworkKey = "default"
  490. }
  491. primaryNetworkMobyNetworkName := project.Networks[primaryNetworkKey].Name
  492. endpointsConfig := map[string]*network.EndpointSettings{
  493. primaryNetworkMobyNetworkName: createEndpointSettings(project, service, serviceIndex, primaryNetworkKey, links, useNetworkAliases),
  494. }
  495. // Starting from API version 1.44, the Engine will take several EndpointsConfigs
  496. // so we can pass all the extra networks we want the container to be connected to
  497. // in the network configuration instead of connecting the container to each extra
  498. // network individually after creation.
  499. if versions.GreaterThanOrEqualTo(version, "1.44") && len(service.Networks) > 1 {
  500. serviceNetworks := service.NetworksByPriority()
  501. for _, networkKey := range serviceNetworks[1:] {
  502. mobyNetworkName := project.Networks[networkKey].Name
  503. epSettings := createEndpointSettings(project, service, serviceIndex, networkKey, links, useNetworkAliases)
  504. endpointsConfig[mobyNetworkName] = epSettings
  505. }
  506. }
  507. networkConfig := &network.NetworkingConfig{
  508. EndpointsConfig: endpointsConfig,
  509. }
  510. // From the Engine API docs:
  511. // > Supported standard values are: bridge, host, none, and container:<name|id>.
  512. // > Any other value is taken as a custom network's name to which this container should connect to.
  513. return container.NetworkMode(primaryNetworkMobyNetworkName), networkConfig
  514. }
  515. func getRestartPolicy(service types.ServiceConfig) container.RestartPolicy {
  516. var restart container.RestartPolicy
  517. if service.Restart != "" {
  518. split := strings.Split(service.Restart, ":")
  519. var attempts int
  520. if len(split) > 1 {
  521. attempts, _ = strconv.Atoi(split[1])
  522. }
  523. restart = container.RestartPolicy{
  524. Name: mapRestartPolicyCondition(split[0]),
  525. MaximumRetryCount: attempts,
  526. }
  527. }
  528. if service.Deploy != nil && service.Deploy.RestartPolicy != nil {
  529. policy := *service.Deploy.RestartPolicy
  530. var attempts int
  531. if policy.MaxAttempts != nil {
  532. attempts = int(*policy.MaxAttempts)
  533. }
  534. restart = container.RestartPolicy{
  535. Name: mapRestartPolicyCondition(policy.Condition),
  536. MaximumRetryCount: attempts,
  537. }
  538. }
  539. return restart
  540. }
  541. func mapRestartPolicyCondition(condition string) container.RestartPolicyMode {
  542. // map definitions of deploy.restart_policy to engine definitions
  543. switch condition {
  544. case "none", "no":
  545. return container.RestartPolicyDisabled
  546. case "on-failure":
  547. return container.RestartPolicyOnFailure
  548. case "unless-stopped":
  549. return container.RestartPolicyUnlessStopped
  550. case "any", "always":
  551. return container.RestartPolicyAlways
  552. default:
  553. return container.RestartPolicyMode(condition)
  554. }
  555. }
  556. func getDeployResources(s types.ServiceConfig) container.Resources {
  557. var swappiness *int64
  558. if s.MemSwappiness != 0 {
  559. val := int64(s.MemSwappiness)
  560. swappiness = &val
  561. }
  562. resources := container.Resources{
  563. CgroupParent: s.CgroupParent,
  564. Memory: int64(s.MemLimit),
  565. MemorySwap: int64(s.MemSwapLimit),
  566. MemorySwappiness: swappiness,
  567. MemoryReservation: int64(s.MemReservation),
  568. OomKillDisable: &s.OomKillDisable,
  569. CPUCount: s.CPUCount,
  570. CPUPeriod: s.CPUPeriod,
  571. CPUQuota: s.CPUQuota,
  572. CPURealtimePeriod: s.CPURTPeriod,
  573. CPURealtimeRuntime: s.CPURTRuntime,
  574. CPUShares: s.CPUShares,
  575. NanoCPUs: int64(s.CPUS * 1e9),
  576. CPUPercent: int64(s.CPUPercent * 100),
  577. CpusetCpus: s.CPUSet,
  578. DeviceCgroupRules: s.DeviceCgroupRules,
  579. }
  580. if s.PidsLimit != 0 {
  581. resources.PidsLimit = &s.PidsLimit
  582. }
  583. setBlkio(s.BlkioConfig, &resources)
  584. if s.Deploy != nil {
  585. setLimits(s.Deploy.Resources.Limits, &resources)
  586. setReservations(s.Deploy.Resources.Reservations, &resources)
  587. }
  588. for _, device := range s.Devices {
  589. // FIXME should use docker/cli parseDevice, unfortunately private
  590. src := ""
  591. dst := ""
  592. permissions := "rwm"
  593. arr := strings.Split(device, ":")
  594. switch len(arr) {
  595. case 3:
  596. permissions = arr[2]
  597. fallthrough
  598. case 2:
  599. dst = arr[1]
  600. fallthrough
  601. case 1:
  602. src = arr[0]
  603. }
  604. if dst == "" {
  605. dst = src
  606. }
  607. resources.Devices = append(resources.Devices, container.DeviceMapping{
  608. PathOnHost: src,
  609. PathInContainer: dst,
  610. CgroupPermissions: permissions,
  611. })
  612. }
  613. ulimits := toUlimits(s.Ulimits)
  614. resources.Ulimits = ulimits
  615. return resources
  616. }
  617. func toUlimits(m map[string]*types.UlimitsConfig) []*units.Ulimit {
  618. var ulimits []*units.Ulimit
  619. for name, u := range m {
  620. soft := u.Single
  621. if u.Soft != 0 {
  622. soft = u.Soft
  623. }
  624. hard := u.Single
  625. if u.Hard != 0 {
  626. hard = u.Hard
  627. }
  628. ulimits = append(ulimits, &units.Ulimit{
  629. Name: name,
  630. Hard: int64(hard),
  631. Soft: int64(soft),
  632. })
  633. }
  634. return ulimits
  635. }
  636. func setReservations(reservations *types.Resource, resources *container.Resources) {
  637. if reservations == nil {
  638. return
  639. }
  640. // Cpu reservation is a swarm option and PIDs is only a limit
  641. // So we only need to map memory reservation and devices
  642. if reservations.MemoryBytes != 0 {
  643. resources.MemoryReservation = int64(reservations.MemoryBytes)
  644. }
  645. for _, device := range reservations.Devices {
  646. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  647. Capabilities: [][]string{device.Capabilities},
  648. Count: int(device.Count),
  649. DeviceIDs: device.IDs,
  650. Driver: device.Driver,
  651. })
  652. }
  653. }
  654. func setLimits(limits *types.Resource, resources *container.Resources) {
  655. if limits == nil {
  656. return
  657. }
  658. if limits.MemoryBytes != 0 {
  659. resources.Memory = int64(limits.MemoryBytes)
  660. }
  661. if limits.NanoCPUs != 0 {
  662. resources.NanoCPUs = int64(limits.NanoCPUs * 1e9)
  663. }
  664. if limits.Pids > 0 {
  665. resources.PidsLimit = &limits.Pids
  666. }
  667. }
  668. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  669. if blkio == nil {
  670. return
  671. }
  672. resources.BlkioWeight = blkio.Weight
  673. for _, b := range blkio.WeightDevice {
  674. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  675. Path: b.Path,
  676. Weight: b.Weight,
  677. })
  678. }
  679. for _, b := range blkio.DeviceReadBps {
  680. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  681. Path: b.Path,
  682. Rate: uint64(b.Rate),
  683. })
  684. }
  685. for _, b := range blkio.DeviceReadIOps {
  686. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  687. Path: b.Path,
  688. Rate: uint64(b.Rate),
  689. })
  690. }
  691. for _, b := range blkio.DeviceWriteBps {
  692. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  693. Path: b.Path,
  694. Rate: uint64(b.Rate),
  695. })
  696. }
  697. for _, b := range blkio.DeviceWriteIOps {
  698. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  699. Path: b.Path,
  700. Rate: uint64(b.Rate),
  701. })
  702. }
  703. }
  704. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  705. ports := nat.PortSet{}
  706. for _, s := range s.Expose {
  707. p := nat.Port(s)
  708. ports[p] = struct{}{}
  709. }
  710. for _, p := range s.Ports {
  711. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  712. ports[p] = struct{}{}
  713. }
  714. return ports
  715. }
  716. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  717. bindings := nat.PortMap{}
  718. for _, port := range s.Ports {
  719. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  720. binding := nat.PortBinding{
  721. HostIP: port.HostIP,
  722. HostPort: port.Published,
  723. }
  724. bindings[p] = append(bindings[p], binding)
  725. }
  726. return bindings
  727. }
  728. func getDependentServiceFromMode(mode string) string {
  729. if strings.HasPrefix(
  730. mode,
  731. types.NetworkModeServicePrefix,
  732. ) {
  733. return mode[len(types.NetworkModeServicePrefix):]
  734. }
  735. return ""
  736. }
  737. func (s *composeService) buildContainerVolumes(
  738. ctx context.Context,
  739. p types.Project,
  740. service types.ServiceConfig,
  741. inherit *moby.Container,
  742. ) ([]string, []mount.Mount, error) {
  743. var mounts []mount.Mount
  744. var binds []string
  745. image := api.GetImageNameOrDefault(service, p.Name)
  746. imgInspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, image)
  747. if err != nil {
  748. return nil, nil, err
  749. }
  750. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  751. if err != nil {
  752. return nil, nil, err
  753. }
  754. MOUNTS:
  755. for _, m := range mountOptions {
  756. if m.Type == mount.TypeNamedPipe {
  757. mounts = append(mounts, m)
  758. continue
  759. }
  760. if m.Type == mount.TypeBind {
  761. // `Mount` is preferred but does not offer option to created host path if missing
  762. // so `Bind` API is used here with raw volume string
  763. // see https://github.com/moby/moby/issues/43483
  764. for _, v := range service.Volumes {
  765. if v.Target == m.Target {
  766. switch {
  767. case string(m.Type) != v.Type:
  768. v.Source = m.Source
  769. fallthrough
  770. case v.Bind != nil && v.Bind.CreateHostPath:
  771. binds = append(binds, v.String())
  772. continue MOUNTS
  773. }
  774. }
  775. }
  776. }
  777. mounts = append(mounts, m)
  778. }
  779. return binds, mounts, nil
  780. }
  781. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  782. var mounts = map[string]mount.Mount{}
  783. if inherit != nil {
  784. for _, m := range inherit.Mounts {
  785. if m.Type == "tmpfs" {
  786. continue
  787. }
  788. src := m.Source
  789. if m.Type == "volume" {
  790. src = m.Name
  791. }
  792. m.Destination = path.Clean(m.Destination)
  793. if img.Config != nil {
  794. if _, ok := img.Config.Volumes[m.Destination]; ok {
  795. // inherit previous container's anonymous volume
  796. mounts[m.Destination] = mount.Mount{
  797. Type: m.Type,
  798. Source: src,
  799. Target: m.Destination,
  800. ReadOnly: !m.RW,
  801. }
  802. }
  803. }
  804. volumes := []types.ServiceVolumeConfig{}
  805. for _, v := range s.Volumes {
  806. if v.Target != m.Destination || v.Source != "" {
  807. volumes = append(volumes, v)
  808. continue
  809. }
  810. // inherit previous container's anonymous volume
  811. mounts[m.Destination] = mount.Mount{
  812. Type: m.Type,
  813. Source: src,
  814. Target: m.Destination,
  815. ReadOnly: !m.RW,
  816. }
  817. }
  818. s.Volumes = volumes
  819. }
  820. }
  821. mounts, err := fillBindMounts(p, s, mounts)
  822. if err != nil {
  823. return nil, err
  824. }
  825. values := make([]mount.Mount, 0, len(mounts))
  826. for _, v := range mounts {
  827. values = append(values, v)
  828. }
  829. return values, nil
  830. }
  831. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  832. for _, v := range s.Volumes {
  833. bindMount, err := buildMount(p, v)
  834. if err != nil {
  835. return nil, err
  836. }
  837. m[bindMount.Target] = bindMount
  838. }
  839. secrets, err := buildContainerSecretMounts(p, s)
  840. if err != nil {
  841. return nil, err
  842. }
  843. for _, s := range secrets {
  844. if _, found := m[s.Target]; found {
  845. continue
  846. }
  847. m[s.Target] = s
  848. }
  849. configs, err := buildContainerConfigMounts(p, s)
  850. if err != nil {
  851. return nil, err
  852. }
  853. for _, c := range configs {
  854. if _, found := m[c.Target]; found {
  855. continue
  856. }
  857. m[c.Target] = c
  858. }
  859. return m, nil
  860. }
  861. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  862. var mounts = map[string]mount.Mount{}
  863. configsBaseDir := "/"
  864. for _, config := range s.Configs {
  865. target := config.Target
  866. if config.Target == "" {
  867. target = configsBaseDir + config.Source
  868. } else if !isAbsTarget(config.Target) {
  869. target = configsBaseDir + config.Target
  870. }
  871. if config.UID != "" || config.GID != "" || config.Mode != nil {
  872. logrus.Warn("config `uid`, `gid` and `mode` are not supported, they will be ignored")
  873. }
  874. definedConfig := p.Configs[config.Source]
  875. if definedConfig.External {
  876. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  877. }
  878. if definedConfig.Driver != "" {
  879. return nil, errors.New("Docker Compose does not support configs.*.driver")
  880. }
  881. if definedConfig.TemplateDriver != "" {
  882. return nil, errors.New("Docker Compose does not support configs.*.template_driver")
  883. }
  884. if definedConfig.Environment != "" || definedConfig.Content != "" {
  885. continue
  886. }
  887. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  888. Type: types.VolumeTypeBind,
  889. Source: definedConfig.File,
  890. Target: target,
  891. ReadOnly: true,
  892. })
  893. if err != nil {
  894. return nil, err
  895. }
  896. mounts[target] = bindMount
  897. }
  898. values := make([]mount.Mount, 0, len(mounts))
  899. for _, v := range mounts {
  900. values = append(values, v)
  901. }
  902. return values, nil
  903. }
  904. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  905. var mounts = map[string]mount.Mount{}
  906. secretsDir := "/run/secrets/"
  907. for _, secret := range s.Secrets {
  908. target := secret.Target
  909. if secret.Target == "" {
  910. target = secretsDir + secret.Source
  911. } else if !isAbsTarget(secret.Target) {
  912. target = secretsDir + secret.Target
  913. }
  914. if secret.UID != "" || secret.GID != "" || secret.Mode != nil {
  915. logrus.Warn("secrets `uid`, `gid` and `mode` are not supported, they will be ignored")
  916. }
  917. definedSecret := p.Secrets[secret.Source]
  918. if definedSecret.External {
  919. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  920. }
  921. if definedSecret.Driver != "" {
  922. return nil, errors.New("Docker Compose does not support secrets.*.driver")
  923. }
  924. if definedSecret.TemplateDriver != "" {
  925. return nil, errors.New("Docker Compose does not support secrets.*.template_driver")
  926. }
  927. if definedSecret.Environment != "" {
  928. continue
  929. }
  930. mnt, err := buildMount(p, types.ServiceVolumeConfig{
  931. Type: types.VolumeTypeBind,
  932. Source: definedSecret.File,
  933. Target: target,
  934. ReadOnly: true,
  935. })
  936. if err != nil {
  937. return nil, err
  938. }
  939. mounts[target] = mnt
  940. }
  941. values := make([]mount.Mount, 0, len(mounts))
  942. for _, v := range mounts {
  943. values = append(values, v)
  944. }
  945. return values, nil
  946. }
  947. func isAbsTarget(p string) bool {
  948. return isUnixAbs(p) || isWindowsAbs(p)
  949. }
  950. func isUnixAbs(p string) bool {
  951. return strings.HasPrefix(p, "/")
  952. }
  953. func isWindowsAbs(p string) bool {
  954. if strings.HasPrefix(p, "\\\\") {
  955. return true
  956. }
  957. if len(p) > 2 && p[1] == ':' {
  958. return p[2] == '\\'
  959. }
  960. return false
  961. }
  962. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  963. source := volume.Source
  964. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  965. // do not replace these with filepath.Abs(source) that will include a default drive.
  966. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  967. // volume source has already been prefixed with workdir if required, by compose-go project loader
  968. var err error
  969. source, err = filepath.Abs(source)
  970. if err != nil {
  971. return mount.Mount{}, err
  972. }
  973. }
  974. if volume.Type == types.VolumeTypeVolume {
  975. if volume.Source != "" {
  976. pVolume, ok := project.Volumes[volume.Source]
  977. if ok {
  978. source = pVolume.Name
  979. }
  980. }
  981. }
  982. bind, vol, tmpfs := buildMountOptions(project, volume)
  983. volume.Target = path.Clean(volume.Target)
  984. if bind != nil {
  985. volume.Type = types.VolumeTypeBind
  986. }
  987. return mount.Mount{
  988. Type: mount.Type(volume.Type),
  989. Source: source,
  990. Target: volume.Target,
  991. ReadOnly: volume.ReadOnly,
  992. Consistency: mount.Consistency(volume.Consistency),
  993. BindOptions: bind,
  994. VolumeOptions: vol,
  995. TmpfsOptions: tmpfs,
  996. }, nil
  997. }
  998. func buildMountOptions(project types.Project, volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  999. switch volume.Type {
  1000. case "bind":
  1001. if volume.Volume != nil {
  1002. logrus.Warnf("mount of type `bind` should not define `volume` option")
  1003. }
  1004. if volume.Tmpfs != nil {
  1005. logrus.Warnf("mount of type `bind` should not define `tmpfs` option")
  1006. }
  1007. return buildBindOption(volume.Bind), nil, nil
  1008. case "volume":
  1009. if volume.Bind != nil {
  1010. logrus.Warnf("mount of type `volume` should not define `bind` option")
  1011. }
  1012. if volume.Tmpfs != nil {
  1013. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  1014. }
  1015. if v, ok := project.Volumes[volume.Source]; ok && v.DriverOpts["o"] == types.VolumeTypeBind {
  1016. return buildBindOption(&types.ServiceVolumeBind{
  1017. CreateHostPath: true,
  1018. }), nil, nil
  1019. }
  1020. return nil, buildVolumeOptions(volume.Volume), nil
  1021. case "tmpfs":
  1022. if volume.Bind != nil {
  1023. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  1024. }
  1025. if volume.Volume != nil {
  1026. logrus.Warnf("mount of type `tmpfs` should not define `volume` option")
  1027. }
  1028. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  1029. }
  1030. return nil, nil, nil
  1031. }
  1032. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  1033. if bind == nil {
  1034. return nil
  1035. }
  1036. return &mount.BindOptions{
  1037. Propagation: mount.Propagation(bind.Propagation),
  1038. // NonRecursive: false, FIXME missing from model ?
  1039. }
  1040. }
  1041. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  1042. if vol == nil {
  1043. return nil
  1044. }
  1045. return &mount.VolumeOptions{
  1046. NoCopy: vol.NoCopy,
  1047. Subpath: vol.Subpath,
  1048. // Labels: , // FIXME missing from model ?
  1049. // DriverConfig: , // FIXME missing from model ?
  1050. }
  1051. }
  1052. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  1053. if tmpfs == nil {
  1054. return nil
  1055. }
  1056. return &mount.TmpfsOptions{
  1057. SizeBytes: int64(tmpfs.Size),
  1058. Mode: os.FileMode(tmpfs.Mode),
  1059. }
  1060. }
  1061. func (s *composeService) ensureNetwork(ctx context.Context, n *types.NetworkConfig) error {
  1062. if n.External {
  1063. return s.resolveExternalNetwork(ctx, n)
  1064. }
  1065. err := s.resolveOrCreateNetwork(ctx, n)
  1066. if errdefs.IsConflict(err) {
  1067. // Maybe another execution of `docker compose up|run` created same network
  1068. // let's retry once
  1069. return s.resolveOrCreateNetwork(ctx, n)
  1070. }
  1071. return err
  1072. }
  1073. func (s *composeService) resolveOrCreateNetwork(ctx context.Context, n *types.NetworkConfig) error { //nolint:gocyclo
  1074. expectedNetworkLabel := n.Labels[api.NetworkLabel]
  1075. expectedProjectLabel := n.Labels[api.ProjectLabel]
  1076. // First, try to find a unique network matching by name or ID
  1077. inspect, err := s.apiClient().NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  1078. if err == nil {
  1079. // NetworkInspect will match on ID prefix, so double check we get the expected one
  1080. // as looking for network named `db` we could erroneously matched network ID `db9086999caf`
  1081. if inspect.Name == n.Name || inspect.ID == n.Name {
  1082. p, ok := inspect.Labels[api.ProjectLabel]
  1083. if !ok {
  1084. logrus.Warnf("a network with name %s exists but was not created by compose.\n"+
  1085. "Set `external: true` to use an existing network", n.Name)
  1086. } else if p != expectedProjectLabel {
  1087. logrus.Warnf("a network with name %s exists but was not created for project %q.\n"+
  1088. "Set `external: true` to use an existing network", n.Name, expectedProjectLabel)
  1089. }
  1090. if inspect.Labels[api.NetworkLabel] != expectedNetworkLabel {
  1091. return fmt.Errorf("network %s was found but has incorrect label %s set to %q", n.Name, api.NetworkLabel, inspect.Labels[api.NetworkLabel])
  1092. }
  1093. return nil
  1094. }
  1095. }
  1096. // ignore other errors. Typically, an ambiguous request by name results in some generic `invalidParameter` error
  1097. // Either not found, or name is ambiguous - use NetworkList to list by name
  1098. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  1099. Filters: filters.NewArgs(filters.Arg("name", n.Name)),
  1100. })
  1101. if err != nil {
  1102. return err
  1103. }
  1104. // NetworkList Matches all or part of a network name, so we have to filter for a strict match
  1105. networks = utils.Filter(networks, func(net moby.NetworkResource) bool {
  1106. return net.Name == n.Name
  1107. })
  1108. for _, net := range networks {
  1109. if net.Labels[api.ProjectLabel] == expectedProjectLabel &&
  1110. net.Labels[api.NetworkLabel] == expectedNetworkLabel {
  1111. return nil
  1112. }
  1113. }
  1114. // we could have set NetworkList with a projectFilter and networkFilter but not doing so allows to catch this
  1115. // scenario were a network with same name exists but doesn't have label, and use of `CheckDuplicate: true`
  1116. // prevents to create another one.
  1117. if len(networks) > 0 {
  1118. logrus.Warnf("a network with name %s exists but was not created by compose.\n"+
  1119. "Set `external: true` to use an existing network", n.Name)
  1120. return nil
  1121. }
  1122. var ipam *network.IPAM
  1123. if n.Ipam.Config != nil {
  1124. var config []network.IPAMConfig
  1125. for _, pool := range n.Ipam.Config {
  1126. config = append(config, network.IPAMConfig{
  1127. Subnet: pool.Subnet,
  1128. IPRange: pool.IPRange,
  1129. Gateway: pool.Gateway,
  1130. AuxAddress: pool.AuxiliaryAddresses,
  1131. })
  1132. }
  1133. ipam = &network.IPAM{
  1134. Driver: n.Ipam.Driver,
  1135. Config: config,
  1136. }
  1137. }
  1138. createOpts := moby.NetworkCreate{
  1139. CheckDuplicate: true,
  1140. Labels: n.Labels,
  1141. Driver: n.Driver,
  1142. Options: n.DriverOpts,
  1143. Internal: n.Internal,
  1144. Attachable: n.Attachable,
  1145. IPAM: ipam,
  1146. EnableIPv6: n.EnableIPv6,
  1147. }
  1148. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  1149. createOpts.IPAM = &network.IPAM{}
  1150. }
  1151. if n.Ipam.Driver != "" {
  1152. createOpts.IPAM.Driver = n.Ipam.Driver
  1153. }
  1154. for _, ipamConfig := range n.Ipam.Config {
  1155. config := network.IPAMConfig{
  1156. Subnet: ipamConfig.Subnet,
  1157. IPRange: ipamConfig.IPRange,
  1158. Gateway: ipamConfig.Gateway,
  1159. AuxAddress: ipamConfig.AuxiliaryAddresses,
  1160. }
  1161. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  1162. }
  1163. networkEventName := fmt.Sprintf("Network %s", n.Name)
  1164. w := progress.ContextWriter(ctx)
  1165. w.Event(progress.CreatingEvent(networkEventName))
  1166. _, err = s.apiClient().NetworkCreate(ctx, n.Name, createOpts)
  1167. if err != nil {
  1168. w.Event(progress.ErrorEvent(networkEventName))
  1169. return fmt.Errorf("failed to create network %s: %w", n.Name, err)
  1170. }
  1171. w.Event(progress.CreatedEvent(networkEventName))
  1172. return nil
  1173. }
  1174. func (s *composeService) resolveExternalNetwork(ctx context.Context, n *types.NetworkConfig) error {
  1175. // NetworkInspect will match on ID prefix, so NetworkList with a name
  1176. // filter is used to look for an exact match to prevent e.g. a network
  1177. // named `db` from getting erroneously matched to a network with an ID
  1178. // like `db9086999caf`
  1179. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  1180. Filters: filters.NewArgs(filters.Arg("name", n.Name)),
  1181. })
  1182. if err != nil {
  1183. return err
  1184. }
  1185. if len(networks) == 0 {
  1186. // in this instance, n.Name is really an ID
  1187. sn, err := s.apiClient().NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  1188. if err != nil {
  1189. return err
  1190. }
  1191. networks = append(networks, sn)
  1192. }
  1193. // NetworkList API doesn't return the exact name match, so we can retrieve more than one network with a request
  1194. networks = utils.Filter(networks, func(net moby.NetworkResource) bool {
  1195. // later in this function, the name is changed the to ID.
  1196. // this function is called during the rebuild stage of `compose watch`.
  1197. // we still require just one network back, but we need to run the search on the ID
  1198. return net.Name == n.Name || net.ID == n.Name
  1199. })
  1200. switch len(networks) {
  1201. case 1:
  1202. n.Name = networks[0].ID
  1203. return nil
  1204. case 0:
  1205. enabled, err := s.isSWarmEnabled(ctx)
  1206. if err != nil {
  1207. return err
  1208. }
  1209. if enabled {
  1210. // Swarm nodes do not register overlay networks that were
  1211. // created on a different node unless they're in use.
  1212. // So we can't preemptively check network exists, but
  1213. // networkAttach will later fail anyway if network actually doesn't exists
  1214. return nil
  1215. }
  1216. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  1217. default:
  1218. return fmt.Errorf("multiple networks with name %q were found. Use network ID as `name` to avoid ambiguity", n.Name)
  1219. }
  1220. }
  1221. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig, project string) error {
  1222. inspected, err := s.apiClient().VolumeInspect(ctx, volume.Name)
  1223. if err != nil {
  1224. if !errdefs.IsNotFound(err) {
  1225. return err
  1226. }
  1227. if volume.External {
  1228. return fmt.Errorf("external volume %q not found", volume.Name)
  1229. }
  1230. err := s.createVolume(ctx, volume)
  1231. return err
  1232. }
  1233. if volume.External {
  1234. return nil
  1235. }
  1236. // Volume exists with name, but let's double-check this is the expected one
  1237. p, ok := inspected.Labels[api.ProjectLabel]
  1238. if !ok {
  1239. logrus.Warnf("volume %q already exists but was not created by Docker Compose. Use `external: true` to use an existing volume", volume.Name)
  1240. }
  1241. if ok && p != project {
  1242. 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)
  1243. }
  1244. return nil
  1245. }
  1246. func (s *composeService) createVolume(ctx context.Context, volume types.VolumeConfig) error {
  1247. eventName := fmt.Sprintf("Volume %q", volume.Name)
  1248. w := progress.ContextWriter(ctx)
  1249. w.Event(progress.CreatingEvent(eventName))
  1250. _, err := s.apiClient().VolumeCreate(ctx, volume_api.CreateOptions{
  1251. Labels: volume.Labels,
  1252. Name: volume.Name,
  1253. Driver: volume.Driver,
  1254. DriverOpts: volume.DriverOpts,
  1255. })
  1256. if err != nil {
  1257. w.Event(progress.ErrorEvent(eventName))
  1258. return err
  1259. }
  1260. w.Event(progress.CreatedEvent(eventName))
  1261. return nil
  1262. }