create.go 32 KB

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