create.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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/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, fmt.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, fmt.Errorf("opening seccomp profile (%s) failed: %w", con[1], err)
  319. }
  320. b := bytes.NewBuffer(nil)
  321. if err := json.Compact(b, f); err != nil {
  322. return securityOpts, false, fmt.Errorf("compacting json for seccomp profile (%s) failed: %w", 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. ulimits := toUlimits(s.Ulimits)
  474. resources.Ulimits = ulimits
  475. return resources
  476. }
  477. func toUlimits(m map[string]*types.UlimitsConfig) []*units.Ulimit {
  478. var ulimits []*units.Ulimit
  479. for name, u := range m {
  480. soft := u.Single
  481. if u.Soft != 0 {
  482. soft = u.Soft
  483. }
  484. hard := u.Single
  485. if u.Hard != 0 {
  486. hard = u.Hard
  487. }
  488. ulimits = append(ulimits, &units.Ulimit{
  489. Name: name,
  490. Hard: int64(hard),
  491. Soft: int64(soft),
  492. })
  493. }
  494. return ulimits
  495. }
  496. func setReservations(reservations *types.Resource, resources *container.Resources) {
  497. if reservations == nil {
  498. return
  499. }
  500. // Cpu reservation is a swarm option and PIDs is only a limit
  501. // So we only need to map memory reservation and devices
  502. if reservations.MemoryBytes != 0 {
  503. resources.MemoryReservation = int64(reservations.MemoryBytes)
  504. }
  505. for _, device := range reservations.Devices {
  506. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  507. Capabilities: [][]string{device.Capabilities},
  508. Count: int(device.Count),
  509. DeviceIDs: device.IDs,
  510. Driver: device.Driver,
  511. })
  512. }
  513. }
  514. func setLimits(limits *types.Resource, resources *container.Resources) {
  515. if limits == nil {
  516. return
  517. }
  518. if limits.MemoryBytes != 0 {
  519. resources.Memory = int64(limits.MemoryBytes)
  520. }
  521. if limits.NanoCPUs != "" {
  522. if f, err := strconv.ParseFloat(limits.NanoCPUs, 64); err == nil {
  523. resources.NanoCPUs = int64(f * 1e9)
  524. }
  525. }
  526. if limits.Pids > 0 {
  527. resources.PidsLimit = &limits.Pids
  528. }
  529. }
  530. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  531. if blkio == nil {
  532. return
  533. }
  534. resources.BlkioWeight = blkio.Weight
  535. for _, b := range blkio.WeightDevice {
  536. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  537. Path: b.Path,
  538. Weight: b.Weight,
  539. })
  540. }
  541. for _, b := range blkio.DeviceReadBps {
  542. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  543. Path: b.Path,
  544. Rate: uint64(b.Rate),
  545. })
  546. }
  547. for _, b := range blkio.DeviceReadIOps {
  548. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  549. Path: b.Path,
  550. Rate: uint64(b.Rate),
  551. })
  552. }
  553. for _, b := range blkio.DeviceWriteBps {
  554. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  555. Path: b.Path,
  556. Rate: uint64(b.Rate),
  557. })
  558. }
  559. for _, b := range blkio.DeviceWriteIOps {
  560. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  561. Path: b.Path,
  562. Rate: uint64(b.Rate),
  563. })
  564. }
  565. }
  566. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  567. ports := nat.PortSet{}
  568. for _, s := range s.Expose {
  569. p := nat.Port(s)
  570. ports[p] = struct{}{}
  571. }
  572. for _, p := range s.Ports {
  573. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  574. ports[p] = struct{}{}
  575. }
  576. return ports
  577. }
  578. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  579. bindings := nat.PortMap{}
  580. for _, port := range s.Ports {
  581. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  582. binding := nat.PortBinding{
  583. HostIP: port.HostIP,
  584. HostPort: port.Published,
  585. }
  586. bindings[p] = append(bindings[p], binding)
  587. }
  588. return bindings
  589. }
  590. func getDependentServiceFromMode(mode string) string {
  591. if strings.HasPrefix(
  592. mode,
  593. types.NetworkModeServicePrefix,
  594. ) {
  595. return mode[len(types.NetworkModeServicePrefix):]
  596. }
  597. return ""
  598. }
  599. func (s *composeService) buildContainerVolumes(
  600. ctx context.Context,
  601. p types.Project,
  602. service types.ServiceConfig,
  603. inherit *moby.Container,
  604. ) ([]string, []mount.Mount, error) {
  605. var mounts []mount.Mount
  606. var binds []string
  607. image := api.GetImageNameOrDefault(service, p.Name)
  608. imgInspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, image)
  609. if err != nil {
  610. return nil, nil, err
  611. }
  612. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  613. if err != nil {
  614. return nil, nil, err
  615. }
  616. MOUNTS:
  617. for _, m := range mountOptions {
  618. if m.Type == mount.TypeNamedPipe {
  619. mounts = append(mounts, m)
  620. continue
  621. }
  622. if m.Type == mount.TypeBind {
  623. // `Mount` is preferred but does not offer option to created host path if missing
  624. // so `Bind` API is used here with raw volume string
  625. // see https://github.com/moby/moby/issues/43483
  626. for _, v := range service.Volumes {
  627. if v.Target == m.Target {
  628. switch {
  629. case string(m.Type) != v.Type:
  630. v.Source = m.Source
  631. fallthrough
  632. case v.Bind != nil && v.Bind.CreateHostPath:
  633. binds = append(binds, v.String())
  634. continue MOUNTS
  635. }
  636. }
  637. }
  638. }
  639. mounts = append(mounts, m)
  640. }
  641. return binds, mounts, nil
  642. }
  643. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  644. var mounts = map[string]mount.Mount{}
  645. if inherit != nil {
  646. for _, m := range inherit.Mounts {
  647. if m.Type == "tmpfs" {
  648. continue
  649. }
  650. src := m.Source
  651. if m.Type == "volume" {
  652. src = m.Name
  653. }
  654. m.Destination = path.Clean(m.Destination)
  655. if img.Config != nil {
  656. if _, ok := img.Config.Volumes[m.Destination]; ok {
  657. // inherit previous container's anonymous volume
  658. mounts[m.Destination] = mount.Mount{
  659. Type: m.Type,
  660. Source: src,
  661. Target: m.Destination,
  662. ReadOnly: !m.RW,
  663. }
  664. }
  665. }
  666. volumes := []types.ServiceVolumeConfig{}
  667. for _, v := range s.Volumes {
  668. if v.Target != m.Destination || v.Source != "" {
  669. volumes = append(volumes, v)
  670. continue
  671. }
  672. // inherit previous container's anonymous volume
  673. mounts[m.Destination] = mount.Mount{
  674. Type: m.Type,
  675. Source: src,
  676. Target: m.Destination,
  677. ReadOnly: !m.RW,
  678. }
  679. }
  680. s.Volumes = volumes
  681. }
  682. }
  683. mounts, err := fillBindMounts(p, s, mounts)
  684. if err != nil {
  685. return nil, err
  686. }
  687. values := make([]mount.Mount, 0, len(mounts))
  688. for _, v := range mounts {
  689. values = append(values, v)
  690. }
  691. return values, nil
  692. }
  693. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  694. for _, v := range s.Volumes {
  695. bindMount, err := buildMount(p, v)
  696. if err != nil {
  697. return nil, err
  698. }
  699. m[bindMount.Target] = bindMount
  700. }
  701. secrets, err := buildContainerSecretMounts(p, s)
  702. if err != nil {
  703. return nil, err
  704. }
  705. for _, s := range secrets {
  706. if _, found := m[s.Target]; found {
  707. continue
  708. }
  709. m[s.Target] = s
  710. }
  711. configs, err := buildContainerConfigMounts(p, s)
  712. if err != nil {
  713. return nil, err
  714. }
  715. for _, c := range configs {
  716. if _, found := m[c.Target]; found {
  717. continue
  718. }
  719. m[c.Target] = c
  720. }
  721. return m, nil
  722. }
  723. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  724. var mounts = map[string]mount.Mount{}
  725. configsBaseDir := "/"
  726. for _, config := range s.Configs {
  727. target := config.Target
  728. if config.Target == "" {
  729. target = configsBaseDir + config.Source
  730. } else if !isAbsTarget(config.Target) {
  731. target = configsBaseDir + config.Target
  732. }
  733. if config.UID != "" || config.GID != "" || config.Mode != nil {
  734. logrus.Warn("config `uid`, `gid` and `mode` are not supported, they will be ignored")
  735. }
  736. definedConfig := p.Configs[config.Source]
  737. if definedConfig.External.External {
  738. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  739. }
  740. if definedConfig.Driver != "" {
  741. return nil, errors.New("Docker Compose does not support configs.*.driver")
  742. }
  743. if definedConfig.TemplateDriver != "" {
  744. return nil, errors.New("Docker Compose does not support configs.*.template_driver")
  745. }
  746. if definedConfig.Environment != "" || definedConfig.Content != "" {
  747. continue
  748. }
  749. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  750. Type: types.VolumeTypeBind,
  751. Source: definedConfig.File,
  752. Target: target,
  753. ReadOnly: true,
  754. })
  755. if err != nil {
  756. return nil, err
  757. }
  758. mounts[target] = bindMount
  759. }
  760. values := make([]mount.Mount, 0, len(mounts))
  761. for _, v := range mounts {
  762. values = append(values, v)
  763. }
  764. return values, nil
  765. }
  766. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  767. var mounts = map[string]mount.Mount{}
  768. secretsDir := "/run/secrets/"
  769. for _, secret := range s.Secrets {
  770. target := secret.Target
  771. if secret.Target == "" {
  772. target = secretsDir + secret.Source
  773. } else if !isAbsTarget(secret.Target) {
  774. target = secretsDir + secret.Target
  775. }
  776. if secret.UID != "" || secret.GID != "" || secret.Mode != nil {
  777. logrus.Warn("secrets `uid`, `gid` and `mode` are not supported, they will be ignored")
  778. }
  779. definedSecret := p.Secrets[secret.Source]
  780. if definedSecret.External.External {
  781. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  782. }
  783. if definedSecret.Driver != "" {
  784. return nil, errors.New("Docker Compose does not support secrets.*.driver")
  785. }
  786. if definedSecret.TemplateDriver != "" {
  787. return nil, errors.New("Docker Compose does not support secrets.*.template_driver")
  788. }
  789. if definedSecret.Environment != "" {
  790. continue
  791. }
  792. mnt, err := buildMount(p, types.ServiceVolumeConfig{
  793. Type: types.VolumeTypeBind,
  794. Source: definedSecret.File,
  795. Target: target,
  796. ReadOnly: true,
  797. })
  798. if err != nil {
  799. return nil, err
  800. }
  801. mounts[target] = mnt
  802. }
  803. values := make([]mount.Mount, 0, len(mounts))
  804. for _, v := range mounts {
  805. values = append(values, v)
  806. }
  807. return values, nil
  808. }
  809. func isAbsTarget(p string) bool {
  810. return isUnixAbs(p) || isWindowsAbs(p)
  811. }
  812. func isUnixAbs(p string) bool {
  813. return strings.HasPrefix(p, "/")
  814. }
  815. func isWindowsAbs(p string) bool {
  816. if strings.HasPrefix(p, "\\\\") {
  817. return true
  818. }
  819. if len(p) > 2 && p[1] == ':' {
  820. return p[2] == '\\'
  821. }
  822. return false
  823. }
  824. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  825. source := volume.Source
  826. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  827. // do not replace these with filepath.Abs(source) that will include a default drive.
  828. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  829. // volume source has already been prefixed with workdir if required, by compose-go project loader
  830. var err error
  831. source, err = filepath.Abs(source)
  832. if err != nil {
  833. return mount.Mount{}, err
  834. }
  835. }
  836. if volume.Type == types.VolumeTypeVolume {
  837. if volume.Source != "" {
  838. pVolume, ok := project.Volumes[volume.Source]
  839. if ok {
  840. source = pVolume.Name
  841. }
  842. }
  843. }
  844. bind, vol, tmpfs := buildMountOptions(project, volume)
  845. volume.Target = path.Clean(volume.Target)
  846. if bind != nil {
  847. volume.Type = types.VolumeTypeBind
  848. }
  849. return mount.Mount{
  850. Type: mount.Type(volume.Type),
  851. Source: source,
  852. Target: volume.Target,
  853. ReadOnly: volume.ReadOnly,
  854. Consistency: mount.Consistency(volume.Consistency),
  855. BindOptions: bind,
  856. VolumeOptions: vol,
  857. TmpfsOptions: tmpfs,
  858. }, nil
  859. }
  860. func buildMountOptions(project types.Project, volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  861. switch volume.Type {
  862. case "bind":
  863. if volume.Volume != nil {
  864. logrus.Warnf("mount of type `bind` should not define `volume` option")
  865. }
  866. if volume.Tmpfs != nil {
  867. logrus.Warnf("mount of type `bind` should not define `tmpfs` option")
  868. }
  869. return buildBindOption(volume.Bind), nil, nil
  870. case "volume":
  871. if volume.Bind != nil {
  872. logrus.Warnf("mount of type `volume` should not define `bind` option")
  873. }
  874. if volume.Tmpfs != nil {
  875. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  876. }
  877. if v, ok := project.Volumes[volume.Source]; ok && v.DriverOpts["o"] == types.VolumeTypeBind {
  878. return buildBindOption(&types.ServiceVolumeBind{
  879. CreateHostPath: true,
  880. }), nil, nil
  881. }
  882. return nil, buildVolumeOptions(volume.Volume), nil
  883. case "tmpfs":
  884. if volume.Bind != nil {
  885. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  886. }
  887. if volume.Volume != nil {
  888. logrus.Warnf("mount of type `tmpfs` should not define `volume` option")
  889. }
  890. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  891. }
  892. return nil, nil, nil
  893. }
  894. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  895. if bind == nil {
  896. return nil
  897. }
  898. return &mount.BindOptions{
  899. Propagation: mount.Propagation(bind.Propagation),
  900. // NonRecursive: false, FIXME missing from model ?
  901. }
  902. }
  903. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  904. if vol == nil {
  905. return nil
  906. }
  907. return &mount.VolumeOptions{
  908. NoCopy: vol.NoCopy,
  909. // Labels: , // FIXME missing from model ?
  910. // DriverConfig: , // FIXME missing from model ?
  911. }
  912. }
  913. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  914. if tmpfs == nil {
  915. return nil
  916. }
  917. return &mount.TmpfsOptions{
  918. SizeBytes: int64(tmpfs.Size),
  919. Mode: os.FileMode(tmpfs.Mode),
  920. }
  921. }
  922. func (s *composeService) ensureNetwork(ctx context.Context, n *types.NetworkConfig) error {
  923. if n.External.External {
  924. return s.resolveExternalNetwork(ctx, n)
  925. }
  926. err := s.resolveOrCreateNetwork(ctx, n)
  927. if errdefs.IsConflict(err) {
  928. // Maybe another execution of `docker compose up|run` created same network
  929. // let's retry once
  930. return s.resolveOrCreateNetwork(ctx, n)
  931. }
  932. return err
  933. }
  934. func (s *composeService) resolveOrCreateNetwork(ctx context.Context, n *types.NetworkConfig) error { //nolint:gocyclo
  935. expectedNetworkLabel := n.Labels[api.NetworkLabel]
  936. expectedProjectLabel := n.Labels[api.ProjectLabel]
  937. // First, try to find a unique network matching by name or ID
  938. inspect, err := s.apiClient().NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  939. if err == nil {
  940. // NetworkInspect will match on ID prefix, so double check we get the expected one
  941. // as looking for network named `db` we could erroneously matched network ID `db9086999caf`
  942. if inspect.Name == n.Name || inspect.ID == n.Name {
  943. p, ok := inspect.Labels[api.ProjectLabel]
  944. if !ok {
  945. logrus.Warnf("a network with name %s exists but was not created by compose.\n"+
  946. "Set `external: true` to use an existing network", n.Name)
  947. } else if p != expectedProjectLabel {
  948. logrus.Warnf("a network with name %s exists but was not created for project %q.\n"+
  949. "Set `external: true` to use an existing network", n.Name, expectedProjectLabel)
  950. }
  951. if inspect.Labels[api.NetworkLabel] != expectedNetworkLabel {
  952. return fmt.Errorf("network %s was found but has incorrect label %s set to %q", n.Name, api.NetworkLabel, inspect.Labels[api.NetworkLabel])
  953. }
  954. return nil
  955. }
  956. }
  957. // ignore other errors. Typically, an ambiguous request by name results in some generic `invalidParameter` error
  958. // Either not found, or name is ambiguous - use NetworkList to list by name
  959. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  960. Filters: filters.NewArgs(filters.Arg("name", n.Name)),
  961. })
  962. if err != nil {
  963. return err
  964. }
  965. // NetworkList Matches all or part of a network name, so we have to filter for a strict match
  966. networks = utils.Filter(networks, func(net moby.NetworkResource) bool {
  967. return net.Name == n.Name
  968. })
  969. for _, net := range networks {
  970. if net.Labels[api.ProjectLabel] == expectedProjectLabel &&
  971. net.Labels[api.NetworkLabel] == expectedNetworkLabel {
  972. return nil
  973. }
  974. }
  975. // we could have set NetworkList with a projectFilter and networkFilter but not doing so allows to catch this
  976. // scenario were a network with same name exists but doesn't have label, and use of `CheckDuplicate: true`
  977. // prevents to create another one.
  978. if len(networks) > 0 {
  979. logrus.Warnf("a network with name %s exists but was not created by compose.\n"+
  980. "Set `external: true` to use an existing network", n.Name)
  981. return nil
  982. }
  983. var ipam *network.IPAM
  984. if n.Ipam.Config != nil {
  985. var config []network.IPAMConfig
  986. for _, pool := range n.Ipam.Config {
  987. config = append(config, network.IPAMConfig{
  988. Subnet: pool.Subnet,
  989. IPRange: pool.IPRange,
  990. Gateway: pool.Gateway,
  991. AuxAddress: pool.AuxiliaryAddresses,
  992. })
  993. }
  994. ipam = &network.IPAM{
  995. Driver: n.Ipam.Driver,
  996. Config: config,
  997. }
  998. }
  999. createOpts := moby.NetworkCreate{
  1000. CheckDuplicate: true,
  1001. Labels: n.Labels,
  1002. Driver: n.Driver,
  1003. Options: n.DriverOpts,
  1004. Internal: n.Internal,
  1005. Attachable: n.Attachable,
  1006. IPAM: ipam,
  1007. EnableIPv6: n.EnableIPv6,
  1008. }
  1009. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  1010. createOpts.IPAM = &network.IPAM{}
  1011. }
  1012. if n.Ipam.Driver != "" {
  1013. createOpts.IPAM.Driver = n.Ipam.Driver
  1014. }
  1015. for _, ipamConfig := range n.Ipam.Config {
  1016. config := network.IPAMConfig{
  1017. Subnet: ipamConfig.Subnet,
  1018. IPRange: ipamConfig.IPRange,
  1019. Gateway: ipamConfig.Gateway,
  1020. AuxAddress: ipamConfig.AuxiliaryAddresses,
  1021. }
  1022. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  1023. }
  1024. networkEventName := fmt.Sprintf("Network %s", n.Name)
  1025. w := progress.ContextWriter(ctx)
  1026. w.Event(progress.CreatingEvent(networkEventName))
  1027. _, err = s.apiClient().NetworkCreate(ctx, n.Name, createOpts)
  1028. if err != nil {
  1029. w.Event(progress.ErrorEvent(networkEventName))
  1030. return fmt.Errorf("failed to create network %s: %w", n.Name, err)
  1031. }
  1032. w.Event(progress.CreatedEvent(networkEventName))
  1033. return nil
  1034. }
  1035. func (s *composeService) resolveExternalNetwork(ctx context.Context, n *types.NetworkConfig) error {
  1036. // NetworkInspect will match on ID prefix, so NetworkList with a name
  1037. // filter is used to look for an exact match to prevent e.g. a network
  1038. // named `db` from getting erroneously matched to a network with an ID
  1039. // like `db9086999caf`
  1040. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  1041. Filters: filters.NewArgs(filters.Arg("name", n.Name)),
  1042. })
  1043. if err != nil {
  1044. return err
  1045. }
  1046. if len(networks) == 0 {
  1047. // in this instance, n.Name is really an ID
  1048. sn, err := s.apiClient().NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  1049. if err != nil {
  1050. return err
  1051. }
  1052. networks = append(networks, sn)
  1053. }
  1054. // NetworkList API doesn't return the exact name match, so we can retrieve more than one network with a request
  1055. networks = utils.Filter(networks, func(net moby.NetworkResource) bool {
  1056. // later in this function, the name is changed the to ID.
  1057. // this function is called during the rebuild stage of `compose watch`.
  1058. // we still require just one network back, but we need to run the search on the ID
  1059. return net.Name == n.Name || net.ID == n.Name
  1060. })
  1061. switch len(networks) {
  1062. case 1:
  1063. n.Name = networks[0].ID
  1064. return nil
  1065. case 0:
  1066. if n.Driver == "overlay" {
  1067. // Swarm nodes do not register overlay networks that were
  1068. // created on a different node unless they're in use.
  1069. // Here we assume `driver` is relevant for a network we don't manage
  1070. // which is a non-sense, but this is our legacy ¯\(ツ)/¯
  1071. // networkAttach will later fail anyway if network actually doesn't exists
  1072. enabled, err := s.isSWarmEnabled(ctx)
  1073. if err != nil {
  1074. return err
  1075. }
  1076. if enabled {
  1077. return nil
  1078. }
  1079. }
  1080. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  1081. default:
  1082. return fmt.Errorf("multiple networks with name %q were found. Use network ID as `name` to avoid ambiguity", n.Name)
  1083. }
  1084. }
  1085. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig, project string) error {
  1086. inspected, err := s.apiClient().VolumeInspect(ctx, volume.Name)
  1087. if err != nil {
  1088. if !errdefs.IsNotFound(err) {
  1089. return err
  1090. }
  1091. if volume.External.External {
  1092. return fmt.Errorf("external volume %q not found", volume.Name)
  1093. }
  1094. err := s.createVolume(ctx, volume)
  1095. return err
  1096. }
  1097. if volume.External.External {
  1098. return nil
  1099. }
  1100. // Volume exists with name, but let's double-check this is the expected one
  1101. p, ok := inspected.Labels[api.ProjectLabel]
  1102. if !ok {
  1103. logrus.Warnf("volume %q already exists but was not created by Docker Compose. Use `external: true` to use an existing volume", volume.Name)
  1104. }
  1105. if ok && p != project {
  1106. 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)
  1107. }
  1108. return nil
  1109. }
  1110. func (s *composeService) createVolume(ctx context.Context, volume types.VolumeConfig) error {
  1111. eventName := fmt.Sprintf("Volume %q", volume.Name)
  1112. w := progress.ContextWriter(ctx)
  1113. w.Event(progress.CreatingEvent(eventName))
  1114. _, err := s.apiClient().VolumeCreate(ctx, volume_api.CreateOptions{
  1115. Labels: volume.Labels,
  1116. Name: volume.Name,
  1117. Driver: volume.Driver,
  1118. DriverOpts: volume.DriverOpts,
  1119. })
  1120. if err != nil {
  1121. w.Event(progress.ErrorEvent(eventName))
  1122. return err
  1123. }
  1124. w.Event(progress.CreatedEvent(eventName))
  1125. return nil
  1126. }