volumes.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. "slices"
  17. "github.com/compose-spec/compose-go/v2/types"
  18. "github.com/docker/compose/v2/pkg/api"
  19. "github.com/docker/docker/api/types/container"
  20. "github.com/docker/docker/api/types/filters"
  21. "github.com/docker/docker/api/types/volume"
  22. )
  23. func (s *composeService) Volumes(ctx context.Context, project *types.Project, options api.VolumesOptions) ([]api.VolumesSummary, error) {
  24. projectName := project.Name
  25. allContainers, err := s.apiClient().ContainerList(ctx, container.ListOptions{
  26. Filters: filters.NewArgs(projectFilter(projectName)),
  27. })
  28. if err != nil {
  29. return nil, err
  30. }
  31. var containers []container.Summary
  32. if len(options.Services) > 0 {
  33. // filter service containers
  34. for _, c := range allContainers {
  35. if slices.Contains(options.Services, c.Labels[api.ServiceLabel]) {
  36. containers = append(containers, c)
  37. }
  38. }
  39. } else {
  40. containers = allContainers
  41. }
  42. volumesResponse, err := s.apiClient().VolumeList(ctx, volume.ListOptions{
  43. Filters: filters.NewArgs(projectFilter(projectName)),
  44. })
  45. if err != nil {
  46. return nil, err
  47. }
  48. projectVolumes := volumesResponse.Volumes
  49. if len(options.Services) == 0 {
  50. return projectVolumes, nil
  51. }
  52. var volumes []api.VolumesSummary
  53. // create a name lookup of volumes used by containers
  54. serviceVolumes := make(map[string]bool)
  55. for _, container := range containers {
  56. for _, mount := range container.Mounts {
  57. serviceVolumes[mount.Name] = true
  58. }
  59. }
  60. // append if volumes in this project are in serviceVolumes
  61. for _, v := range projectVolumes {
  62. if serviceVolumes[v.Name] {
  63. volumes = append(volumes, v)
  64. }
  65. }
  66. return volumes, nil
  67. }