start.go 5.2 KB

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