wait.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. Copyright 2023 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. "os"
  17. "github.com/docker/cli/cli"
  18. "github.com/docker/cli/cli/command"
  19. "github.com/spf13/cobra"
  20. "github.com/docker/compose/v5/pkg/api"
  21. "github.com/docker/compose/v5/pkg/compose"
  22. )
  23. type waitOptions struct {
  24. *ProjectOptions
  25. services []string
  26. downProject bool
  27. }
  28. func waitCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command {
  29. opts := waitOptions{
  30. ProjectOptions: p,
  31. }
  32. var statusCode int64
  33. var err error
  34. cmd := &cobra.Command{
  35. Use: "wait SERVICE [SERVICE...] [OPTIONS]",
  36. Short: "Block until containers of all (or specified) services stop.",
  37. Args: cli.RequiresMinArgs(1),
  38. RunE: Adapt(func(ctx context.Context, services []string) error {
  39. opts.services = services
  40. statusCode, err = runWait(ctx, dockerCli, backendOptions, &opts)
  41. return err
  42. }),
  43. PostRun: func(cmd *cobra.Command, args []string) {
  44. os.Exit(int(statusCode))
  45. },
  46. }
  47. cmd.Flags().BoolVar(&opts.downProject, "down-project", false, "Drops project when the first container stops")
  48. return cmd
  49. }
  50. func runWait(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts *waitOptions) (int64, error) {
  51. _, name, err := opts.projectOrName(ctx, dockerCli)
  52. if err != nil {
  53. return 0, err
  54. }
  55. backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...)
  56. if err != nil {
  57. return 0, err
  58. }
  59. return backend.Wait(ctx, name, api.WaitOptions{
  60. Services: opts.services,
  61. DownProjectOnContainerExit: opts.downProject,
  62. })
  63. }