stop.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. "time"
  17. "github.com/docker/cli/cli/command"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/compose/v2/pkg/api"
  20. )
  21. type stopOptions struct {
  22. *ProjectOptions
  23. timeChanged bool
  24. timeout int
  25. }
  26. func stopCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  27. opts := stopOptions{
  28. ProjectOptions: p,
  29. }
  30. cmd := &cobra.Command{
  31. Use: "stop [OPTIONS] [SERVICE...]",
  32. Short: "Stop services",
  33. PreRun: func(cmd *cobra.Command, args []string) {
  34. opts.timeChanged = cmd.Flags().Changed("timeout")
  35. },
  36. RunE: Adapt(func(ctx context.Context, args []string) error {
  37. return runStop(ctx, dockerCli, backend, opts, args)
  38. }),
  39. ValidArgsFunction: completeServiceNames(dockerCli, p),
  40. }
  41. flags := cmd.Flags()
  42. flags.IntVarP(&opts.timeout, "timeout", "t", 0, "Specify a shutdown timeout in seconds")
  43. return cmd
  44. }
  45. func runStop(ctx context.Context, dockerCli command.Cli, backend api.Service, opts stopOptions, services []string) error {
  46. project, name, err := opts.projectOrName(ctx, dockerCli, services...)
  47. if err != nil {
  48. return err
  49. }
  50. var timeout *time.Duration
  51. if opts.timeChanged {
  52. timeoutValue := time.Duration(opts.timeout) * time.Second
  53. timeout = &timeoutValue
  54. }
  55. return backend.Stop(ctx, name, api.StopOptions{
  56. Timeout: timeout,
  57. Services: services,
  58. Project: project,
  59. })
  60. }