create.go 31 KB

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