down.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. "path/filepath"
  17. "strings"
  18. "time"
  19. "github.com/docker/compose-cli/api/compose"
  20. "github.com/docker/compose-cli/api/progress"
  21. "github.com/compose-spec/compose-go/cli"
  22. "github.com/compose-spec/compose-go/types"
  23. moby "github.com/docker/docker/api/types"
  24. "github.com/docker/docker/api/types/filters"
  25. "golang.org/x/sync/errgroup"
  26. )
  27. func (s *composeService) Down(ctx context.Context, projectName string, options compose.DownOptions) error {
  28. w := progress.ContextWriter(ctx)
  29. resourceToRemove := false
  30. if options.Project == nil {
  31. project, err := s.projectFromContainerLabels(ctx, projectName)
  32. if err != nil {
  33. return err
  34. }
  35. options.Project = project
  36. }
  37. var containers Containers
  38. containers, err := s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
  39. Filters: filters.NewArgs(projectFilter(options.Project.Name)),
  40. All: true,
  41. })
  42. if err != nil {
  43. return err
  44. }
  45. if len(containers) > 0 {
  46. resourceToRemove = true
  47. }
  48. err = InReverseDependencyOrder(ctx, options.Project, func(c context.Context, service types.ServiceConfig) error {
  49. serviceContainers := containers.filter(isService(service.Name))
  50. err := s.removeContainers(ctx, w, serviceContainers, options.Timeout)
  51. return err
  52. })
  53. if err != nil {
  54. return err
  55. }
  56. orphans := containers.filter(isNotService(options.Project.ServiceNames()...))
  57. if options.RemoveOrphans && len(orphans) > 0 {
  58. err := s.removeContainers(ctx, w, orphans, options.Timeout)
  59. if err != nil {
  60. return err
  61. }
  62. }
  63. networks, err := s.apiClient.NetworkList(ctx, moby.NetworkListOptions{Filters: filters.NewArgs(projectFilter(projectName))})
  64. if err != nil {
  65. return err
  66. }
  67. eg, _ := errgroup.WithContext(ctx)
  68. for _, n := range networks {
  69. resourceToRemove = true
  70. networkID := n.ID
  71. networkName := n.Name
  72. eg.Go(func() error {
  73. return s.ensureNetworkDown(ctx, networkID, networkName)
  74. })
  75. }
  76. if !resourceToRemove {
  77. w.Event(progress.NewEvent(projectName, progress.Done, "Warning: No resource found to remove"))
  78. }
  79. return eg.Wait()
  80. }
  81. func (s *composeService) stopContainers(ctx context.Context, w progress.Writer, containers []moby.Container, timeout *time.Duration) error {
  82. for _, container := range containers {
  83. toStop := container
  84. eventName := getContainerProgressName(toStop)
  85. w.Event(progress.StoppingEvent(eventName))
  86. err := s.apiClient.ContainerStop(ctx, toStop.ID, timeout)
  87. if err != nil {
  88. w.Event(progress.ErrorMessageEvent(eventName, "Error while Stopping"))
  89. return err
  90. }
  91. w.Event(progress.StoppedEvent(eventName))
  92. }
  93. return nil
  94. }
  95. func (s *composeService) removeContainers(ctx context.Context, w progress.Writer, containers []moby.Container, timeout *time.Duration) error {
  96. eg, _ := errgroup.WithContext(ctx)
  97. for _, container := range containers {
  98. toDelete := container
  99. eg.Go(func() error {
  100. eventName := getContainerProgressName(toDelete)
  101. w.Event(progress.StoppingEvent(eventName))
  102. err := s.stopContainers(ctx, w, []moby.Container{toDelete}, timeout)
  103. if err != nil {
  104. w.Event(progress.ErrorMessageEvent(eventName, "Error while Stopping"))
  105. return err
  106. }
  107. w.Event(progress.RemovingEvent(eventName))
  108. err = s.apiClient.ContainerRemove(ctx, toDelete.ID, moby.ContainerRemoveOptions{Force: true})
  109. if err != nil {
  110. w.Event(progress.ErrorMessageEvent(eventName, "Error while Removing"))
  111. return err
  112. }
  113. w.Event(progress.RemovedEvent(eventName))
  114. return nil
  115. })
  116. }
  117. return eg.Wait()
  118. }
  119. func projectFilterListOpt(projectName string) moby.ContainerListOptions {
  120. return moby.ContainerListOptions{
  121. Filters: filters.NewArgs(projectFilter(projectName)),
  122. All: true,
  123. }
  124. }
  125. func (s *composeService) projectFromContainerLabels(ctx context.Context, projectName string) (*types.Project, error) {
  126. containers, err := s.apiClient.ContainerList(ctx, projectFilterListOpt(projectName))
  127. if err != nil {
  128. return nil, err
  129. }
  130. fakeProject := &types.Project{
  131. Name: projectName,
  132. }
  133. if len(containers) == 0 {
  134. return fakeProject, nil
  135. }
  136. options, err := loadProjectOptionsFromLabels(containers[0])
  137. if err != nil {
  138. return nil, err
  139. }
  140. if options.ConfigPaths[0] == "-" {
  141. for _, container := range containers {
  142. fakeProject.Services = append(fakeProject.Services, types.ServiceConfig{
  143. Name: container.Labels[serviceLabel],
  144. })
  145. }
  146. return fakeProject, nil
  147. }
  148. project, err := cli.ProjectFromOptions(options)
  149. if err != nil {
  150. return nil, err
  151. }
  152. return project, nil
  153. }
  154. func loadProjectOptionsFromLabels(c moby.Container) (*cli.ProjectOptions, error) {
  155. var configFiles []string
  156. relativePathConfigFiles := strings.Split(c.Labels[configFilesLabel], ",")
  157. for _, c := range relativePathConfigFiles {
  158. configFiles = append(configFiles, filepath.Base(c))
  159. }
  160. return cli.NewProjectOptions(configFiles,
  161. cli.WithOsEnv,
  162. cli.WithWorkingDirectory(c.Labels[workingDirLabel]),
  163. cli.WithName(c.Labels[projectLabel]))
  164. }