start.go 5.9 KB

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