stop.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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/spf13/cobra"
  18. "github.com/docker/compose-cli/api/client"
  19. "github.com/docker/compose-cli/api/compose"
  20. "github.com/docker/compose-cli/api/progress"
  21. )
  22. type stopOptions struct {
  23. *projectOptions
  24. timeChanged bool
  25. timeout int
  26. }
  27. func stopCommand(p *projectOptions) *cobra.Command {
  28. opts := stopOptions{
  29. projectOptions: p,
  30. }
  31. cmd := &cobra.Command{
  32. Use: "stop [SERVICE...]",
  33. Short: "Stop services",
  34. RunE: func(cmd *cobra.Command, args []string) error {
  35. opts.timeChanged = cmd.Flags().Changed("timeout")
  36. return runStop(cmd.Context(), opts, args)
  37. },
  38. }
  39. flags := cmd.Flags()
  40. flags.IntVarP(&opts.timeout, "timeout", "t", 10, "Specify a shutdown timeout in seconds")
  41. return cmd
  42. }
  43. func runStop(ctx context.Context, opts stopOptions, services []string) error {
  44. c, err := client.New(ctx)
  45. if err != nil {
  46. return err
  47. }
  48. project, err := opts.toProject(services)
  49. if err != nil {
  50. return err
  51. }
  52. var timeout *time.Duration
  53. if opts.timeChanged {
  54. timeoutValue := time.Duration(opts.timeout) * time.Second
  55. timeout = &timeoutValue
  56. }
  57. _, err = progress.Run(ctx, func(ctx context.Context) (string, error) {
  58. return "", c.ComposeService().Stop(ctx, project, compose.StopOptions{
  59. Timeout: timeout,
  60. })
  61. })
  62. return err
  63. }