start.go 5.3 KB

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