create.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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, options api.CreateOptions) error {
  55. return progress.RunWithTitle(ctx, func(ctx context.Context) error {
  56. return s.create(ctx, project, options)
  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.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. definedConfig := p.Configs[config.Source]
  794. if definedConfig.External.External {
  795. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  796. }
  797. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  798. Type: types.VolumeTypeBind,
  799. Source: definedConfig.File,
  800. Target: target,
  801. ReadOnly: true,
  802. })
  803. if err != nil {
  804. return nil, err
  805. }
  806. mounts[target] = bindMount
  807. }
  808. values := make([]mount.Mount, 0, len(mounts))
  809. for _, v := range mounts {
  810. values = append(values, v)
  811. }
  812. return values, nil
  813. }
  814. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  815. var mounts = map[string]mount.Mount{}
  816. secretsDir := "/run/secrets/"
  817. for _, secret := range s.Secrets {
  818. target := secret.Target
  819. if secret.Target == "" {
  820. target = secretsDir + secret.Source
  821. } else if !isAbsTarget(secret.Target) {
  822. target = secretsDir + secret.Target
  823. }
  824. definedSecret := p.Secrets[secret.Source]
  825. if definedSecret.External.External {
  826. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  827. }
  828. if definedSecret.Environment != "" {
  829. continue
  830. }
  831. mnt, err := buildMount(p, types.ServiceVolumeConfig{
  832. Type: types.VolumeTypeBind,
  833. Source: definedSecret.File,
  834. Target: target,
  835. ReadOnly: true,
  836. })
  837. if err != nil {
  838. return nil, err
  839. }
  840. mounts[target] = mnt
  841. }
  842. values := make([]mount.Mount, 0, len(mounts))
  843. for _, v := range mounts {
  844. values = append(values, v)
  845. }
  846. return values, nil
  847. }
  848. func isAbsTarget(p string) bool {
  849. return isUnixAbs(p) || isWindowsAbs(p)
  850. }
  851. func isUnixAbs(p string) bool {
  852. return strings.HasPrefix(p, "/")
  853. }
  854. func isWindowsAbs(p string) bool {
  855. if strings.HasPrefix(p, "\\\\") {
  856. return true
  857. }
  858. if len(p) > 2 && p[1] == ':' {
  859. return p[2] == '\\'
  860. }
  861. return false
  862. }
  863. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  864. source := volume.Source
  865. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  866. // do not replace these with filepath.Abs(source) that will include a default drive.
  867. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  868. // volume source has already been prefixed with workdir if required, by compose-go project loader
  869. var err error
  870. source, err = filepath.Abs(source)
  871. if err != nil {
  872. return mount.Mount{}, err
  873. }
  874. }
  875. if volume.Type == types.VolumeTypeVolume {
  876. if volume.Source != "" {
  877. pVolume, ok := project.Volumes[volume.Source]
  878. if ok {
  879. source = pVolume.Name
  880. }
  881. }
  882. }
  883. bind, vol, tmpfs := buildMountOptions(project, volume)
  884. volume.Target = path.Clean(volume.Target)
  885. if bind != nil {
  886. volume.Type = types.VolumeTypeBind
  887. }
  888. return mount.Mount{
  889. Type: mount.Type(volume.Type),
  890. Source: source,
  891. Target: volume.Target,
  892. ReadOnly: volume.ReadOnly,
  893. Consistency: mount.Consistency(volume.Consistency),
  894. BindOptions: bind,
  895. VolumeOptions: vol,
  896. TmpfsOptions: tmpfs,
  897. }, nil
  898. }
  899. func buildMountOptions(project types.Project, volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  900. switch volume.Type {
  901. case "bind":
  902. if volume.Volume != nil {
  903. logrus.Warnf("mount of type `bind` should not define `volume` option")
  904. }
  905. if volume.Tmpfs != nil {
  906. logrus.Warnf("mount of type `bind` should not define `tmpfs` option")
  907. }
  908. return buildBindOption(volume.Bind), nil, nil
  909. case "volume":
  910. if volume.Bind != nil {
  911. logrus.Warnf("mount of type `volume` should not define `bind` option")
  912. }
  913. if volume.Tmpfs != nil {
  914. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  915. }
  916. if v, ok := project.Volumes[volume.Source]; ok && v.DriverOpts["o"] == types.VolumeTypeBind {
  917. return buildBindOption(&types.ServiceVolumeBind{
  918. CreateHostPath: true,
  919. }), nil, nil
  920. }
  921. return nil, buildVolumeOptions(volume.Volume), nil
  922. case "tmpfs":
  923. if volume.Bind != nil {
  924. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  925. }
  926. if volume.Volume != nil {
  927. logrus.Warnf("mount of type `tmpfs` should not define `volume` option")
  928. }
  929. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  930. }
  931. return nil, nil, nil
  932. }
  933. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  934. if bind == nil {
  935. return nil
  936. }
  937. return &mount.BindOptions{
  938. Propagation: mount.Propagation(bind.Propagation),
  939. // NonRecursive: false, FIXME missing from model ?
  940. }
  941. }
  942. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  943. if vol == nil {
  944. return nil
  945. }
  946. return &mount.VolumeOptions{
  947. NoCopy: vol.NoCopy,
  948. // Labels: , // FIXME missing from model ?
  949. // DriverConfig: , // FIXME missing from model ?
  950. }
  951. }
  952. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  953. if tmpfs == nil {
  954. return nil
  955. }
  956. return &mount.TmpfsOptions{
  957. SizeBytes: int64(tmpfs.Size),
  958. Mode: os.FileMode(tmpfs.Mode),
  959. }
  960. }
  961. func (s *composeService) ensureNetwork(ctx context.Context, n *types.NetworkConfig) error {
  962. if n.External.External {
  963. return s.resolveExternalNetwork(ctx, n)
  964. }
  965. err := s.resolveOrCreateNetwork(ctx, n)
  966. if errdefs.IsConflict(err) {
  967. // Maybe another execution of `docker compose up|run` created same network
  968. // let's retry once
  969. return s.resolveOrCreateNetwork(ctx, n)
  970. }
  971. return err
  972. }
  973. func (s *composeService) resolveOrCreateNetwork(ctx context.Context, n *types.NetworkConfig) error { //nolint:gocyclo
  974. expectedNetworkLabel := n.Labels[api.NetworkLabel]
  975. expectedProjectLabel := n.Labels[api.ProjectLabel]
  976. // First, try to find a unique network matching by name or ID
  977. inspect, err := s.apiClient().NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  978. if err == nil {
  979. // NetworkInspect will match on ID prefix, so double check we get the expected one
  980. // as looking for network named `db` we could erroneously matched network ID `db9086999caf`
  981. if inspect.Name == n.Name || inspect.ID == n.Name {
  982. p, ok := inspect.Labels[api.ProjectLabel]
  983. if !ok {
  984. logrus.Warnf("a network with name %s exists but was not created by compose.\n"+
  985. "Set `external: true` to use an existing network", n.Name)
  986. } else if p != expectedProjectLabel {
  987. logrus.Warnf("a network with name %s exists but was not created for project %q.\n"+
  988. "Set `external: true` to use an existing network", n.Name, expectedProjectLabel)
  989. }
  990. if inspect.Labels[api.NetworkLabel] != expectedNetworkLabel {
  991. return fmt.Errorf("network %s was found but has incorrect label %s set to %q", n.Name, api.NetworkLabel, inspect.Labels[api.NetworkLabel])
  992. }
  993. return nil
  994. }
  995. }
  996. // ignore other errors. Typically, an ambiguous request by name results in some generic `invalidParameter` error
  997. // Either not found, or name is ambiguous - use NetworkList to list by name
  998. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  999. Filters: filters.NewArgs(filters.Arg("name", n.Name)),
  1000. })
  1001. if err != nil {
  1002. return err
  1003. }
  1004. // NetworkList Matches all or part of a network name, so we have to filter for a strict match
  1005. networks = utils.Filter(networks, func(net moby.NetworkResource) bool {
  1006. return net.Name == n.Name
  1007. })
  1008. for _, net := range networks {
  1009. if net.Labels[api.ProjectLabel] == expectedProjectLabel &&
  1010. net.Labels[api.NetworkLabel] == expectedNetworkLabel {
  1011. return nil
  1012. }
  1013. }
  1014. // we could have set NetworkList with a projectFilter and networkFilter but not doing so allows to catch this
  1015. // scenario were a network with same name exists but doesn't have label, and use of `CheckDuplicate: true`
  1016. // prevents to create another one.
  1017. if len(networks) > 0 {
  1018. logrus.Warnf("a network with name %s exists but was not created by compose.\n"+
  1019. "Set `external: true` to use an existing network", n.Name)
  1020. return nil
  1021. }
  1022. var ipam *network.IPAM
  1023. if n.Ipam.Config != nil {
  1024. var config []network.IPAMConfig
  1025. for _, pool := range n.Ipam.Config {
  1026. config = append(config, network.IPAMConfig{
  1027. Subnet: pool.Subnet,
  1028. IPRange: pool.IPRange,
  1029. Gateway: pool.Gateway,
  1030. AuxAddress: pool.AuxiliaryAddresses,
  1031. })
  1032. }
  1033. ipam = &network.IPAM{
  1034. Driver: n.Ipam.Driver,
  1035. Config: config,
  1036. }
  1037. }
  1038. createOpts := moby.NetworkCreate{
  1039. CheckDuplicate: true,
  1040. Labels: n.Labels,
  1041. Driver: n.Driver,
  1042. Options: n.DriverOpts,
  1043. Internal: n.Internal,
  1044. Attachable: n.Attachable,
  1045. IPAM: ipam,
  1046. EnableIPv6: n.EnableIPv6,
  1047. }
  1048. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  1049. createOpts.IPAM = &network.IPAM{}
  1050. }
  1051. if n.Ipam.Driver != "" {
  1052. createOpts.IPAM.Driver = n.Ipam.Driver
  1053. }
  1054. for _, ipamConfig := range n.Ipam.Config {
  1055. config := network.IPAMConfig{
  1056. Subnet: ipamConfig.Subnet,
  1057. IPRange: ipamConfig.IPRange,
  1058. Gateway: ipamConfig.Gateway,
  1059. AuxAddress: ipamConfig.AuxiliaryAddresses,
  1060. }
  1061. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  1062. }
  1063. networkEventName := fmt.Sprintf("Network %s", n.Name)
  1064. w := progress.ContextWriter(ctx)
  1065. w.Event(progress.CreatingEvent(networkEventName))
  1066. _, err = s.apiClient().NetworkCreate(ctx, n.Name, createOpts)
  1067. if err != nil {
  1068. w.Event(progress.ErrorEvent(networkEventName))
  1069. return errors.Wrapf(err, "failed to create network %s", n.Name)
  1070. }
  1071. w.Event(progress.CreatedEvent(networkEventName))
  1072. return nil
  1073. }
  1074. func (s *composeService) resolveExternalNetwork(ctx context.Context, n *types.NetworkConfig) error {
  1075. // NetworkInspect will match on ID prefix, so NetworkList with a name
  1076. // filter is used to look for an exact match to prevent e.g. a network
  1077. // named `db` from getting erroneously matched to a network with an ID
  1078. // like `db9086999caf`
  1079. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  1080. Filters: filters.NewArgs(filters.Arg("name", n.Name)),
  1081. })
  1082. if err != nil {
  1083. return err
  1084. }
  1085. // NetworkList API doesn't return the exact name match, so we can retrieve more than one network with a request
  1086. networks = utils.Filter(networks, func(net moby.NetworkResource) bool {
  1087. return net.Name == n.Name
  1088. })
  1089. switch len(networks) {
  1090. case 1:
  1091. n.Name = networks[0].ID
  1092. return nil
  1093. case 0:
  1094. if n.Driver == "overlay" {
  1095. // Swarm nodes do not register overlay networks that were
  1096. // created on a different node unless they're in use.
  1097. // Here we assume `driver` is relevant for a network we don't manage
  1098. // which is a non-sense, but this is our legacy ¯\(ツ)/¯
  1099. // networkAttach will later fail anyway if network actually doesn't exists
  1100. enabled, err := s.isSWarmEnabled(ctx)
  1101. if err != nil {
  1102. return err
  1103. }
  1104. if enabled {
  1105. return nil
  1106. }
  1107. }
  1108. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  1109. default:
  1110. return fmt.Errorf("multiple networks with name %q were found. Use network ID as `name` to avoid ambiguity", n.Name)
  1111. }
  1112. }
  1113. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig, project string) error {
  1114. inspected, err := s.apiClient().VolumeInspect(ctx, volume.Name)
  1115. if err != nil {
  1116. if !errdefs.IsNotFound(err) {
  1117. return err
  1118. }
  1119. if volume.External.External {
  1120. return fmt.Errorf("external volume %q not found", volume.Name)
  1121. }
  1122. err := s.createVolume(ctx, volume)
  1123. return err
  1124. }
  1125. if volume.External.External {
  1126. return nil
  1127. }
  1128. // Volume exists with name, but let's double-check this is the expected one
  1129. p, ok := inspected.Labels[api.ProjectLabel]
  1130. if !ok {
  1131. logrus.Warnf("volume %q already exists but was not created by Docker Compose. Use `external: true` to use an existing volume", volume.Name)
  1132. }
  1133. if ok && p != project {
  1134. 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)
  1135. }
  1136. return nil
  1137. }
  1138. func (s *composeService) createVolume(ctx context.Context, volume types.VolumeConfig) error {
  1139. eventName := fmt.Sprintf("Volume %q", volume.Name)
  1140. w := progress.ContextWriter(ctx)
  1141. w.Event(progress.CreatingEvent(eventName))
  1142. _, err := s.apiClient().VolumeCreate(ctx, volume_api.CreateOptions{
  1143. Labels: volume.Labels,
  1144. Name: volume.Name,
  1145. Driver: volume.Driver,
  1146. DriverOpts: volume.DriverOpts,
  1147. })
  1148. if err != nil {
  1149. w.Event(progress.ErrorEvent(eventName))
  1150. return err
  1151. }
  1152. w.Event(progress.CreatedEvent(eventName))
  1153. return nil
  1154. }