start.go 5.3 KB

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