containers.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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.Slice(containers, func(i, j int) bool {
  85. x, _ := strconv.Atoi(containers[i].Labels[api.ContainerNumberLabel])
  86. y, _ := strconv.Atoi(containers[j].Labels[api.ContainerNumberLabel])
  87. return x < y
  88. })
  89. container := containers[0]
  90. return container, nil
  91. }
  92. // containerPredicate define a predicate we want container to satisfy for filtering operations
  93. type containerPredicate func(c moby.Container) bool
  94. func isService(services ...string) containerPredicate {
  95. return func(c moby.Container) bool {
  96. service := c.Labels[api.ServiceLabel]
  97. return utils.StringContains(services, service)
  98. }
  99. }
  100. func isRunning() containerPredicate {
  101. return func(c moby.Container) bool {
  102. return c.State == "running"
  103. }
  104. }
  105. // isOrphaned is a predicate to select containers without a matching service definition in compose project
  106. func isOrphaned(project *types.Project) containerPredicate {
  107. services := append(project.ServiceNames(), project.DisabledServiceNames()...)
  108. return func(c moby.Container) bool {
  109. // One-off container
  110. v, ok := c.Labels[api.OneoffLabel]
  111. if ok && v == "True" {
  112. return c.State == ContainerExited || c.State == ContainerDead
  113. }
  114. // Service that is not defined in the compose model
  115. service := c.Labels[api.ServiceLabel]
  116. return !utils.StringContains(services, service)
  117. }
  118. }
  119. func isNotOneOff(c moby.Container) bool {
  120. v, ok := c.Labels[api.OneoffLabel]
  121. return !ok || v == "False"
  122. }
  123. // filter return Containers with elements to match predicate
  124. func (containers Containers) filter(predicate containerPredicate) Containers {
  125. var filtered Containers
  126. for _, c := range containers {
  127. if predicate(c) {
  128. filtered = append(filtered, c)
  129. }
  130. }
  131. return filtered
  132. }
  133. func (containers Containers) names() []string {
  134. var names []string
  135. for _, c := range containers {
  136. names = append(names, getCanonicalContainerName(c))
  137. }
  138. return names
  139. }
  140. func (containers Containers) forEach(fn func(moby.Container)) {
  141. for _, c := range containers {
  142. fn(c)
  143. }
  144. }
  145. func (containers Containers) sorted() Containers {
  146. sort.Slice(containers, func(i, j int) bool {
  147. return getCanonicalContainerName(containers[i]) < getCanonicalContainerName(containers[j])
  148. })
  149. return containers
  150. }