create.go 41 KB

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