create.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. "context"
  16. "fmt"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. convert "github.com/docker/compose-cli/local/moby"
  21. "github.com/docker/compose-cli/progress"
  22. "github.com/compose-spec/compose-go/types"
  23. moby "github.com/docker/docker/api/types"
  24. "github.com/docker/docker/api/types/container"
  25. "github.com/docker/docker/api/types/mount"
  26. "github.com/docker/docker/api/types/network"
  27. "github.com/docker/docker/api/types/strslice"
  28. volume_api "github.com/docker/docker/api/types/volume"
  29. "github.com/docker/docker/errdefs"
  30. "github.com/docker/go-connections/nat"
  31. "github.com/pkg/errors"
  32. )
  33. func (s *composeService) Create(ctx context.Context, project *types.Project) error {
  34. err := s.ensureImagesExists(ctx, project)
  35. if err != nil {
  36. return err
  37. }
  38. if err := s.ensureProjectNetworks(ctx, project); err != nil {
  39. return err
  40. }
  41. if err := s.ensureProjectVolumes(ctx, project); err != nil {
  42. return err
  43. }
  44. return InDependencyOrder(ctx, project, func(c context.Context, service types.ServiceConfig) error {
  45. return s.ensureService(c, project, service)
  46. })
  47. }
  48. func (s *composeService) ensureProjectNetworks(ctx context.Context, project *types.Project) error {
  49. for k, network := range project.Networks {
  50. if !network.External.External && network.Name != "" {
  51. network.Name = fmt.Sprintf("%s_%s", project.Name, k)
  52. project.Networks[k] = network
  53. }
  54. network.Labels = network.Labels.Add(networkLabel, k)
  55. network.Labels = network.Labels.Add(projectLabel, project.Name)
  56. network.Labels = network.Labels.Add(versionLabel, ComposeVersion)
  57. err := s.ensureNetwork(ctx, network)
  58. if err != nil {
  59. return err
  60. }
  61. }
  62. return nil
  63. }
  64. func (s *composeService) ensureProjectVolumes(ctx context.Context, project *types.Project) error {
  65. for k, volume := range project.Volumes {
  66. if !volume.External.External && volume.Name != "" {
  67. volume.Name = fmt.Sprintf("%s_%s", project.Name, k)
  68. project.Volumes[k] = volume
  69. }
  70. volume.Labels = volume.Labels.Add(volumeLabel, k)
  71. volume.Labels = volume.Labels.Add(projectLabel, project.Name)
  72. volume.Labels = volume.Labels.Add(versionLabel, ComposeVersion)
  73. err := s.ensureVolume(ctx, volume)
  74. if err != nil {
  75. return err
  76. }
  77. }
  78. return nil
  79. }
  80. func getCreateOptions(p *types.Project, s types.ServiceConfig, number int, inherit *moby.Container, autoRemove bool) (*container.Config, *container.HostConfig, *network.NetworkingConfig, error) {
  81. hash, err := jsonHash(s)
  82. if err != nil {
  83. return nil, nil, nil, err
  84. }
  85. labels := map[string]string{}
  86. for k, v := range s.Labels {
  87. labels[k] = v
  88. }
  89. labels[projectLabel] = p.Name
  90. labels[serviceLabel] = s.Name
  91. labels[versionLabel] = ComposeVersion
  92. if _, ok := s.Labels[oneoffLabel]; !ok {
  93. labels[oneoffLabel] = "False"
  94. }
  95. labels[configHashLabel] = hash
  96. labels[workingDirLabel] = p.WorkingDir
  97. labels[configFilesLabel] = strings.Join(p.ComposeFiles, ",")
  98. labels[containerNumberLabel] = strconv.Itoa(number)
  99. var (
  100. runCmd strslice.StrSlice
  101. entrypoint strslice.StrSlice
  102. )
  103. if len(s.Command) > 0 {
  104. runCmd = strslice.StrSlice(s.Command)
  105. }
  106. if len(s.Entrypoint) > 0 {
  107. entrypoint = strslice.StrSlice(s.Entrypoint)
  108. }
  109. image := s.Image
  110. if s.Image == "" {
  111. image = fmt.Sprintf("%s_%s", p.Name, s.Name)
  112. }
  113. var (
  114. tty = s.Tty
  115. stdinOpen = s.StdinOpen
  116. attachStdin = false
  117. )
  118. containerConfig := container.Config{
  119. Hostname: s.Hostname,
  120. Domainname: s.DomainName,
  121. User: s.User,
  122. ExposedPorts: buildContainerPorts(s),
  123. Tty: tty,
  124. OpenStdin: stdinOpen,
  125. StdinOnce: true,
  126. AttachStdin: attachStdin,
  127. AttachStderr: true,
  128. AttachStdout: true,
  129. Cmd: runCmd,
  130. Image: image,
  131. WorkingDir: s.WorkingDir,
  132. Entrypoint: entrypoint,
  133. NetworkDisabled: s.NetworkMode == "disabled",
  134. MacAddress: s.MacAddress,
  135. Labels: labels,
  136. StopSignal: s.StopSignal,
  137. Env: convert.ToMobyEnv(s.Environment),
  138. Healthcheck: convert.ToMobyHealthCheck(s.HealthCheck),
  139. // Volumes: // FIXME unclear to me the overlap with HostConfig.Mounts
  140. StopTimeout: convert.ToSeconds(s.StopGracePeriod),
  141. }
  142. mountOptions, err := buildContainerMountOptions(*p, s, inherit)
  143. if err != nil {
  144. return nil, nil, nil, err
  145. }
  146. bindings := buildContainerBindingOptions(s)
  147. networkMode := getNetworkMode(p, s)
  148. hostConfig := container.HostConfig{
  149. AutoRemove: autoRemove,
  150. Mounts: mountOptions,
  151. CapAdd: strslice.StrSlice(s.CapAdd),
  152. CapDrop: strslice.StrSlice(s.CapDrop),
  153. NetworkMode: networkMode,
  154. Init: s.Init,
  155. ReadonlyRootfs: s.ReadOnly,
  156. // ShmSize: , TODO
  157. Sysctls: s.Sysctls,
  158. PortBindings: bindings,
  159. }
  160. networkConfig := buildDefaultNetworkConfig(s, networkMode)
  161. return &containerConfig, &hostConfig, networkConfig, nil
  162. }
  163. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  164. ports := nat.PortSet{}
  165. for _, p := range s.Ports {
  166. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  167. ports[p] = struct{}{}
  168. }
  169. return ports
  170. }
  171. func buildContainerBindingOptions(s types.ServiceConfig) nat.PortMap {
  172. bindings := nat.PortMap{}
  173. for _, port := range s.Ports {
  174. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  175. bind := []nat.PortBinding{}
  176. binding := nat.PortBinding{}
  177. if port.Published > 0 {
  178. binding.HostPort = fmt.Sprint(port.Published)
  179. }
  180. bind = append(bind, binding)
  181. bindings[p] = bind
  182. }
  183. return bindings
  184. }
  185. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, inherit *moby.Container) ([]mount.Mount, error) {
  186. mounts := []mount.Mount{}
  187. var inherited []string
  188. if inherit != nil {
  189. for _, m := range inherit.Mounts {
  190. if m.Type == "tmpfs" {
  191. continue
  192. }
  193. src := m.Source
  194. if m.Type == "volume" {
  195. src = m.Name
  196. }
  197. mounts = append(mounts, mount.Mount{
  198. Type: m.Type,
  199. Source: src,
  200. Target: m.Destination,
  201. ReadOnly: !m.RW,
  202. })
  203. inherited = append(inherited, m.Destination)
  204. }
  205. }
  206. for _, v := range s.Volumes {
  207. if contains(inherited, v.Target) {
  208. continue
  209. }
  210. mount, err := buildMount(p, v)
  211. if err != nil {
  212. return nil, err
  213. }
  214. mounts = append(mounts, mount)
  215. }
  216. return mounts, nil
  217. }
  218. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  219. source := volume.Source
  220. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) {
  221. // volume source has already been prefixed with workdir if required, by compose-go project loader
  222. var err error
  223. source, err = filepath.Abs(source)
  224. if err != nil {
  225. return mount.Mount{}, err
  226. }
  227. }
  228. if volume.Type == types.VolumeTypeVolume {
  229. pVolume, ok := project.Volumes[volume.Source]
  230. if ok {
  231. source = pVolume.Name
  232. }
  233. }
  234. return mount.Mount{
  235. Type: mount.Type(volume.Type),
  236. Source: source,
  237. Target: volume.Target,
  238. ReadOnly: volume.ReadOnly,
  239. Consistency: mount.Consistency(volume.Consistency),
  240. BindOptions: buildBindOption(volume.Bind),
  241. VolumeOptions: buildVolumeOptions(volume.Volume),
  242. TmpfsOptions: buildTmpfsOptions(volume.Tmpfs),
  243. }, nil
  244. }
  245. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  246. if bind == nil {
  247. return nil
  248. }
  249. return &mount.BindOptions{
  250. Propagation: mount.Propagation(bind.Propagation),
  251. // NonRecursive: false, FIXME missing from model ?
  252. }
  253. }
  254. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  255. if vol == nil {
  256. return nil
  257. }
  258. return &mount.VolumeOptions{
  259. NoCopy: vol.NoCopy,
  260. // Labels: , // FIXME missing from model ?
  261. // DriverConfig: , // FIXME missing from model ?
  262. }
  263. }
  264. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  265. if tmpfs == nil {
  266. return nil
  267. }
  268. return &mount.TmpfsOptions{
  269. SizeBytes: tmpfs.Size,
  270. // Mode: , // FIXME missing from model ?
  271. }
  272. }
  273. func buildDefaultNetworkConfig(s types.ServiceConfig, networkMode container.NetworkMode) *network.NetworkingConfig {
  274. config := map[string]*network.EndpointSettings{}
  275. net := string(networkMode)
  276. config[net] = &network.EndpointSettings{
  277. Aliases: getAliases(s, s.Networks[net]),
  278. }
  279. return &network.NetworkingConfig{
  280. EndpointsConfig: config,
  281. }
  282. }
  283. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  284. aliases := []string{s.Name}
  285. if c != nil {
  286. aliases = append(aliases, c.Aliases...)
  287. }
  288. return aliases
  289. }
  290. func getNetworkMode(p *types.Project, service types.ServiceConfig) container.NetworkMode {
  291. mode := service.NetworkMode
  292. if mode == "" {
  293. if len(p.Networks) > 0 {
  294. for name := range getNetworksForService(service) {
  295. return container.NetworkMode(p.Networks[name].Name)
  296. }
  297. }
  298. return container.NetworkMode("none")
  299. }
  300. // FIXME incomplete implementation
  301. if strings.HasPrefix(mode, "service:") {
  302. panic("Not yet implemented")
  303. }
  304. if strings.HasPrefix(mode, "container:") {
  305. panic("Not yet implemented")
  306. }
  307. return container.NetworkMode(mode)
  308. }
  309. func getNetworksForService(s types.ServiceConfig) map[string]*types.ServiceNetworkConfig {
  310. if len(s.Networks) > 0 {
  311. return s.Networks
  312. }
  313. return map[string]*types.ServiceNetworkConfig{"default": nil}
  314. }
  315. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  316. _, err := s.apiClient.NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  317. if err != nil {
  318. if errdefs.IsNotFound(err) {
  319. if n.External.External {
  320. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  321. }
  322. createOpts := moby.NetworkCreate{
  323. // TODO NameSpace Labels
  324. Labels: n.Labels,
  325. Driver: n.Driver,
  326. Options: n.DriverOpts,
  327. Internal: n.Internal,
  328. Attachable: n.Attachable,
  329. }
  330. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  331. createOpts.IPAM = &network.IPAM{}
  332. }
  333. if n.Ipam.Driver != "" {
  334. createOpts.IPAM.Driver = n.Ipam.Driver
  335. }
  336. for _, ipamConfig := range n.Ipam.Config {
  337. config := network.IPAMConfig{
  338. Subnet: ipamConfig.Subnet,
  339. }
  340. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  341. }
  342. networkEventName := fmt.Sprintf("Network %q", n.Name)
  343. w := progress.ContextWriter(ctx)
  344. w.Event(progress.CreatingEvent(networkEventName))
  345. if _, err := s.apiClient.NetworkCreate(ctx, n.Name, createOpts); err != nil {
  346. w.Event(progress.ErrorEvent(networkEventName))
  347. return errors.Wrapf(err, "failed to create network %s", n.Name)
  348. }
  349. w.Event(progress.CreatedEvent(networkEventName))
  350. return nil
  351. }
  352. return err
  353. }
  354. return nil
  355. }
  356. func (s *composeService) ensureNetworkDown(ctx context.Context, networkID string, networkName string) error {
  357. w := progress.ContextWriter(ctx)
  358. eventName := fmt.Sprintf("Network %q", networkName)
  359. w.Event(progress.RemovingEvent(eventName))
  360. if err := s.apiClient.NetworkRemove(ctx, networkID); err != nil {
  361. w.Event(progress.ErrorEvent(eventName))
  362. return errors.Wrapf(err, fmt.Sprintf("failed to create network %s", networkID))
  363. }
  364. w.Event(progress.RemovedEvent(eventName))
  365. return nil
  366. }
  367. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig) error {
  368. // TODO could identify volume by label vs name
  369. _, err := s.apiClient.VolumeInspect(ctx, volume.Name)
  370. if err != nil {
  371. if !errdefs.IsNotFound(err) {
  372. return err
  373. }
  374. eventName := fmt.Sprintf("Volume %q", volume.Name)
  375. w := progress.ContextWriter(ctx)
  376. w.Event(progress.CreatingEvent(eventName))
  377. // TODO we miss support for driver_opts and labels
  378. _, err := s.apiClient.VolumeCreate(ctx, volume_api.VolumeCreateBody{
  379. Labels: volume.Labels,
  380. Name: volume.Name,
  381. Driver: volume.Driver,
  382. DriverOpts: volume.DriverOpts,
  383. })
  384. if err != nil {
  385. w.Event(progress.ErrorEvent(eventName))
  386. return err
  387. }
  388. w.Event(progress.CreatedEvent(eventName))
  389. }
  390. return nil
  391. }