kill.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. "strings"
  17. "github.com/moby/moby/api/types/container"
  18. "github.com/moby/moby/client"
  19. "golang.org/x/sync/errgroup"
  20. "github.com/docker/compose/v5/pkg/api"
  21. )
  22. func (s *composeService) Kill(ctx context.Context, projectName string, options api.KillOptions) error {
  23. return Run(ctx, func(ctx context.Context) error {
  24. return s.kill(ctx, strings.ToLower(projectName), options)
  25. }, "kill", s.events)
  26. }
  27. func (s *composeService) kill(ctx context.Context, projectName string, options api.KillOptions) error {
  28. services := options.Services
  29. var containers Containers
  30. containers, err := s.getContainers(ctx, projectName, oneOffInclude, options.All, services...)
  31. if err != nil {
  32. return err
  33. }
  34. project := options.Project
  35. if project == nil {
  36. project, err = s.getProjectWithResources(ctx, containers, projectName)
  37. if err != nil {
  38. return err
  39. }
  40. }
  41. if !options.RemoveOrphans {
  42. containers = containers.filter(isService(project.ServiceNames()...))
  43. }
  44. if len(containers) == 0 {
  45. return api.ErrNoResources
  46. }
  47. eg, ctx := errgroup.WithContext(ctx)
  48. containers.forEach(func(ctr container.Summary) {
  49. eg.Go(func() error {
  50. eventName := getContainerProgressName(ctr)
  51. s.events.On(killingEvent(eventName))
  52. _, err := s.apiClient().ContainerKill(ctx, ctr.ID, client.ContainerKillOptions{
  53. Signal: options.Signal,
  54. })
  55. if err != nil {
  56. s.events.On(errorEvent(eventName, "Error while Killing"))
  57. return err
  58. }
  59. s.events.On(killedEvent(eventName))
  60. return nil
  61. })
  62. })
  63. return eg.Wait()
  64. }