start.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. }, func(container moby.Container, _ time.Time) error {
  55. listener(api.ContainerEvent{
  56. Type: api.ContainerEventAttach,
  57. Container: "", // actual name will be set by start event
  58. ID: container.ID,
  59. Service: container.Labels[api.ServiceLabel],
  60. })
  61. return nil
  62. })
  63. })
  64. }
  65. err := InDependencyOrder(ctx, project, func(c context.Context, name string) error {
  66. service, err := project.GetService(name)
  67. if err != nil {
  68. return err
  69. }
  70. return s.startService(ctx, project, service)
  71. })
  72. if err != nil {
  73. return err
  74. }
  75. if options.Wait {
  76. depends := types.DependsOnConfig{}
  77. for _, s := range project.Services {
  78. depends[s.Name] = types.ServiceDependency{
  79. Condition: getDependencyCondition(s, project),
  80. }
  81. }
  82. err = s.waitDependencies(ctx, project, depends)
  83. if err != nil {
  84. return err
  85. }
  86. }
  87. return eg.Wait()
  88. }
  89. // getDependencyCondition checks if service is depended on by other services
  90. // with service_completed_successfully condition, and applies that condition
  91. // instead, or --wait will never finish waiting for one-shot containers
  92. func getDependencyCondition(service types.ServiceConfig, project *types.Project) string {
  93. for _, services := range project.Services {
  94. for dependencyService, dependencyConfig := range services.DependsOn {
  95. if dependencyService == service.Name && dependencyConfig.Condition == types.ServiceConditionCompletedSuccessfully {
  96. return types.ServiceConditionCompletedSuccessfully
  97. }
  98. }
  99. }
  100. return ServiceConditionRunningOrHealthy
  101. }
  102. type containerWatchFn func(container moby.Container, t time.Time) error
  103. // watchContainers uses engine events to capture container start/die and notify ContainerEventListener
  104. func (s *composeService) watchContainers(ctx context.Context, //nolint:gocyclo
  105. projectName string, services, required []string,
  106. listener api.ContainerEventListener, containers Containers, onStart, onRecreate containerWatchFn) error {
  107. if len(containers) == 0 {
  108. return nil
  109. }
  110. if len(required) == 0 {
  111. required = services
  112. }
  113. var (
  114. expected []string
  115. watched = map[string]int{}
  116. replaced []string
  117. )
  118. for _, c := range containers {
  119. if utils.Contains(required, c.Labels[api.ServiceLabel]) {
  120. expected = append(expected, c.ID)
  121. }
  122. watched[c.ID] = 0
  123. }
  124. ctx, stop := context.WithCancel(ctx)
  125. err := s.Events(ctx, projectName, api.EventsOptions{
  126. Services: services,
  127. Consumer: func(event api.Event) error {
  128. if event.Status == "destroy" {
  129. // This container can't be inspected, because it's gone.
  130. // It's already been removed from the watched map.
  131. return nil
  132. }
  133. inspected, err := s.apiClient().ContainerInspect(ctx, event.Container)
  134. if err != nil {
  135. return err
  136. }
  137. container := moby.Container{
  138. ID: inspected.ID,
  139. Names: []string{inspected.Name},
  140. Labels: inspected.Config.Labels,
  141. }
  142. name := getContainerNameWithoutProject(container)
  143. service := container.Labels[api.ServiceLabel]
  144. switch event.Status {
  145. case "stop":
  146. if _, ok := watched[container.ID]; ok {
  147. eType := api.ContainerEventStopped
  148. if utils.Contains(replaced, container.ID) {
  149. utils.Remove(replaced, container.ID)
  150. eType = api.ContainerEventRecreated
  151. }
  152. listener(api.ContainerEvent{
  153. Type: eType,
  154. Container: name,
  155. ID: container.ID,
  156. Service: service,
  157. })
  158. }
  159. delete(watched, container.ID)
  160. expected = utils.Remove(expected, container.ID)
  161. case "die":
  162. restarted := watched[container.ID]
  163. watched[container.ID] = restarted + 1
  164. // Container terminated.
  165. willRestart := inspected.State.Restarting
  166. eType := api.ContainerEventExit
  167. if utils.Contains(replaced, container.ID) {
  168. utils.Remove(replaced, container.ID)
  169. eType = api.ContainerEventRecreated
  170. }
  171. listener(api.ContainerEvent{
  172. Type: eType,
  173. Container: name,
  174. ID: container.ID,
  175. Service: service,
  176. ExitCode: inspected.State.ExitCode,
  177. Restarting: willRestart,
  178. })
  179. if !willRestart {
  180. // we're done with this one
  181. delete(watched, container.ID)
  182. expected = utils.Remove(expected, container.ID)
  183. }
  184. case "start":
  185. count, ok := watched[container.ID]
  186. mustAttach := ok && count > 0 // Container restarted, need to re-attach
  187. if !ok {
  188. // A new container has just been added to service by scale
  189. watched[container.ID] = 0
  190. expected = append(expected, container.ID)
  191. mustAttach = true
  192. }
  193. if mustAttach {
  194. // Container restarted, need to re-attach
  195. err := onStart(container, event.Timestamp)
  196. if err != nil {
  197. return err
  198. }
  199. }
  200. case "create":
  201. if id, ok := container.Labels[api.ContainerReplaceLabel]; ok {
  202. replaced = append(replaced, id)
  203. err = onRecreate(container, event.Timestamp)
  204. if err != nil {
  205. return err
  206. }
  207. if utils.StringContains(expected, id) {
  208. expected = append(expected, inspected.ID)
  209. }
  210. watched[container.ID] = 1
  211. if utils.Contains(expected, id) {
  212. expected = append(expected, container.ID)
  213. }
  214. }
  215. }
  216. if len(expected) == 0 {
  217. stop()
  218. }
  219. return nil
  220. },
  221. })
  222. if errors.Is(ctx.Err(), context.Canceled) {
  223. return nil
  224. }
  225. return err
  226. }