create.go 38 KB

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