create.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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. 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. StopTimeout: ToSeconds(service.StopGracePeriod),
  252. }
  253. portBindings := buildContainerPortBindingOptions(service)
  254. resources := getDeployResources(service)
  255. if service.NetworkMode == "" {
  256. service.NetworkMode = getDefaultNetworkMode(p, service)
  257. }
  258. var networkConfig *network.NetworkingConfig
  259. for _, id := range service.NetworksByPriority() {
  260. net := p.Networks[id]
  261. config := service.Networks[id]
  262. var ipam *network.EndpointIPAMConfig
  263. var (
  264. ipv4Address string
  265. ipv6Address string
  266. )
  267. if config != nil {
  268. ipv4Address = config.Ipv4Address
  269. ipv6Address = config.Ipv6Address
  270. ipam = &network.EndpointIPAMConfig{
  271. IPv4Address: ipv4Address,
  272. IPv6Address: ipv6Address,
  273. LinkLocalIPs: config.LinkLocalIPs,
  274. }
  275. }
  276. networkConfig = &network.NetworkingConfig{
  277. EndpointsConfig: map[string]*network.EndpointSettings{
  278. net.Name: {
  279. Aliases: getAliases(service, config),
  280. IPAddress: ipv4Address,
  281. IPv6Gateway: ipv6Address,
  282. IPAMConfig: ipam,
  283. },
  284. },
  285. }
  286. break //nolint:staticcheck
  287. }
  288. tmpfs := map[string]string{}
  289. for _, t := range service.Tmpfs {
  290. if arr := strings.SplitN(t, ":", 2); len(arr) > 1 {
  291. tmpfs[arr[0]] = arr[1]
  292. } else {
  293. tmpfs[arr[0]] = ""
  294. }
  295. }
  296. var logConfig container.LogConfig
  297. if service.Logging != nil {
  298. logConfig = container.LogConfig{
  299. Type: service.Logging.Driver,
  300. Config: service.Logging.Options,
  301. }
  302. }
  303. var volumesFrom []string
  304. for _, v := range service.VolumesFrom {
  305. if !strings.HasPrefix(v, "container:") {
  306. return nil, nil, nil, fmt.Errorf("invalid volume_from: %s", v)
  307. }
  308. volumesFrom = append(volumesFrom, v[len("container:"):])
  309. }
  310. links, err := s.getLinks(ctx, p.Name, service, number)
  311. if err != nil {
  312. return nil, nil, nil, err
  313. }
  314. securityOpts, err := parseSecurityOpts(p, service.SecurityOpt)
  315. if err != nil {
  316. return nil, nil, nil, err
  317. }
  318. hostConfig := container.HostConfig{
  319. AutoRemove: autoRemove,
  320. Binds: binds,
  321. Mounts: mounts,
  322. CapAdd: strslice.StrSlice(service.CapAdd),
  323. CapDrop: strslice.StrSlice(service.CapDrop),
  324. NetworkMode: container.NetworkMode(service.NetworkMode),
  325. Init: service.Init,
  326. IpcMode: container.IpcMode(service.Ipc),
  327. CgroupnsMode: container.CgroupnsMode(service.Cgroup),
  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. NanoCPUs: int64(s.CPUS * 1e9),
  470. CPUPercent: int64(s.CPUPercent * 100),
  471. CpusetCpus: s.CPUSet,
  472. DeviceCgroupRules: s.DeviceCgroupRules,
  473. }
  474. if s.PidsLimit != 0 {
  475. resources.PidsLimit = &s.PidsLimit
  476. }
  477. setBlkio(s.BlkioConfig, &resources)
  478. if s.Deploy != nil {
  479. setLimits(s.Deploy.Resources.Limits, &resources)
  480. setReservations(s.Deploy.Resources.Reservations, &resources)
  481. }
  482. for _, device := range s.Devices {
  483. // FIXME should use docker/cli parseDevice, unfortunately private
  484. src := ""
  485. dst := ""
  486. permissions := "rwm"
  487. arr := strings.Split(device, ":")
  488. switch len(arr) {
  489. case 3:
  490. permissions = arr[2]
  491. fallthrough
  492. case 2:
  493. dst = arr[1]
  494. fallthrough
  495. case 1:
  496. src = arr[0]
  497. }
  498. if dst == "" {
  499. dst = src
  500. }
  501. resources.Devices = append(resources.Devices, container.DeviceMapping{
  502. PathOnHost: src,
  503. PathInContainer: dst,
  504. CgroupPermissions: permissions,
  505. })
  506. }
  507. for name, u := range s.Ulimits {
  508. soft := u.Single
  509. if u.Soft != 0 {
  510. soft = u.Soft
  511. }
  512. hard := u.Single
  513. if u.Hard != 0 {
  514. hard = u.Hard
  515. }
  516. resources.Ulimits = append(resources.Ulimits, &units.Ulimit{
  517. Name: name,
  518. Hard: int64(hard),
  519. Soft: int64(soft),
  520. })
  521. }
  522. return resources
  523. }
  524. func setReservations(reservations *types.Resource, resources *container.Resources) {
  525. if reservations == nil {
  526. return
  527. }
  528. // Cpu reservation is a swarm option and PIDs is only a limit
  529. // So we only need to map memory reservation and devices
  530. if reservations.MemoryBytes != 0 {
  531. resources.MemoryReservation = int64(reservations.MemoryBytes)
  532. }
  533. for _, device := range reservations.Devices {
  534. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  535. Capabilities: [][]string{device.Capabilities},
  536. Count: int(device.Count),
  537. DeviceIDs: device.IDs,
  538. Driver: device.Driver,
  539. })
  540. }
  541. }
  542. func setLimits(limits *types.Resource, resources *container.Resources) {
  543. if limits == nil {
  544. return
  545. }
  546. if limits.MemoryBytes != 0 {
  547. resources.Memory = int64(limits.MemoryBytes)
  548. }
  549. if limits.NanoCPUs != "" {
  550. if f, err := strconv.ParseFloat(limits.NanoCPUs, 64); err == nil {
  551. resources.NanoCPUs = int64(f * 1e9)
  552. }
  553. }
  554. if limits.PIds > 0 {
  555. resources.PidsLimit = &limits.PIds
  556. }
  557. }
  558. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  559. if blkio == nil {
  560. return
  561. }
  562. resources.BlkioWeight = blkio.Weight
  563. for _, b := range blkio.WeightDevice {
  564. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  565. Path: b.Path,
  566. Weight: b.Weight,
  567. })
  568. }
  569. for _, b := range blkio.DeviceReadBps {
  570. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  571. Path: b.Path,
  572. Rate: b.Rate,
  573. })
  574. }
  575. for _, b := range blkio.DeviceReadIOps {
  576. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  577. Path: b.Path,
  578. Rate: b.Rate,
  579. })
  580. }
  581. for _, b := range blkio.DeviceWriteBps {
  582. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  583. Path: b.Path,
  584. Rate: b.Rate,
  585. })
  586. }
  587. for _, b := range blkio.DeviceWriteIOps {
  588. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  589. Path: b.Path,
  590. Rate: b.Rate,
  591. })
  592. }
  593. }
  594. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  595. ports := nat.PortSet{}
  596. for _, s := range s.Expose {
  597. p := nat.Port(s)
  598. ports[p] = struct{}{}
  599. }
  600. for _, p := range s.Ports {
  601. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  602. ports[p] = struct{}{}
  603. }
  604. return ports
  605. }
  606. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  607. bindings := nat.PortMap{}
  608. for _, port := range s.Ports {
  609. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  610. binding := nat.PortBinding{
  611. HostIP: port.HostIP,
  612. HostPort: port.Published,
  613. }
  614. bindings[p] = append(bindings[p], binding)
  615. }
  616. return bindings
  617. }
  618. func getVolumesFrom(project *types.Project, volumesFrom []string) ([]string, []string, error) {
  619. var volumes = []string{}
  620. var services = []string{}
  621. // parse volumes_from
  622. if len(volumesFrom) == 0 {
  623. return volumes, services, nil
  624. }
  625. for _, vol := range volumesFrom {
  626. spec := strings.Split(vol, ":")
  627. if len(spec) == 0 {
  628. continue
  629. }
  630. if spec[0] == "container" {
  631. volumes = append(volumes, vol)
  632. continue
  633. }
  634. serviceName := spec[0]
  635. services = append(services, serviceName)
  636. service, err := project.GetService(serviceName)
  637. if err != nil {
  638. return nil, nil, err
  639. }
  640. firstContainer := getContainerName(project.Name, service, 1)
  641. v := fmt.Sprintf("container:%s", firstContainer)
  642. if len(spec) > 2 {
  643. v = fmt.Sprintf("container:%s:%s", firstContainer, strings.Join(spec[1:], ":"))
  644. }
  645. volumes = append(volumes, v)
  646. }
  647. return volumes, services, nil
  648. }
  649. func getDependentServiceFromMode(mode string) string {
  650. if strings.HasPrefix(mode, types.NetworkModeServicePrefix) {
  651. return mode[len(types.NetworkModeServicePrefix):]
  652. }
  653. return ""
  654. }
  655. func (s *composeService) buildContainerVolumes(
  656. ctx context.Context,
  657. p types.Project,
  658. service types.ServiceConfig,
  659. inherit *moby.Container,
  660. ) ([]string, []mount.Mount, error) {
  661. var mounts []mount.Mount
  662. var binds []string
  663. image := api.GetImageNameOrDefault(service, p.Name)
  664. imgInspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, image)
  665. if err != nil {
  666. return nil, nil, err
  667. }
  668. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  669. if err != nil {
  670. return nil, nil, err
  671. }
  672. MOUNTS:
  673. for _, m := range mountOptions {
  674. if m.Type == mount.TypeNamedPipe {
  675. mounts = append(mounts, m)
  676. continue
  677. }
  678. if m.Type == mount.TypeBind {
  679. // `Mount` is preferred but does not offer option to created host path if missing
  680. // so `Bind` API is used here with raw volume string
  681. // see https://github.com/moby/moby/issues/43483
  682. for _, v := range service.Volumes {
  683. if v.Target == m.Target {
  684. switch {
  685. case string(m.Type) != v.Type:
  686. v.Source = m.Source
  687. fallthrough
  688. case v.Bind != nil && v.Bind.CreateHostPath:
  689. binds = append(binds, v.String())
  690. continue MOUNTS
  691. }
  692. }
  693. }
  694. }
  695. mounts = append(mounts, m)
  696. }
  697. return binds, mounts, nil
  698. }
  699. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  700. var mounts = map[string]mount.Mount{}
  701. if inherit != nil {
  702. for _, m := range inherit.Mounts {
  703. if m.Type == "tmpfs" {
  704. continue
  705. }
  706. src := m.Source
  707. if m.Type == "volume" {
  708. src = m.Name
  709. }
  710. m.Destination = path.Clean(m.Destination)
  711. if img.Config != nil {
  712. if _, ok := img.Config.Volumes[m.Destination]; ok {
  713. // inherit previous container's anonymous volume
  714. mounts[m.Destination] = mount.Mount{
  715. Type: m.Type,
  716. Source: src,
  717. Target: m.Destination,
  718. ReadOnly: !m.RW,
  719. }
  720. }
  721. }
  722. volumes := []types.ServiceVolumeConfig{}
  723. for _, v := range s.Volumes {
  724. if v.Target != m.Destination || v.Source != "" {
  725. volumes = append(volumes, v)
  726. continue
  727. }
  728. // inherit previous container's anonymous volume
  729. mounts[m.Destination] = mount.Mount{
  730. Type: m.Type,
  731. Source: src,
  732. Target: m.Destination,
  733. ReadOnly: !m.RW,
  734. }
  735. }
  736. s.Volumes = volumes
  737. }
  738. }
  739. mounts, err := fillBindMounts(p, s, mounts)
  740. if err != nil {
  741. return nil, err
  742. }
  743. values := make([]mount.Mount, 0, len(mounts))
  744. for _, v := range mounts {
  745. values = append(values, v)
  746. }
  747. return values, nil
  748. }
  749. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  750. for _, v := range s.Volumes {
  751. bindMount, err := buildMount(p, v)
  752. if err != nil {
  753. return nil, err
  754. }
  755. m[bindMount.Target] = bindMount
  756. }
  757. secrets, err := buildContainerSecretMounts(p, s)
  758. if err != nil {
  759. return nil, err
  760. }
  761. for _, s := range secrets {
  762. if _, found := m[s.Target]; found {
  763. continue
  764. }
  765. m[s.Target] = s
  766. }
  767. configs, err := buildContainerConfigMounts(p, s)
  768. if err != nil {
  769. return nil, err
  770. }
  771. for _, c := range configs {
  772. if _, found := m[c.Target]; found {
  773. continue
  774. }
  775. m[c.Target] = c
  776. }
  777. return m, nil
  778. }
  779. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  780. var mounts = map[string]mount.Mount{}
  781. configsBaseDir := "/"
  782. for _, config := range s.Configs {
  783. target := config.Target
  784. if config.Target == "" {
  785. target = configsBaseDir + config.Source
  786. } else if !isUnixAbs(config.Target) {
  787. target = configsBaseDir + config.Target
  788. }
  789. definedConfig := p.Configs[config.Source]
  790. if definedConfig.External.External {
  791. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  792. }
  793. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  794. Type: types.VolumeTypeBind,
  795. Source: definedConfig.File,
  796. Target: target,
  797. ReadOnly: true,
  798. })
  799. if err != nil {
  800. return nil, err
  801. }
  802. mounts[target] = bindMount
  803. }
  804. values := make([]mount.Mount, 0, len(mounts))
  805. for _, v := range mounts {
  806. values = append(values, v)
  807. }
  808. return values, nil
  809. }
  810. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  811. var mounts = map[string]mount.Mount{}
  812. secretsDir := "/run/secrets/"
  813. for _, secret := range s.Secrets {
  814. target := secret.Target
  815. if secret.Target == "" {
  816. target = secretsDir + secret.Source
  817. } else if !isUnixAbs(secret.Target) {
  818. target = secretsDir + secret.Target
  819. }
  820. definedSecret := p.Secrets[secret.Source]
  821. if definedSecret.External.External {
  822. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  823. }
  824. if definedSecret.Environment != "" {
  825. continue
  826. }
  827. mnt, err := buildMount(p, types.ServiceVolumeConfig{
  828. Type: types.VolumeTypeBind,
  829. Source: definedSecret.File,
  830. Target: target,
  831. ReadOnly: true,
  832. })
  833. if err != nil {
  834. return nil, err
  835. }
  836. mounts[target] = mnt
  837. }
  838. values := make([]mount.Mount, 0, len(mounts))
  839. for _, v := range mounts {
  840. values = append(values, v)
  841. }
  842. return values, nil
  843. }
  844. func isUnixAbs(p string) bool {
  845. return strings.HasPrefix(p, "/")
  846. }
  847. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  848. source := volume.Source
  849. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  850. // do not replace these with filepath.Abs(source) that will include a default drive.
  851. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  852. // volume source has already been prefixed with workdir if required, by compose-go project loader
  853. var err error
  854. source, err = filepath.Abs(source)
  855. if err != nil {
  856. return mount.Mount{}, err
  857. }
  858. }
  859. if volume.Type == types.VolumeTypeVolume {
  860. if volume.Source != "" {
  861. pVolume, ok := project.Volumes[volume.Source]
  862. if ok {
  863. source = pVolume.Name
  864. }
  865. }
  866. }
  867. bind, vol, tmpfs := buildMountOptions(project, volume)
  868. volume.Target = path.Clean(volume.Target)
  869. if bind != nil {
  870. volume.Type = types.VolumeTypeBind
  871. }
  872. return mount.Mount{
  873. Type: mount.Type(volume.Type),
  874. Source: source,
  875. Target: volume.Target,
  876. ReadOnly: volume.ReadOnly,
  877. Consistency: mount.Consistency(volume.Consistency),
  878. BindOptions: bind,
  879. VolumeOptions: vol,
  880. TmpfsOptions: tmpfs,
  881. }, nil
  882. }
  883. func buildMountOptions(project types.Project, volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  884. switch volume.Type {
  885. case "bind":
  886. if volume.Volume != nil {
  887. logrus.Warnf("mount of type `bind` should not define `volume` option")
  888. }
  889. if volume.Tmpfs != nil {
  890. logrus.Warnf("mount of type `bind` should not define `tmpfs` option")
  891. }
  892. return buildBindOption(volume.Bind), nil, nil
  893. case "volume":
  894. if volume.Bind != nil {
  895. logrus.Warnf("mount of type `volume` should not define `bind` option")
  896. }
  897. if volume.Tmpfs != nil {
  898. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  899. }
  900. if v, ok := project.Volumes[volume.Source]; ok && v.DriverOpts["o"] == types.VolumeTypeBind {
  901. return buildBindOption(&types.ServiceVolumeBind{
  902. CreateHostPath: true,
  903. }), nil, nil
  904. }
  905. return nil, buildVolumeOptions(volume.Volume), nil
  906. case "tmpfs":
  907. if volume.Bind != nil {
  908. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  909. }
  910. if volume.Volume != nil {
  911. logrus.Warnf("mount of type `tmpfs` should not define `volume` option")
  912. }
  913. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  914. }
  915. return nil, nil, nil
  916. }
  917. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  918. if bind == nil {
  919. return nil
  920. }
  921. return &mount.BindOptions{
  922. Propagation: mount.Propagation(bind.Propagation),
  923. // NonRecursive: false, FIXME missing from model ?
  924. }
  925. }
  926. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  927. if vol == nil {
  928. return nil
  929. }
  930. return &mount.VolumeOptions{
  931. NoCopy: vol.NoCopy,
  932. // Labels: , // FIXME missing from model ?
  933. // DriverConfig: , // FIXME missing from model ?
  934. }
  935. }
  936. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  937. if tmpfs == nil {
  938. return nil
  939. }
  940. return &mount.TmpfsOptions{
  941. SizeBytes: int64(tmpfs.Size),
  942. Mode: os.FileMode(tmpfs.Mode),
  943. }
  944. }
  945. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  946. aliases := []string{s.Name}
  947. if c != nil {
  948. aliases = append(aliases, c.Aliases...)
  949. }
  950. return aliases
  951. }
  952. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  953. // NetworkInspect will match on ID prefix, so NetworkList with a name
  954. // filter is used to look for an exact match to prevent e.g. a network
  955. // named `db` from getting erroneously matched to a network with an ID
  956. // like `db9086999caf`
  957. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  958. Filters: filters.NewArgs(filters.Arg("name", n.Name)),
  959. })
  960. if err != nil {
  961. return err
  962. }
  963. networkNotFound := true
  964. for _, net := range networks {
  965. if net.Name == n.Name {
  966. networkNotFound = false
  967. break
  968. }
  969. }
  970. if networkNotFound {
  971. if n.External.External {
  972. if n.Driver == "overlay" {
  973. // Swarm nodes do not register overlay networks that were
  974. // created on a different node unless they're in use.
  975. // Here we assume `driver` is relevant for a network we don't manage
  976. // which is a non-sense, but this is our legacy ¯\(ツ)/¯
  977. // networkAttach will later fail anyway if network actually doesn't exists
  978. return nil
  979. }
  980. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  981. }
  982. var ipam *network.IPAM
  983. if n.Ipam.Config != nil {
  984. var config []network.IPAMConfig
  985. for _, pool := range n.Ipam.Config {
  986. config = append(config, network.IPAMConfig{
  987. Subnet: pool.Subnet,
  988. IPRange: pool.IPRange,
  989. Gateway: pool.Gateway,
  990. AuxAddress: pool.AuxiliaryAddresses,
  991. })
  992. }
  993. ipam = &network.IPAM{
  994. Driver: n.Ipam.Driver,
  995. Config: config,
  996. }
  997. }
  998. createOpts := moby.NetworkCreate{
  999. CheckDuplicate: true,
  1000. // TODO NameSpace Labels
  1001. Labels: n.Labels,
  1002. Driver: n.Driver,
  1003. Options: n.DriverOpts,
  1004. Internal: n.Internal,
  1005. Attachable: n.Attachable,
  1006. IPAM: ipam,
  1007. EnableIPv6: n.EnableIPv6,
  1008. }
  1009. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  1010. createOpts.IPAM = &network.IPAM{}
  1011. }
  1012. if n.Ipam.Driver != "" {
  1013. createOpts.IPAM.Driver = n.Ipam.Driver
  1014. }
  1015. for _, ipamConfig := range n.Ipam.Config {
  1016. config := network.IPAMConfig{
  1017. Subnet: ipamConfig.Subnet,
  1018. IPRange: ipamConfig.IPRange,
  1019. Gateway: ipamConfig.Gateway,
  1020. AuxAddress: ipamConfig.AuxiliaryAddresses,
  1021. }
  1022. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  1023. }
  1024. networkEventName := fmt.Sprintf("Network %s", n.Name)
  1025. w := progress.ContextWriter(ctx)
  1026. w.Event(progress.CreatingEvent(networkEventName))
  1027. if _, err := s.apiClient().NetworkCreate(ctx, n.Name, createOpts); err != nil {
  1028. w.Event(progress.ErrorEvent(networkEventName))
  1029. return errors.Wrapf(err, "failed to create network %s", n.Name)
  1030. }
  1031. w.Event(progress.CreatedEvent(networkEventName))
  1032. return nil
  1033. }
  1034. return nil
  1035. }
  1036. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig, project string) error {
  1037. inspected, err := s.apiClient().VolumeInspect(ctx, volume.Name)
  1038. if err != nil {
  1039. if !errdefs.IsNotFound(err) {
  1040. return err
  1041. }
  1042. if volume.External.External {
  1043. return fmt.Errorf("external volume %q not found", volume.Name)
  1044. }
  1045. err := s.createVolume(ctx, volume)
  1046. return err
  1047. }
  1048. if volume.External.External {
  1049. return nil
  1050. }
  1051. // Volume exists with name, but let's double-check this is the expected one
  1052. p, ok := inspected.Labels[api.ProjectLabel]
  1053. if !ok {
  1054. logrus.Warnf("volume %q already exists but was not created by Docker Compose. Use `external: true` to use an existing volume", volume.Name)
  1055. }
  1056. if ok && p != project {
  1057. logrus.Warnf("volume %q already exists but was not created for project %q. Use `external: true` to use an existing volume", volume.Name, p)
  1058. }
  1059. return nil
  1060. }
  1061. func (s *composeService) createVolume(ctx context.Context, volume types.VolumeConfig) error {
  1062. eventName := fmt.Sprintf("Volume %q", volume.Name)
  1063. w := progress.ContextWriter(ctx)
  1064. w.Event(progress.CreatingEvent(eventName))
  1065. _, err := s.apiClient().VolumeCreate(ctx, volume_api.CreateOptions{
  1066. Labels: volume.Labels,
  1067. Name: volume.Name,
  1068. Driver: volume.Driver,
  1069. DriverOpts: volume.DriverOpts,
  1070. })
  1071. if err != nil {
  1072. w.Event(progress.ErrorEvent(eventName))
  1073. return err
  1074. }
  1075. w.Event(progress.CreatedEvent(eventName))
  1076. return nil
  1077. }