start.go 7.9 KB

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