create.go 46 KB

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