containers.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. "slices"
  18. "sort"
  19. "strconv"
  20. "github.com/compose-spec/compose-go/v2/types"
  21. "github.com/docker/compose/v2/pkg/api"
  22. "github.com/docker/docker/api/types/container"
  23. "github.com/docker/docker/api/types/filters"
  24. )
  25. // Containers is a set of moby Container
  26. type Containers []container.Summary
  27. type oneOff int
  28. const (
  29. oneOffInclude = oneOff(iota)
  30. oneOffExclude
  31. oneOffOnly
  32. )
  33. func (s *composeService) getContainers(ctx context.Context, project string, oneOff oneOff, all bool, selectedServices ...string) (Containers, error) {
  34. var containers Containers
  35. f := getDefaultFilters(project, oneOff, selectedServices...)
  36. containers, err := s.apiClient().ContainerList(ctx, container.ListOptions{
  37. Filters: filters.NewArgs(f...),
  38. All: all,
  39. })
  40. if err != nil {
  41. return nil, err
  42. }
  43. if len(selectedServices) > 1 {
  44. containers = containers.filter(isService(selectedServices...))
  45. }
  46. return containers, nil
  47. }
  48. func getDefaultFilters(projectName string, oneOff oneOff, selectedServices ...string) []filters.KeyValuePair {
  49. f := []filters.KeyValuePair{projectFilter(projectName)}
  50. if len(selectedServices) == 1 {
  51. f = append(f, serviceFilter(selectedServices[0]))
  52. }
  53. f = append(f, hasConfigHashLabel())
  54. switch oneOff {
  55. case oneOffOnly:
  56. f = append(f, oneOffFilter(true))
  57. case oneOffExclude:
  58. f = append(f, oneOffFilter(false))
  59. case oneOffInclude:
  60. }
  61. return f
  62. }
  63. func (s *composeService) getSpecifiedContainer(ctx context.Context, projectName string, oneOff oneOff, all bool, serviceName string, containerIndex int) (container.Summary, error) {
  64. defaultFilters := getDefaultFilters(projectName, oneOff, serviceName)
  65. if containerIndex > 0 {
  66. defaultFilters = append(defaultFilters, containerNumberFilter(containerIndex))
  67. }
  68. containers, err := s.apiClient().ContainerList(ctx, container.ListOptions{
  69. Filters: filters.NewArgs(
  70. defaultFilters...,
  71. ),
  72. All: all,
  73. })
  74. if err != nil {
  75. return container.Summary{}, err
  76. }
  77. if len(containers) < 1 {
  78. if containerIndex > 0 {
  79. return container.Summary{}, fmt.Errorf("service %q is not running container #%d", serviceName, containerIndex)
  80. }
  81. return container.Summary{}, fmt.Errorf("service %q is not running", serviceName)
  82. }
  83. // Sort by container number first, then put one-off containers at the end
  84. sort.Slice(containers, func(i, j int) bool {
  85. numberLabelX, _ := strconv.Atoi(containers[i].Labels[api.ContainerNumberLabel])
  86. numberLabelY, _ := strconv.Atoi(containers[j].Labels[api.ContainerNumberLabel])
  87. IsOneOffLabelTrueX := containers[i].Labels[api.OneoffLabel] == "True"
  88. IsOneOffLabelTrueY := containers[j].Labels[api.OneoffLabel] == "True"
  89. if numberLabelX == numberLabelY {
  90. return !IsOneOffLabelTrueX && IsOneOffLabelTrueY
  91. }
  92. return numberLabelX < numberLabelY
  93. })
  94. return containers[0], nil
  95. }
  96. // containerPredicate define a predicate we want container to satisfy for filtering operations
  97. type containerPredicate func(c container.Summary) bool
  98. func matches(c container.Summary, predicates ...containerPredicate) bool {
  99. for _, predicate := range predicates {
  100. if !predicate(c) {
  101. return false
  102. }
  103. }
  104. return true
  105. }
  106. func isService(services ...string) containerPredicate {
  107. return func(c container.Summary) bool {
  108. service := c.Labels[api.ServiceLabel]
  109. return slices.Contains(services, service)
  110. }
  111. }
  112. // isOrphaned is a predicate to select containers without a matching service definition in compose project
  113. func isOrphaned(project *types.Project) containerPredicate {
  114. services := append(project.ServiceNames(), project.DisabledServiceNames()...)
  115. return func(c container.Summary) bool {
  116. // One-off container
  117. v, ok := c.Labels[api.OneoffLabel]
  118. if ok && v == "True" {
  119. return c.State == ContainerExited || c.State == ContainerDead
  120. }
  121. // Service that is not defined in the compose model
  122. service := c.Labels[api.ServiceLabel]
  123. return !slices.Contains(services, service)
  124. }
  125. }
  126. func isNotOneOff(c container.Summary) bool {
  127. v, ok := c.Labels[api.OneoffLabel]
  128. return !ok || v == "False"
  129. }
  130. // filter return Containers with elements to match predicate
  131. func (containers Containers) filter(predicates ...containerPredicate) Containers {
  132. var filtered Containers
  133. for _, c := range containers {
  134. if matches(c, predicates...) {
  135. filtered = append(filtered, c)
  136. }
  137. }
  138. return filtered
  139. }
  140. func (containers Containers) names() []string {
  141. var names []string
  142. for _, c := range containers {
  143. names = append(names, getCanonicalContainerName(c))
  144. }
  145. return names
  146. }
  147. func (containers Containers) forEach(fn func(container.Summary)) {
  148. for _, c := range containers {
  149. fn(c)
  150. }
  151. }
  152. func (containers Containers) sorted() Containers {
  153. sort.Slice(containers, func(i, j int) bool {
  154. return getCanonicalContainerName(containers[i]) < getCanonicalContainerName(containers[j])
  155. })
  156. return containers
  157. }