create.go 32 KB

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