create.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  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. var ipam *network.EndpointIPAMConfig
  254. var (
  255. ipv4Address string
  256. ipv6Address string
  257. )
  258. if config != nil {
  259. ipv4Address = config.Ipv4Address
  260. ipv6Address = config.Ipv6Address
  261. ipam = &network.EndpointIPAMConfig{
  262. IPv4Address: ipv4Address,
  263. IPv6Address: ipv6Address,
  264. }
  265. }
  266. networkConfig = &network.NetworkingConfig{
  267. EndpointsConfig: map[string]*network.EndpointSettings{
  268. net.Name: {
  269. Aliases: getAliases(service, config),
  270. IPAddress: ipv4Address,
  271. IPv6Gateway: ipv6Address,
  272. IPAMConfig: ipam,
  273. },
  274. },
  275. }
  276. break //nolint:staticcheck
  277. }
  278. ipcmode, err := getMode(ctx, service.Name, service.Ipc)
  279. if err != nil {
  280. return nil, nil, nil, err
  281. }
  282. tmpfs := map[string]string{}
  283. for _, t := range service.Tmpfs {
  284. if arr := strings.SplitN(t, ":", 2); len(arr) > 1 {
  285. tmpfs[arr[0]] = arr[1]
  286. } else {
  287. tmpfs[arr[0]] = ""
  288. }
  289. }
  290. var logConfig container.LogConfig
  291. if service.Logging != nil {
  292. logConfig = container.LogConfig{
  293. Type: service.Logging.Driver,
  294. Config: service.Logging.Options,
  295. }
  296. }
  297. hostConfig := container.HostConfig{
  298. AutoRemove: autoRemove,
  299. Binds: binds,
  300. Mounts: mounts,
  301. CapAdd: strslice.StrSlice(service.CapAdd),
  302. CapDrop: strslice.StrSlice(service.CapDrop),
  303. NetworkMode: container.NetworkMode(networkMode),
  304. Init: service.Init,
  305. IpcMode: container.IpcMode(ipcmode),
  306. ReadonlyRootfs: service.ReadOnly,
  307. RestartPolicy: getRestartPolicy(service),
  308. ShmSize: int64(service.ShmSize),
  309. Sysctls: service.Sysctls,
  310. PortBindings: portBindings,
  311. Resources: resources,
  312. VolumeDriver: service.VolumeDriver,
  313. VolumesFrom: service.VolumesFrom,
  314. DNS: service.DNS,
  315. DNSSearch: service.DNSSearch,
  316. DNSOptions: service.DNSOpts,
  317. ExtraHosts: service.ExtraHosts,
  318. SecurityOpt: service.SecurityOpt,
  319. UsernsMode: container.UsernsMode(service.UserNSMode),
  320. Privileged: service.Privileged,
  321. PidMode: container.PidMode(service.Pid),
  322. Tmpfs: tmpfs,
  323. Isolation: container.Isolation(service.Isolation),
  324. LogConfig: logConfig,
  325. }
  326. return &containerConfig, &hostConfig, networkConfig, nil
  327. }
  328. func getDefaultNetworkMode(project *types.Project, service types.ServiceConfig) string {
  329. mode := "none"
  330. if len(project.Networks) > 0 {
  331. for name := range getNetworksForService(service) {
  332. mode = project.Networks[name].Name
  333. break
  334. }
  335. }
  336. return mode
  337. }
  338. func getRestartPolicy(service types.ServiceConfig) container.RestartPolicy {
  339. var restart container.RestartPolicy
  340. if service.Restart != "" {
  341. split := strings.Split(service.Restart, ":")
  342. var attempts int
  343. if len(split) > 1 {
  344. attempts, _ = strconv.Atoi(split[1])
  345. }
  346. restart = container.RestartPolicy{
  347. Name: split[0],
  348. MaximumRetryCount: attempts,
  349. }
  350. }
  351. if service.Deploy != nil && service.Deploy.RestartPolicy != nil {
  352. policy := *service.Deploy.RestartPolicy
  353. var attempts int
  354. if policy.MaxAttempts != nil {
  355. attempts = int(*policy.MaxAttempts)
  356. }
  357. restart = container.RestartPolicy{
  358. Name: policy.Condition,
  359. MaximumRetryCount: attempts,
  360. }
  361. }
  362. return restart
  363. }
  364. func getDeployResources(s types.ServiceConfig) container.Resources {
  365. var swappiness *int64
  366. if s.MemSwappiness != 0 {
  367. val := int64(s.MemSwappiness)
  368. swappiness = &val
  369. }
  370. resources := container.Resources{
  371. CgroupParent: s.CgroupParent,
  372. Memory: int64(s.MemLimit),
  373. MemorySwap: int64(s.MemSwapLimit),
  374. MemorySwappiness: swappiness,
  375. MemoryReservation: int64(s.MemReservation),
  376. CPUCount: s.CPUCount,
  377. CPUPeriod: s.CPUPeriod,
  378. CPUQuota: s.CPUQuota,
  379. CPURealtimePeriod: s.CPURTPeriod,
  380. CPURealtimeRuntime: s.CPURTRuntime,
  381. CPUShares: s.CPUShares,
  382. CPUPercent: int64(s.CPUS * 100),
  383. CpusetCpus: s.CPUSet,
  384. }
  385. setBlkio(s.BlkioConfig, &resources)
  386. if s.Deploy != nil {
  387. setLimits(s.Deploy.Resources.Limits, &resources)
  388. setReservations(s.Deploy.Resources.Reservations, &resources)
  389. }
  390. for _, device := range s.Devices {
  391. // FIXME should use docker/cli parseDevice, unfortunately private
  392. src := ""
  393. dst := ""
  394. permissions := "rwm"
  395. arr := strings.Split(device, ":")
  396. switch len(arr) {
  397. case 3:
  398. permissions = arr[2]
  399. fallthrough
  400. case 2:
  401. dst = arr[1]
  402. fallthrough
  403. case 1:
  404. src = arr[0]
  405. }
  406. resources.Devices = append(resources.Devices, container.DeviceMapping{
  407. PathOnHost: src,
  408. PathInContainer: dst,
  409. CgroupPermissions: permissions,
  410. })
  411. }
  412. for name, u := range s.Ulimits {
  413. soft := u.Single
  414. if u.Soft != 0 {
  415. soft = u.Soft
  416. }
  417. hard := u.Single
  418. if u.Hard != 0 {
  419. hard = u.Hard
  420. }
  421. resources.Ulimits = append(resources.Ulimits, &units.Ulimit{
  422. Name: name,
  423. Hard: int64(hard),
  424. Soft: int64(soft),
  425. })
  426. }
  427. return resources
  428. }
  429. func setReservations(reservations *types.Resource, resources *container.Resources) {
  430. if reservations == nil {
  431. return
  432. }
  433. for _, device := range reservations.Devices {
  434. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  435. Capabilities: [][]string{device.Capabilities},
  436. Count: int(device.Count),
  437. DeviceIDs: device.IDs,
  438. Driver: device.Driver,
  439. })
  440. }
  441. }
  442. func setLimits(limits *types.Resource, resources *container.Resources) {
  443. if limits == nil {
  444. return
  445. }
  446. if limits.MemoryBytes != 0 {
  447. resources.Memory = int64(limits.MemoryBytes)
  448. }
  449. if limits.NanoCPUs != "" {
  450. i, _ := strconv.ParseInt(limits.NanoCPUs, 10, 64)
  451. resources.NanoCPUs = i
  452. }
  453. }
  454. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  455. if blkio == nil {
  456. return
  457. }
  458. resources.BlkioWeight = blkio.Weight
  459. for _, b := range blkio.WeightDevice {
  460. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  461. Path: b.Path,
  462. Weight: b.Weight,
  463. })
  464. }
  465. for _, b := range blkio.DeviceReadBps {
  466. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  467. Path: b.Path,
  468. Rate: b.Rate,
  469. })
  470. }
  471. for _, b := range blkio.DeviceReadIOps {
  472. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  473. Path: b.Path,
  474. Rate: b.Rate,
  475. })
  476. }
  477. for _, b := range blkio.DeviceWriteBps {
  478. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  479. Path: b.Path,
  480. Rate: b.Rate,
  481. })
  482. }
  483. for _, b := range blkio.DeviceWriteIOps {
  484. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  485. Path: b.Path,
  486. Rate: b.Rate,
  487. })
  488. }
  489. }
  490. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  491. ports := nat.PortSet{}
  492. for _, p := range s.Ports {
  493. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  494. ports[p] = struct{}{}
  495. }
  496. return ports
  497. }
  498. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  499. bindings := nat.PortMap{}
  500. for _, port := range s.Ports {
  501. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  502. bind := bindings[p]
  503. binding := nat.PortBinding{
  504. HostIP: port.HostIP,
  505. }
  506. if port.Published > 0 {
  507. binding.HostPort = fmt.Sprint(port.Published)
  508. }
  509. bind = append(bind, binding)
  510. bindings[p] = bind
  511. }
  512. return bindings
  513. }
  514. func getVolumesFrom(project *types.Project, volumesFrom []string) ([]string, []string, error) {
  515. var volumes = []string{}
  516. var services = []string{}
  517. // parse volumes_from
  518. if len(volumesFrom) == 0 {
  519. return volumes, services, nil
  520. }
  521. for _, vol := range volumesFrom {
  522. spec := strings.Split(vol, ":")
  523. if len(spec) == 0 {
  524. continue
  525. }
  526. if spec[0] == "container" {
  527. volumes = append(volumes, strings.Join(spec[1:], ":"))
  528. continue
  529. }
  530. serviceName := spec[0]
  531. services = append(services, serviceName)
  532. service, err := project.GetService(serviceName)
  533. if err != nil {
  534. return nil, nil, err
  535. }
  536. firstContainer := getContainerName(project.Name, service, 1)
  537. v := fmt.Sprintf("%s:%s", firstContainer, strings.Join(spec[1:], ":"))
  538. volumes = append(volumes, v)
  539. }
  540. return volumes, services, nil
  541. }
  542. func getDependentServiceFromMode(mode string) string {
  543. if strings.HasPrefix(mode, types.NetworkModeServicePrefix) {
  544. return mode[len(types.NetworkModeServicePrefix):]
  545. }
  546. return ""
  547. }
  548. func (s *composeService) buildContainerVolumes(ctx context.Context, p types.Project, service types.ServiceConfig,
  549. inherit *moby.Container) (map[string]struct{}, []string, []mount.Mount, error) {
  550. var mounts = []mount.Mount{}
  551. image := getImageName(service, p.Name)
  552. imgInspect, _, err := s.apiClient.ImageInspectWithRaw(ctx, image)
  553. if err != nil {
  554. return nil, nil, nil, err
  555. }
  556. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  557. if err != nil {
  558. return nil, nil, nil, err
  559. }
  560. volumeMounts := map[string]struct{}{}
  561. binds := []string{}
  562. MOUNTS:
  563. for _, m := range mountOptions {
  564. volumeMounts[m.Target] = struct{}{}
  565. // `Bind` API is used when host path need to be created if missing, `Mount` is preferred otherwise
  566. if m.Type == mount.TypeBind || m.Type == mount.TypeNamedPipe {
  567. for _, v := range service.Volumes {
  568. if v.Target == m.Target && v.Bind != nil && v.Bind.CreateHostPath {
  569. mode := "rw"
  570. if m.ReadOnly {
  571. mode = "ro"
  572. }
  573. binds = append(binds, fmt.Sprintf("%s:%s:%s", m.Source, m.Target, mode))
  574. continue MOUNTS
  575. }
  576. }
  577. }
  578. mounts = append(mounts, m)
  579. }
  580. return volumeMounts, binds, mounts, nil
  581. }
  582. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  583. var mounts = map[string]mount.Mount{}
  584. if inherit != nil {
  585. for _, m := range inherit.Mounts {
  586. if m.Type == "tmpfs" {
  587. continue
  588. }
  589. src := m.Source
  590. if m.Type == "volume" {
  591. src = m.Name
  592. }
  593. m.Destination = path.Clean(m.Destination)
  594. if img.Config != nil {
  595. if _, ok := img.Config.Volumes[m.Destination]; ok {
  596. // inherit previous container's anonymous volume
  597. mounts[m.Destination] = mount.Mount{
  598. Type: m.Type,
  599. Source: src,
  600. Target: m.Destination,
  601. ReadOnly: !m.RW,
  602. }
  603. }
  604. }
  605. for i, v := range s.Volumes {
  606. if v.Target != m.Destination {
  607. continue
  608. }
  609. if v.Source == "" {
  610. // inherit previous container's anonymous volume
  611. mounts[m.Destination] = mount.Mount{
  612. Type: m.Type,
  613. Source: src,
  614. Target: m.Destination,
  615. ReadOnly: !m.RW,
  616. }
  617. // Avoid mount to be later re-defined
  618. l := len(s.Volumes) - 1
  619. s.Volumes[i] = s.Volumes[l]
  620. s.Volumes = s.Volumes[:l]
  621. }
  622. }
  623. }
  624. }
  625. mounts, err := fillBindMounts(p, s, mounts)
  626. if err != nil {
  627. return nil, err
  628. }
  629. values := make([]mount.Mount, 0, len(mounts))
  630. for _, v := range mounts {
  631. values = append(values, v)
  632. }
  633. return values, nil
  634. }
  635. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  636. for _, v := range s.Volumes {
  637. bindMount, err := buildMount(p, v)
  638. if err != nil {
  639. return nil, err
  640. }
  641. m[bindMount.Target] = bindMount
  642. }
  643. secrets, err := buildContainerSecretMounts(p, s)
  644. if err != nil {
  645. return nil, err
  646. }
  647. for _, s := range secrets {
  648. if _, found := m[s.Target]; found {
  649. continue
  650. }
  651. m[s.Target] = s
  652. }
  653. configs, err := buildContainerConfigMounts(p, s)
  654. if err != nil {
  655. return nil, err
  656. }
  657. for _, c := range configs {
  658. if _, found := m[c.Target]; found {
  659. continue
  660. }
  661. m[c.Target] = c
  662. }
  663. return m, nil
  664. }
  665. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  666. var mounts = map[string]mount.Mount{}
  667. configsBaseDir := "/"
  668. for _, config := range s.Configs {
  669. target := config.Target
  670. if config.Target == "" {
  671. target = configsBaseDir + config.Source
  672. } else if !isUnixAbs(config.Target) {
  673. target = configsBaseDir + config.Target
  674. }
  675. definedConfig := p.Configs[config.Source]
  676. if definedConfig.External.External {
  677. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  678. }
  679. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  680. Type: types.VolumeTypeBind,
  681. Source: definedConfig.File,
  682. Target: target,
  683. ReadOnly: true,
  684. })
  685. if err != nil {
  686. return nil, err
  687. }
  688. mounts[target] = bindMount
  689. }
  690. values := make([]mount.Mount, 0, len(mounts))
  691. for _, v := range mounts {
  692. values = append(values, v)
  693. }
  694. return values, nil
  695. }
  696. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  697. var mounts = map[string]mount.Mount{}
  698. secretsDir := "/run/secrets/"
  699. for _, secret := range s.Secrets {
  700. target := secret.Target
  701. if secret.Target == "" {
  702. target = secretsDir + secret.Source
  703. } else if !isUnixAbs(secret.Target) {
  704. target = secretsDir + secret.Target
  705. }
  706. definedSecret := p.Secrets[secret.Source]
  707. if definedSecret.External.External {
  708. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  709. }
  710. mount, err := buildMount(p, types.ServiceVolumeConfig{
  711. Type: types.VolumeTypeBind,
  712. Source: definedSecret.File,
  713. Target: target,
  714. ReadOnly: true,
  715. })
  716. if err != nil {
  717. return nil, err
  718. }
  719. mounts[target] = mount
  720. }
  721. values := make([]mount.Mount, 0, len(mounts))
  722. for _, v := range mounts {
  723. values = append(values, v)
  724. }
  725. return values, nil
  726. }
  727. func isUnixAbs(path string) bool {
  728. return strings.HasPrefix(path, "/")
  729. }
  730. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  731. source := volume.Source
  732. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  733. // do not replace these with filepath.Abs(source) that will include a default drive.
  734. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  735. // volume source has already been prefixed with workdir if required, by compose-go project loader
  736. var err error
  737. source, err = filepath.Abs(source)
  738. if err != nil {
  739. return mount.Mount{}, err
  740. }
  741. }
  742. if volume.Type == types.VolumeTypeVolume {
  743. if volume.Source != "" {
  744. pVolume, ok := project.Volumes[volume.Source]
  745. if ok {
  746. source = pVolume.Name
  747. }
  748. }
  749. }
  750. bind, vol, tmpfs := buildMountOptions(volume)
  751. volume.Target = path.Clean(volume.Target)
  752. return mount.Mount{
  753. Type: mount.Type(volume.Type),
  754. Source: source,
  755. Target: volume.Target,
  756. ReadOnly: volume.ReadOnly,
  757. Consistency: mount.Consistency(volume.Consistency),
  758. BindOptions: bind,
  759. VolumeOptions: vol,
  760. TmpfsOptions: tmpfs,
  761. }, nil
  762. }
  763. func buildMountOptions(volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  764. switch volume.Type {
  765. case "bind":
  766. if volume.Volume != nil {
  767. logrus.Warnf("mount of type `bind` should not define `volume` option")
  768. }
  769. if volume.Tmpfs != nil {
  770. logrus.Warnf("mount of type `tmpfs` should not define `tmpfs` option")
  771. }
  772. return buildBindOption(volume.Bind), nil, nil
  773. case "volume":
  774. if volume.Bind != nil {
  775. logrus.Warnf("mount of type `volume` should not define `bind` option")
  776. }
  777. if volume.Tmpfs != nil {
  778. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  779. }
  780. return nil, buildVolumeOptions(volume.Volume), nil
  781. case "tmpfs":
  782. if volume.Bind != nil {
  783. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  784. }
  785. if volume.Tmpfs != nil {
  786. logrus.Warnf("mount of type `tmpfs` should not define `volumeZ` option")
  787. }
  788. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  789. }
  790. return nil, nil, nil
  791. }
  792. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  793. if bind == nil {
  794. return nil
  795. }
  796. return &mount.BindOptions{
  797. Propagation: mount.Propagation(bind.Propagation),
  798. // NonRecursive: false, FIXME missing from model ?
  799. }
  800. }
  801. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  802. if vol == nil {
  803. return nil
  804. }
  805. return &mount.VolumeOptions{
  806. NoCopy: vol.NoCopy,
  807. // Labels: , // FIXME missing from model ?
  808. // DriverConfig: , // FIXME missing from model ?
  809. }
  810. }
  811. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  812. if tmpfs == nil {
  813. return nil
  814. }
  815. return &mount.TmpfsOptions{
  816. SizeBytes: tmpfs.Size,
  817. // Mode: , // FIXME missing from model ?
  818. }
  819. }
  820. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  821. aliases := []string{s.Name}
  822. if c != nil {
  823. aliases = append(aliases, c.Aliases...)
  824. }
  825. return aliases
  826. }
  827. func getMode(ctx context.Context, serviceName string, mode string) (string, error) {
  828. cState, err := GetContextContainerState(ctx)
  829. if err != nil {
  830. return "", nil
  831. }
  832. observedState := cState.GetContainers()
  833. depService := getDependentServiceFromMode(mode)
  834. if depService != "" {
  835. depServiceContainers := observedState.filter(isService(depService))
  836. if len(depServiceContainers) > 0 {
  837. return types.NetworkModeContainerPrefix + depServiceContainers[0].ID, nil
  838. }
  839. return "", fmt.Errorf(`no containers started for %q in service %q -> %v`,
  840. mode, serviceName, observedState)
  841. }
  842. return mode, nil
  843. }
  844. func getNetworksForService(s types.ServiceConfig) map[string]*types.ServiceNetworkConfig {
  845. if len(s.Networks) > 0 {
  846. return s.Networks
  847. }
  848. if s.NetworkMode != "" {
  849. return nil
  850. }
  851. return map[string]*types.ServiceNetworkConfig{"default": nil}
  852. }
  853. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  854. _, err := s.apiClient.NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  855. if err != nil {
  856. if errdefs.IsNotFound(err) {
  857. if n.External.External {
  858. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  859. }
  860. var ipam *network.IPAM
  861. if n.Ipam.Config != nil {
  862. var config []network.IPAMConfig
  863. for _, pool := range n.Ipam.Config {
  864. config = append(config, network.IPAMConfig{
  865. Subnet: pool.Subnet,
  866. IPRange: pool.IPRange,
  867. Gateway: pool.Gateway,
  868. AuxAddress: pool.AuxiliaryAddresses,
  869. })
  870. }
  871. ipam = &network.IPAM{
  872. Driver: n.Ipam.Driver,
  873. Config: config,
  874. }
  875. }
  876. createOpts := moby.NetworkCreate{
  877. // TODO NameSpace Labels
  878. Labels: n.Labels,
  879. Driver: n.Driver,
  880. Options: n.DriverOpts,
  881. Internal: n.Internal,
  882. Attachable: n.Attachable,
  883. IPAM: ipam,
  884. }
  885. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  886. createOpts.IPAM = &network.IPAM{}
  887. }
  888. if n.Ipam.Driver != "" {
  889. createOpts.IPAM.Driver = n.Ipam.Driver
  890. }
  891. for _, ipamConfig := range n.Ipam.Config {
  892. config := network.IPAMConfig{
  893. Subnet: ipamConfig.Subnet,
  894. }
  895. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  896. }
  897. networkEventName := fmt.Sprintf("Network %s", n.Name)
  898. w := progress.ContextWriter(ctx)
  899. w.Event(progress.CreatingEvent(networkEventName))
  900. if _, err := s.apiClient.NetworkCreate(ctx, n.Name, createOpts); err != nil {
  901. w.Event(progress.ErrorEvent(networkEventName))
  902. return errors.Wrapf(err, "failed to create network %s", n.Name)
  903. }
  904. w.Event(progress.CreatedEvent(networkEventName))
  905. return nil
  906. }
  907. return err
  908. }
  909. return nil
  910. }
  911. func (s *composeService) removeNetwork(ctx context.Context, networkID string, networkName string) error {
  912. w := progress.ContextWriter(ctx)
  913. eventName := fmt.Sprintf("Network %s", networkName)
  914. w.Event(progress.RemovingEvent(eventName))
  915. if err := s.apiClient.NetworkRemove(ctx, networkID); err != nil {
  916. w.Event(progress.ErrorEvent(eventName))
  917. return errors.Wrapf(err, fmt.Sprintf("failed to remove network %s", networkID))
  918. }
  919. w.Event(progress.RemovedEvent(eventName))
  920. return nil
  921. }
  922. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig) error {
  923. // TODO could identify volume by label vs name
  924. _, err := s.apiClient.VolumeInspect(ctx, volume.Name)
  925. if err != nil {
  926. if !errdefs.IsNotFound(err) {
  927. return err
  928. }
  929. eventName := fmt.Sprintf("Volume %q", volume.Name)
  930. w := progress.ContextWriter(ctx)
  931. w.Event(progress.CreatingEvent(eventName))
  932. _, err := s.apiClient.VolumeCreate(ctx, volume_api.VolumeCreateBody{
  933. Labels: volume.Labels,
  934. Name: volume.Name,
  935. Driver: volume.Driver,
  936. DriverOpts: volume.DriverOpts,
  937. })
  938. if err != nil {
  939. w.Event(progress.ErrorEvent(eventName))
  940. return err
  941. }
  942. w.Event(progress.CreatedEvent(eventName))
  943. }
  944. return nil
  945. }