start.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. "github.com/docker/compose-cli/api/compose"
  17. "github.com/compose-spec/compose-go/types"
  18. moby "github.com/docker/docker/api/types"
  19. "github.com/docker/docker/api/types/container"
  20. "github.com/sirupsen/logrus"
  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, options.Services)
  26. if err != nil {
  27. return err
  28. }
  29. containers = c
  30. }
  31. err := InDependencyOrder(ctx, project, func(c context.Context, service types.ServiceConfig) error {
  32. return s.startService(ctx, project, service)
  33. })
  34. if err != nil {
  35. return err
  36. }
  37. if options.Attach == nil {
  38. return nil
  39. }
  40. for _, c := range containers {
  41. c := c
  42. go func() {
  43. s.waitContainer(ctx, c, options.Attach)
  44. }()
  45. }
  46. return nil
  47. }
  48. func (s *composeService) waitContainer(ctx context.Context, c moby.Container, listener compose.ContainerEventListener) {
  49. statusC, errC := s.apiClient.ContainerWait(ctx, c.ID, container.WaitConditionNotRunning)
  50. name := getContainerNameWithoutProject(c)
  51. select {
  52. case status := <-statusC:
  53. listener(compose.ContainerEvent{
  54. Type: compose.ContainerEventExit,
  55. Container: name,
  56. Service: c.Labels[serviceLabel],
  57. ExitCode: int(status.StatusCode),
  58. })
  59. case err := <-errC:
  60. logrus.Warnf("Unexpected API error for %s : %s", name, err.Error())
  61. }
  62. }