create.go 36 KB

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