volumes.go 2.1 KB

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