start.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. "strings"
  17. "github.com/compose-spec/compose-go/types"
  18. "github.com/docker/compose/v2/pkg/utils"
  19. moby "github.com/docker/docker/api/types"
  20. "github.com/pkg/errors"
  21. "golang.org/x/sync/errgroup"
  22. "github.com/docker/compose/v2/pkg/api"
  23. "github.com/docker/compose/v2/pkg/progress"
  24. )
  25. func (s *composeService) Start(ctx context.Context, projectName string, options api.StartOptions) error {
  26. return progress.Run(ctx, func(ctx context.Context) error {
  27. return s.start(ctx, strings.ToLower(projectName), options, nil)
  28. })
  29. }
  30. func (s *composeService) start(ctx context.Context, projectName string, options api.StartOptions, listener api.ContainerEventListener) error {
  31. project := options.Project
  32. if project == nil {
  33. var containers Containers
  34. containers, err := s.getContainers(ctx, projectName, oneOffExclude, true)
  35. if err != nil {
  36. return err
  37. }
  38. project, err = s.projectFromName(containers, projectName, options.AttachTo...)
  39. if err != nil {
  40. return err
  41. }
  42. }
  43. eg, ctx := errgroup.WithContext(ctx)
  44. if listener != nil {
  45. attached, err := s.attach(ctx, project, listener, options.AttachTo)
  46. if err != nil {
  47. return err
  48. }
  49. eg.Go(func() error {
  50. return s.watchContainers(context.Background(), project.Name, options.AttachTo, options.Services, listener, attached, func(container moby.Container) error {
  51. return s.attachContainer(ctx, container, listener)
  52. })
  53. })
  54. }
  55. err := InDependencyOrder(ctx, project, func(c context.Context, name string) error {
  56. service, err := project.GetService(name)
  57. if err != nil {
  58. return err
  59. }
  60. return s.startService(ctx, project, service)
  61. })
  62. if err != nil {
  63. return err
  64. }
  65. if options.Wait {
  66. depends := types.DependsOnConfig{}
  67. for _, s := range project.Services {
  68. depends[s.Name] = types.ServiceDependency{
  69. Condition: getDependencyCondition(s, project),
  70. }
  71. }
  72. err = s.waitDependencies(ctx, project, depends)
  73. if err != nil {
  74. return err
  75. }
  76. }
  77. return eg.Wait()
  78. }
  79. // getDependencyCondition checks if service is depended on by other services
  80. // with service_completed_successfully condition, and applies that condition
  81. // instead, or --wait will never finish waiting for one-shot containers
  82. func getDependencyCondition(service types.ServiceConfig, project *types.Project) string {
  83. for _, services := range project.Services {
  84. for dependencyService, dependencyConfig := range services.DependsOn {
  85. if dependencyService == service.Name && dependencyConfig.Condition == types.ServiceConditionCompletedSuccessfully {
  86. return types.ServiceConditionCompletedSuccessfully
  87. }
  88. }
  89. }
  90. return ServiceConditionRunningOrHealthy
  91. }
  92. type containerWatchFn func(container moby.Container) error
  93. // watchContainers uses engine events to capture container start/die and notify ContainerEventListener
  94. func (s *composeService) watchContainers(ctx context.Context, //nolint:gocyclo
  95. projectName string, services, required []string,
  96. listener api.ContainerEventListener, containers Containers, onStart containerWatchFn) error {
  97. if len(containers) == 0 {
  98. return nil
  99. }
  100. if len(required) == 0 {
  101. required = services
  102. }
  103. var (
  104. expected Containers
  105. watched = map[string]int{}
  106. )
  107. for _, c := range containers {
  108. if utils.Contains(required, c.Labels[api.ServiceLabel]) {
  109. expected = append(expected, c)
  110. }
  111. watched[c.ID] = 0
  112. }
  113. ctx, stop := context.WithCancel(ctx)
  114. err := s.Events(ctx, projectName, api.EventsOptions{
  115. Services: services,
  116. Consumer: func(event api.Event) error {
  117. if event.Status == "destroy" {
  118. // This container can't be inspected, because it's gone.
  119. // It's already been removed from the watched map.
  120. return nil
  121. }
  122. inspected, err := s.apiClient().ContainerInspect(ctx, event.Container)
  123. if err != nil {
  124. return err
  125. }
  126. container := moby.Container{
  127. ID: inspected.ID,
  128. Names: []string{inspected.Name},
  129. Labels: inspected.Config.Labels,
  130. }
  131. name := getContainerNameWithoutProject(container)
  132. service := container.Labels[api.ServiceLabel]
  133. switch event.Status {
  134. case "stop":
  135. listener(api.ContainerEvent{
  136. Type: api.ContainerEventStopped,
  137. Container: name,
  138. Service: service,
  139. })
  140. delete(watched, container.ID)
  141. expected = expected.remove(container.ID)
  142. case "die":
  143. restarted := watched[container.ID]
  144. watched[container.ID] = restarted + 1
  145. // Container terminated.
  146. willRestart := willContainerRestart(inspected, restarted)
  147. listener(api.ContainerEvent{
  148. Type: api.ContainerEventExit,
  149. Container: name,
  150. Service: service,
  151. ExitCode: inspected.State.ExitCode,
  152. Restarting: willRestart,
  153. })
  154. if !willRestart {
  155. // we're done with this one
  156. delete(watched, container.ID)
  157. expected = expected.remove(container.ID)
  158. }
  159. case "start":
  160. count, ok := watched[container.ID]
  161. mustAttach := ok && count > 0 // Container restarted, need to re-attach
  162. if !ok {
  163. // A new container has just been added to service by scale
  164. watched[container.ID] = 0
  165. expected = append(expected, container)
  166. mustAttach = true
  167. }
  168. if mustAttach {
  169. // Container restarted, need to re-attach
  170. err := onStart(container)
  171. if err != nil {
  172. return err
  173. }
  174. }
  175. }
  176. if len(expected) == 0 {
  177. stop()
  178. }
  179. return nil
  180. },
  181. })
  182. if errors.Is(ctx.Err(), context.Canceled) {
  183. return nil
  184. }
  185. return err
  186. }
  187. func willContainerRestart(container moby.ContainerJSON, restarted int) bool {
  188. policy := container.HostConfig.RestartPolicy
  189. if policy.IsAlways() || policy.IsUnlessStopped() {
  190. return true
  191. }
  192. if policy.IsOnFailure() {
  193. return container.State.ExitCode != 0 && policy.MaximumRetryCount > restarted
  194. }
  195. return false
  196. }