create.go 42 KB

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