create.go 41 KB

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