create.go 44 KB

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