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