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. Binds: binds,
  276. Mounts: mounts,
  277. CapAdd: strslice.StrSlice(service.CapAdd),
  278. CapDrop: strslice.StrSlice(service.CapDrop),
  279. NetworkMode: networkMode,
  280. Init: service.Init,
  281. IpcMode: container.IpcMode(service.Ipc),
  282. CgroupnsMode: container.CgroupnsMode(service.Cgroup),
  283. ReadonlyRootfs: service.ReadOnly,
  284. RestartPolicy: getRestartPolicy(service),
  285. ShmSize: int64(service.ShmSize),
  286. Sysctls: service.Sysctls,
  287. PortBindings: portBindings,
  288. Resources: resources,
  289. VolumeDriver: service.VolumeDriver,
  290. VolumesFrom: service.VolumesFrom,
  291. DNS: service.DNS,
  292. DNSSearch: service.DNSSearch,
  293. DNSOptions: service.DNSOpts,
  294. ExtraHosts: service.ExtraHosts.AsList(":"),
  295. SecurityOpt: securityOpts,
  296. StorageOpt: service.StorageOpt,
  297. UsernsMode: container.UsernsMode(service.UserNSMode),
  298. UTSMode: container.UTSMode(service.Uts),
  299. Privileged: service.Privileged,
  300. PidMode: container.PidMode(service.Pid),
  301. Tmpfs: tmpfs,
  302. Isolation: container.Isolation(service.Isolation),
  303. Runtime: service.Runtime,
  304. LogConfig: logConfig,
  305. GroupAdd: service.GroupAdd,
  306. Links: links,
  307. OomScoreAdj: int(service.OomScoreAdj),
  308. }
  309. if unconfined {
  310. hostConfig.MaskedPaths = []string{}
  311. hostConfig.ReadonlyPaths = []string{}
  312. }
  313. cfgs := createConfigs{
  314. Container: &containerConfig,
  315. Host: &hostConfig,
  316. Network: networkingConfig,
  317. Links: links,
  318. }
  319. return cfgs, nil
  320. }
  321. // prepareContainerMACAddress handles the service-level mac_address field and the newer mac_address field added to service
  322. // network config. This newer field is only compatible with the Engine API v1.44 (and onwards), and this API version
  323. // also deprecates the container-wide mac_address field. Thus, this method will validate service config and mutate the
  324. // passed mainNw to provide backward-compatibility whenever possible.
  325. //
  326. // It returns the container-wide MAC address, but this value will be kept empty for newer API versions.
  327. func (s *composeService) prepareContainerMACAddress(ctx context.Context, service types.ServiceConfig, mainNw *types.ServiceNetworkConfig, nwName string) (string, error) {
  328. version, err := s.RuntimeVersion(ctx)
  329. if err != nil {
  330. return "", err
  331. }
  332. // Engine API 1.44 added support for endpoint-specific MAC address and now returns a warning when a MAC address is
  333. // set in container.Config. Thus, we have to jump through a number of hoops:
  334. //
  335. // 1. Top-level mac_address and main endpoint's MAC address should be the same ;
  336. // 2. If supported by the API, top-level mac_address should be migrated to the main endpoint and container.Config
  337. // should be kept empty ;
  338. // 3. Otherwise, the endpoint mac_address should be set in container.Config and no other endpoint-specific
  339. // mac_address can be specified. If that's the case, use top-level mac_address ;
  340. //
  341. // After that, if an endpoint mac_address is set, it's either user-defined or migrated by the code below, so
  342. // there's no need to check for API version in defaultNetworkSettings.
  343. macAddress := service.MacAddress
  344. if macAddress != "" && mainNw != nil && mainNw.MacAddress != "" && mainNw.MacAddress != macAddress {
  345. return "", fmt.Errorf("the service-level mac_address should have the same value as network %s", nwName)
  346. }
  347. if versions.GreaterThanOrEqualTo(version, "1.44") {
  348. if mainNw != nil && mainNw.MacAddress == "" {
  349. mainNw.MacAddress = macAddress
  350. }
  351. macAddress = ""
  352. } else if len(service.Networks) > 0 {
  353. var withMacAddress []string
  354. for nwName, nw := range service.Networks {
  355. if nw != nil && nw.MacAddress != "" {
  356. withMacAddress = append(withMacAddress, nwName)
  357. }
  358. }
  359. if len(withMacAddress) > 1 {
  360. 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)
  361. }
  362. if mainNw != nil {
  363. macAddress = mainNw.MacAddress
  364. }
  365. }
  366. return macAddress, nil
  367. }
  368. func getAliases(project *types.Project, service types.ServiceConfig, serviceIndex int, networkKey string, useNetworkAliases bool) []string {
  369. aliases := []string{getContainerName(project.Name, service, serviceIndex)}
  370. if useNetworkAliases {
  371. aliases = append(aliases, service.Name)
  372. if cfg := service.Networks[networkKey]; cfg != nil {
  373. aliases = append(aliases, cfg.Aliases...)
  374. }
  375. }
  376. return aliases
  377. }
  378. func createEndpointSettings(p *types.Project, service types.ServiceConfig, serviceIndex int, networkKey string, links []string, useNetworkAliases bool) *network.EndpointSettings {
  379. config := service.Networks[networkKey]
  380. var ipam *network.EndpointIPAMConfig
  381. var (
  382. ipv4Address string
  383. ipv6Address string
  384. macAddress string
  385. )
  386. if config != nil {
  387. ipv4Address = config.Ipv4Address
  388. ipv6Address = config.Ipv6Address
  389. ipam = &network.EndpointIPAMConfig{
  390. IPv4Address: ipv4Address,
  391. IPv6Address: ipv6Address,
  392. LinkLocalIPs: config.LinkLocalIPs,
  393. }
  394. macAddress = config.MacAddress
  395. }
  396. return &network.EndpointSettings{
  397. Aliases: getAliases(p, service, serviceIndex, networkKey, useNetworkAliases),
  398. Links: links,
  399. IPAddress: ipv4Address,
  400. IPv6Gateway: ipv6Address,
  401. IPAMConfig: ipam,
  402. MacAddress: macAddress,
  403. }
  404. }
  405. // copy/pasted from https://github.com/docker/cli/blob/9de1b162f/cli/command/container/opts.go#L673-L697 + RelativePath
  406. // TODO find so way to share this code with docker/cli
  407. func parseSecurityOpts(p *types.Project, securityOpts []string) ([]string, bool, error) {
  408. var (
  409. unconfined bool
  410. parsed []string
  411. )
  412. for _, opt := range securityOpts {
  413. if opt == "systempaths=unconfined" {
  414. unconfined = true
  415. continue
  416. }
  417. con := strings.SplitN(opt, "=", 2)
  418. if len(con) == 1 && con[0] != "no-new-privileges" {
  419. if strings.Contains(opt, ":") {
  420. con = strings.SplitN(opt, ":", 2)
  421. } else {
  422. return securityOpts, false, fmt.Errorf("Invalid security-opt: %q", opt)
  423. }
  424. }
  425. if con[0] == "seccomp" && con[1] != "unconfined" {
  426. f, err := os.ReadFile(p.RelativePath(con[1]))
  427. if err != nil {
  428. return securityOpts, false, fmt.Errorf("opening seccomp profile (%s) failed: %w", con[1], err)
  429. }
  430. b := bytes.NewBuffer(nil)
  431. if err := json.Compact(b, f); err != nil {
  432. return securityOpts, false, fmt.Errorf("compacting json for seccomp profile (%s) failed: %w", con[1], err)
  433. }
  434. parsed = append(parsed, fmt.Sprintf("seccomp=%s", b.Bytes()))
  435. } else {
  436. parsed = append(parsed, opt)
  437. }
  438. }
  439. return parsed, unconfined, nil
  440. }
  441. func (s *composeService) prepareLabels(labels types.Labels, service types.ServiceConfig, number int) (map[string]string, error) {
  442. hash, err := ServiceHash(service)
  443. if err != nil {
  444. return nil, err
  445. }
  446. labels[api.ConfigHashLabel] = hash
  447. labels[api.ContainerNumberLabel] = strconv.Itoa(number)
  448. var dependencies []string
  449. for s, d := range service.DependsOn {
  450. dependencies = append(dependencies, fmt.Sprintf("%s:%s:%t", s, d.Condition, d.Restart))
  451. }
  452. labels[api.DependenciesLabel] = strings.Join(dependencies, ",")
  453. return labels, nil
  454. }
  455. // defaultNetworkSettings determines the container.NetworkMode and corresponding network.NetworkingConfig (nil if not applicable).
  456. func defaultNetworkSettings(
  457. project *types.Project,
  458. service types.ServiceConfig,
  459. serviceIndex int,
  460. links []string,
  461. useNetworkAliases bool,
  462. version string,
  463. ) (container.NetworkMode, *network.NetworkingConfig) {
  464. if service.NetworkMode != "" {
  465. return container.NetworkMode(service.NetworkMode), nil
  466. }
  467. if len(project.Networks) == 0 {
  468. return "none", nil
  469. }
  470. var primaryNetworkKey string
  471. if len(service.Networks) > 0 {
  472. primaryNetworkKey = service.NetworksByPriority()[0]
  473. } else {
  474. primaryNetworkKey = "default"
  475. }
  476. primaryNetworkMobyNetworkName := project.Networks[primaryNetworkKey].Name
  477. endpointsConfig := map[string]*network.EndpointSettings{
  478. primaryNetworkMobyNetworkName: createEndpointSettings(project, service, serviceIndex, primaryNetworkKey, links, useNetworkAliases),
  479. }
  480. // Starting from API version 1.44, the Engine will take several EndpointsConfigs
  481. // so we can pass all the extra networks we want the container to be connected to
  482. // in the network configuration instead of connecting the container to each extra
  483. // network individually after creation.
  484. if versions.GreaterThanOrEqualTo(version, "1.44") && len(service.Networks) > 1 {
  485. serviceNetworks := service.NetworksByPriority()
  486. for _, networkKey := range serviceNetworks[1:] {
  487. mobyNetworkName := project.Networks[networkKey].Name
  488. epSettings := createEndpointSettings(project, service, serviceIndex, networkKey, links, useNetworkAliases)
  489. endpointsConfig[mobyNetworkName] = epSettings
  490. }
  491. }
  492. networkConfig := &network.NetworkingConfig{
  493. EndpointsConfig: endpointsConfig,
  494. }
  495. // From the Engine API docs:
  496. // > Supported standard values are: bridge, host, none, and container:<name|id>.
  497. // > Any other value is taken as a custom network's name to which this container should connect to.
  498. return container.NetworkMode(primaryNetworkMobyNetworkName), networkConfig
  499. }
  500. func getRestartPolicy(service types.ServiceConfig) container.RestartPolicy {
  501. var restart container.RestartPolicy
  502. if service.Restart != "" {
  503. split := strings.Split(service.Restart, ":")
  504. var attempts int
  505. if len(split) > 1 {
  506. attempts, _ = strconv.Atoi(split[1])
  507. }
  508. restart = container.RestartPolicy{
  509. Name: mapRestartPolicyCondition(split[0]),
  510. MaximumRetryCount: attempts,
  511. }
  512. }
  513. if service.Deploy != nil && service.Deploy.RestartPolicy != nil {
  514. policy := *service.Deploy.RestartPolicy
  515. var attempts int
  516. if policy.MaxAttempts != nil {
  517. attempts = int(*policy.MaxAttempts)
  518. }
  519. restart = container.RestartPolicy{
  520. Name: mapRestartPolicyCondition(policy.Condition),
  521. MaximumRetryCount: attempts,
  522. }
  523. }
  524. return restart
  525. }
  526. func mapRestartPolicyCondition(condition string) container.RestartPolicyMode {
  527. // map definitions of deploy.restart_policy to engine definitions
  528. switch condition {
  529. case "none", "no":
  530. return container.RestartPolicyDisabled
  531. case "on-failure":
  532. return container.RestartPolicyOnFailure
  533. case "unless-stopped":
  534. return container.RestartPolicyUnlessStopped
  535. case "any", "always":
  536. return container.RestartPolicyAlways
  537. default:
  538. return container.RestartPolicyMode(condition)
  539. }
  540. }
  541. func getDeployResources(s types.ServiceConfig) container.Resources {
  542. var swappiness *int64
  543. if s.MemSwappiness != 0 {
  544. val := int64(s.MemSwappiness)
  545. swappiness = &val
  546. }
  547. resources := container.Resources{
  548. CgroupParent: s.CgroupParent,
  549. Memory: int64(s.MemLimit),
  550. MemorySwap: int64(s.MemSwapLimit),
  551. MemorySwappiness: swappiness,
  552. MemoryReservation: int64(s.MemReservation),
  553. OomKillDisable: &s.OomKillDisable,
  554. CPUCount: s.CPUCount,
  555. CPUPeriod: s.CPUPeriod,
  556. CPUQuota: s.CPUQuota,
  557. CPURealtimePeriod: s.CPURTPeriod,
  558. CPURealtimeRuntime: s.CPURTRuntime,
  559. CPUShares: s.CPUShares,
  560. NanoCPUs: int64(s.CPUS * 1e9),
  561. CPUPercent: int64(s.CPUPercent * 100),
  562. CpusetCpus: s.CPUSet,
  563. DeviceCgroupRules: s.DeviceCgroupRules,
  564. }
  565. if s.PidsLimit != 0 {
  566. resources.PidsLimit = &s.PidsLimit
  567. }
  568. setBlkio(s.BlkioConfig, &resources)
  569. if s.Deploy != nil {
  570. setLimits(s.Deploy.Resources.Limits, &resources)
  571. setReservations(s.Deploy.Resources.Reservations, &resources)
  572. }
  573. for _, device := range s.Devices {
  574. // FIXME should use docker/cli parseDevice, unfortunately private
  575. src := ""
  576. dst := ""
  577. permissions := "rwm"
  578. arr := strings.Split(device, ":")
  579. switch len(arr) {
  580. case 3:
  581. permissions = arr[2]
  582. fallthrough
  583. case 2:
  584. dst = arr[1]
  585. fallthrough
  586. case 1:
  587. src = arr[0]
  588. }
  589. if dst == "" {
  590. dst = src
  591. }
  592. resources.Devices = append(resources.Devices, container.DeviceMapping{
  593. PathOnHost: src,
  594. PathInContainer: dst,
  595. CgroupPermissions: permissions,
  596. })
  597. }
  598. ulimits := toUlimits(s.Ulimits)
  599. resources.Ulimits = ulimits
  600. return resources
  601. }
  602. func toUlimits(m map[string]*types.UlimitsConfig) []*units.Ulimit {
  603. var ulimits []*units.Ulimit
  604. for name, u := range m {
  605. soft := u.Single
  606. if u.Soft != 0 {
  607. soft = u.Soft
  608. }
  609. hard := u.Single
  610. if u.Hard != 0 {
  611. hard = u.Hard
  612. }
  613. ulimits = append(ulimits, &units.Ulimit{
  614. Name: name,
  615. Hard: int64(hard),
  616. Soft: int64(soft),
  617. })
  618. }
  619. return ulimits
  620. }
  621. func setReservations(reservations *types.Resource, resources *container.Resources) {
  622. if reservations == nil {
  623. return
  624. }
  625. // Cpu reservation is a swarm option and PIDs is only a limit
  626. // So we only need to map memory reservation and devices
  627. if reservations.MemoryBytes != 0 {
  628. resources.MemoryReservation = int64(reservations.MemoryBytes)
  629. }
  630. for _, device := range reservations.Devices {
  631. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  632. Capabilities: [][]string{device.Capabilities},
  633. Count: int(device.Count),
  634. DeviceIDs: device.IDs,
  635. Driver: device.Driver,
  636. })
  637. }
  638. }
  639. func setLimits(limits *types.Resource, resources *container.Resources) {
  640. if limits == nil {
  641. return
  642. }
  643. if limits.MemoryBytes != 0 {
  644. resources.Memory = int64(limits.MemoryBytes)
  645. }
  646. if limits.NanoCPUs != "" {
  647. if f, err := strconv.ParseFloat(limits.NanoCPUs, 64); err == nil {
  648. resources.NanoCPUs = int64(f * 1e9)
  649. }
  650. }
  651. if limits.Pids > 0 {
  652. resources.PidsLimit = &limits.Pids
  653. }
  654. }
  655. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  656. if blkio == nil {
  657. return
  658. }
  659. resources.BlkioWeight = blkio.Weight
  660. for _, b := range blkio.WeightDevice {
  661. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  662. Path: b.Path,
  663. Weight: b.Weight,
  664. })
  665. }
  666. for _, b := range blkio.DeviceReadBps {
  667. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  668. Path: b.Path,
  669. Rate: uint64(b.Rate),
  670. })
  671. }
  672. for _, b := range blkio.DeviceReadIOps {
  673. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  674. Path: b.Path,
  675. Rate: uint64(b.Rate),
  676. })
  677. }
  678. for _, b := range blkio.DeviceWriteBps {
  679. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  680. Path: b.Path,
  681. Rate: uint64(b.Rate),
  682. })
  683. }
  684. for _, b := range blkio.DeviceWriteIOps {
  685. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  686. Path: b.Path,
  687. Rate: uint64(b.Rate),
  688. })
  689. }
  690. }
  691. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  692. ports := nat.PortSet{}
  693. for _, s := range s.Expose {
  694. p := nat.Port(s)
  695. ports[p] = struct{}{}
  696. }
  697. for _, p := range s.Ports {
  698. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  699. ports[p] = struct{}{}
  700. }
  701. return ports
  702. }
  703. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  704. bindings := nat.PortMap{}
  705. for _, port := range s.Ports {
  706. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  707. binding := nat.PortBinding{
  708. HostIP: port.HostIP,
  709. HostPort: port.Published,
  710. }
  711. bindings[p] = append(bindings[p], binding)
  712. }
  713. return bindings
  714. }
  715. func getDependentServiceFromMode(mode string) string {
  716. if strings.HasPrefix(
  717. mode,
  718. types.NetworkModeServicePrefix,
  719. ) {
  720. return mode[len(types.NetworkModeServicePrefix):]
  721. }
  722. return ""
  723. }
  724. func (s *composeService) buildContainerVolumes(
  725. ctx context.Context,
  726. p types.Project,
  727. service types.ServiceConfig,
  728. inherit *moby.Container,
  729. ) ([]string, []mount.Mount, error) {
  730. var mounts []mount.Mount
  731. var binds []string
  732. image := api.GetImageNameOrDefault(service, p.Name)
  733. imgInspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, image)
  734. if err != nil {
  735. return nil, nil, err
  736. }
  737. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  738. if err != nil {
  739. return nil, nil, err
  740. }
  741. MOUNTS:
  742. for _, m := range mountOptions {
  743. if m.Type == mount.TypeNamedPipe {
  744. mounts = append(mounts, m)
  745. continue
  746. }
  747. if m.Type == mount.TypeBind {
  748. // `Mount` is preferred but does not offer option to created host path if missing
  749. // so `Bind` API is used here with raw volume string
  750. // see https://github.com/moby/moby/issues/43483
  751. for _, v := range service.Volumes {
  752. if v.Target == m.Target {
  753. switch {
  754. case string(m.Type) != v.Type:
  755. v.Source = m.Source
  756. fallthrough
  757. case v.Bind != nil && v.Bind.CreateHostPath:
  758. binds = append(binds, v.String())
  759. continue MOUNTS
  760. }
  761. }
  762. }
  763. }
  764. mounts = append(mounts, m)
  765. }
  766. return binds, mounts, nil
  767. }
  768. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  769. var mounts = map[string]mount.Mount{}
  770. if inherit != nil {
  771. for _, m := range inherit.Mounts {
  772. if m.Type == "tmpfs" {
  773. continue
  774. }
  775. src := m.Source
  776. if m.Type == "volume" {
  777. src = m.Name
  778. }
  779. m.Destination = path.Clean(m.Destination)
  780. if img.Config != nil {
  781. if _, ok := img.Config.Volumes[m.Destination]; ok {
  782. // inherit previous container's anonymous volume
  783. mounts[m.Destination] = mount.Mount{
  784. Type: m.Type,
  785. Source: src,
  786. Target: m.Destination,
  787. ReadOnly: !m.RW,
  788. }
  789. }
  790. }
  791. volumes := []types.ServiceVolumeConfig{}
  792. for _, v := range s.Volumes {
  793. if v.Target != m.Destination || v.Source != "" {
  794. volumes = append(volumes, v)
  795. continue
  796. }
  797. // inherit previous container's anonymous volume
  798. mounts[m.Destination] = mount.Mount{
  799. Type: m.Type,
  800. Source: src,
  801. Target: m.Destination,
  802. ReadOnly: !m.RW,
  803. }
  804. }
  805. s.Volumes = volumes
  806. }
  807. }
  808. mounts, err := fillBindMounts(p, s, mounts)
  809. if err != nil {
  810. return nil, err
  811. }
  812. values := make([]mount.Mount, 0, len(mounts))
  813. for _, v := range mounts {
  814. values = append(values, v)
  815. }
  816. return values, nil
  817. }
  818. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  819. for _, v := range s.Volumes {
  820. bindMount, err := buildMount(p, v)
  821. if err != nil {
  822. return nil, err
  823. }
  824. m[bindMount.Target] = bindMount
  825. }
  826. secrets, err := buildContainerSecretMounts(p, s)
  827. if err != nil {
  828. return nil, err
  829. }
  830. for _, s := range secrets {
  831. if _, found := m[s.Target]; found {
  832. continue
  833. }
  834. m[s.Target] = s
  835. }
  836. configs, err := buildContainerConfigMounts(p, s)
  837. if err != nil {
  838. return nil, err
  839. }
  840. for _, c := range configs {
  841. if _, found := m[c.Target]; found {
  842. continue
  843. }
  844. m[c.Target] = c
  845. }
  846. return m, nil
  847. }
  848. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  849. var mounts = map[string]mount.Mount{}
  850. configsBaseDir := "/"
  851. for _, config := range s.Configs {
  852. target := config.Target
  853. if config.Target == "" {
  854. target = configsBaseDir + config.Source
  855. } else if !isAbsTarget(config.Target) {
  856. target = configsBaseDir + config.Target
  857. }
  858. if config.UID != "" || config.GID != "" || config.Mode != nil {
  859. logrus.Warn("config `uid`, `gid` and `mode` are not supported, they will be ignored")
  860. }
  861. definedConfig := p.Configs[config.Source]
  862. if definedConfig.External {
  863. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  864. }
  865. if definedConfig.Driver != "" {
  866. return nil, errors.New("Docker Compose does not support configs.*.driver")
  867. }
  868. if definedConfig.TemplateDriver != "" {
  869. return nil, errors.New("Docker Compose does not support configs.*.template_driver")
  870. }
  871. if definedConfig.Environment != "" || definedConfig.Content != "" {
  872. continue
  873. }
  874. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  875. Type: types.VolumeTypeBind,
  876. Source: definedConfig.File,
  877. Target: target,
  878. ReadOnly: true,
  879. })
  880. if err != nil {
  881. return nil, err
  882. }
  883. mounts[target] = bindMount
  884. }
  885. values := make([]mount.Mount, 0, len(mounts))
  886. for _, v := range mounts {
  887. values = append(values, v)
  888. }
  889. return values, nil
  890. }
  891. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  892. var mounts = map[string]mount.Mount{}
  893. secretsDir := "/run/secrets/"
  894. for _, secret := range s.Secrets {
  895. target := secret.Target
  896. if secret.Target == "" {
  897. target = secretsDir + secret.Source
  898. } else if !isAbsTarget(secret.Target) {
  899. target = secretsDir + secret.Target
  900. }
  901. if secret.UID != "" || secret.GID != "" || secret.Mode != nil {
  902. logrus.Warn("secrets `uid`, `gid` and `mode` are not supported, they will be ignored")
  903. }
  904. definedSecret := p.Secrets[secret.Source]
  905. if definedSecret.External {
  906. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  907. }
  908. if definedSecret.Driver != "" {
  909. return nil, errors.New("Docker Compose does not support secrets.*.driver")
  910. }
  911. if definedSecret.TemplateDriver != "" {
  912. return nil, errors.New("Docker Compose does not support secrets.*.template_driver")
  913. }
  914. if definedSecret.Environment != "" {
  915. continue
  916. }
  917. mnt, err := buildMount(p, types.ServiceVolumeConfig{
  918. Type: types.VolumeTypeBind,
  919. Source: definedSecret.File,
  920. Target: target,
  921. ReadOnly: true,
  922. })
  923. if err != nil {
  924. return nil, err
  925. }
  926. mounts[target] = mnt
  927. }
  928. values := make([]mount.Mount, 0, len(mounts))
  929. for _, v := range mounts {
  930. values = append(values, v)
  931. }
  932. return values, nil
  933. }
  934. func isAbsTarget(p string) bool {
  935. return isUnixAbs(p) || isWindowsAbs(p)
  936. }
  937. func isUnixAbs(p string) bool {
  938. return strings.HasPrefix(p, "/")
  939. }
  940. func isWindowsAbs(p string) bool {
  941. if strings.HasPrefix(p, "\\\\") {
  942. return true
  943. }
  944. if len(p) > 2 && p[1] == ':' {
  945. return p[2] == '\\'
  946. }
  947. return false
  948. }
  949. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  950. source := volume.Source
  951. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  952. // do not replace these with filepath.Abs(source) that will include a default drive.
  953. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  954. // volume source has already been prefixed with workdir if required, by compose-go project loader
  955. var err error
  956. source, err = filepath.Abs(source)
  957. if err != nil {
  958. return mount.Mount{}, err
  959. }
  960. }
  961. if volume.Type == types.VolumeTypeVolume {
  962. if volume.Source != "" {
  963. pVolume, ok := project.Volumes[volume.Source]
  964. if ok {
  965. source = pVolume.Name
  966. }
  967. }
  968. }
  969. bind, vol, tmpfs := buildMountOptions(project, volume)
  970. volume.Target = path.Clean(volume.Target)
  971. if bind != nil {
  972. volume.Type = types.VolumeTypeBind
  973. }
  974. return mount.Mount{
  975. Type: mount.Type(volume.Type),
  976. Source: source,
  977. Target: volume.Target,
  978. ReadOnly: volume.ReadOnly,
  979. Consistency: mount.Consistency(volume.Consistency),
  980. BindOptions: bind,
  981. VolumeOptions: vol,
  982. TmpfsOptions: tmpfs,
  983. }, nil
  984. }
  985. func buildMountOptions(project types.Project, volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  986. switch volume.Type {
  987. case "bind":
  988. if volume.Volume != nil {
  989. logrus.Warnf("mount of type `bind` should not define `volume` option")
  990. }
  991. if volume.Tmpfs != nil {
  992. logrus.Warnf("mount of type `bind` should not define `tmpfs` option")
  993. }
  994. return buildBindOption(volume.Bind), nil, nil
  995. case "volume":
  996. if volume.Bind != nil {
  997. logrus.Warnf("mount of type `volume` should not define `bind` option")
  998. }
  999. if volume.Tmpfs != nil {
  1000. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  1001. }
  1002. if v, ok := project.Volumes[volume.Source]; ok && v.DriverOpts["o"] == types.VolumeTypeBind {
  1003. return buildBindOption(&types.ServiceVolumeBind{
  1004. CreateHostPath: true,
  1005. }), nil, nil
  1006. }
  1007. return nil, buildVolumeOptions(volume.Volume), nil
  1008. case "tmpfs":
  1009. if volume.Bind != nil {
  1010. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  1011. }
  1012. if volume.Volume != nil {
  1013. logrus.Warnf("mount of type `tmpfs` should not define `volume` option")
  1014. }
  1015. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  1016. }
  1017. return nil, nil, nil
  1018. }
  1019. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  1020. if bind == nil {
  1021. return nil
  1022. }
  1023. return &mount.BindOptions{
  1024. Propagation: mount.Propagation(bind.Propagation),
  1025. // NonRecursive: false, FIXME missing from model ?
  1026. }
  1027. }
  1028. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  1029. if vol == nil {
  1030. return nil
  1031. }
  1032. return &mount.VolumeOptions{
  1033. NoCopy: vol.NoCopy,
  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. }