start.go 6.0 KB

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