create.go 33 KB

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