create.go 32 KB

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