create.go 31 KB

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