create.go 34 KB

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