start.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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-cli/api/compose"
  18. "github.com/compose-spec/compose-go/types"
  19. "github.com/docker/docker/api/types/container"
  20. "golang.org/x/sync/errgroup"
  21. )
  22. func (s *composeService) Start(ctx context.Context, project *types.Project, options compose.StartOptions) error {
  23. var containers Containers
  24. if options.Attach != nil {
  25. c, err := s.attach(ctx, project, options.Attach)
  26. if err != nil {
  27. return err
  28. }
  29. containers = c
  30. } else {
  31. c, err := s.getContainers(ctx, project)
  32. if err != nil {
  33. return err
  34. }
  35. containers = c
  36. }
  37. err := InDependencyOrder(ctx, project, func(c context.Context, service types.ServiceConfig) error {
  38. return s.startService(ctx, project, service)
  39. })
  40. if err != nil {
  41. return err
  42. }
  43. if options.Attach == nil {
  44. return nil
  45. }
  46. eg, ctx := errgroup.WithContext(ctx)
  47. for _, c := range containers {
  48. c := c
  49. eg.Go(func() error {
  50. statusC, errC := s.apiClient.ContainerWait(ctx, c.ID, container.WaitConditionNotRunning)
  51. select {
  52. case status := <-statusC:
  53. service := c.Labels[serviceLabel]
  54. options.Attach.Status(service, getCanonicalContainerName(c), fmt.Sprintf("exited with code %d", status.StatusCode))
  55. if options.Listener != nil {
  56. options.Listener <- compose.ContainerExited{
  57. Service: service,
  58. Status: int(status.StatusCode),
  59. }
  60. }
  61. return nil
  62. case err := <-errC:
  63. return err
  64. }
  65. })
  66. }
  67. return eg.Wait()
  68. }