wait.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. "fmt"
  17. "github.com/docker/compose/v2/pkg/api"
  18. "golang.org/x/sync/errgroup"
  19. )
  20. func (s *composeService) Wait(ctx context.Context, projectName string, options api.WaitOptions) (int64, error) {
  21. containers, err := s.getContainers(ctx, projectName, oneOffInclude, false, options.Services...)
  22. if err != nil {
  23. return 0, err
  24. }
  25. if len(containers) == 0 {
  26. return 0, fmt.Errorf("no containers for project %q", projectName)
  27. }
  28. eg, waitCtx := errgroup.WithContext(ctx)
  29. var statusCode int64
  30. for _, c := range containers {
  31. c := c
  32. eg.Go(func() error {
  33. var err error
  34. resultC, errC := s.dockerCli.Client().ContainerWait(waitCtx, c.ID, "")
  35. select {
  36. case result := <-resultC:
  37. fmt.Fprintf(s.dockerCli.Out(), "container %q exited with status code %d\n", c.ID, result.StatusCode)
  38. statusCode = result.StatusCode
  39. case err = <-errC:
  40. }
  41. return err
  42. })
  43. }
  44. err = eg.Wait()
  45. if err != nil {
  46. return 42, err // Ignore abort flag in case of error in wait
  47. }
  48. if options.DownProjectOnContainerExit {
  49. return statusCode, s.Down(ctx, projectName, api.DownOptions{
  50. RemoveOrphans: true,
  51. })
  52. }
  53. return statusCode, err
  54. }