down.go 7.2 KB

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