create.go 31 KB

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