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