create.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  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)
  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. LogConfig: logConfig,
  338. }
  339. return &containerConfig, &hostConfig, networkConfig, nil
  340. }
  341. // copy/pasted from https://github.com/docker/cli/blob/9de1b162f/cli/command/container/opts.go#L673-L697 + RelativePath
  342. // TODO find so way to share this code with docker/cli
  343. func parseSecurityOpts(p *types.Project, securityOpts []string) ([]string, error) {
  344. for key, opt := range securityOpts {
  345. con := strings.SplitN(opt, "=", 2)
  346. if len(con) == 1 && con[0] != "no-new-privileges" {
  347. if strings.Contains(opt, ":") {
  348. con = strings.SplitN(opt, ":", 2)
  349. } else {
  350. return securityOpts, errors.Errorf("Invalid security-opt: %q", opt)
  351. }
  352. }
  353. if con[0] == "seccomp" && con[1] != "unconfined" {
  354. f, err := ioutil.ReadFile(p.RelativePath(con[1]))
  355. if err != nil {
  356. return securityOpts, errors.Errorf("opening seccomp profile (%s) failed: %v", con[1], err)
  357. }
  358. b := bytes.NewBuffer(nil)
  359. if err := json.Compact(b, f); err != nil {
  360. return securityOpts, errors.Errorf("compacting json for seccomp profile (%s) failed: %v", con[1], err)
  361. }
  362. securityOpts[key] = fmt.Sprintf("seccomp=%s", b.Bytes())
  363. }
  364. }
  365. return securityOpts, nil
  366. }
  367. func (s *composeService) prepareLabels(p *types.Project, service types.ServiceConfig, number int) (map[string]string, error) {
  368. labels := map[string]string{}
  369. for k, v := range service.Labels {
  370. labels[k] = v
  371. }
  372. labels[api.ProjectLabel] = p.Name
  373. labels[api.ServiceLabel] = service.Name
  374. labels[api.VersionLabel] = api.ComposeVersion
  375. if _, ok := service.Labels[api.OneoffLabel]; !ok {
  376. labels[api.OneoffLabel] = "False"
  377. }
  378. hash, err := ServiceHash(service)
  379. if err != nil {
  380. return nil, err
  381. }
  382. labels[api.ConfigHashLabel] = hash
  383. labels[api.WorkingDirLabel] = p.WorkingDir
  384. labels[api.ConfigFilesLabel] = strings.Join(p.ComposeFiles, ",")
  385. labels[api.ContainerNumberLabel] = strconv.Itoa(number)
  386. var dependencies []string
  387. for s := range service.DependsOn {
  388. dependencies = append(dependencies, s)
  389. }
  390. labels[api.DependenciesLabel] = strings.Join(dependencies, ",")
  391. return labels, nil
  392. }
  393. func getDefaultNetworkMode(project *types.Project, service types.ServiceConfig) string {
  394. mode := "none"
  395. if len(project.Networks) > 0 {
  396. for name := range getNetworksForService(service) {
  397. mode = project.Networks[name].Name
  398. break
  399. }
  400. }
  401. return mode
  402. }
  403. func getRestartPolicy(service types.ServiceConfig) container.RestartPolicy {
  404. var restart container.RestartPolicy
  405. if service.Restart != "" {
  406. split := strings.Split(service.Restart, ":")
  407. var attempts int
  408. if len(split) > 1 {
  409. attempts, _ = strconv.Atoi(split[1])
  410. }
  411. restart = container.RestartPolicy{
  412. Name: split[0],
  413. MaximumRetryCount: attempts,
  414. }
  415. }
  416. if service.Deploy != nil && service.Deploy.RestartPolicy != nil {
  417. policy := *service.Deploy.RestartPolicy
  418. var attempts int
  419. if policy.MaxAttempts != nil {
  420. attempts = int(*policy.MaxAttempts)
  421. }
  422. restart = container.RestartPolicy{
  423. Name: policy.Condition,
  424. MaximumRetryCount: attempts,
  425. }
  426. }
  427. return restart
  428. }
  429. func getDeployResources(s types.ServiceConfig) container.Resources {
  430. var swappiness *int64
  431. if s.MemSwappiness != 0 {
  432. val := int64(s.MemSwappiness)
  433. swappiness = &val
  434. }
  435. resources := container.Resources{
  436. CgroupParent: s.CgroupParent,
  437. Memory: int64(s.MemLimit),
  438. MemorySwap: int64(s.MemSwapLimit),
  439. MemorySwappiness: swappiness,
  440. MemoryReservation: int64(s.MemReservation),
  441. CPUCount: s.CPUCount,
  442. CPUPeriod: s.CPUPeriod,
  443. CPUQuota: s.CPUQuota,
  444. CPURealtimePeriod: s.CPURTPeriod,
  445. CPURealtimeRuntime: s.CPURTRuntime,
  446. CPUShares: s.CPUShares,
  447. CPUPercent: int64(s.CPUS * 100),
  448. CpusetCpus: s.CPUSet,
  449. }
  450. setBlkio(s.BlkioConfig, &resources)
  451. if s.Deploy != nil {
  452. setLimits(s.Deploy.Resources.Limits, &resources)
  453. setReservations(s.Deploy.Resources.Reservations, &resources)
  454. }
  455. for _, device := range s.Devices {
  456. // FIXME should use docker/cli parseDevice, unfortunately private
  457. src := ""
  458. dst := ""
  459. permissions := "rwm"
  460. arr := strings.Split(device, ":")
  461. switch len(arr) {
  462. case 3:
  463. permissions = arr[2]
  464. fallthrough
  465. case 2:
  466. dst = arr[1]
  467. fallthrough
  468. case 1:
  469. src = arr[0]
  470. }
  471. resources.Devices = append(resources.Devices, container.DeviceMapping{
  472. PathOnHost: src,
  473. PathInContainer: dst,
  474. CgroupPermissions: permissions,
  475. })
  476. }
  477. for name, u := range s.Ulimits {
  478. soft := u.Single
  479. if u.Soft != 0 {
  480. soft = u.Soft
  481. }
  482. hard := u.Single
  483. if u.Hard != 0 {
  484. hard = u.Hard
  485. }
  486. resources.Ulimits = append(resources.Ulimits, &units.Ulimit{
  487. Name: name,
  488. Hard: int64(hard),
  489. Soft: int64(soft),
  490. })
  491. }
  492. return resources
  493. }
  494. func setReservations(reservations *types.Resource, resources *container.Resources) {
  495. if reservations == nil {
  496. return
  497. }
  498. for _, device := range reservations.Devices {
  499. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  500. Capabilities: [][]string{device.Capabilities},
  501. Count: int(device.Count),
  502. DeviceIDs: device.IDs,
  503. Driver: device.Driver,
  504. })
  505. }
  506. }
  507. func setLimits(limits *types.Resource, resources *container.Resources) {
  508. if limits == nil {
  509. return
  510. }
  511. if limits.MemoryBytes != 0 {
  512. resources.Memory = int64(limits.MemoryBytes)
  513. }
  514. if limits.NanoCPUs != "" {
  515. i, _ := strconv.ParseInt(limits.NanoCPUs, 10, 64)
  516. resources.NanoCPUs = i
  517. }
  518. }
  519. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  520. if blkio == nil {
  521. return
  522. }
  523. resources.BlkioWeight = blkio.Weight
  524. for _, b := range blkio.WeightDevice {
  525. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  526. Path: b.Path,
  527. Weight: b.Weight,
  528. })
  529. }
  530. for _, b := range blkio.DeviceReadBps {
  531. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  532. Path: b.Path,
  533. Rate: b.Rate,
  534. })
  535. }
  536. for _, b := range blkio.DeviceReadIOps {
  537. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  538. Path: b.Path,
  539. Rate: b.Rate,
  540. })
  541. }
  542. for _, b := range blkio.DeviceWriteBps {
  543. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  544. Path: b.Path,
  545. Rate: b.Rate,
  546. })
  547. }
  548. for _, b := range blkio.DeviceWriteIOps {
  549. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  550. Path: b.Path,
  551. Rate: b.Rate,
  552. })
  553. }
  554. }
  555. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  556. ports := nat.PortSet{}
  557. for _, s := range s.Expose {
  558. p := nat.Port(s)
  559. ports[p] = struct{}{}
  560. }
  561. for _, p := range s.Ports {
  562. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  563. ports[p] = struct{}{}
  564. }
  565. return ports
  566. }
  567. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  568. bindings := nat.PortMap{}
  569. for _, port := range s.Ports {
  570. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  571. bind := bindings[p]
  572. binding := nat.PortBinding{
  573. HostIP: port.HostIP,
  574. }
  575. if port.Published > 0 {
  576. binding.HostPort = fmt.Sprint(port.Published)
  577. }
  578. bind = append(bind, binding)
  579. bindings[p] = bind
  580. }
  581. return bindings
  582. }
  583. func getVolumesFrom(project *types.Project, volumesFrom []string) ([]string, []string, error) {
  584. var volumes = []string{}
  585. var services = []string{}
  586. // parse volumes_from
  587. if len(volumesFrom) == 0 {
  588. return volumes, services, nil
  589. }
  590. for _, vol := range volumesFrom {
  591. spec := strings.Split(vol, ":")
  592. if len(spec) == 0 {
  593. continue
  594. }
  595. if spec[0] == "container" {
  596. volumes = append(volumes, strings.Join(spec[1:], ":"))
  597. continue
  598. }
  599. serviceName := spec[0]
  600. services = append(services, serviceName)
  601. service, err := project.GetService(serviceName)
  602. if err != nil {
  603. return nil, nil, err
  604. }
  605. firstContainer := getContainerName(project.Name, service, 1)
  606. v := fmt.Sprintf("container:%s", firstContainer)
  607. if len(spec) > 2 {
  608. v = fmt.Sprintf("container:%s:%s", firstContainer, strings.Join(spec[1:], ":"))
  609. }
  610. volumes = append(volumes, v)
  611. }
  612. return volumes, services, nil
  613. }
  614. func getDependentServiceFromMode(mode string) string {
  615. if strings.HasPrefix(mode, types.NetworkModeServicePrefix) {
  616. return mode[len(types.NetworkModeServicePrefix):]
  617. }
  618. return ""
  619. }
  620. func (s *composeService) buildContainerVolumes(ctx context.Context, p types.Project, service types.ServiceConfig,
  621. inherit *moby.Container) (map[string]struct{}, []string, []mount.Mount, error) {
  622. var mounts = []mount.Mount{}
  623. image := getImageName(service, p.Name)
  624. imgInspect, _, err := s.apiClient.ImageInspectWithRaw(ctx, image)
  625. if err != nil {
  626. return nil, nil, nil, err
  627. }
  628. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  629. if err != nil {
  630. return nil, nil, nil, err
  631. }
  632. volumeMounts := map[string]struct{}{}
  633. binds := []string{}
  634. MOUNTS:
  635. for _, m := range mountOptions {
  636. volumeMounts[m.Target] = struct{}{}
  637. // `Bind` API is used when host path need to be created if missing, `Mount` is preferred otherwise
  638. if m.Type == mount.TypeBind || m.Type == mount.TypeNamedPipe {
  639. for _, v := range service.Volumes {
  640. if v.Target == m.Target && v.Bind != nil && v.Bind.CreateHostPath {
  641. mode := "rw"
  642. if m.ReadOnly {
  643. mode = "ro"
  644. }
  645. binds = append(binds, fmt.Sprintf("%s:%s:%s", m.Source, m.Target, mode))
  646. continue MOUNTS
  647. }
  648. }
  649. }
  650. mounts = append(mounts, m)
  651. }
  652. return volumeMounts, binds, mounts, nil
  653. }
  654. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  655. var mounts = map[string]mount.Mount{}
  656. if inherit != nil {
  657. for _, m := range inherit.Mounts {
  658. if m.Type == "tmpfs" {
  659. continue
  660. }
  661. src := m.Source
  662. if m.Type == "volume" {
  663. src = m.Name
  664. }
  665. m.Destination = path.Clean(m.Destination)
  666. if img.Config != nil {
  667. if _, ok := img.Config.Volumes[m.Destination]; ok {
  668. // inherit previous container's anonymous volume
  669. mounts[m.Destination] = mount.Mount{
  670. Type: m.Type,
  671. Source: src,
  672. Target: m.Destination,
  673. ReadOnly: !m.RW,
  674. }
  675. }
  676. }
  677. for i, v := range s.Volumes {
  678. if v.Target != m.Destination {
  679. continue
  680. }
  681. if v.Source == "" {
  682. // inherit previous container's anonymous volume
  683. mounts[m.Destination] = mount.Mount{
  684. Type: m.Type,
  685. Source: src,
  686. Target: m.Destination,
  687. ReadOnly: !m.RW,
  688. }
  689. // Avoid mount to be later re-defined
  690. l := len(s.Volumes) - 1
  691. s.Volumes[i] = s.Volumes[l]
  692. s.Volumes = s.Volumes[:l]
  693. }
  694. }
  695. }
  696. }
  697. mounts, err := fillBindMounts(p, s, mounts)
  698. if err != nil {
  699. return nil, err
  700. }
  701. values := make([]mount.Mount, 0, len(mounts))
  702. for _, v := range mounts {
  703. values = append(values, v)
  704. }
  705. return values, nil
  706. }
  707. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  708. for _, v := range s.Volumes {
  709. bindMount, err := buildMount(p, v)
  710. if err != nil {
  711. return nil, err
  712. }
  713. m[bindMount.Target] = bindMount
  714. }
  715. secrets, err := buildContainerSecretMounts(p, s)
  716. if err != nil {
  717. return nil, err
  718. }
  719. for _, s := range secrets {
  720. if _, found := m[s.Target]; found {
  721. continue
  722. }
  723. m[s.Target] = s
  724. }
  725. configs, err := buildContainerConfigMounts(p, s)
  726. if err != nil {
  727. return nil, err
  728. }
  729. for _, c := range configs {
  730. if _, found := m[c.Target]; found {
  731. continue
  732. }
  733. m[c.Target] = c
  734. }
  735. return m, nil
  736. }
  737. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  738. var mounts = map[string]mount.Mount{}
  739. configsBaseDir := "/"
  740. for _, config := range s.Configs {
  741. target := config.Target
  742. if config.Target == "" {
  743. target = configsBaseDir + config.Source
  744. } else if !isUnixAbs(config.Target) {
  745. target = configsBaseDir + config.Target
  746. }
  747. definedConfig := p.Configs[config.Source]
  748. if definedConfig.External.External {
  749. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  750. }
  751. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  752. Type: types.VolumeTypeBind,
  753. Source: definedConfig.File,
  754. Target: target,
  755. ReadOnly: true,
  756. })
  757. if err != nil {
  758. return nil, err
  759. }
  760. mounts[target] = bindMount
  761. }
  762. values := make([]mount.Mount, 0, len(mounts))
  763. for _, v := range mounts {
  764. values = append(values, v)
  765. }
  766. return values, nil
  767. }
  768. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  769. var mounts = map[string]mount.Mount{}
  770. secretsDir := "/run/secrets/"
  771. for _, secret := range s.Secrets {
  772. target := secret.Target
  773. if secret.Target == "" {
  774. target = secretsDir + secret.Source
  775. } else if !isUnixAbs(secret.Target) {
  776. target = secretsDir + secret.Target
  777. }
  778. definedSecret := p.Secrets[secret.Source]
  779. if definedSecret.External.External {
  780. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  781. }
  782. mount, err := buildMount(p, types.ServiceVolumeConfig{
  783. Type: types.VolumeTypeBind,
  784. Source: definedSecret.File,
  785. Target: target,
  786. ReadOnly: true,
  787. })
  788. if err != nil {
  789. return nil, err
  790. }
  791. mounts[target] = mount
  792. }
  793. values := make([]mount.Mount, 0, len(mounts))
  794. for _, v := range mounts {
  795. values = append(values, v)
  796. }
  797. return values, nil
  798. }
  799. func isUnixAbs(path string) bool {
  800. return strings.HasPrefix(path, "/")
  801. }
  802. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  803. source := volume.Source
  804. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  805. // do not replace these with filepath.Abs(source) that will include a default drive.
  806. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  807. // volume source has already been prefixed with workdir if required, by compose-go project loader
  808. var err error
  809. source, err = filepath.Abs(source)
  810. if err != nil {
  811. return mount.Mount{}, err
  812. }
  813. }
  814. if volume.Type == types.VolumeTypeVolume {
  815. if volume.Source != "" {
  816. pVolume, ok := project.Volumes[volume.Source]
  817. if ok {
  818. source = pVolume.Name
  819. }
  820. }
  821. }
  822. bind, vol, tmpfs := buildMountOptions(volume)
  823. volume.Target = path.Clean(volume.Target)
  824. return mount.Mount{
  825. Type: mount.Type(volume.Type),
  826. Source: source,
  827. Target: volume.Target,
  828. ReadOnly: volume.ReadOnly,
  829. Consistency: mount.Consistency(volume.Consistency),
  830. BindOptions: bind,
  831. VolumeOptions: vol,
  832. TmpfsOptions: tmpfs,
  833. }, nil
  834. }
  835. func buildMountOptions(volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  836. switch volume.Type {
  837. case "bind":
  838. if volume.Volume != nil {
  839. logrus.Warnf("mount of type `bind` should not define `volume` option")
  840. }
  841. if volume.Tmpfs != nil {
  842. logrus.Warnf("mount of type `tmpfs` should not define `tmpfs` option")
  843. }
  844. return buildBindOption(volume.Bind), nil, nil
  845. case "volume":
  846. if volume.Bind != nil {
  847. logrus.Warnf("mount of type `volume` should not define `bind` option")
  848. }
  849. if volume.Tmpfs != nil {
  850. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  851. }
  852. return nil, buildVolumeOptions(volume.Volume), nil
  853. case "tmpfs":
  854. if volume.Bind != nil {
  855. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  856. }
  857. if volume.Tmpfs != nil {
  858. logrus.Warnf("mount of type `tmpfs` should not define `volumeZ` option")
  859. }
  860. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  861. }
  862. return nil, nil, nil
  863. }
  864. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  865. if bind == nil {
  866. return nil
  867. }
  868. return &mount.BindOptions{
  869. Propagation: mount.Propagation(bind.Propagation),
  870. // NonRecursive: false, FIXME missing from model ?
  871. }
  872. }
  873. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  874. if vol == nil {
  875. return nil
  876. }
  877. return &mount.VolumeOptions{
  878. NoCopy: vol.NoCopy,
  879. // Labels: , // FIXME missing from model ?
  880. // DriverConfig: , // FIXME missing from model ?
  881. }
  882. }
  883. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  884. if tmpfs == nil {
  885. return nil
  886. }
  887. return &mount.TmpfsOptions{
  888. SizeBytes: int64(tmpfs.Size),
  889. // Mode: , // FIXME missing from model ?
  890. }
  891. }
  892. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  893. aliases := []string{s.Name}
  894. if c != nil {
  895. aliases = append(aliases, c.Aliases...)
  896. }
  897. return aliases
  898. }
  899. func getNetworksForService(s types.ServiceConfig) map[string]*types.ServiceNetworkConfig {
  900. if len(s.Networks) > 0 {
  901. return s.Networks
  902. }
  903. if s.NetworkMode != "" {
  904. return nil
  905. }
  906. return map[string]*types.ServiceNetworkConfig{"default": nil}
  907. }
  908. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  909. _, err := s.apiClient.NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  910. if err != nil {
  911. if errdefs.IsNotFound(err) {
  912. if n.External.External {
  913. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  914. }
  915. var ipam *network.IPAM
  916. if n.Ipam.Config != nil {
  917. var config []network.IPAMConfig
  918. for _, pool := range n.Ipam.Config {
  919. config = append(config, network.IPAMConfig{
  920. Subnet: pool.Subnet,
  921. IPRange: pool.IPRange,
  922. Gateway: pool.Gateway,
  923. AuxAddress: pool.AuxiliaryAddresses,
  924. })
  925. }
  926. ipam = &network.IPAM{
  927. Driver: n.Ipam.Driver,
  928. Config: config,
  929. }
  930. }
  931. createOpts := moby.NetworkCreate{
  932. // TODO NameSpace Labels
  933. Labels: n.Labels,
  934. Driver: n.Driver,
  935. Options: n.DriverOpts,
  936. Internal: n.Internal,
  937. Attachable: n.Attachable,
  938. IPAM: ipam,
  939. }
  940. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  941. createOpts.IPAM = &network.IPAM{}
  942. }
  943. if n.Ipam.Driver != "" {
  944. createOpts.IPAM.Driver = n.Ipam.Driver
  945. }
  946. for _, ipamConfig := range n.Ipam.Config {
  947. config := network.IPAMConfig{
  948. Subnet: ipamConfig.Subnet,
  949. }
  950. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  951. }
  952. networkEventName := fmt.Sprintf("Network %s", n.Name)
  953. w := progress.ContextWriter(ctx)
  954. w.Event(progress.CreatingEvent(networkEventName))
  955. if _, err := s.apiClient.NetworkCreate(ctx, n.Name, createOpts); err != nil {
  956. w.Event(progress.ErrorEvent(networkEventName))
  957. return errors.Wrapf(err, "failed to create network %s", n.Name)
  958. }
  959. w.Event(progress.CreatedEvent(networkEventName))
  960. return nil
  961. }
  962. return err
  963. }
  964. return nil
  965. }
  966. func (s *composeService) removeNetwork(ctx context.Context, networkID string, networkName string) error {
  967. w := progress.ContextWriter(ctx)
  968. eventName := fmt.Sprintf("Network %s", networkName)
  969. w.Event(progress.RemovingEvent(eventName))
  970. if err := s.apiClient.NetworkRemove(ctx, networkID); err != nil {
  971. w.Event(progress.ErrorEvent(eventName))
  972. return errors.Wrapf(err, fmt.Sprintf("failed to remove network %s", networkID))
  973. }
  974. w.Event(progress.RemovedEvent(eventName))
  975. return nil
  976. }
  977. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig) error {
  978. // TODO could identify volume by label vs name
  979. _, err := s.apiClient.VolumeInspect(ctx, volume.Name)
  980. if err != nil {
  981. if !errdefs.IsNotFound(err) {
  982. return err
  983. }
  984. eventName := fmt.Sprintf("Volume %q", volume.Name)
  985. w := progress.ContextWriter(ctx)
  986. w.Event(progress.CreatingEvent(eventName))
  987. _, err := s.apiClient.VolumeCreate(ctx, volume_api.VolumeCreateBody{
  988. Labels: volume.Labels,
  989. Name: volume.Name,
  990. Driver: volume.Driver,
  991. DriverOpts: volume.DriverOpts,
  992. })
  993. if err != nil {
  994. w.Event(progress.ErrorEvent(eventName))
  995. return err
  996. }
  997. w.Event(progress.CreatedEvent(eventName))
  998. }
  999. return nil
  1000. }