create.go 31 KB

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