down.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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/compose-spec/compose-go/types"
  18. "github.com/docker/compose-cli/api/compose"
  19. "github.com/spf13/cobra"
  20. "github.com/docker/compose-cli/api/client"
  21. "github.com/docker/compose-cli/api/progress"
  22. )
  23. type downOptions struct {
  24. *projectOptions
  25. removeOrphans bool
  26. timeChanged bool
  27. timeout int
  28. }
  29. func downCommand(p *projectOptions) *cobra.Command {
  30. opts := downOptions{
  31. projectOptions: p,
  32. }
  33. downCmd := &cobra.Command{
  34. Use: "down",
  35. Short: "Stop and remove containers, networks",
  36. RunE: func(cmd *cobra.Command, args []string) error {
  37. opts.timeChanged = cmd.Flags().Changed("timeout")
  38. return runDown(cmd.Context(), opts)
  39. },
  40. }
  41. flags := downCmd.Flags()
  42. flags.BoolVar(&opts.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file.")
  43. flags.IntVarP(&opts.timeout, "timeout", "t", 10, "Specify a shutdown timeout in seconds")
  44. return downCmd
  45. }
  46. func runDown(ctx context.Context, opts downOptions) error {
  47. c, err := client.NewWithDefaultLocalBackend(ctx)
  48. if err != nil {
  49. return err
  50. }
  51. _, err = progress.Run(ctx, func(ctx context.Context) (string, error) {
  52. name := opts.ProjectName
  53. var project *types.Project
  54. if opts.ProjectName == "" {
  55. p, err := opts.toProject(nil)
  56. if err != nil {
  57. return "", err
  58. }
  59. project = p
  60. name = p.Name
  61. }
  62. var timeout *time.Duration
  63. if opts.timeChanged {
  64. timeoutValue := time.Duration(opts.timeout) * time.Second
  65. timeout = &timeoutValue
  66. }
  67. return name, c.ComposeService().Down(ctx, name, compose.DownOptions{
  68. RemoveOrphans: opts.removeOrphans,
  69. Project: project,
  70. Timeout: timeout,
  71. })
  72. })
  73. return err
  74. }