create.go 41 KB

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