create.go 33 KB

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