stop.go 1.8 KB

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