start.go 6.1 KB

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