kill.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. "os"
  17. "github.com/docker/cli/cli/command"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/compose/v2/pkg/api"
  20. "github.com/docker/compose/v2/pkg/utils"
  21. )
  22. type killOptions struct {
  23. *ProjectOptions
  24. removeOrphans bool
  25. signal string
  26. }
  27. func killCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  28. opts := killOptions{
  29. ProjectOptions: p,
  30. }
  31. cmd := &cobra.Command{
  32. Use: "kill [OPTIONS] [SERVICE...]",
  33. Short: "Force stop service containers",
  34. RunE: Adapt(func(ctx context.Context, args []string) error {
  35. return runKill(ctx, dockerCli, backend, opts, args)
  36. }),
  37. ValidArgsFunction: completeServiceNames(dockerCli, p),
  38. }
  39. flags := cmd.Flags()
  40. removeOrphans := utils.StringToBool(os.Getenv(ComposeRemoveOrphans))
  41. flags.BoolVar(&opts.removeOrphans, "remove-orphans", removeOrphans, "Remove containers for services not defined in the Compose file")
  42. flags.StringVarP(&opts.signal, "signal", "s", "SIGKILL", "SIGNAL to send to the container")
  43. return cmd
  44. }
  45. func runKill(ctx context.Context, dockerCli command.Cli, backend api.Service, opts killOptions, services []string) error {
  46. project, name, err := opts.projectOrName(ctx, dockerCli, services...)
  47. if err != nil {
  48. return err
  49. }
  50. return backend.Kill(ctx, name, api.KillOptions{
  51. RemoveOrphans: opts.removeOrphans,
  52. Project: project,
  53. Services: services,
  54. Signal: opts.signal,
  55. })
  56. }