create.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  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. "github.com/compose-spec/compose-go/types"
  25. moby "github.com/docker/docker/api/types"
  26. "github.com/docker/docker/api/types/blkiodev"
  27. "github.com/docker/docker/api/types/container"
  28. "github.com/docker/docker/api/types/filters"
  29. "github.com/docker/docker/api/types/mount"
  30. "github.com/docker/docker/api/types/network"
  31. "github.com/docker/docker/api/types/strslice"
  32. volume_api "github.com/docker/docker/api/types/volume"
  33. "github.com/docker/docker/errdefs"
  34. "github.com/docker/go-connections/nat"
  35. "github.com/docker/go-units"
  36. "github.com/pkg/errors"
  37. "github.com/sirupsen/logrus"
  38. "github.com/docker/compose/v2/pkg/api"
  39. "github.com/docker/compose/v2/pkg/progress"
  40. "github.com/docker/compose/v2/pkg/utils"
  41. )
  42. func (s *composeService) Create(ctx context.Context, project *types.Project, options api.CreateOptions) error {
  43. return progress.Run(ctx, func(ctx context.Context) error {
  44. return s.create(ctx, project, options)
  45. })
  46. }
  47. func (s *composeService) create(ctx context.Context, project *types.Project, options api.CreateOptions) error {
  48. if len(options.Services) == 0 {
  49. options.Services = project.ServiceNames()
  50. }
  51. var observedState Containers
  52. observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true)
  53. if err != nil {
  54. return err
  55. }
  56. err = s.ensureImagesExists(ctx, project, options.QuietPull)
  57. if err != nil {
  58. return err
  59. }
  60. prepareNetworks(project)
  61. err = prepareVolumes(project)
  62. if err != nil {
  63. return err
  64. }
  65. if err := s.ensureNetworks(ctx, project.Networks); err != nil {
  66. return err
  67. }
  68. if err := s.ensureProjectVolumes(ctx, project); err != nil {
  69. return err
  70. }
  71. allServices := project.AllServices()
  72. allServiceNames := []string{}
  73. for _, service := range allServices {
  74. allServiceNames = append(allServiceNames, service.Name)
  75. }
  76. orphans := observedState.filter(isNotService(allServiceNames...))
  77. if len(orphans) > 0 && !options.IgnoreOrphans {
  78. if options.RemoveOrphans {
  79. w := progress.ContextWriter(ctx)
  80. err := s.removeContainers(ctx, w, orphans, nil, false)
  81. if err != nil {
  82. return err
  83. }
  84. } else {
  85. logrus.Warnf("Found orphan containers (%s) for this project. If "+
  86. "you removed or renamed this service in your compose "+
  87. "file, you can run this command with the "+
  88. "--remove-orphans flag to clean it up.", orphans.names())
  89. }
  90. }
  91. err = prepareServicesDependsOn(project)
  92. if err != nil {
  93. return err
  94. }
  95. return newConvergence(options.Services, observedState, s).apply(ctx, project, options)
  96. }
  97. func prepareVolumes(p *types.Project) error {
  98. for i := range p.Services {
  99. volumesFrom, dependServices, err := getVolumesFrom(p, p.Services[i].VolumesFrom)
  100. if err != nil {
  101. return err
  102. }
  103. p.Services[i].VolumesFrom = volumesFrom
  104. if len(dependServices) > 0 {
  105. if p.Services[i].DependsOn == nil {
  106. p.Services[i].DependsOn = make(types.DependsOnConfig, len(dependServices))
  107. }
  108. for _, service := range p.Services {
  109. if utils.StringContains(dependServices, service.Name) &&
  110. p.Services[i].DependsOn[service.Name].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. volumeMounts, 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. Volumes: volumeMounts,
  252. StopTimeout: ToSeconds(service.StopGracePeriod),
  253. }
  254. portBindings := buildContainerPortBindingOptions(service)
  255. resources := getDeployResources(service)
  256. if service.NetworkMode == "" {
  257. service.NetworkMode = getDefaultNetworkMode(p, service)
  258. }
  259. var networkConfig *network.NetworkingConfig
  260. for _, id := range service.NetworksByPriority() {
  261. net := p.Networks[id]
  262. config := service.Networks[id]
  263. var ipam *network.EndpointIPAMConfig
  264. var (
  265. ipv4Address string
  266. ipv6Address string
  267. )
  268. if config != nil {
  269. ipv4Address = config.Ipv4Address
  270. ipv6Address = config.Ipv6Address
  271. ipam = &network.EndpointIPAMConfig{
  272. IPv4Address: ipv4Address,
  273. IPv6Address: ipv6Address,
  274. LinkLocalIPs: config.LinkLocalIPs,
  275. }
  276. }
  277. networkConfig = &network.NetworkingConfig{
  278. EndpointsConfig: map[string]*network.EndpointSettings{
  279. net.Name: {
  280. Aliases: getAliases(service, config),
  281. IPAddress: ipv4Address,
  282. IPv6Gateway: ipv6Address,
  283. IPAMConfig: ipam,
  284. },
  285. },
  286. }
  287. break //nolint:staticcheck
  288. }
  289. tmpfs := map[string]string{}
  290. for _, t := range service.Tmpfs {
  291. if arr := strings.SplitN(t, ":", 2); len(arr) > 1 {
  292. tmpfs[arr[0]] = arr[1]
  293. } else {
  294. tmpfs[arr[0]] = ""
  295. }
  296. }
  297. var logConfig container.LogConfig
  298. if service.Logging != nil {
  299. logConfig = container.LogConfig{
  300. Type: service.Logging.Driver,
  301. Config: service.Logging.Options,
  302. }
  303. }
  304. var volumesFrom []string
  305. for _, v := range service.VolumesFrom {
  306. if !strings.HasPrefix(v, "container:") {
  307. return nil, nil, nil, fmt.Errorf("invalid volume_from: %s", v)
  308. }
  309. volumesFrom = append(volumesFrom, v[len("container:"):])
  310. }
  311. links, err := s.getLinks(ctx, p.Name, service, number)
  312. if err != nil {
  313. return nil, nil, nil, err
  314. }
  315. securityOpts, err := parseSecurityOpts(p, service.SecurityOpt)
  316. if err != nil {
  317. return nil, nil, nil, err
  318. }
  319. hostConfig := container.HostConfig{
  320. AutoRemove: autoRemove,
  321. Binds: binds,
  322. Mounts: mounts,
  323. CapAdd: strslice.StrSlice(service.CapAdd),
  324. CapDrop: strslice.StrSlice(service.CapDrop),
  325. NetworkMode: container.NetworkMode(service.NetworkMode),
  326. Init: service.Init,
  327. IpcMode: container.IpcMode(service.Ipc),
  328. ReadonlyRootfs: service.ReadOnly,
  329. RestartPolicy: getRestartPolicy(service),
  330. ShmSize: int64(service.ShmSize),
  331. Sysctls: service.Sysctls,
  332. PortBindings: portBindings,
  333. Resources: resources,
  334. VolumeDriver: service.VolumeDriver,
  335. VolumesFrom: volumesFrom,
  336. DNS: service.DNS,
  337. DNSSearch: service.DNSSearch,
  338. DNSOptions: service.DNSOpts,
  339. ExtraHosts: service.ExtraHosts.AsList(),
  340. SecurityOpt: securityOpts,
  341. UsernsMode: container.UsernsMode(service.UserNSMode),
  342. Privileged: service.Privileged,
  343. PidMode: container.PidMode(service.Pid),
  344. Tmpfs: tmpfs,
  345. Isolation: container.Isolation(service.Isolation),
  346. Runtime: service.Runtime,
  347. LogConfig: logConfig,
  348. GroupAdd: service.GroupAdd,
  349. Links: links,
  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(ctx context.Context, p types.Project, service types.ServiceConfig,
  654. inherit *moby.Container) (map[string]struct{}, []string, []mount.Mount, error) {
  655. var mounts = []mount.Mount{}
  656. image := api.GetImageNameOrDefault(service, p.Name)
  657. imgInspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, image)
  658. if err != nil {
  659. return nil, nil, nil, err
  660. }
  661. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  662. if err != nil {
  663. return nil, nil, nil, err
  664. }
  665. volumeMounts := map[string]struct{}{}
  666. binds := []string{}
  667. MOUNTS:
  668. for _, m := range mountOptions {
  669. if m.Type == mount.TypeNamedPipe {
  670. mounts = append(mounts, m)
  671. continue
  672. }
  673. volumeMounts[m.Target] = struct{}{}
  674. if m.Type == mount.TypeBind {
  675. // `Mount` is preferred but does not offer option to created host path if missing
  676. // so `Bind` API is used here with raw volume string
  677. // see https://github.com/moby/moby/issues/43483
  678. for _, v := range service.Volumes {
  679. if v.Target == m.Target {
  680. switch {
  681. case string(m.Type) != v.Type:
  682. v.Source = m.Source
  683. fallthrough
  684. case v.Bind != nil && v.Bind.CreateHostPath:
  685. binds = append(binds, v.String())
  686. continue MOUNTS
  687. }
  688. }
  689. }
  690. }
  691. mounts = append(mounts, m)
  692. }
  693. return volumeMounts, binds, mounts, nil
  694. }
  695. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  696. var mounts = map[string]mount.Mount{}
  697. if inherit != nil {
  698. for _, m := range inherit.Mounts {
  699. if m.Type == "tmpfs" {
  700. continue
  701. }
  702. src := m.Source
  703. if m.Type == "volume" {
  704. src = m.Name
  705. }
  706. m.Destination = path.Clean(m.Destination)
  707. if img.Config != nil {
  708. if _, ok := img.Config.Volumes[m.Destination]; ok {
  709. // inherit previous container's anonymous volume
  710. mounts[m.Destination] = mount.Mount{
  711. Type: m.Type,
  712. Source: src,
  713. Target: m.Destination,
  714. ReadOnly: !m.RW,
  715. }
  716. }
  717. }
  718. volumes := []types.ServiceVolumeConfig{}
  719. for _, v := range s.Volumes {
  720. if v.Target != m.Destination || v.Source != "" {
  721. volumes = append(volumes, v)
  722. continue
  723. }
  724. // inherit previous container's anonymous volume
  725. mounts[m.Destination] = mount.Mount{
  726. Type: m.Type,
  727. Source: src,
  728. Target: m.Destination,
  729. ReadOnly: !m.RW,
  730. }
  731. }
  732. s.Volumes = volumes
  733. }
  734. }
  735. mounts, err := fillBindMounts(p, s, mounts)
  736. if err != nil {
  737. return nil, err
  738. }
  739. values := make([]mount.Mount, 0, len(mounts))
  740. for _, v := range mounts {
  741. values = append(values, v)
  742. }
  743. return values, nil
  744. }
  745. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  746. for _, v := range s.Volumes {
  747. bindMount, err := buildMount(p, v)
  748. if err != nil {
  749. return nil, err
  750. }
  751. m[bindMount.Target] = bindMount
  752. }
  753. secrets, err := buildContainerSecretMounts(p, s)
  754. if err != nil {
  755. return nil, err
  756. }
  757. for _, s := range secrets {
  758. if _, found := m[s.Target]; found {
  759. continue
  760. }
  761. m[s.Target] = s
  762. }
  763. configs, err := buildContainerConfigMounts(p, s)
  764. if err != nil {
  765. return nil, err
  766. }
  767. for _, c := range configs {
  768. if _, found := m[c.Target]; found {
  769. continue
  770. }
  771. m[c.Target] = c
  772. }
  773. return m, nil
  774. }
  775. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  776. var mounts = map[string]mount.Mount{}
  777. configsBaseDir := "/"
  778. for _, config := range s.Configs {
  779. target := config.Target
  780. if config.Target == "" {
  781. target = configsBaseDir + config.Source
  782. } else if !isUnixAbs(config.Target) {
  783. target = configsBaseDir + config.Target
  784. }
  785. definedConfig := p.Configs[config.Source]
  786. if definedConfig.External.External {
  787. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  788. }
  789. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  790. Type: types.VolumeTypeBind,
  791. Source: definedConfig.File,
  792. Target: target,
  793. ReadOnly: true,
  794. })
  795. if err != nil {
  796. return nil, err
  797. }
  798. mounts[target] = bindMount
  799. }
  800. values := make([]mount.Mount, 0, len(mounts))
  801. for _, v := range mounts {
  802. values = append(values, v)
  803. }
  804. return values, nil
  805. }
  806. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  807. var mounts = map[string]mount.Mount{}
  808. secretsDir := "/run/secrets/"
  809. for _, secret := range s.Secrets {
  810. target := secret.Target
  811. if secret.Target == "" {
  812. target = secretsDir + secret.Source
  813. } else if !isUnixAbs(secret.Target) {
  814. target = secretsDir + secret.Target
  815. }
  816. definedSecret := p.Secrets[secret.Source]
  817. if definedSecret.External.External {
  818. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  819. }
  820. if definedSecret.Environment != "" {
  821. continue
  822. }
  823. mnt, err := buildMount(p, types.ServiceVolumeConfig{
  824. Type: types.VolumeTypeBind,
  825. Source: definedSecret.File,
  826. Target: target,
  827. ReadOnly: true,
  828. })
  829. if err != nil {
  830. return nil, err
  831. }
  832. mounts[target] = mnt
  833. }
  834. values := make([]mount.Mount, 0, len(mounts))
  835. for _, v := range mounts {
  836. values = append(values, v)
  837. }
  838. return values, nil
  839. }
  840. func isUnixAbs(p string) bool {
  841. return strings.HasPrefix(p, "/")
  842. }
  843. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  844. source := volume.Source
  845. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  846. // do not replace these with filepath.Abs(source) that will include a default drive.
  847. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  848. // volume source has already been prefixed with workdir if required, by compose-go project loader
  849. var err error
  850. source, err = filepath.Abs(source)
  851. if err != nil {
  852. return mount.Mount{}, err
  853. }
  854. }
  855. if volume.Type == types.VolumeTypeVolume {
  856. if volume.Source != "" {
  857. pVolume, ok := project.Volumes[volume.Source]
  858. if ok {
  859. source = pVolume.Name
  860. }
  861. }
  862. }
  863. bind, vol, tmpfs := buildMountOptions(project, volume)
  864. volume.Target = path.Clean(volume.Target)
  865. if bind != nil {
  866. volume.Type = types.VolumeTypeBind
  867. }
  868. return mount.Mount{
  869. Type: mount.Type(volume.Type),
  870. Source: source,
  871. Target: volume.Target,
  872. ReadOnly: volume.ReadOnly,
  873. Consistency: mount.Consistency(volume.Consistency),
  874. BindOptions: bind,
  875. VolumeOptions: vol,
  876. TmpfsOptions: tmpfs,
  877. }, nil
  878. }
  879. func buildMountOptions(project types.Project, volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  880. switch volume.Type {
  881. case "bind":
  882. if volume.Volume != nil {
  883. logrus.Warnf("mount of type `bind` should not define `volume` option")
  884. }
  885. if volume.Tmpfs != nil {
  886. logrus.Warnf("mount of type `tmpfs` should not define `tmpfs` option")
  887. }
  888. return buildBindOption(volume.Bind), nil, nil
  889. case "volume":
  890. if volume.Bind != nil {
  891. logrus.Warnf("mount of type `volume` should not define `bind` option")
  892. }
  893. if volume.Tmpfs != nil {
  894. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  895. }
  896. if v, ok := project.Volumes[volume.Source]; ok && v.DriverOpts["o"] == types.VolumeTypeBind {
  897. return buildBindOption(&types.ServiceVolumeBind{
  898. CreateHostPath: true,
  899. }), nil, nil
  900. }
  901. return nil, buildVolumeOptions(volume.Volume), nil
  902. case "tmpfs":
  903. if volume.Bind != nil {
  904. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  905. }
  906. if volume.Volume != nil {
  907. logrus.Warnf("mount of type `tmpfs` should not define `volume` option")
  908. }
  909. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  910. }
  911. return nil, nil, nil
  912. }
  913. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  914. if bind == nil {
  915. return nil
  916. }
  917. return &mount.BindOptions{
  918. Propagation: mount.Propagation(bind.Propagation),
  919. // NonRecursive: false, FIXME missing from model ?
  920. }
  921. }
  922. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  923. if vol == nil {
  924. return nil
  925. }
  926. return &mount.VolumeOptions{
  927. NoCopy: vol.NoCopy,
  928. // Labels: , // FIXME missing from model ?
  929. // DriverConfig: , // FIXME missing from model ?
  930. }
  931. }
  932. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  933. if tmpfs == nil {
  934. return nil
  935. }
  936. return &mount.TmpfsOptions{
  937. SizeBytes: int64(tmpfs.Size),
  938. // Mode: , // FIXME missing from model ?
  939. }
  940. }
  941. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  942. aliases := []string{s.Name}
  943. if c != nil {
  944. aliases = append(aliases, c.Aliases...)
  945. }
  946. return aliases
  947. }
  948. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  949. // NetworkInspect will match on ID prefix, so NetworkList with a name
  950. // filter is used to look for an exact match to prevent e.g. a network
  951. // named `db` from getting erroneously matched to a network with an ID
  952. // like `db9086999caf`
  953. networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{
  954. Filters: filters.NewArgs(filters.Arg("name", n.Name)),
  955. })
  956. if err != nil {
  957. return err
  958. }
  959. networkNotFound := true
  960. for _, net := range networks {
  961. if net.Name == n.Name {
  962. networkNotFound = false
  963. break
  964. }
  965. }
  966. if networkNotFound {
  967. if n.External.External {
  968. if n.Driver == "overlay" {
  969. // Swarm nodes do not register overlay networks that were
  970. // created on a different node unless they're in use.
  971. // Here we assume `driver` is relevant for a network we don't manage
  972. // which is a non-sense, but this is our legacy ¯\(ツ)/¯
  973. // networkAttach will later fail anyway if network actually doesn't exists
  974. return nil
  975. }
  976. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  977. }
  978. var ipam *network.IPAM
  979. if n.Ipam.Config != nil {
  980. var config []network.IPAMConfig
  981. for _, pool := range n.Ipam.Config {
  982. config = append(config, network.IPAMConfig{
  983. Subnet: pool.Subnet,
  984. IPRange: pool.IPRange,
  985. Gateway: pool.Gateway,
  986. AuxAddress: pool.AuxiliaryAddresses,
  987. })
  988. }
  989. ipam = &network.IPAM{
  990. Driver: n.Ipam.Driver,
  991. Config: config,
  992. }
  993. }
  994. createOpts := moby.NetworkCreate{
  995. CheckDuplicate: true,
  996. // TODO NameSpace Labels
  997. Labels: n.Labels,
  998. Driver: n.Driver,
  999. Options: n.DriverOpts,
  1000. Internal: n.Internal,
  1001. Attachable: n.Attachable,
  1002. IPAM: ipam,
  1003. EnableIPv6: n.EnableIPv6,
  1004. }
  1005. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  1006. createOpts.IPAM = &network.IPAM{}
  1007. }
  1008. if n.Ipam.Driver != "" {
  1009. createOpts.IPAM.Driver = n.Ipam.Driver
  1010. }
  1011. for _, ipamConfig := range n.Ipam.Config {
  1012. config := network.IPAMConfig{
  1013. Subnet: ipamConfig.Subnet,
  1014. IPRange: ipamConfig.IPRange,
  1015. Gateway: ipamConfig.Gateway,
  1016. AuxAddress: ipamConfig.AuxiliaryAddresses,
  1017. }
  1018. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  1019. }
  1020. networkEventName := fmt.Sprintf("Network %s", n.Name)
  1021. w := progress.ContextWriter(ctx)
  1022. w.Event(progress.CreatingEvent(networkEventName))
  1023. if _, err := s.apiClient().NetworkCreate(ctx, n.Name, createOpts); err != nil {
  1024. w.Event(progress.ErrorEvent(networkEventName))
  1025. return errors.Wrapf(err, "failed to create network %s", n.Name)
  1026. }
  1027. w.Event(progress.CreatedEvent(networkEventName))
  1028. return nil
  1029. }
  1030. return nil
  1031. }
  1032. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig, project string) error {
  1033. inspected, err := s.apiClient().VolumeInspect(ctx, volume.Name)
  1034. if err != nil {
  1035. if !errdefs.IsNotFound(err) {
  1036. return err
  1037. }
  1038. if volume.External.External {
  1039. return fmt.Errorf("external volume %q not found", volume.Name)
  1040. }
  1041. err := s.createVolume(ctx, volume)
  1042. return err
  1043. }
  1044. if volume.External.External {
  1045. return nil
  1046. }
  1047. // Volume exists with name, but let's double-check this is the expected one
  1048. p, ok := inspected.Labels[api.ProjectLabel]
  1049. if !ok {
  1050. logrus.Warnf("volume %q already exists but was not created by Docker Compose. Use `external: true` to use an existing volume", volume.Name)
  1051. }
  1052. if ok && p != project {
  1053. logrus.Warnf("volume %q already exists but was not created for project %q. Use `external: true` to use an existing volume", volume.Name, p)
  1054. }
  1055. return nil
  1056. }
  1057. func (s *composeService) createVolume(ctx context.Context, volume types.VolumeConfig) error {
  1058. eventName := fmt.Sprintf("Volume %q", volume.Name)
  1059. w := progress.ContextWriter(ctx)
  1060. w.Event(progress.CreatingEvent(eventName))
  1061. _, err := s.apiClient().VolumeCreate(ctx, volume_api.CreateOptions{
  1062. Labels: volume.Labels,
  1063. Name: volume.Name,
  1064. Driver: volume.Driver,
  1065. DriverOpts: volume.DriverOpts,
  1066. })
  1067. if err != nil {
  1068. w.Event(progress.ErrorEvent(eventName))
  1069. return err
  1070. }
  1071. w.Event(progress.CreatedEvent(eventName))
  1072. return nil
  1073. }