create.go 30 KB

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