stop.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/hashicorp/go-multierror"
  18. "github.com/pkg/errors"
  19. "github.com/spf13/cobra"
  20. "github.com/docker/compose-cli/api/client"
  21. "github.com/docker/compose-cli/api/errdefs"
  22. "github.com/docker/compose-cli/cli/formatter"
  23. )
  24. type stopOpts struct {
  25. timeout uint32
  26. }
  27. // StopCommand deletes containers
  28. func StopCommand() *cobra.Command {
  29. var opts stopOpts
  30. cmd := &cobra.Command{
  31. Use: "stop",
  32. Short: "Stop one or more running containers",
  33. Args: cobra.MinimumNArgs(1),
  34. RunE: func(cmd *cobra.Command, args []string) error {
  35. return runStop(cmd.Context(), args, opts)
  36. },
  37. }
  38. cmd.Flags().Uint32Var(&opts.timeout, "timeout", 0, "Seconds to wait for stop before killing it (default 0, no timeout)")
  39. return cmd
  40. }
  41. func runStop(ctx context.Context, args []string, opts stopOpts) error {
  42. c, err := client.New(ctx)
  43. if err != nil {
  44. return errors.Wrap(err, "cannot connect to backend")
  45. }
  46. var errs *multierror.Error
  47. for _, id := range args {
  48. err := c.ContainerService().Stop(ctx, id, &opts.timeout)
  49. if err != nil {
  50. if errdefs.IsNotFoundError(err) {
  51. errs = multierror.Append(errs, fmt.Errorf("container %s not found", id))
  52. } else {
  53. errs = multierror.Append(errs, err)
  54. }
  55. continue
  56. }
  57. fmt.Println(id)
  58. }
  59. formatter.SetMultiErrorFormat(errs)
  60. return errs.ErrorOrNil()
  61. }