down.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. "strings"
  18. "time"
  19. "github.com/compose-spec/compose-go/types"
  20. moby "github.com/docker/docker/api/types"
  21. "github.com/docker/docker/errdefs"
  22. "golang.org/x/sync/errgroup"
  23. "github.com/docker/compose/v2/pkg/api"
  24. "github.com/docker/compose/v2/pkg/progress"
  25. )
  26. type downOp func() error
  27. func (s *composeService) Down(ctx context.Context, projectName string, options api.DownOptions) error {
  28. return progress.Run(ctx, func(ctx context.Context) error {
  29. return s.down(ctx, strings.ToLower(projectName), options)
  30. })
  31. }
  32. func (s *composeService) down(ctx context.Context, projectName string, options api.DownOptions) error {
  33. w := progress.ContextWriter(ctx)
  34. resourceToRemove := false
  35. var containers Containers
  36. containers, err := s.getContainers(ctx, projectName, oneOffInclude, true)
  37. if err != nil {
  38. return err
  39. }
  40. project := options.Project
  41. if project == nil {
  42. project, err = s.getProjectWithResources(ctx, containers, projectName)
  43. if err != nil {
  44. return err
  45. }
  46. }
  47. if len(containers) > 0 {
  48. resourceToRemove = true
  49. }
  50. err = InReverseDependencyOrder(ctx, project, func(c context.Context, service string) error {
  51. serviceContainers := containers.filter(isService(service))
  52. err := s.removeContainers(ctx, w, serviceContainers, options.Timeout, options.Volumes)
  53. return err
  54. })
  55. if err != nil {
  56. return err
  57. }
  58. orphans := containers.filter(isNotService(project.ServiceNames()...))
  59. if options.RemoveOrphans && len(orphans) > 0 {
  60. err := s.removeContainers(ctx, w, orphans, options.Timeout, false)
  61. if err != nil {
  62. return err
  63. }
  64. }
  65. ops := s.ensureNetworksDown(ctx, project, w)
  66. if options.Images != "" {
  67. ops = append(ops, s.ensureImagesDown(ctx, projectName, options, w)...)
  68. }
  69. if options.Volumes {
  70. ops = append(ops, s.ensureVolumesDown(ctx, project, w)...)
  71. }
  72. if !resourceToRemove && len(ops) == 0 {
  73. w.Event(progress.NewEvent(projectName, progress.Done, "Warning: No resource found to remove"))
  74. }
  75. eg, _ := errgroup.WithContext(ctx)
  76. for _, op := range ops {
  77. eg.Go(op)
  78. }
  79. return eg.Wait()
  80. }
  81. func (s *composeService) ensureVolumesDown(ctx context.Context, project *types.Project, w progress.Writer) []downOp {
  82. var ops []downOp
  83. for _, vol := range project.Volumes {
  84. if vol.External.External {
  85. continue
  86. }
  87. volumeName := vol.Name
  88. ops = append(ops, func() error {
  89. return s.removeVolume(ctx, volumeName, w)
  90. })
  91. }
  92. return ops
  93. }
  94. func (s *composeService) ensureImagesDown(ctx context.Context, projectName string, options api.DownOptions, w progress.Writer) []downOp {
  95. var ops []downOp
  96. for image := range s.getServiceImages(options, projectName) {
  97. image := image
  98. ops = append(ops, func() error {
  99. return s.removeImage(ctx, image, w)
  100. })
  101. }
  102. return ops
  103. }
  104. func (s *composeService) ensureNetworksDown(ctx context.Context, project *types.Project, w progress.Writer) []downOp {
  105. var ops []downOp
  106. for _, n := range project.Networks {
  107. if n.External.External {
  108. continue
  109. }
  110. networkName := n.Name
  111. ops = append(ops, func() error {
  112. return s.removeNetwork(ctx, networkName, w)
  113. })
  114. }
  115. return ops
  116. }
  117. func (s *composeService) getServiceImages(options api.DownOptions, projectName string) map[string]struct{} {
  118. images := map[string]struct{}{}
  119. for _, service := range options.Project.Services {
  120. image := service.Image
  121. if options.Images == "local" && image != "" {
  122. continue
  123. }
  124. if image == "" {
  125. image = getImageName(service, projectName)
  126. }
  127. images[image] = struct{}{}
  128. }
  129. return images
  130. }
  131. func (s *composeService) removeImage(ctx context.Context, image string, w progress.Writer) error {
  132. id := fmt.Sprintf("Image %s", image)
  133. w.Event(progress.NewEvent(id, progress.Working, "Removing"))
  134. _, err := s.apiClient().ImageRemove(ctx, image, moby.ImageRemoveOptions{})
  135. if err == nil {
  136. w.Event(progress.NewEvent(id, progress.Done, "Removed"))
  137. return nil
  138. }
  139. if errdefs.IsNotFound(err) {
  140. w.Event(progress.NewEvent(id, progress.Done, "Warning: No resource found to remove"))
  141. return nil
  142. }
  143. return err
  144. }
  145. func (s *composeService) removeVolume(ctx context.Context, id string, w progress.Writer) error {
  146. resource := fmt.Sprintf("Volume %s", id)
  147. w.Event(progress.NewEvent(resource, progress.Working, "Removing"))
  148. err := s.apiClient().VolumeRemove(ctx, id, true)
  149. if err == nil {
  150. w.Event(progress.NewEvent(resource, progress.Done, "Removed"))
  151. return nil
  152. }
  153. if errdefs.IsNotFound(err) {
  154. w.Event(progress.NewEvent(resource, progress.Done, "Warning: No resource found to remove"))
  155. return nil
  156. }
  157. return err
  158. }
  159. func (s *composeService) stopContainers(ctx context.Context, w progress.Writer, containers []moby.Container, timeout *time.Duration) error {
  160. eg, ctx := errgroup.WithContext(ctx)
  161. for _, container := range containers {
  162. container := container
  163. eg.Go(func() error {
  164. eventName := getContainerProgressName(container)
  165. w.Event(progress.StoppingEvent(eventName))
  166. err := s.apiClient().ContainerStop(ctx, container.ID, timeout)
  167. if err != nil {
  168. w.Event(progress.ErrorMessageEvent(eventName, "Error while Stopping"))
  169. return err
  170. }
  171. w.Event(progress.StoppedEvent(eventName))
  172. return nil
  173. })
  174. }
  175. return eg.Wait()
  176. }
  177. func (s *composeService) removeContainers(ctx context.Context, w progress.Writer, containers []moby.Container, timeout *time.Duration, volumes bool) error {
  178. eg, _ := errgroup.WithContext(ctx)
  179. for _, container := range containers {
  180. container := container
  181. eg.Go(func() error {
  182. eventName := getContainerProgressName(container)
  183. w.Event(progress.StoppingEvent(eventName))
  184. err := s.stopContainers(ctx, w, []moby.Container{container}, timeout)
  185. if err != nil {
  186. w.Event(progress.ErrorMessageEvent(eventName, "Error while Stopping"))
  187. return err
  188. }
  189. w.Event(progress.RemovingEvent(eventName))
  190. err = s.apiClient().ContainerRemove(ctx, container.ID, moby.ContainerRemoveOptions{
  191. Force: true,
  192. RemoveVolumes: volumes,
  193. })
  194. if err != nil {
  195. w.Event(progress.ErrorMessageEvent(eventName, "Error while Removing"))
  196. return err
  197. }
  198. w.Event(progress.RemovedEvent(eventName))
  199. return nil
  200. })
  201. }
  202. return eg.Wait()
  203. }
  204. func (s *composeService) getProjectWithResources(ctx context.Context, containers Containers, projectName string) (*types.Project, error) {
  205. containers = containers.filter(isNotOneOff)
  206. project, _ := s.projectFromName(containers, projectName)
  207. volumes, err := s.actualVolumes(ctx, projectName)
  208. if err != nil {
  209. return nil, err
  210. }
  211. project.Volumes = volumes
  212. networks, err := s.actualNetworks(ctx, projectName)
  213. if err != nil {
  214. return nil, err
  215. }
  216. project.Networks = networks
  217. return project, nil
  218. }