create.go 32 KB

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