create.go 32 KB

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