create.go 35 KB

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