create.go 31 KB

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