start.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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/compose-spec/compose-go/types"
  17. moby "github.com/docker/docker/api/types"
  18. "github.com/pkg/errors"
  19. "golang.org/x/sync/errgroup"
  20. "github.com/docker/compose/v2/pkg/api"
  21. "github.com/docker/compose/v2/pkg/progress"
  22. )
  23. func (s *composeService) Start(ctx context.Context, project *types.Project, options api.StartOptions) error {
  24. return progress.Run(ctx, func(ctx context.Context) error {
  25. return s.start(ctx, project, options, nil)
  26. })
  27. }
  28. func (s *composeService) start(ctx context.Context, project *types.Project, options api.StartOptions, listener api.ContainerEventListener) error {
  29. if len(options.AttachTo) == 0 {
  30. options.AttachTo = project.ServiceNames()
  31. }
  32. eg, ctx := errgroup.WithContext(ctx)
  33. if listener != nil {
  34. attached, err := s.attach(ctx, project, listener, options.AttachTo)
  35. if err != nil {
  36. return err
  37. }
  38. eg.Go(func() error {
  39. return s.watchContainers(context.Background(), project.Name, options.AttachTo, listener, attached, func(container moby.Container) error {
  40. return s.attachContainer(ctx, container, listener, project)
  41. })
  42. })
  43. }
  44. err := InDependencyOrder(ctx, project, func(c context.Context, name string) error {
  45. service, err := project.GetService(name)
  46. if err != nil {
  47. return err
  48. }
  49. return s.startService(ctx, project, service)
  50. })
  51. if err != nil {
  52. return err
  53. }
  54. if options.Wait {
  55. depends := types.DependsOnConfig{}
  56. for _, s := range project.Services {
  57. depends[s.Name] = types.ServiceDependency{
  58. Condition: ServiceConditionRunningOrHealthy,
  59. }
  60. }
  61. err = s.waitDependencies(ctx, project, depends)
  62. if err != nil {
  63. return err
  64. }
  65. }
  66. return eg.Wait()
  67. }
  68. type containerWatchFn func(container moby.Container) error
  69. // watchContainers uses engine events to capture container start/die and notify ContainerEventListener
  70. func (s *composeService) watchContainers(ctx context.Context, projectName string, services []string, listener api.ContainerEventListener, containers Containers, onStart containerWatchFn) error {
  71. watched := map[string]int{}
  72. for _, c := range containers {
  73. watched[c.ID] = 0
  74. }
  75. ctx, stop := context.WithCancel(ctx)
  76. err := s.Events(ctx, projectName, api.EventsOptions{
  77. Services: services,
  78. Consumer: func(event api.Event) error {
  79. if event.Status == "destroy" {
  80. // This container can't be inspected, because it's gone.
  81. // It's already been removed from the watched map.
  82. return nil
  83. }
  84. inspected, err := s.apiClient.ContainerInspect(ctx, event.Container)
  85. if err != nil {
  86. return err
  87. }
  88. container := moby.Container{
  89. ID: inspected.ID,
  90. Names: []string{inspected.Name},
  91. Labels: inspected.Config.Labels,
  92. }
  93. name := getContainerNameWithoutProject(container)
  94. if event.Status == "die" {
  95. restarted := watched[container.ID]
  96. watched[container.ID] = restarted + 1
  97. // Container terminated.
  98. willRestart := willContainerRestart(inspected, restarted)
  99. listener(api.ContainerEvent{
  100. Type: api.ContainerEventExit,
  101. Container: name,
  102. Service: container.Labels[api.ServiceLabel],
  103. ExitCode: inspected.State.ExitCode,
  104. Restarting: willRestart,
  105. })
  106. if !willRestart {
  107. // we're done with this one
  108. delete(watched, container.ID)
  109. }
  110. if len(watched) == 0 {
  111. // all project containers stopped, we're done
  112. stop()
  113. }
  114. return nil
  115. }
  116. if event.Status == "start" {
  117. count, ok := watched[container.ID]
  118. mustAttach := ok && count > 0 // Container restarted, need to re-attach
  119. if !ok {
  120. // A new container has just been added to service by scale
  121. watched[container.ID] = 0
  122. mustAttach = true
  123. }
  124. if mustAttach {
  125. // Container restarted, need to re-attach
  126. err := onStart(container)
  127. if err != nil {
  128. return err
  129. }
  130. }
  131. }
  132. return nil
  133. },
  134. })
  135. if errors.Is(ctx.Err(), context.Canceled) {
  136. return nil
  137. }
  138. return err
  139. }
  140. func willContainerRestart(container moby.ContainerJSON, restarted int) bool {
  141. policy := container.HostConfig.RestartPolicy
  142. if policy.IsAlways() || policy.IsUnlessStopped() {
  143. return true
  144. }
  145. if policy.IsOnFailure() {
  146. return container.State.ExitCode != 0 && policy.MaximumRetryCount > restarted
  147. }
  148. return false
  149. }