create.go 32 KB

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