create.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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)
  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. 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. }
  451. setBlkio(s.BlkioConfig, &resources)
  452. if s.Deploy != nil {
  453. setLimits(s.Deploy.Resources.Limits, &resources)
  454. setReservations(s.Deploy.Resources.Reservations, &resources)
  455. }
  456. for _, device := range s.Devices {
  457. // FIXME should use docker/cli parseDevice, unfortunately private
  458. src := ""
  459. dst := ""
  460. permissions := "rwm"
  461. arr := strings.Split(device, ":")
  462. switch len(arr) {
  463. case 3:
  464. permissions = arr[2]
  465. fallthrough
  466. case 2:
  467. dst = arr[1]
  468. fallthrough
  469. case 1:
  470. src = arr[0]
  471. }
  472. if dst == "" {
  473. dst = src
  474. }
  475. resources.Devices = append(resources.Devices, container.DeviceMapping{
  476. PathOnHost: src,
  477. PathInContainer: dst,
  478. CgroupPermissions: permissions,
  479. })
  480. }
  481. for name, u := range s.Ulimits {
  482. soft := u.Single
  483. if u.Soft != 0 {
  484. soft = u.Soft
  485. }
  486. hard := u.Single
  487. if u.Hard != 0 {
  488. hard = u.Hard
  489. }
  490. resources.Ulimits = append(resources.Ulimits, &units.Ulimit{
  491. Name: name,
  492. Hard: int64(hard),
  493. Soft: int64(soft),
  494. })
  495. }
  496. return resources
  497. }
  498. func setReservations(reservations *types.Resource, resources *container.Resources) {
  499. if reservations == nil {
  500. return
  501. }
  502. for _, device := range reservations.Devices {
  503. resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{
  504. Capabilities: [][]string{device.Capabilities},
  505. Count: int(device.Count),
  506. DeviceIDs: device.IDs,
  507. Driver: device.Driver,
  508. })
  509. }
  510. }
  511. func setLimits(limits *types.Resource, resources *container.Resources) {
  512. if limits == nil {
  513. return
  514. }
  515. if limits.MemoryBytes != 0 {
  516. resources.Memory = int64(limits.MemoryBytes)
  517. }
  518. if limits.NanoCPUs != "" {
  519. i, _ := strconv.ParseInt(limits.NanoCPUs, 10, 64)
  520. resources.NanoCPUs = i
  521. }
  522. }
  523. func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) {
  524. if blkio == nil {
  525. return
  526. }
  527. resources.BlkioWeight = blkio.Weight
  528. for _, b := range blkio.WeightDevice {
  529. resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{
  530. Path: b.Path,
  531. Weight: b.Weight,
  532. })
  533. }
  534. for _, b := range blkio.DeviceReadBps {
  535. resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{
  536. Path: b.Path,
  537. Rate: b.Rate,
  538. })
  539. }
  540. for _, b := range blkio.DeviceReadIOps {
  541. resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{
  542. Path: b.Path,
  543. Rate: b.Rate,
  544. })
  545. }
  546. for _, b := range blkio.DeviceWriteBps {
  547. resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{
  548. Path: b.Path,
  549. Rate: b.Rate,
  550. })
  551. }
  552. for _, b := range blkio.DeviceWriteIOps {
  553. resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{
  554. Path: b.Path,
  555. Rate: b.Rate,
  556. })
  557. }
  558. }
  559. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  560. ports := nat.PortSet{}
  561. for _, s := range s.Expose {
  562. p := nat.Port(s)
  563. ports[p] = struct{}{}
  564. }
  565. for _, p := range s.Ports {
  566. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  567. ports[p] = struct{}{}
  568. }
  569. return ports
  570. }
  571. func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap {
  572. bindings := nat.PortMap{}
  573. for _, port := range s.Ports {
  574. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  575. bind := bindings[p]
  576. binding := nat.PortBinding{
  577. HostIP: port.HostIP,
  578. }
  579. if port.Published > 0 {
  580. binding.HostPort = fmt.Sprint(port.Published)
  581. }
  582. bind = append(bind, binding)
  583. bindings[p] = bind
  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. // `Bind` API is used when host path need to be created if missing, `Mount` is preferred otherwise
  642. if m.Type == mount.TypeBind || m.Type == mount.TypeNamedPipe {
  643. for _, v := range service.Volumes {
  644. if v.Target == m.Target && v.Bind != nil && v.Bind.CreateHostPath {
  645. mode := "rw"
  646. if m.ReadOnly {
  647. mode = "ro"
  648. }
  649. binds = append(binds, fmt.Sprintf("%s:%s:%s", m.Source, m.Target, mode))
  650. continue MOUNTS
  651. }
  652. }
  653. }
  654. mounts = append(mounts, m)
  655. }
  656. return volumeMounts, binds, mounts, nil
  657. }
  658. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) {
  659. var mounts = map[string]mount.Mount{}
  660. if inherit != nil {
  661. for _, m := range inherit.Mounts {
  662. if m.Type == "tmpfs" {
  663. continue
  664. }
  665. src := m.Source
  666. if m.Type == "volume" {
  667. src = m.Name
  668. }
  669. m.Destination = path.Clean(m.Destination)
  670. if img.Config != nil {
  671. if _, ok := img.Config.Volumes[m.Destination]; ok {
  672. // inherit previous container's anonymous volume
  673. mounts[m.Destination] = mount.Mount{
  674. Type: m.Type,
  675. Source: src,
  676. Target: m.Destination,
  677. ReadOnly: !m.RW,
  678. }
  679. }
  680. }
  681. volumes := []types.ServiceVolumeConfig{}
  682. for _, v := range s.Volumes {
  683. if v.Target != m.Destination || v.Source != "" {
  684. volumes = append(volumes, v)
  685. continue
  686. }
  687. // inherit previous container's anonymous volume
  688. mounts[m.Destination] = mount.Mount{
  689. Type: m.Type,
  690. Source: src,
  691. Target: m.Destination,
  692. ReadOnly: !m.RW,
  693. }
  694. }
  695. s.Volumes = volumes
  696. }
  697. }
  698. mounts, err := fillBindMounts(p, s, mounts)
  699. if err != nil {
  700. return nil, err
  701. }
  702. values := make([]mount.Mount, 0, len(mounts))
  703. for _, v := range mounts {
  704. values = append(values, v)
  705. }
  706. return values, nil
  707. }
  708. func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) {
  709. for _, v := range s.Volumes {
  710. bindMount, err := buildMount(p, v)
  711. if err != nil {
  712. return nil, err
  713. }
  714. m[bindMount.Target] = bindMount
  715. }
  716. secrets, err := buildContainerSecretMounts(p, s)
  717. if err != nil {
  718. return nil, err
  719. }
  720. for _, s := range secrets {
  721. if _, found := m[s.Target]; found {
  722. continue
  723. }
  724. m[s.Target] = s
  725. }
  726. configs, err := buildContainerConfigMounts(p, s)
  727. if err != nil {
  728. return nil, err
  729. }
  730. for _, c := range configs {
  731. if _, found := m[c.Target]; found {
  732. continue
  733. }
  734. m[c.Target] = c
  735. }
  736. return m, nil
  737. }
  738. func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  739. var mounts = map[string]mount.Mount{}
  740. configsBaseDir := "/"
  741. for _, config := range s.Configs {
  742. target := config.Target
  743. if config.Target == "" {
  744. target = configsBaseDir + config.Source
  745. } else if !isUnixAbs(config.Target) {
  746. target = configsBaseDir + config.Target
  747. }
  748. definedConfig := p.Configs[config.Source]
  749. if definedConfig.External.External {
  750. return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name)
  751. }
  752. bindMount, err := buildMount(p, types.ServiceVolumeConfig{
  753. Type: types.VolumeTypeBind,
  754. Source: definedConfig.File,
  755. Target: target,
  756. ReadOnly: true,
  757. })
  758. if err != nil {
  759. return nil, err
  760. }
  761. mounts[target] = bindMount
  762. }
  763. values := make([]mount.Mount, 0, len(mounts))
  764. for _, v := range mounts {
  765. values = append(values, v)
  766. }
  767. return values, nil
  768. }
  769. func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) {
  770. var mounts = map[string]mount.Mount{}
  771. secretsDir := "/run/secrets/"
  772. for _, secret := range s.Secrets {
  773. target := secret.Target
  774. if secret.Target == "" {
  775. target = secretsDir + secret.Source
  776. } else if !isUnixAbs(secret.Target) {
  777. target = secretsDir + secret.Target
  778. }
  779. definedSecret := p.Secrets[secret.Source]
  780. if definedSecret.External.External {
  781. return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name)
  782. }
  783. mount, err := buildMount(p, types.ServiceVolumeConfig{
  784. Type: types.VolumeTypeBind,
  785. Source: definedSecret.File,
  786. Target: target,
  787. ReadOnly: true,
  788. })
  789. if err != nil {
  790. return nil, err
  791. }
  792. mounts[target] = mount
  793. }
  794. values := make([]mount.Mount, 0, len(mounts))
  795. for _, v := range mounts {
  796. values = append(values, v)
  797. }
  798. return values, nil
  799. }
  800. func isUnixAbs(path string) bool {
  801. return strings.HasPrefix(path, "/")
  802. }
  803. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  804. source := volume.Source
  805. // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock.
  806. // do not replace these with filepath.Abs(source) that will include a default drive.
  807. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") {
  808. // volume source has already been prefixed with workdir if required, by compose-go project loader
  809. var err error
  810. source, err = filepath.Abs(source)
  811. if err != nil {
  812. return mount.Mount{}, err
  813. }
  814. }
  815. if volume.Type == types.VolumeTypeVolume {
  816. if volume.Source != "" {
  817. pVolume, ok := project.Volumes[volume.Source]
  818. if ok {
  819. source = pVolume.Name
  820. }
  821. }
  822. }
  823. bind, vol, tmpfs := buildMountOptions(volume)
  824. volume.Target = path.Clean(volume.Target)
  825. return mount.Mount{
  826. Type: mount.Type(volume.Type),
  827. Source: source,
  828. Target: volume.Target,
  829. ReadOnly: volume.ReadOnly,
  830. Consistency: mount.Consistency(volume.Consistency),
  831. BindOptions: bind,
  832. VolumeOptions: vol,
  833. TmpfsOptions: tmpfs,
  834. }, nil
  835. }
  836. func buildMountOptions(volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) {
  837. switch volume.Type {
  838. case "bind":
  839. if volume.Volume != nil {
  840. logrus.Warnf("mount of type `bind` should not define `volume` option")
  841. }
  842. if volume.Tmpfs != nil {
  843. logrus.Warnf("mount of type `tmpfs` should not define `tmpfs` option")
  844. }
  845. return buildBindOption(volume.Bind), nil, nil
  846. case "volume":
  847. if volume.Bind != nil {
  848. logrus.Warnf("mount of type `volume` should not define `bind` option")
  849. }
  850. if volume.Tmpfs != nil {
  851. logrus.Warnf("mount of type `volume` should not define `tmpfs` option")
  852. }
  853. return nil, buildVolumeOptions(volume.Volume), nil
  854. case "tmpfs":
  855. if volume.Bind != nil {
  856. logrus.Warnf("mount of type `tmpfs` should not define `bind` option")
  857. }
  858. if volume.Tmpfs != nil {
  859. logrus.Warnf("mount of type `tmpfs` should not define `volumeZ` option")
  860. }
  861. return nil, nil, buildTmpfsOptions(volume.Tmpfs)
  862. }
  863. return nil, nil, nil
  864. }
  865. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  866. if bind == nil {
  867. return nil
  868. }
  869. return &mount.BindOptions{
  870. Propagation: mount.Propagation(bind.Propagation),
  871. // NonRecursive: false, FIXME missing from model ?
  872. }
  873. }
  874. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  875. if vol == nil {
  876. return nil
  877. }
  878. return &mount.VolumeOptions{
  879. NoCopy: vol.NoCopy,
  880. // Labels: , // FIXME missing from model ?
  881. // DriverConfig: , // FIXME missing from model ?
  882. }
  883. }
  884. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  885. if tmpfs == nil {
  886. return nil
  887. }
  888. return &mount.TmpfsOptions{
  889. SizeBytes: int64(tmpfs.Size),
  890. // Mode: , // FIXME missing from model ?
  891. }
  892. }
  893. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  894. aliases := []string{s.Name}
  895. if c != nil {
  896. aliases = append(aliases, c.Aliases...)
  897. }
  898. return aliases
  899. }
  900. func getNetworksForService(s types.ServiceConfig) map[string]*types.ServiceNetworkConfig {
  901. if len(s.Networks) > 0 {
  902. return s.Networks
  903. }
  904. if s.NetworkMode != "" {
  905. return nil
  906. }
  907. return map[string]*types.ServiceNetworkConfig{"default": nil}
  908. }
  909. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  910. _, err := s.apiClient.NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  911. if err != nil {
  912. if errdefs.IsNotFound(err) {
  913. if n.External.External {
  914. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  915. }
  916. var ipam *network.IPAM
  917. if n.Ipam.Config != nil {
  918. var config []network.IPAMConfig
  919. for _, pool := range n.Ipam.Config {
  920. config = append(config, network.IPAMConfig{
  921. Subnet: pool.Subnet,
  922. IPRange: pool.IPRange,
  923. Gateway: pool.Gateway,
  924. AuxAddress: pool.AuxiliaryAddresses,
  925. })
  926. }
  927. ipam = &network.IPAM{
  928. Driver: n.Ipam.Driver,
  929. Config: config,
  930. }
  931. }
  932. createOpts := moby.NetworkCreate{
  933. // TODO NameSpace Labels
  934. Labels: n.Labels,
  935. Driver: n.Driver,
  936. Options: n.DriverOpts,
  937. Internal: n.Internal,
  938. Attachable: n.Attachable,
  939. IPAM: ipam,
  940. EnableIPv6: n.EnableIPv6,
  941. }
  942. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  943. createOpts.IPAM = &network.IPAM{}
  944. }
  945. if n.Ipam.Driver != "" {
  946. createOpts.IPAM.Driver = n.Ipam.Driver
  947. }
  948. for _, ipamConfig := range n.Ipam.Config {
  949. config := network.IPAMConfig{
  950. Subnet: ipamConfig.Subnet,
  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, networkID string, networkName string) error {
  969. w := progress.ContextWriter(ctx)
  970. eventName := fmt.Sprintf("Network %s", networkName)
  971. w.Event(progress.RemovingEvent(eventName))
  972. if err := s.apiClient.NetworkRemove(ctx, networkID); err != nil {
  973. w.Event(progress.ErrorEvent(eventName))
  974. return errors.Wrapf(err, fmt.Sprintf("failed to remove network %s", networkID))
  975. }
  976. w.Event(progress.RemovedEvent(eventName))
  977. return nil
  978. }
  979. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig) error {
  980. // TODO could identify volume by label vs name
  981. _, err := s.apiClient.VolumeInspect(ctx, volume.Name)
  982. if err != nil {
  983. if !errdefs.IsNotFound(err) {
  984. return err
  985. }
  986. eventName := fmt.Sprintf("Volume %q", volume.Name)
  987. w := progress.ContextWriter(ctx)
  988. w.Event(progress.CreatingEvent(eventName))
  989. _, err := s.apiClient.VolumeCreate(ctx, volume_api.VolumeCreateBody{
  990. Labels: volume.Labels,
  991. Name: volume.Name,
  992. Driver: volume.Driver,
  993. DriverOpts: volume.DriverOpts,
  994. })
  995. if err != nil {
  996. w.Event(progress.ErrorEvent(eventName))
  997. return err
  998. }
  999. w.Event(progress.CreatedEvent(eventName))
  1000. }
  1001. return nil
  1002. }