stop.go 1.8 KB

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