create.go 36 KB

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