create.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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. "context"
  16. "fmt"
  17. "path"
  18. "path/filepath"
  19. "strconv"
  20. "strings"
  21. "github.com/compose-spec/compose-go/types"
  22. moby "github.com/docker/docker/api/types"
  23. "github.com/docker/docker/api/types/blkiodev"
  24. "github.com/docker/docker/api/types/container"
  25. "github.com/docker/docker/api/types/mount"
  26. "github.com/docker/docker/api/types/network"
  27. "github.com/docker/docker/api/types/strslice"
  28. volume_api "github.com/docker/docker/api/types/volume"
  29. "github.com/docker/docker/errdefs"
  30. "github.com/docker/go-connections/nat"
  31. "github.com/docker/go-units"
  32. "github.com/pkg/errors"
  33. "github.com/sirupsen/logrus"
  34. "github.com/docker/compose-cli/pkg/api"
  35. "github.com/docker/compose-cli/pkg/progress"
  36. "github.com/docker/compose-cli/pkg/utils"
  37. )
  38. func (s *composeService) Create(ctx context.Context, project *types.Project, options api.CreateOptions) error {
  39. return progress.Run(ctx, func(ctx context.Context) error {
  40. return s.create(ctx, project, options)
  41. })
  42. }
  43. func (s *composeService) create(ctx context.Context, project *types.Project, options api.CreateOptions) error {
  44. if len(options.Services) == 0 {
  45. options.Services = project.ServiceNames()
  46. }
  47. var observedState Containers
  48. observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true)
  49. if err != nil {
  50. return err
  51. }
  52. containerState := NewContainersState(observedState)
  53. ctx = context.WithValue(ctx, ContainersKey{}, containerState)
  54. err = s.ensureImagesExists(ctx, project, observedState, options.QuietPull)
  55. if err != nil {
  56. return err
  57. }
  58. prepareNetworks(project)
  59. err = prepareVolumes(project)
  60. if err != nil {
  61. return err
  62. }
  63. if err := s.ensureNetworks(ctx, project.Networks); err != nil {
  64. return err
  65. }
  66. if err := s.ensureProjectVolumes(ctx, project); err != nil {
  67. return err
  68. }
  69. allServices := project.AllServices()
  70. allServiceNames := []string{}
  71. for _, service := range allServices {
  72. allServiceNames = append(allServiceNames, service.Name)
  73. }
  74. orphans := observedState.filter(isNotService(allServiceNames...))
  75. if len(orphans) > 0 {
  76. if options.RemoveOrphans {
  77. w := progress.ContextWriter(ctx)
  78. err := s.removeContainers(ctx, w, orphans, nil, false)
  79. if err != nil {
  80. return err
  81. }
  82. } else {
  83. logrus.Warnf("Found orphan containers (%s) for this project. If "+
  84. "you removed or renamed this service in your compose "+
  85. "file, you can run this command with the "+
  86. "--remove-orphans flag to clean it up.", orphans.names())
  87. }
  88. }
  89. prepareServicesDependsOn(project)
  90. return InDependencyOrder(ctx, project, func(c context.Context, service types.ServiceConfig) error {
  91. if utils.StringContains(options.Services, service.Name) {
  92. return s.ensureService(c, project, service, options.Recreate, options.Inherit, options.Timeout)
  93. }
  94. return s.ensureService(c, project, service, options.RecreateDependencies, options.Inherit, options.Timeout)
  95. })
  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) {
  128. outLoop:
  129. for i := range p.Services {
  130. networkDependency := getDependentServiceFromMode(p.Services[i].NetworkMode)
  131. ipcDependency := getDependentServiceFromMode(p.Services[i].Ipc)
  132. pidDependency := getDependentServiceFromMode(p.Services[i].Pid)
  133. if networkDependency == "" && ipcDependency == "" && pidDependency == "" {
  134. continue
  135. }
  136. if p.Services[i].DependsOn == nil {
  137. p.Services[i].DependsOn = make(types.DependsOnConfig)
  138. }
  139. for _, service := range p.Services {
  140. if service.Name == networkDependency || service.Name == ipcDependency || service.Name == pidDependency {
  141. p.Services[i].DependsOn[service.Name] = types.ServiceDependency{
  142. Condition: types.ServiceConditionStarted,
  143. }
  144. continue outLoop
  145. }
  146. }
  147. }
  148. }
  149. func (s *composeService) ensureNetworks(ctx context.Context, networks types.Networks) error {
  150. for _, network := range networks {
  151. err := s.ensureNetwork(ctx, network)
  152. if err != nil {
  153. return err
  154. }
  155. }
  156. return nil
  157. }
  158. func (s *composeService) ensureProjectVolumes(ctx context.Context, project *types.Project) error {
  159. for k, volume := range project.Volumes {
  160. volume.Labels = volume.Labels.Add(api.VolumeLabel, k)
  161. volume.Labels = volume.Labels.Add(api.ProjectLabel, project.Name)
  162. volume.Labels = volume.Labels.Add(api.VersionLabel, api.ComposeVersion)
  163. err := s.ensureVolume(ctx, volume)
  164. if err != nil {
  165. return err
  166. }
  167. }
  168. return nil
  169. }
  170. func getImageName(service types.ServiceConfig, projectName string) string {
  171. imageName := service.Image
  172. if imageName == "" {
  173. imageName = projectName + "_" + service.Name
  174. }
  175. return imageName
  176. }
  177. func (s *composeService) getCreateOptions(ctx context.Context, p *types.Project, service types.ServiceConfig, number int, inherit *moby.Container,
  178. autoRemove bool) (*container.Config, *container.HostConfig, *network.NetworkingConfig, error) {
  179. hash, err := ServiceHash(service)
  180. if err != nil {
  181. return nil, nil, nil, err
  182. }
  183. labels := map[string]string{}
  184. for k, v := range service.Labels {
  185. labels[k] = v
  186. }
  187. labels[api.ProjectLabel] = p.Name
  188. labels[api.ServiceLabel] = service.Name
  189. labels[api.VersionLabel] = api.ComposeVersion
  190. if _, ok := service.Labels[api.OneoffLabel]; !ok {
  191. labels[api.OneoffLabel] = "False"
  192. }
  193. labels[api.ConfigHashLabel] = hash
  194. labels[api.WorkingDirLabel] = p.WorkingDir
  195. labels[api.ConfigFilesLabel] = strings.Join(p.ComposeFiles, ",")
  196. labels[api.ContainerNumberLabel] = strconv.Itoa(number)
  197. var (
  198. runCmd strslice.StrSlice
  199. entrypoint strslice.StrSlice
  200. )
  201. if len(service.Command) > 0 {
  202. runCmd = strslice.StrSlice(service.Command)
  203. }
  204. if len(service.Entrypoint) > 0 {
  205. entrypoint = strslice.StrSlice(service.Entrypoint)
  206. }
  207. var (
  208. tty = service.Tty
  209. stdinOpen = service.StdinOpen
  210. attachStdin = false
  211. )
  212. volumeMounts, binds, mounts, err := s.buildContainerVolumes(ctx, *p, service, inherit)
  213. if err != nil {
  214. return nil, nil, nil, err
  215. }
  216. containerConfig := container.Config{
  217. Hostname: service.Hostname,
  218. Domainname: service.DomainName,
  219. User: service.User,
  220. ExposedPorts: buildContainerPorts(service),
  221. Tty: tty,
  222. OpenStdin: stdinOpen,
  223. StdinOnce: attachStdin && stdinOpen,
  224. AttachStdin: attachStdin,
  225. AttachStderr: true,
  226. AttachStdout: true,
  227. Cmd: runCmd,
  228. Image: getImageName(service, p.Name),
  229. WorkingDir: service.WorkingDir,
  230. Entrypoint: entrypoint,
  231. NetworkDisabled: service.NetworkMode == "disabled",
  232. MacAddress: service.MacAddress,
  233. Labels: labels,
  234. StopSignal: service.StopSignal,
  235. Env: ToMobyEnv(service.Environment),
  236. Healthcheck: ToMobyHealthCheck(service.HealthCheck),
  237. Volumes: volumeMounts,
  238. StopTimeout: ToSeconds(service.StopGracePeriod),
  239. }
  240. portBindings := buildContainerPortBindingOptions(service)
  241. resources := getDeployResources(service)
  242. networkMode, err := getMode(ctx, service.Name, service.NetworkMode)
  243. if err != nil {
  244. return nil, nil, nil, err
  245. }
  246. if networkMode == "" {
  247. networkMode = getDefaultNetworkMode(p, service)
  248. }
  249. var networkConfig *network.NetworkingConfig
  250. for _, id := range service.NetworksByPriority() {
  251. net := p.Networks[id]
  252. config := service.Networks[id]
  253. networkConfig = &network.NetworkingConfig{
  254. EndpointsConfig: map[string]*network.EndpointSettings{
  255. net.Name: {
  256. Aliases: getAliases(service, config),
  257. },
  258. },
  259. }
  260. break
  261. }
  262. ipcmode, err := getMode(ctx, service.Name, service.Ipc)
  263. if err != nil {
  264. return nil, nil, nil, err
  265. }
  266. tmpfs := map[string]string{}
  267. for _, t := range service.Tmpfs {
  268. if arr := strings.SplitN(t, ":", 2); len(arr) > 1 {
  269. tmpfs[arr[0]] = arr[1]
  270. } else {
  271. tmpfs[arr[0]] = ""
  272. }
  273. }
  274. var logConfig container.LogConfig
  275. if service.Logging != nil {
  276. logConfig = container.LogConfig{
  277. Type: service.Logging.Driver,
  278. Config: service.Logging.Options,
  279. }
  280. }
  281. hostConfig := container.HostConfig{
  282. AutoRemove: autoRemove,
  283. Binds: binds,
  284. Mounts: mounts,
  285. CapAdd: strslice.StrSlice(service.CapAdd),
  286. CapDrop: strslice.StrSlice(service.CapDrop),
  287. NetworkMode: container.NetworkMode(networkMode),
  288. Init: service.Init,
  289. IpcMode: container.IpcMode(ipcmode),
  290. ReadonlyRootfs: service.ReadOnly,
  291. RestartPolicy: getRestartPolicy(service),
  292. ShmSize: int64(service.ShmSize),
  293. Sysctls: service.Sysctls,
  294. PortBindings: portBindings,
  295. Resources: resources,
  296. VolumeDriver: service.VolumeDriver,
  297. VolumesFrom: service.VolumesFrom,
  298. DNS: service.DNS,
  299. DNSSearch: service.DNSSearch,
  300. DNSOptions: service.DNSOpts,
  301. ExtraHosts: service.ExtraHosts,
  302. SecurityOpt: service.SecurityOpt,
  303. UsernsMode: container.UsernsMode(service.UserNSMode),
  304. Privileged: service.Privileged,
  305. PidMode: container.PidMode(service.Pid),
  306. Tmpfs: tmpfs,
  307. Isolation: container.Isolation(service.Isolation),
  308. LogConfig: logConfig,
  309. }
  310. return &containerConfig, &hostConfig, networkConfig, nil
  311. }
  312. func getDefaultNetworkMode(project *types.Project, service types.ServiceConfig) string {
  313. mode := "none"
  314. if len(project.Networks) > 0 {
  315. for name := range getNetworksForService(service) {
  316. mode = project.Networks[name].Name
  317. break
  318. }
  319. }
  320. return mode
  321. }
  322. func getRestartPolicy(service types.ServiceConfig) container.RestartPolicy {
  323. var restart container.RestartPolicy
  324. if service.Restart != "" {
  325. split := strings.Split(service.Restart, ":")
  326. var attempts int
  327. if len(split) > 1 {
  328. attempts, _ = strconv.Atoi(split[1])
  329. }
  330. restart = container.RestartPolicy{
  331. Name: split[0],
  332. MaximumRetryCount: attempts,
  333. }
  334. }
  335. if service.Deploy != nil && service.Deploy.RestartPolicy != nil {
  336. policy := *service.Deploy.RestartPolicy
  337. var attempts int
  338. if policy.MaxAttempts != nil {
  339. attempts = int(*policy.MaxAttempts)
  340. }
  341. restart = container.RestartPolicy{
  342. Name: policy.Condition,
  343. MaximumRetryCount: attempts,
  344. }
  345. }
  346. return restart
  347. }
  348. func getDeployResources(s types.ServiceConfig) container.Resources {
  349. var swappiness *int64
  350. if s.MemSwappiness != 0 {
  351. val := int64(s.MemSwappiness)
  352. swappiness = &val
  353. }
  354. resources := container.Resources{
  355. CgroupParent: s.CgroupParent,
  356. Memory: int64(s.MemLimit),
  357. MemorySwap: int64(s.MemSwapLimit),
  358. MemorySwappiness: swappiness,
  359. MemoryReservation: int64(s.MemReservation),
  360. CPUCount: s.CPUCount,
  361. CPUPeriod: s.CPUPeriod,
  362. CPUQuota: s.CPUQuota,
  363. CPURealtimePeriod: s.CPURTPeriod,
  364. CPURealtimeRuntime: s.CPURTRuntime,
  365. CPUShares: s.CPUShares,
  366. CPUPercent: int64(s.CPUS * 100),
  367. CpusetCpus: s.CPUSet,
  368. }
  369. setBlkio(s.BlkioConfig, &resources)
  370. if s.Deploy != nil {
  371. setLimits(s.Deploy.Resources.Limits, &resources)
  372. setReservations(s.Deploy.Resources.Reservations, &resources)
  373. }
  374. for _, device := range s.Devices {
  375. // FIXME should use docker/cli parseDevice, unfortunately private
  376. src := ""
  377. dst := ""
  378. permissions := "rwm"
  379. arr := strings.Split(device, ":")
  380. switch len(arr) {
  381. case 3:
  382. permissions = arr[2]
  383. fallthrough
  384. case 2:
  385. dst = arr[1]
  386. fallthrough
  387. case 1:
  388. src = arr[0]
  389. }
  390. resources.Devices = append(resources.Devices, container.DeviceMapping{
  391. PathOnHost: src,
  392. PathInContainer: dst,
  393. CgroupPermissions: permissions,
  394. })
  395. }
  396. for name, u := range s.Ulimits {
  397. soft := u.Single
  398. if u.Soft != 0 {
  399. soft = u.Soft
  400. }
  401. hard := u.Single
  402. if u.Hard != 0 {
  403. hard = u.Hard
  404. }
  405. resources.Ulimits = append(resources.Ulimits, &units.Ulimit{
  406. Name: name,
  407. Hard: int64(hard),
  408. Soft: int64(soft),
  409. })
  410. }
  411. return resources
  412. }
  413. func setReservations(reservations *types.Resource, resources *container.Resources) {
  414. if reservations == nil {
  415. return
  416. }
  417. for _, device := range reservations.Devices {
  418. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  419. Capabilities: [][]string{device.Capabilities},
  420. Count: int(device.Count),
  421. DeviceIDs: device.IDs,
  422. Driver: device.Driver,
  423. })
  424. }
  425. }
  426. func setLimits(limits *types.Resource, resources *container.Resources) {
  427. if limits == nil {
  428. return
  429. }
  430. if limits.MemoryBytes != 0 {
  431. resources.Memory = int64(limits.MemoryBytes)
  432. }
  433. if limits.NanoCPUs != "" {
  434. i, _ := strconv.ParseInt(limits.NanoCPUs, 10, 64)
  435. resources.NanoCPUs = i
  436. }
  437. }
  438. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  439. if blkio == nil {
  440. return
  441. }
  442. resources.BlkioWeight = blkio.Weight
  443. for _, b := range blkio.WeightDevice {
  444. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  445. Path: b.Path,
  446. Weight: b.Weight,
  447. })
  448. }
  449. for _, b := range blkio.DeviceReadBps {
  450. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  451. Path: b.Path,
  452. Rate: b.Rate,
  453. })
  454. }
  455. for _, b := range blkio.DeviceReadIOps {
  456. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  457. Path: b.Path,
  458. Rate: b.Rate,
  459. })
  460. }
  461. for _, b := range blkio.DeviceWriteBps {
  462. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  463. Path: b.Path,
  464. Rate: b.Rate,
  465. })
  466. }
  467. for _, b := range blkio.DeviceWriteIOps {
  468. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  469. Path: b.Path,
  470. Rate: b.Rate,
  471. })
  472. }
  473. }
  474. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  475. ports := nat.PortSet{}
  476. for _, p := range s.Ports {
  477. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  478. ports[p] = struct{}{}
  479. }
  480. return ports
  481. }
  482. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  483. bindings := nat.PortMap{}
  484. for _, port := range s.Ports {
  485. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  486. bind := bindings[p]
  487. binding := nat.PortBinding{
  488. HostIP: port.HostIP,
  489. }
  490. if port.Published > 0 {
  491. binding.HostPort = fmt.Sprint(port.Published)
  492. }
  493. bind = append(bind, binding)
  494. bindings[p] = bind
  495. }
  496. return bindings
  497. }
  498. func getVolumesFrom(project *types.Project, volumesFrom []string) ([]string, []string, error) {
  499. var volumes = []string{}
  500. var services = []string{}
  501. // parse volumes_from
  502. if len(volumesFrom) == 0 {
  503. return volumes, services, nil
  504. }
  505. for _, vol := range volumesFrom {
  506. spec := strings.Split(vol, ":")
  507. if len(spec) == 0 {
  508. continue
  509. }
  510. if spec[0] == "container" {
  511. volumes = append(volumes, strings.Join(spec[1:], ":"))
  512. continue
  513. }
  514. serviceName := spec[0]
  515. services = append(services, serviceName)
  516. service, err := project.GetService(serviceName)
  517. if err != nil {
  518. return nil, nil, err
  519. }
  520. firstContainer := getContainerName(project.Name, service, 1)
  521. v := fmt.Sprintf("%s:%s", firstContainer, strings.Join(spec[1:], ":"))
  522. volumes = append(volumes, v)
  523. }
  524. return volumes, services, nil
  525. }
  526. func getDependentServiceFromMode(mode string) string {
  527. if strings.HasPrefix(mode, types.NetworkModeServicePrefix) {
  528. return mode[len(types.NetworkModeServicePrefix):]
  529. }
  530. return ""
  531. }
  532. func (s *composeService) buildContainerVolumes(ctx context.Context, p types.Project, service types.ServiceConfig,
  533. inherit *moby.Container) (map[string]struct{}, []string, []mount.Mount, error) {
  534. var mounts = []mount.Mount{}
  535. image := getImageName(service, p.Name)
  536. imgInspect, _, err := s.apiClient.ImageInspectWithRaw(ctx, image)
  537. if err != nil {
  538. return nil, nil, nil, err
  539. }
  540. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  541. if err != nil {
  542. return nil, nil, nil, err
  543. }
  544. volumeMounts := map[string]struct{}{}
  545. binds := []string{}
  546. MOUNTS:
  547. for _, m := range mountOptions {
  548. volumeMounts[m.Target] = struct{}{}
  549. // `Bind` API is used when host path need to be created if missing, `Mount` is preferred otherwise
  550. if m.Type == mount.TypeBind || m.Type == mount.TypeNamedPipe {
  551. for _, v := range service.Volumes {
  552. if v.Target == m.Target && v.Bind != nil && v.Bind.CreateHostPath {
  553. mode := "rw"
  554. if m.ReadOnly {
  555. mode = "ro"
  556. }
  557. binds = append(binds, fmt.Sprintf("%s:%s:%s", m.Source, m.Target, mode))
  558. continue MOUNTS
  559. }
  560. }
  561. }
  562. mounts = append(mounts, m)
  563. }
  564. return volumeMounts, binds, mounts, nil
  565. }
  566. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  567. var mounts = map[string]mount.Mount{}
  568. if inherit != nil {
  569. for _, m := range inherit.Mounts {
  570. if m.Type == "tmpfs" {
  571. continue
  572. }
  573. src := m.Source
  574. if m.Type == "volume" {
  575. src = m.Name
  576. }
  577. m.Destination = path.Clean(m.Destination)
  578. if img.Config != nil {
  579. if _, ok := img.Config.Volumes[m.Destination]; ok {
  580. // inherit previous container's anonymous volume
  581. mounts[m.Destination] = mount.Mount{
  582. Type: m.Type,
  583. Source: src,
  584. Target: m.Destination,
  585. ReadOnly: !m.RW,
  586. }
  587. }
  588. }
  589. for i, v := range s.Volumes {
  590. if v.Target != m.Destination {
  591. continue
  592. }
  593. if v.Source == "" {
  594. // inherit previous container's anonymous volume
  595. mounts[m.Destination] = mount.Mount{
  596. Type: m.Type,
  597. Source: src,
  598. Target: m.Destination,
  599. ReadOnly: !m.RW,
  600. }
  601. // Avoid mount to be later re-defined
  602. l := len(s.Volumes) - 1
  603. s.Volumes[i] = s.Volumes[l]
  604. s.Volumes = s.Volumes[:l]
  605. }
  606. }
  607. }
  608. }
  609. mounts, err := fillBindMounts(p, s, mounts)
  610. if err != nil {
  611. return nil, err
  612. }
  613. values := make([]mount.Mount, 0, len(mounts))
  614. for _, v := range mounts {
  615. values = append(values, v)
  616. }
  617. return values, nil
  618. }
  619. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  620. for _, v := range s.Volumes {
  621. bindMount, err := buildMount(p, v)
  622. if err != nil {
  623. return nil, err
  624. }
  625. m[bindMount.Target] = bindMount
  626. }
  627. secrets, err := buildContainerSecretMounts(p, s)
  628. if err != nil {
  629. return nil, err
  630. }
  631. for _, s := range secrets {
  632. if _, found := m[s.Target]; found {
  633. continue
  634. }
  635. m[s.Target] = s
  636. }
  637. configs, err := buildContainerConfigMounts(p, s)
  638. if err != nil {
  639. return nil, err
  640. }
  641. for _, c := range configs {
  642. if _, found := m[c.Target]; found {
  643. continue
  644. }
  645. m[c.Target] = c
  646. }
  647. return m, nil
  648. }
  649. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  650. var mounts = map[string]mount.Mount{}
  651. configsBaseDir := "/"
  652. for _, config := range s.Configs {
  653. target := config.Target
  654. if config.Target == "" {
  655. target = configsBaseDir + config.Source
  656. } else if !isUnixAbs(config.Target) {
  657. target = configsBaseDir + config.Target
  658. }
  659. definedConfig := p.Configs[config.Source]
  660. if definedConfig.External.External {
  661. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  662. }
  663. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  664. Type: types.VolumeTypeBind,
  665. Source: definedConfig.File,
  666. Target: target,
  667. ReadOnly: true,
  668. })
  669. if err != nil {
  670. return nil, err
  671. }
  672. mounts[target] = bindMount
  673. }
  674. values := make([]mount.Mount, 0, len(mounts))
  675. for _, v := range mounts {
  676. values = append(values, v)
  677. }
  678. return values, nil
  679. }
  680. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  681. var mounts = map[string]mount.Mount{}
  682. secretsDir := "/run/secrets/"
  683. for _, secret := range s.Secrets {
  684. target := secret.Target
  685. if secret.Target == "" {
  686. target = secretsDir + secret.Source
  687. } else if !isUnixAbs(secret.Target) {
  688. target = secretsDir + secret.Target
  689. }
  690. definedSecret := p.Secrets[secret.Source]
  691. if definedSecret.External.External {
  692. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  693. }
  694. mount, err := buildMount(p, types.ServiceVolumeConfig{
  695. Type: types.VolumeTypeBind,
  696. Source: definedSecret.File,
  697. Target: target,
  698. ReadOnly: true,
  699. })
  700. if err != nil {
  701. return nil, err
  702. }
  703. mounts[target] = mount
  704. }
  705. values := make([]mount.Mount, 0, len(mounts))
  706. for _, v := range mounts {
  707. values = append(values, v)
  708. }
  709. return values, nil
  710. }
  711. func isUnixAbs(path string) bool {
  712. return strings.HasPrefix(path, "/")
  713. }
  714. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  715. source := volume.Source
  716. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  717. // do not replace these with filepath.Abs(source) that will include a default drive.
  718. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  719. // volume source has already been prefixed with workdir if required, by compose-go project loader
  720. var err error
  721. source, err = filepath.Abs(source)
  722. if err != nil {
  723. return mount.Mount{}, err
  724. }
  725. }
  726. if volume.Type == types.VolumeTypeVolume {
  727. if volume.Source != "" {
  728. pVolume, ok := project.Volumes[volume.Source]
  729. if ok {
  730. source = pVolume.Name
  731. }
  732. }
  733. }
  734. bind, vol, tmpfs := buildMountOptions(volume)
  735. volume.Target = path.Clean(volume.Target)
  736. return mount.Mount{
  737. Type: mount.Type(volume.Type),
  738. Source: source,
  739. Target: volume.Target,
  740. ReadOnly: volume.ReadOnly,
  741. Consistency: mount.Consistency(volume.Consistency),
  742. BindOptions: bind,
  743. VolumeOptions: vol,
  744. TmpfsOptions: tmpfs,
  745. }, nil
  746. }
  747. func buildMountOptions(volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  748. switch volume.Type {
  749. case "bind":
  750. if volume.Volume != nil {
  751. logrus.Warnf("mount of type `bind` should not define `volume` option")
  752. }
  753. if volume.Tmpfs != nil {
  754. logrus.Warnf("mount of type `tmpfs` should not define `tmpfs` option")
  755. }
  756. return buildBindOption(volume.Bind), nil, nil
  757. case "volume":
  758. if volume.Bind != nil {
  759. logrus.Warnf("mount of type `volume` should not define `bind` option")
  760. }
  761. if volume.Tmpfs != nil {
  762. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  763. }
  764. return nil, buildVolumeOptions(volume.Volume), nil
  765. case "tmpfs":
  766. if volume.Bind != nil {
  767. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  768. }
  769. if volume.Tmpfs != nil {
  770. logrus.Warnf("mount of type `tmpfs` should not define `volumeZ` option")
  771. }
  772. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  773. }
  774. return nil, nil, nil
  775. }
  776. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  777. if bind == nil {
  778. return nil
  779. }
  780. return &mount.BindOptions{
  781. Propagation: mount.Propagation(bind.Propagation),
  782. // NonRecursive: false, FIXME missing from model ?
  783. }
  784. }
  785. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  786. if vol == nil {
  787. return nil
  788. }
  789. return &mount.VolumeOptions{
  790. NoCopy: vol.NoCopy,
  791. // Labels: , // FIXME missing from model ?
  792. // DriverConfig: , // FIXME missing from model ?
  793. }
  794. }
  795. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  796. if tmpfs == nil {
  797. return nil
  798. }
  799. return &mount.TmpfsOptions{
  800. SizeBytes: tmpfs.Size,
  801. // Mode: , // FIXME missing from model ?
  802. }
  803. }
  804. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  805. aliases := []string{s.Name}
  806. if c != nil {
  807. aliases = append(aliases, c.Aliases...)
  808. }
  809. return aliases
  810. }
  811. func getMode(ctx context.Context, serviceName string, mode string) (string, error) {
  812. cState, err := GetContextContainerState(ctx)
  813. if err != nil {
  814. return "", nil
  815. }
  816. observedState := cState.GetContainers()
  817. depService := getDependentServiceFromMode(mode)
  818. if depService != "" {
  819. depServiceContainers := observedState.filter(isService(depService))
  820. if len(depServiceContainers) > 0 {
  821. return types.NetworkModeContainerPrefix + depServiceContainers[0].ID, nil
  822. }
  823. return "", fmt.Errorf(`no containers started for %q in service %q -> %v`,
  824. mode, serviceName, observedState)
  825. }
  826. return mode, nil
  827. }
  828. func getNetworksForService(s types.ServiceConfig) map[string]*types.ServiceNetworkConfig {
  829. if len(s.Networks) > 0 {
  830. return s.Networks
  831. }
  832. if s.NetworkMode != "" {
  833. return nil
  834. }
  835. return map[string]*types.ServiceNetworkConfig{"default": nil}
  836. }
  837. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  838. _, err := s.apiClient.NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  839. if err != nil {
  840. if errdefs.IsNotFound(err) {
  841. if n.External.External {
  842. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  843. }
  844. createOpts := moby.NetworkCreate{
  845. // TODO NameSpace Labels
  846. Labels: n.Labels,
  847. Driver: n.Driver,
  848. Options: n.DriverOpts,
  849. Internal: n.Internal,
  850. Attachable: n.Attachable,
  851. }
  852. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  853. createOpts.IPAM = &network.IPAM{}
  854. }
  855. if n.Ipam.Driver != "" {
  856. createOpts.IPAM.Driver = n.Ipam.Driver
  857. }
  858. for _, ipamConfig := range n.Ipam.Config {
  859. config := network.IPAMConfig{
  860. Subnet: ipamConfig.Subnet,
  861. }
  862. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  863. }
  864. networkEventName := fmt.Sprintf("Network %s", n.Name)
  865. w := progress.ContextWriter(ctx)
  866. w.Event(progress.CreatingEvent(networkEventName))
  867. if _, err := s.apiClient.NetworkCreate(ctx, n.Name, createOpts); err != nil {
  868. w.Event(progress.ErrorEvent(networkEventName))
  869. return errors.Wrapf(err, "failed to create network %s", n.Name)
  870. }
  871. w.Event(progress.CreatedEvent(networkEventName))
  872. return nil
  873. }
  874. return err
  875. }
  876. return nil
  877. }
  878. func (s *composeService) removeNetwork(ctx context.Context, networkID string, networkName string) error {
  879. w := progress.ContextWriter(ctx)
  880. eventName := fmt.Sprintf("Network %s", networkName)
  881. w.Event(progress.RemovingEvent(eventName))
  882. if err := s.apiClient.NetworkRemove(ctx, networkID); err != nil {
  883. w.Event(progress.ErrorEvent(eventName))
  884. return errors.Wrapf(err, fmt.Sprintf("failed to remove network %s", networkID))
  885. }
  886. w.Event(progress.RemovedEvent(eventName))
  887. return nil
  888. }
  889. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig) error {
  890. // TODO could identify volume by label vs name
  891. _, err := s.apiClient.VolumeInspect(ctx, volume.Name)
  892. if err != nil {
  893. if !errdefs.IsNotFound(err) {
  894. return err
  895. }
  896. eventName := fmt.Sprintf("Volume %q", volume.Name)
  897. w := progress.ContextWriter(ctx)
  898. w.Event(progress.CreatingEvent(eventName))
  899. _, err := s.apiClient.VolumeCreate(ctx, volume_api.VolumeCreateBody{
  900. Labels: volume.Labels,
  901. Name: volume.Name,
  902. Driver: volume.Driver,
  903. DriverOpts: volume.DriverOpts,
  904. })
  905. if err != nil {
  906. w.Event(progress.ErrorEvent(eventName))
  907. return err
  908. }
  909. w.Event(progress.CreatedEvent(eventName))
  910. }
  911. return nil
  912. }