create.go 50 KB

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