start.go 7.5 KB

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