create.go 31 KB

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