create.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 getContainerCreateOptions(p *types.Project, s types.ServiceConfig, number int, inherit *moby.Container) (*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. Mounts: mountOptions,
  150. CapAdd: strslice.StrSlice(s.CapAdd),
  151. CapDrop: strslice.StrSlice(s.CapDrop),
  152. NetworkMode: networkMode,
  153. Init: s.Init,
  154. ReadonlyRootfs: s.ReadOnly,
  155. // ShmSize: , TODO
  156. Sysctls: s.Sysctls,
  157. PortBindings: bindings,
  158. }
  159. networkConfig := buildDefaultNetworkConfig(s, networkMode)
  160. return &containerConfig, &hostConfig, networkConfig, nil
  161. }
  162. func buildContainerPorts(s types.ServiceConfig) nat.PortSet {
  163. ports := nat.PortSet{}
  164. for _, p := range s.Ports {
  165. p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol))
  166. ports[p] = struct{}{}
  167. }
  168. return ports
  169. }
  170. func buildContainerBindingOptions(s types.ServiceConfig) nat.PortMap {
  171. bindings := nat.PortMap{}
  172. for _, port := range s.Ports {
  173. p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol))
  174. bind := []nat.PortBinding{}
  175. binding := nat.PortBinding{}
  176. if port.Published > 0 {
  177. binding.HostPort = fmt.Sprint(port.Published)
  178. }
  179. bind = append(bind, binding)
  180. bindings[p] = bind
  181. }
  182. return bindings
  183. }
  184. func buildContainerMountOptions(p types.Project, s types.ServiceConfig, inherit *moby.Container) ([]mount.Mount, error) {
  185. mounts := []mount.Mount{}
  186. var inherited []string
  187. if inherit != nil {
  188. for _, m := range inherit.Mounts {
  189. if m.Type == "tmpfs" {
  190. continue
  191. }
  192. src := m.Source
  193. if m.Type == "volume" {
  194. src = m.Name
  195. }
  196. mounts = append(mounts, mount.Mount{
  197. Type: m.Type,
  198. Source: src,
  199. Target: m.Destination,
  200. ReadOnly: !m.RW,
  201. })
  202. inherited = append(inherited, m.Destination)
  203. }
  204. }
  205. for _, v := range s.Volumes {
  206. if contains(inherited, v.Target) {
  207. continue
  208. }
  209. mount, err := buildMount(p, v)
  210. if err != nil {
  211. return nil, err
  212. }
  213. mounts = append(mounts, mount)
  214. }
  215. return mounts, nil
  216. }
  217. func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) {
  218. source := volume.Source
  219. if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) {
  220. // volume source has already been prefixed with workdir if required, by compose-go project loader
  221. var err error
  222. source, err = filepath.Abs(source)
  223. if err != nil {
  224. return mount.Mount{}, err
  225. }
  226. }
  227. if volume.Type == types.VolumeTypeVolume {
  228. pVolume, ok := project.Volumes[volume.Source]
  229. if ok {
  230. source = pVolume.Name
  231. }
  232. }
  233. return mount.Mount{
  234. Type: mount.Type(volume.Type),
  235. Source: source,
  236. Target: volume.Target,
  237. ReadOnly: volume.ReadOnly,
  238. Consistency: mount.Consistency(volume.Consistency),
  239. BindOptions: buildBindOption(volume.Bind),
  240. VolumeOptions: buildVolumeOptions(volume.Volume),
  241. TmpfsOptions: buildTmpfsOptions(volume.Tmpfs),
  242. }, nil
  243. }
  244. func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions {
  245. if bind == nil {
  246. return nil
  247. }
  248. return &mount.BindOptions{
  249. Propagation: mount.Propagation(bind.Propagation),
  250. // NonRecursive: false, FIXME missing from model ?
  251. }
  252. }
  253. func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions {
  254. if vol == nil {
  255. return nil
  256. }
  257. return &mount.VolumeOptions{
  258. NoCopy: vol.NoCopy,
  259. // Labels: , // FIXME missing from model ?
  260. // DriverConfig: , // FIXME missing from model ?
  261. }
  262. }
  263. func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions {
  264. if tmpfs == nil {
  265. return nil
  266. }
  267. return &mount.TmpfsOptions{
  268. SizeBytes: tmpfs.Size,
  269. // Mode: , // FIXME missing from model ?
  270. }
  271. }
  272. func buildDefaultNetworkConfig(s types.ServiceConfig, networkMode container.NetworkMode) *network.NetworkingConfig {
  273. config := map[string]*network.EndpointSettings{}
  274. net := string(networkMode)
  275. config[net] = &network.EndpointSettings{
  276. Aliases: getAliases(s, s.Networks[net]),
  277. }
  278. return &network.NetworkingConfig{
  279. EndpointsConfig: config,
  280. }
  281. }
  282. func getAliases(s types.ServiceConfig, c *types.ServiceNetworkConfig) []string {
  283. aliases := []string{s.Name}
  284. if c != nil {
  285. aliases = append(aliases, c.Aliases...)
  286. }
  287. return aliases
  288. }
  289. func getNetworkMode(p *types.Project, service types.ServiceConfig) container.NetworkMode {
  290. mode := service.NetworkMode
  291. if mode == "" {
  292. if len(p.Networks) > 0 {
  293. for name := range getNetworksForService(service) {
  294. return container.NetworkMode(p.Networks[name].Name)
  295. }
  296. }
  297. return container.NetworkMode("none")
  298. }
  299. // FIXME incomplete implementation
  300. if strings.HasPrefix(mode, "service:") {
  301. panic("Not yet implemented")
  302. }
  303. if strings.HasPrefix(mode, "container:") {
  304. panic("Not yet implemented")
  305. }
  306. return container.NetworkMode(mode)
  307. }
  308. func getNetworksForService(s types.ServiceConfig) map[string]*types.ServiceNetworkConfig {
  309. if len(s.Networks) > 0 {
  310. return s.Networks
  311. }
  312. return map[string]*types.ServiceNetworkConfig{"default": nil}
  313. }
  314. func (s *composeService) ensureNetwork(ctx context.Context, n types.NetworkConfig) error {
  315. _, err := s.apiClient.NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{})
  316. if err != nil {
  317. if errdefs.IsNotFound(err) {
  318. if n.External.External {
  319. return fmt.Errorf("network %s declared as external, but could not be found", n.Name)
  320. }
  321. createOpts := moby.NetworkCreate{
  322. // TODO NameSpace Labels
  323. Labels: n.Labels,
  324. Driver: n.Driver,
  325. Options: n.DriverOpts,
  326. Internal: n.Internal,
  327. Attachable: n.Attachable,
  328. }
  329. if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 {
  330. createOpts.IPAM = &network.IPAM{}
  331. }
  332. if n.Ipam.Driver != "" {
  333. createOpts.IPAM.Driver = n.Ipam.Driver
  334. }
  335. for _, ipamConfig := range n.Ipam.Config {
  336. config := network.IPAMConfig{
  337. Subnet: ipamConfig.Subnet,
  338. }
  339. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  340. }
  341. networkEventName := fmt.Sprintf("Network %q", n.Name)
  342. w := progress.ContextWriter(ctx)
  343. w.Event(progress.CreatingEvent(networkEventName))
  344. if _, err := s.apiClient.NetworkCreate(ctx, n.Name, createOpts); err != nil {
  345. w.Event(progress.ErrorEvent(networkEventName))
  346. return errors.Wrapf(err, "failed to create network %s", n.Name)
  347. }
  348. w.Event(progress.CreatedEvent(networkEventName))
  349. return nil
  350. }
  351. return err
  352. }
  353. return nil
  354. }
  355. func (s *composeService) ensureNetworkDown(ctx context.Context, networkID string, networkName string) error {
  356. w := progress.ContextWriter(ctx)
  357. eventName := fmt.Sprintf("Network %q", networkName)
  358. w.Event(progress.RemovingEvent(eventName))
  359. if err := s.apiClient.NetworkRemove(ctx, networkID); err != nil {
  360. w.Event(progress.ErrorEvent(eventName))
  361. return errors.Wrapf(err, fmt.Sprintf("failed to create network %s", networkID))
  362. }
  363. w.Event(progress.RemovedEvent(eventName))
  364. return nil
  365. }
  366. func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig) error {
  367. // TODO could identify volume by label vs name
  368. _, err := s.apiClient.VolumeInspect(ctx, volume.Name)
  369. if err != nil {
  370. if !errdefs.IsNotFound(err) {
  371. return err
  372. }
  373. eventName := fmt.Sprintf("Volume %q", volume.Name)
  374. w := progress.ContextWriter(ctx)
  375. w.Event(progress.CreatingEvent(eventName))
  376. // TODO we miss support for driver_opts and labels
  377. _, err := s.apiClient.VolumeCreate(ctx, volume_api.VolumeCreateBody{
  378. Labels: volume.Labels,
  379. Name: volume.Name,
  380. Driver: volume.Driver,
  381. DriverOpts: volume.DriverOpts,
  382. })
  383. if err != nil {
  384. w.Event(progress.ErrorEvent(eventName))
  385. return err
  386. }
  387. w.Event(progress.CreatedEvent(eventName))
  388. }
  389. return nil
  390. }