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