containers.go 5.3 KB

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