create.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  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. if len(dependencies) == 0 {
  152. continue
  153. }
  154. if service.DependsOn == nil {
  155. service.DependsOn = make(types.DependsOnConfig)
  156. }
  157. deps, err := p.GetServices(dependencies...)
  158. if err != nil {
  159. return err
  160. }
  161. for _, d := range deps {
  162. if _, ok := service.DependsOn[d.Name]; !ok {
  163. service.DependsOn[d.Name] = types.ServiceDependency{
  164. Condition: types.ServiceConditionStarted,
  165. }
  166. }
  167. }
  168. p.Services[i] = service
  169. }
  170. return nil
  171. }
  172. func (s *composeService) ensureNetworks(ctx context.Context, networks types.Networks) error {
  173. for _, network := range networks {
  174. err := s.ensureNetwork(ctx, network)
  175. if err != nil {
  176. return err
  177. }
  178. }
  179. return nil
  180. }
  181. func (s *composeService) ensureProjectVolumes(ctx context.Context, project *types.Project) error {
  182. for k, volume := range project.Volumes {
  183. volume.Labels = volume.Labels.Add(api.VolumeLabel, k)
  184. volume.Labels = volume.Labels.Add(api.ProjectLabel, project.Name)
  185. volume.Labels = volume.Labels.Add(api.VersionLabel, api.ComposeVersion)
  186. err := s.ensureVolume(ctx, volume, project.Name)
  187. if err != nil {
  188. return err
  189. }
  190. }
  191. return nil
  192. }
  193. func getImageName(service types.ServiceConfig, projectName string) string {
  194. imageName := service.Image
  195. if imageName == "" {
  196. imageName = projectName + "_" + service.Name
  197. }
  198. return imageName
  199. }
  200. func (s *composeService) getCreateOptions(ctx context.Context, p *types.Project, service types.ServiceConfig,
  201. number int, inherit *moby.Container, autoRemove bool, attachStdin bool) (*container.Config, *container.HostConfig, *network.NetworkingConfig, error) {
  202. labels, err := s.prepareLabels(p, service, number)
  203. if err != nil {
  204. return nil, nil, nil, err
  205. }
  206. var (
  207. runCmd strslice.StrSlice
  208. entrypoint strslice.StrSlice
  209. )
  210. if service.Command != nil {
  211. runCmd = strslice.StrSlice(service.Command)
  212. }
  213. if service.Entrypoint != nil {
  214. entrypoint = strslice.StrSlice(service.Entrypoint)
  215. }
  216. var (
  217. tty = service.Tty
  218. stdinOpen = service.StdinOpen
  219. )
  220. volumeMounts, binds, mounts, err := s.buildContainerVolumes(ctx, *p, service, inherit)
  221. if err != nil {
  222. return nil, nil, nil, err
  223. }
  224. proxyConfig := types.MappingWithEquals(s.configFile.ParseProxyConfig(s.apiClient.DaemonHost(), nil))
  225. env := proxyConfig.OverrideBy(service.Environment)
  226. containerConfig := container.Config{
  227. Hostname: service.Hostname,
  228. Domainname: service.DomainName,
  229. User: service.User,
  230. ExposedPorts: buildContainerPorts(service),
  231. Tty: tty,
  232. OpenStdin: stdinOpen,
  233. StdinOnce: attachStdin && stdinOpen,
  234. AttachStdin: attachStdin,
  235. AttachStderr: true,
  236. AttachStdout: true,
  237. Cmd: runCmd,
  238. Image: getImageName(service, p.Name),
  239. WorkingDir: service.WorkingDir,
  240. Entrypoint: entrypoint,
  241. NetworkDisabled: service.NetworkMode == "disabled",
  242. MacAddress: service.MacAddress,
  243. Labels: labels,
  244. StopSignal: service.StopSignal,
  245. Env: ToMobyEnv(env),
  246. Healthcheck: ToMobyHealthCheck(service.HealthCheck),
  247. Volumes: volumeMounts,
  248. StopTimeout: ToSeconds(service.StopGracePeriod),
  249. }
  250. portBindings := buildContainerPortBindingOptions(service)
  251. resources := getDeployResources(service)
  252. if service.NetworkMode == "" {
  253. service.NetworkMode = getDefaultNetworkMode(p, service)
  254. }
  255. var networkConfig *network.NetworkingConfig
  256. for _, id := range service.NetworksByPriority() {
  257. net := p.Networks[id]
  258. config := service.Networks[id]
  259. var ipam *network.EndpointIPAMConfig
  260. var (
  261. ipv4Address string
  262. ipv6Address string
  263. )
  264. if config != nil {
  265. ipv4Address = config.Ipv4Address
  266. ipv6Address = config.Ipv6Address
  267. ipam = &network.EndpointIPAMConfig{
  268. IPv4Address: ipv4Address,
  269. IPv6Address: ipv6Address,
  270. }
  271. }
  272. networkConfig = &network.NetworkingConfig{
  273. EndpointsConfig: map[string]*network.EndpointSettings{
  274. net.Name: {
  275. Aliases: getAliases(service, config),
  276. IPAddress: ipv4Address,
  277. IPv6Gateway: ipv6Address,
  278. IPAMConfig: ipam,
  279. },
  280. },
  281. }
  282. break //nolint:staticcheck
  283. }
  284. tmpfs := map[string]string{}
  285. for _, t := range service.Tmpfs {
  286. if arr := strings.SplitN(t, ":", 2); len(arr) > 1 {
  287. tmpfs[arr[0]] = arr[1]
  288. } else {
  289. tmpfs[arr[0]] = ""
  290. }
  291. }
  292. var logConfig container.LogConfig
  293. if service.Logging != nil {
  294. logConfig = container.LogConfig{
  295. Type: service.Logging.Driver,
  296. Config: service.Logging.Options,
  297. }
  298. }
  299. var volumesFrom []string
  300. for _, v := range service.VolumesFrom {
  301. if !strings.HasPrefix(v, "container:") {
  302. return nil, nil, nil, fmt.Errorf("invalid volume_from: %s", v)
  303. }
  304. volumesFrom = append(volumesFrom, v[len("container:"):])
  305. }
  306. securityOpts, err := parseSecurityOpts(p, service.SecurityOpt)
  307. if err != nil {
  308. return nil, nil, nil, err
  309. }
  310. hostConfig := container.HostConfig{
  311. AutoRemove: autoRemove,
  312. Binds: binds,
  313. Mounts: mounts,
  314. CapAdd: strslice.StrSlice(service.CapAdd),
  315. CapDrop: strslice.StrSlice(service.CapDrop),
  316. NetworkMode: container.NetworkMode(service.NetworkMode),
  317. Init: service.Init,
  318. IpcMode: container.IpcMode(service.Ipc),
  319. ReadonlyRootfs: service.ReadOnly,
  320. RestartPolicy: getRestartPolicy(service),
  321. ShmSize: int64(service.ShmSize),
  322. Sysctls: service.Sysctls,
  323. PortBindings: portBindings,
  324. Resources: resources,
  325. VolumeDriver: service.VolumeDriver,
  326. VolumesFrom: volumesFrom,
  327. DNS: service.DNS,
  328. DNSSearch: service.DNSSearch,
  329. DNSOptions: service.DNSOpts,
  330. ExtraHosts: service.ExtraHosts,
  331. SecurityOpt: securityOpts,
  332. UsernsMode: container.UsernsMode(service.UserNSMode),
  333. Privileged: service.Privileged,
  334. PidMode: container.PidMode(service.Pid),
  335. Tmpfs: tmpfs,
  336. Isolation: container.Isolation(service.Isolation),
  337. Runtime: service.Runtime,
  338. LogConfig: logConfig,
  339. }
  340. return &containerConfig, &hostConfig, networkConfig, nil
  341. }
  342. // copy/pasted from https://github.com/docker/cli/blob/9de1b162f/cli/command/container/opts.go#L673-L697 + RelativePath
  343. // TODO find so way to share this code with docker/cli
  344. func parseSecurityOpts(p *types.Project, securityOpts []string) ([]string, error) {
  345. for key, opt := range securityOpts {
  346. con := strings.SplitN(opt, "=", 2)
  347. if len(con) == 1 && con[0] != "no-new-privileges" {
  348. if strings.Contains(opt, ":") {
  349. con = strings.SplitN(opt, ":", 2)
  350. } else {
  351. return securityOpts, errors.Errorf("Invalid security-opt: %q", opt)
  352. }
  353. }
  354. if con[0] == "seccomp" && con[1] != "unconfined" {
  355. f, err := ioutil.ReadFile(p.RelativePath(con[1]))
  356. if err != nil {
  357. return securityOpts, errors.Errorf("opening seccomp profile (%s) failed: %v", con[1], err)
  358. }
  359. b := bytes.NewBuffer(nil)
  360. if err := json.Compact(b, f); err != nil {
  361. return securityOpts, errors.Errorf("compacting json for seccomp profile (%s) failed: %v", con[1], err)
  362. }
  363. securityOpts[key] = fmt.Sprintf("seccomp=%s", b.Bytes())
  364. }
  365. }
  366. return securityOpts, nil
  367. }
  368. func (s *composeService) prepareLabels(p *types.Project, service types.ServiceConfig, number int) (map[string]string, error) {
  369. labels := map[string]string{}
  370. for k, v := range service.Labels {
  371. labels[k] = v
  372. }
  373. labels[api.ProjectLabel] = p.Name
  374. labels[api.ServiceLabel] = service.Name
  375. labels[api.VersionLabel] = api.ComposeVersion
  376. if _, ok := service.Labels[api.OneoffLabel]; !ok {
  377. labels[api.OneoffLabel] = "False"
  378. }
  379. hash, err := ServiceHash(service)
  380. if err != nil {
  381. return nil, err
  382. }
  383. labels[api.ConfigHashLabel] = hash
  384. labels[api.WorkingDirLabel] = p.WorkingDir
  385. labels[api.ConfigFilesLabel] = strings.Join(p.ComposeFiles, ",")
  386. labels[api.ContainerNumberLabel] = strconv.Itoa(number)
  387. var dependencies []string
  388. for s := range service.DependsOn {
  389. dependencies = append(dependencies, s)
  390. }
  391. labels[api.DependenciesLabel] = strings.Join(dependencies, ",")
  392. return labels, nil
  393. }
  394. func getDefaultNetworkMode(project *types.Project, service types.ServiceConfig) string {
  395. mode := "none"
  396. if len(project.Networks) > 0 {
  397. for name := range getNetworksForService(service) {
  398. mode = project.Networks[name].Name
  399. break
  400. }
  401. }
  402. return mode
  403. }
  404. func getRestartPolicy(service types.ServiceConfig) container.RestartPolicy {
  405. var restart container.RestartPolicy
  406. if service.Restart != "" {
  407. split := strings.Split(service.Restart, ":")
  408. var attempts int
  409. if len(split) > 1 {
  410. attempts, _ = strconv.Atoi(split[1])
  411. }
  412. restart = container.RestartPolicy{
  413. Name: split[0],
  414. MaximumRetryCount: attempts,
  415. }
  416. }
  417. if service.Deploy != nil && service.Deploy.RestartPolicy != nil {
  418. policy := *service.Deploy.RestartPolicy
  419. var attempts int
  420. if policy.MaxAttempts != nil {
  421. attempts = int(*policy.MaxAttempts)
  422. }
  423. restart = container.RestartPolicy{
  424. Name: policy.Condition,
  425. MaximumRetryCount: attempts,
  426. }
  427. }
  428. return restart
  429. }
  430. func getDeployResources(s types.ServiceConfig) container.Resources {
  431. var swappiness *int64
  432. if s.MemSwappiness != 0 {
  433. val := int64(s.MemSwappiness)
  434. swappiness = &val
  435. }
  436. resources := container.Resources{
  437. CgroupParent: s.CgroupParent,
  438. Memory: int64(s.MemLimit),
  439. MemorySwap: int64(s.MemSwapLimit),
  440. MemorySwappiness: swappiness,
  441. MemoryReservation: int64(s.MemReservation),
  442. OomKillDisable: &s.OomKillDisable,
  443. CPUCount: s.CPUCount,
  444. CPUPeriod: s.CPUPeriod,
  445. CPUQuota: s.CPUQuota,
  446. CPURealtimePeriod: s.CPURTPeriod,
  447. CPURealtimeRuntime: s.CPURTRuntime,
  448. CPUShares: s.CPUShares,
  449. CPUPercent: int64(s.CPUS * 100),
  450. CpusetCpus: s.CPUSet,
  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. bind := bindings[p]
  580. binding := nat.PortBinding{
  581. HostIP: port.HostIP,
  582. }
  583. if port.Published > 0 {
  584. binding.HostPort = fmt.Sprint(port.Published)
  585. }
  586. bind = append(bind, binding)
  587. bindings[p] = bind
  588. }
  589. return bindings
  590. }
  591. func getVolumesFrom(project *types.Project, volumesFrom []string) ([]string, []string, error) {
  592. var volumes = []string{}
  593. var services = []string{}
  594. // parse volumes_from
  595. if len(volumesFrom) == 0 {
  596. return volumes, services, nil
  597. }
  598. for _, vol := range volumesFrom {
  599. spec := strings.Split(vol, ":")
  600. if len(spec) == 0 {
  601. continue
  602. }
  603. if spec[0] == "container" {
  604. volumes = append(volumes, strings.Join(spec[1:], ":"))
  605. continue
  606. }
  607. serviceName := spec[0]
  608. services = append(services, serviceName)
  609. service, err := project.GetService(serviceName)
  610. if err != nil {
  611. return nil, nil, err
  612. }
  613. firstContainer := getContainerName(project.Name, service, 1)
  614. v := fmt.Sprintf("container:%s", firstContainer)
  615. if len(spec) > 2 {
  616. v = fmt.Sprintf("container:%s:%s", firstContainer, strings.Join(spec[1:], ":"))
  617. }
  618. volumes = append(volumes, v)
  619. }
  620. return volumes, services, nil
  621. }
  622. func getDependentServiceFromMode(mode string) string {
  623. if strings.HasPrefix(mode, types.NetworkModeServicePrefix) {
  624. return mode[len(types.NetworkModeServicePrefix):]
  625. }
  626. return ""
  627. }
  628. func (s *composeService) buildContainerVolumes(ctx context.Context, p types.Project, service types.ServiceConfig,
  629. inherit *moby.Container) (map[string]struct{}, []string, []mount.Mount, error) {
  630. var mounts = []mount.Mount{}
  631. image := getImageName(service, p.Name)
  632. imgInspect, _, err := s.apiClient.ImageInspectWithRaw(ctx, image)
  633. if err != nil {
  634. return nil, nil, nil, err
  635. }
  636. mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit)
  637. if err != nil {
  638. return nil, nil, nil, err
  639. }
  640. volumeMounts := map[string]struct{}{}
  641. binds := []string{}
  642. MOUNTS:
  643. for _, m := range mountOptions {
  644. volumeMounts[m.Target] = struct{}{}
  645. // `Bind` API is used when host path need to be created if missing, `Mount` is preferred otherwise
  646. if m.Type == mount.TypeBind || m.Type == mount.TypeNamedPipe {
  647. for _, v := range service.Volumes {
  648. if v.Target == m.Target && v.Bind != nil && v.Bind.CreateHostPath {
  649. mode := "rw"
  650. if m.ReadOnly {
  651. mode = "ro"
  652. }
  653. binds = append(binds, fmt.Sprintf("%s:%s:%s", m.Source, m.Target, mode))
  654. continue MOUNTS
  655. }
  656. }
  657. }
  658. mounts = append(mounts, m)
  659. }
  660. return volumeMounts, binds, mounts, nil
  661. }
  662. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  663. var mounts = map[string]mount.Mount{}
  664. if inherit != nil {
  665. for _, m := range inherit.Mounts {
  666. if m.Type == "tmpfs" {
  667. continue
  668. }
  669. src := m.Source
  670. if m.Type == "volume" {
  671. src = m.Name
  672. }
  673. m.Destination = path.Clean(m.Destination)
  674. if img.Config != nil {
  675. if _, ok := img.Config.Volumes[m.Destination]; ok {
  676. // inherit previous container's anonymous volume
  677. mounts[m.Destination] = mount.Mount{
  678. Type: m.Type,
  679. Source: src,
  680. Target: m.Destination,
  681. ReadOnly: !m.RW,
  682. }
  683. }
  684. }
  685. volumes := []types.ServiceVolumeConfig{}
  686. for _, v := range s.Volumes {
  687. if v.Target != m.Destination || v.Source != "" {
  688. volumes = append(volumes, v)
  689. continue
  690. }
  691. // inherit previous container's anonymous volume
  692. mounts[m.Destination] = mount.Mount{
  693. Type: m.Type,
  694. Source: src,
  695. Target: m.Destination,
  696. ReadOnly: !m.RW,
  697. }
  698. }
  699. s.Volumes = volumes
  700. }
  701. }
  702. mounts, err := fillBindMounts(p, s, mounts)
  703. if err != nil {
  704. return nil, err
  705. }
  706. values := make([]mount.Mount, 0, len(mounts))
  707. for _, v := range mounts {
  708. values = append(values, v)
  709. }
  710. return values, nil
  711. }
  712. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  713. for _, v := range s.Volumes {
  714. bindMount, err := buildMount(p, v)
  715. if err != nil {
  716. return nil, err
  717. }
  718. m[bindMount.Target] = bindMount
  719. }
  720. secrets, err := buildContainerSecretMounts(p, s)
  721. if err != nil {
  722. return nil, err
  723. }
  724. for _, s := range secrets {
  725. if _, found := m[s.Target]; found {
  726. continue
  727. }
  728. m[s.Target] = s
  729. }
  730. configs, err := buildContainerConfigMounts(p, s)
  731. if err != nil {
  732. return nil, err
  733. }
  734. for _, c := range configs {
  735. if _, found := m[c.Target]; found {
  736. continue
  737. }
  738. m[c.Target] = c
  739. }
  740. return m, nil
  741. }
  742. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  743. var mounts = map[string]mount.Mount{}
  744. configsBaseDir := "/"
  745. for _, config := range s.Configs {
  746. target := config.Target
  747. if config.Target == "" {
  748. target = configsBaseDir + config.Source
  749. } else if !isUnixAbs(config.Target) {
  750. target = configsBaseDir + config.Target
  751. }
  752. definedConfig := p.Configs[config.Source]
  753. if definedConfig.External.External {
  754. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  755. }
  756. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  757. Type: types.VolumeTypeBind,
  758. Source: definedConfig.File,
  759. Target: target,
  760. ReadOnly: true,
  761. })
  762. if err != nil {
  763. return nil, err
  764. }
  765. mounts[target] = bindMount
  766. }
  767. values := make([]mount.Mount, 0, len(mounts))
  768. for _, v := range mounts {
  769. values = append(values, v)
  770. }
  771. return values, nil
  772. }
  773. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  774. var mounts = map[string]mount.Mount{}
  775. secretsDir := "/run/secrets/"
  776. for _, secret := range s.Secrets {
  777. target := secret.Target
  778. if secret.Target == "" {
  779. target = secretsDir + secret.Source
  780. } else if !isUnixAbs(secret.Target) {
  781. target = secretsDir + secret.Target
  782. }
  783. definedSecret := p.Secrets[secret.Source]
  784. if definedSecret.External.External {
  785. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  786. }
  787. mount, err := buildMount(p, types.ServiceVolumeConfig{
  788. Type: types.VolumeTypeBind,
  789. Source: definedSecret.File,
  790. Target: target,
  791. ReadOnly: true,
  792. })
  793. if err != nil {
  794. return nil, err
  795. }
  796. mounts[target] = mount
  797. }
  798. values := make([]mount.Mount, 0, len(mounts))
  799. for _, v := range mounts {
  800. values = append(values, v)
  801. }
  802. return values, nil
  803. }
  804. func isUnixAbs(path string) bool {
  805. return strings.HasPrefix(path, "/")
  806. }
  807. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  808. source := volume.Source
  809. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  810. // do not replace these with filepath.Abs(source) that will include a default drive.
  811. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  812. // volume source has already been prefixed with workdir if required, by compose-go project loader
  813. var err error
  814. source, err = filepath.Abs(source)
  815. if err != nil {
  816. return mount.Mount{}, err
  817. }
  818. }
  819. if volume.Type == types.VolumeTypeVolume {
  820. if volume.Source != "" {
  821. pVolume, ok := project.Volumes[volume.Source]
  822. if ok {
  823. source = pVolume.Name
  824. }
  825. }
  826. }
  827. bind, vol, tmpfs := buildMountOptions(volume)
  828. volume.Target = path.Clean(volume.Target)
  829. return mount.Mount{
  830. Type: mount.Type(volume.Type),
  831. Source: source,
  832. Target: volume.Target,
  833. ReadOnly: volume.ReadOnly,
  834. Consistency: mount.Consistency(volume.Consistency),
  835. BindOptions: bind,
  836. VolumeOptions: vol,
  837. TmpfsOptions: tmpfs,
  838. }, nil
  839. }
  840. func buildMountOptions(volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  841. switch volume.Type {
  842. case "bind":
  843. if volume.Volume != nil {
  844. logrus.Warnf("mount of type `bind` should not define `volume` option")
  845. }
  846. if volume.Tmpfs != nil {
  847. logrus.Warnf("mount of type `tmpfs` should not define `tmpfs` option")
  848. }
  849. return buildBindOption(volume.Bind), nil, nil
  850. case "volume":
  851. if volume.Bind != nil {
  852. logrus.Warnf("mount of type `volume` should not define `bind` option")
  853. }
  854. if volume.Tmpfs != nil {
  855. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  856. }
  857. return nil, buildVolumeOptions(volume.Volume), nil
  858. case "tmpfs":
  859. if volume.Bind != nil {
  860. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  861. }
  862. if volume.Volume != nil {
  863. logrus.Warnf("mount of type `tmpfs` should not define `volume` option")
  864. }
  865. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  866. }
  867. return nil, nil, nil
  868. }
  869. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  870. if bind == nil {
  871. return nil
  872. }
  873. return &mount.BindOptions{
  874. Propagation: mount.Propagation(bind.Propagation),
  875. // NonRecursive: false, FIXME missing from model ?
  876. }
  877. }
  878. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  879. if vol == nil {
  880. return nil
  881. }
  882. return &mount.VolumeOptions{
  883. NoCopy: vol.NoCopy,
  884. // Labels: , // FIXME missing from model ?
  885. // DriverConfig: , // FIXME missing from model ?
  886. }
  887. }
  888. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  889. if tmpfs == nil {
  890. return nil
  891. }
  892. return &mount.TmpfsOptions{
  893. SizeBytes: int64(tmpfs.Size),
  894. // Mode: , // FIXME missing from model ?
  895. }
  896. }
  897. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  898. aliases := []string{s.Name}
  899. if c != nil {
  900. aliases = append(aliases, c.Aliases...)
  901. }
  902. return aliases
  903. }
  904. func getNetworksForService(s types.ServiceConfig) map[string]*types.ServiceNetworkConfig {
  905. if len(s.Networks) > 0 {
  906. return s.Networks
  907. }
  908. if s.NetworkMode != "" {
  909. return nil
  910. }
  911. return map[string]*types.ServiceNetworkConfig{"default": nil}
  912. }
  913. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  914. _, err := s.apiClient.NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  915. if err != nil {
  916. if errdefs.IsNotFound(err) {
  917. if n.External.External {
  918. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  919. }
  920. var ipam *network.IPAM
  921. if n.Ipam.Config != nil {
  922. var config []network.IPAMConfig
  923. for _, pool := range n.Ipam.Config {
  924. config = append(config, network.IPAMConfig{
  925. Subnet: pool.Subnet,
  926. IPRange: pool.IPRange,
  927. Gateway: pool.Gateway,
  928. AuxAddress: pool.AuxiliaryAddresses,
  929. })
  930. }
  931. ipam = &network.IPAM{
  932. Driver: n.Ipam.Driver,
  933. Config: config,
  934. }
  935. }
  936. createOpts := moby.NetworkCreate{
  937. // TODO NameSpace Labels
  938. Labels: n.Labels,
  939. Driver: n.Driver,
  940. Options: n.DriverOpts,
  941. Internal: n.Internal,
  942. Attachable: n.Attachable,
  943. IPAM: ipam,
  944. EnableIPv6: n.EnableIPv6,
  945. }
  946. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  947. createOpts.IPAM = &network.IPAM{}
  948. }
  949. if n.Ipam.Driver != "" {
  950. createOpts.IPAM.Driver = n.Ipam.Driver
  951. }
  952. for _, ipamConfig := range n.Ipam.Config {
  953. config := network.IPAMConfig{
  954. Subnet: ipamConfig.Subnet,
  955. }
  956. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  957. }
  958. networkEventName := fmt.Sprintf("Network %s", n.Name)
  959. w := progress.ContextWriter(ctx)
  960. w.Event(progress.CreatingEvent(networkEventName))
  961. if _, err := s.apiClient.NetworkCreate(ctx, n.Name, createOpts); err != nil {
  962. w.Event(progress.ErrorEvent(networkEventName))
  963. return errors.Wrapf(err, "failed to create network %s", n.Name)
  964. }
  965. w.Event(progress.CreatedEvent(networkEventName))
  966. return nil
  967. }
  968. return err
  969. }
  970. return nil
  971. }
  972. func (s *composeService) removeNetwork(ctx context.Context, networkID string, networkName string) error {
  973. w := progress.ContextWriter(ctx)
  974. eventName := fmt.Sprintf("Network %s", networkName)
  975. w.Event(progress.RemovingEvent(eventName))
  976. if err := s.apiClient.NetworkRemove(ctx, networkID); err != nil {
  977. w.Event(progress.ErrorEvent(eventName))
  978. return errors.Wrapf(err, fmt.Sprintf("failed to remove network %s", networkID))
  979. }
  980. w.Event(progress.RemovedEvent(eventName))
  981. return nil
  982. }
  983. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig, project string) error {
  984. inspected, err := s.apiClient.VolumeInspect(ctx, volume.Name)
  985. if err != nil {
  986. if !errdefs.IsNotFound(err) {
  987. return err
  988. }
  989. err := s.createVolume(ctx, volume)
  990. return err
  991. }
  992. // Volume exists with name, but let's double check this is the expected one
  993. // (better safe than sorry when it comes to user's data)
  994. p, ok := inspected.Labels[api.ProjectLabel]
  995. if !ok {
  996. return fmt.Errorf("volume %q already exists but was not created by Docker Compose. Use `external: true` to use an existing volume", volume.Name)
  997. }
  998. if p != project {
  999. return fmt.Errorf("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. }