kill.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 cmd
  14. import (
  15. "context"
  16. "fmt"
  17. "github.com/docker/compose-cli/cmd/formatter"
  18. "github.com/hashicorp/go-multierror"
  19. "github.com/pkg/errors"
  20. "github.com/spf13/cobra"
  21. "github.com/docker/compose-cli/api/client"
  22. "github.com/docker/compose-cli/pkg/api"
  23. )
  24. type killOpts struct {
  25. signal string
  26. }
  27. // KillCommand kills containers
  28. func KillCommand() *cobra.Command {
  29. var opts killOpts
  30. cmd := &cobra.Command{
  31. Use: "kill",
  32. Short: "Kill one or more running containers",
  33. Args: cobra.MinimumNArgs(1),
  34. RunE: func(cmd *cobra.Command, args []string) error {
  35. return runKill(cmd.Context(), args, opts)
  36. },
  37. }
  38. flags := cmd.Flags()
  39. flags.StringVarP(&opts.signal, "signal", "s", "KILL", "Signal to send to the container")
  40. return cmd
  41. }
  42. func runKill(ctx context.Context, args []string, opts killOpts) error {
  43. c, err := client.New(ctx)
  44. if err != nil {
  45. return errors.Wrap(err, "cannot connect to backend")
  46. }
  47. var errs *multierror.Error
  48. for _, id := range args {
  49. err := c.ContainerService().Kill(ctx, id, opts.signal)
  50. if err != nil {
  51. if api.IsNotFoundError(err) {
  52. errs = multierror.Append(errs, fmt.Errorf("container %s not found", id))
  53. } else {
  54. errs = multierror.Append(errs, err)
  55. }
  56. continue
  57. }
  58. fmt.Println(id)
  59. }
  60. formatter.SetMultiErrorFormat(errs)
  61. return errs.ErrorOrNil()
  62. }