create.go 34 KB

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