wait.go 1.9 KB

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