create.go 32 KB

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