create.go 32 KB

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