create.go 31 KB

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