containers.go 2.3 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. "github.com/compose-spec/compose-go/types"
  17. moby "github.com/docker/docker/api/types"
  18. "github.com/docker/docker/api/types/filters"
  19. )
  20. // Containers is a set of moby Container
  21. type Containers []moby.Container
  22. func (s *composeService) getContainers(ctx context.Context, project *types.Project) (Containers, error) {
  23. var containers Containers
  24. containers, err := s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
  25. Filters: filters.NewArgs(
  26. projectFilter(project.Name),
  27. ),
  28. All: true,
  29. })
  30. if err != nil {
  31. return nil, err
  32. }
  33. containers = containers.filter(isService(project.ServiceNames()...))
  34. return containers, nil
  35. }
  36. // containerPredicate define a predicate we want container to satisfy for filtering operations
  37. type containerPredicate func(c moby.Container) bool
  38. func isService(services ...string) containerPredicate {
  39. return func(c moby.Container) bool {
  40. service := c.Labels[serviceLabel]
  41. return contains(services, service)
  42. }
  43. }
  44. func isNotService(services ...string) containerPredicate {
  45. return func(c moby.Container) bool {
  46. service := c.Labels[serviceLabel]
  47. return !contains(services, service)
  48. }
  49. }
  50. // filter return Containers with elements to match predicate
  51. func (containers Containers) filter(predicate containerPredicate) Containers {
  52. var filtered Containers
  53. for _, c := range containers {
  54. if predicate(c) {
  55. filtered = append(filtered, c)
  56. }
  57. }
  58. return filtered
  59. }
  60. func (containers Containers) names() []string {
  61. var names []string
  62. for _, c := range containers {
  63. names = append(names, getCanonicalContainerName(c))
  64. }
  65. return names
  66. }
  67. func (containers Containers) forEach(fn func(moby.Container)) {
  68. for _, c := range containers {
  69. fn(c)
  70. }
  71. }