create.go 32 KB

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