start.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. "errors"
  17. "fmt"
  18. "slices"
  19. "strings"
  20. "time"
  21. cerrdefs "github.com/containerd/errdefs"
  22. "github.com/docker/compose/v2/pkg/api"
  23. "github.com/docker/compose/v2/pkg/progress"
  24. "github.com/docker/compose/v2/pkg/utils"
  25. containerType "github.com/docker/docker/api/types/container"
  26. "github.com/compose-spec/compose-go/v2/types"
  27. "github.com/docker/docker/api/types/filters"
  28. "golang.org/x/sync/errgroup"
  29. )
  30. func (s *composeService) Start(ctx context.Context, projectName string, options api.StartOptions) error {
  31. return progress.Run(ctx, func(ctx context.Context) error {
  32. return s.start(ctx, strings.ToLower(projectName), options, nil)
  33. }, s.stdinfo())
  34. }
  35. func (s *composeService) start(ctx context.Context, projectName string, options api.StartOptions, listener api.ContainerEventListener) error {
  36. project := options.Project
  37. if project == nil {
  38. var containers Containers
  39. containers, err := s.getContainers(ctx, projectName, oneOffExclude, true)
  40. if err != nil {
  41. return err
  42. }
  43. project, err = s.projectFromName(containers, projectName, options.AttachTo...)
  44. if err != nil {
  45. return err
  46. }
  47. }
  48. // use an independent context tied to the errgroup for background attach operations
  49. // the primary context is still used for other operations
  50. // this means that once any attach operation fails, all other attaches are cancelled,
  51. // but an attach failing won't interfere with the rest of the start
  52. eg, attachCtx := errgroup.WithContext(ctx)
  53. if listener != nil {
  54. _, err := s.attach(attachCtx, project, listener, options.AttachTo)
  55. if err != nil {
  56. return err
  57. }
  58. eg.Go(func() error {
  59. // it's possible to have a required service whose log output is not desired
  60. // (i.e. it's not in the attach set), so watch everything and then filter
  61. // calls to attach; this ensures that `watchContainers` blocks until all
  62. // required containers have exited, even if their output is not being shown
  63. attachTo := utils.NewSet[string](options.AttachTo...)
  64. required := utils.NewSet[string](options.Services...)
  65. toWatch := attachTo.Union(required).Elements()
  66. containers, err := s.getContainers(ctx, projectName, oneOffExclude, true, toWatch...)
  67. if err != nil {
  68. return err
  69. }
  70. // N.B. this uses the parent context (instead of attachCtx) so that the watch itself can
  71. // continue even if one of the log streams fails
  72. return s.watchContainers(ctx, project.Name, toWatch, required.Elements(), listener, containers,
  73. func(ctr containerType.Summary, _ time.Time) error {
  74. svc := ctr.Labels[api.ServiceLabel]
  75. if attachTo.Has(svc) {
  76. return s.attachContainer(attachCtx, ctr, listener)
  77. }
  78. // HACK: simulate an "attach" event
  79. listener(api.ContainerEvent{
  80. Type: api.ContainerEventAttach,
  81. Container: getContainerNameWithoutProject(ctr),
  82. ID: ctr.ID,
  83. Service: svc,
  84. })
  85. return nil
  86. }, func(ctr containerType.Summary, _ time.Time) error {
  87. listener(api.ContainerEvent{
  88. Type: api.ContainerEventAttach,
  89. Container: "", // actual name will be set by start event
  90. ID: ctr.ID,
  91. Service: ctr.Labels[api.ServiceLabel],
  92. })
  93. return nil
  94. })
  95. })
  96. }
  97. var containers Containers
  98. containers, err := s.apiClient().ContainerList(ctx, containerType.ListOptions{
  99. Filters: filters.NewArgs(
  100. projectFilter(project.Name),
  101. oneOffFilter(false),
  102. ),
  103. All: true,
  104. })
  105. if err != nil {
  106. return err
  107. }
  108. err = InDependencyOrder(ctx, project, func(c context.Context, name string) error {
  109. service, err := project.GetService(name)
  110. if err != nil {
  111. return err
  112. }
  113. return s.startService(ctx, project, service, containers, listener, options.WaitTimeout)
  114. })
  115. if err != nil {
  116. return err
  117. }
  118. if options.Wait {
  119. depends := types.DependsOnConfig{}
  120. for _, s := range project.Services {
  121. depends[s.Name] = types.ServiceDependency{
  122. Condition: getDependencyCondition(s, project),
  123. Required: true,
  124. }
  125. }
  126. if options.WaitTimeout > 0 {
  127. withTimeout, cancel := context.WithTimeout(ctx, options.WaitTimeout)
  128. ctx = withTimeout
  129. defer cancel()
  130. }
  131. err = s.waitDependencies(ctx, project, project.Name, depends, containers, 0)
  132. if err != nil {
  133. if errors.Is(ctx.Err(), context.DeadlineExceeded) {
  134. return fmt.Errorf("application not healthy after %s", options.WaitTimeout)
  135. }
  136. return err
  137. }
  138. }
  139. return eg.Wait()
  140. }
  141. // getDependencyCondition checks if service is depended on by other services
  142. // with service_completed_successfully condition, and applies that condition
  143. // instead, or --wait will never finish waiting for one-shot containers
  144. func getDependencyCondition(service types.ServiceConfig, project *types.Project) string {
  145. for _, services := range project.Services {
  146. for dependencyService, dependencyConfig := range services.DependsOn {
  147. if dependencyService == service.Name && dependencyConfig.Condition == types.ServiceConditionCompletedSuccessfully {
  148. return types.ServiceConditionCompletedSuccessfully
  149. }
  150. }
  151. }
  152. return ServiceConditionRunningOrHealthy
  153. }
  154. type containerWatchFn func(ctr containerType.Summary, t time.Time) error
  155. // watchContainers uses engine events to capture container start/die and notify ContainerEventListener
  156. func (s *composeService) watchContainers(ctx context.Context, //nolint:gocyclo
  157. projectName string, services, required []string,
  158. listener api.ContainerEventListener, containers Containers, onStart, onRecreate containerWatchFn,
  159. ) error {
  160. if len(containers) == 0 {
  161. return nil
  162. }
  163. if len(required) == 0 {
  164. required = services
  165. }
  166. unexpected := utils.NewSet[string](required...).Diff(utils.NewSet[string](services...))
  167. if len(unexpected) != 0 {
  168. return fmt.Errorf(`required service(s) "%s" not present in watched service(s) "%s"`,
  169. strings.Join(unexpected.Elements(), ", "),
  170. strings.Join(services, ", "))
  171. }
  172. // predicate to tell if a container we receive event for should be considered or ignored
  173. ofInterest := func(c containerType.Summary) bool {
  174. if len(services) > 0 {
  175. // we only watch some services
  176. return slices.Contains(services, c.Labels[api.ServiceLabel])
  177. }
  178. return true
  179. }
  180. // predicate to tell if a container we receive event for should be watched until termination
  181. isRequired := func(c containerType.Summary) bool {
  182. if len(services) > 0 && len(required) > 0 {
  183. // we only watch some services
  184. return slices.Contains(required, c.Labels[api.ServiceLabel])
  185. }
  186. return true
  187. }
  188. var (
  189. expected = utils.NewSet[string]()
  190. watched = map[string]int{}
  191. replaced []string
  192. )
  193. for _, c := range containers {
  194. if isRequired(c) {
  195. expected.Add(c.ID)
  196. }
  197. watched[c.ID] = 0
  198. }
  199. ctx, stop := context.WithCancel(ctx)
  200. err := s.Events(ctx, projectName, api.EventsOptions{
  201. Services: services,
  202. Consumer: func(event api.Event) error {
  203. defer func() {
  204. // after consuming each event, check to see if we're done
  205. if len(expected) == 0 {
  206. stop()
  207. }
  208. }()
  209. inspected, err := s.apiClient().ContainerInspect(ctx, event.Container)
  210. if err != nil {
  211. if cerrdefs.IsNotFound(err) {
  212. // it's possible to get "destroy" or "kill" events but not
  213. // be able to inspect in time before they're gone from the
  214. // API, so just remove the watch without erroring
  215. delete(watched, event.Container)
  216. expected.Remove(event.Container)
  217. return nil
  218. }
  219. return err
  220. }
  221. container := containerType.Summary{
  222. ID: inspected.ID,
  223. Names: []string{inspected.Name},
  224. Labels: inspected.Config.Labels,
  225. }
  226. name := getContainerNameWithoutProject(container)
  227. service := container.Labels[api.ServiceLabel]
  228. switch event.Status {
  229. case "stop":
  230. if inspected.State.Running {
  231. // on sync+restart action the container stops -> dies -> start -> restart
  232. // we do not want to stop the current container, we want to restart it
  233. return nil
  234. }
  235. if _, ok := watched[container.ID]; ok {
  236. eType := api.ContainerEventStopped
  237. if slices.Contains(replaced, container.ID) {
  238. replaced = slices.DeleteFunc(replaced, func(e string) bool { return e == container.ID })
  239. eType = api.ContainerEventRecreated
  240. }
  241. listener(api.ContainerEvent{
  242. Type: eType,
  243. Container: name,
  244. ID: container.ID,
  245. Service: service,
  246. ExitCode: inspected.State.ExitCode,
  247. })
  248. }
  249. delete(watched, container.ID)
  250. expected.Remove(container.ID)
  251. case "die":
  252. restarted := watched[container.ID]
  253. watched[container.ID] = restarted + 1
  254. // Container terminated.
  255. willRestart := inspected.State.Restarting
  256. if inspected.State.Running {
  257. // on sync+restart action inspected.State.Restarting is false,
  258. // however the container is already running before it restarts
  259. willRestart = true
  260. }
  261. eType := api.ContainerEventExit
  262. if slices.Contains(replaced, container.ID) {
  263. replaced = slices.DeleteFunc(replaced, func(e string) bool { return e == container.ID })
  264. eType = api.ContainerEventRecreated
  265. }
  266. listener(api.ContainerEvent{
  267. Type: eType,
  268. Container: name,
  269. ID: container.ID,
  270. Service: service,
  271. ExitCode: inspected.State.ExitCode,
  272. Restarting: willRestart,
  273. })
  274. if !willRestart {
  275. // we're done with this one
  276. delete(watched, container.ID)
  277. expected.Remove(container.ID)
  278. }
  279. case "start":
  280. count, ok := watched[container.ID]
  281. mustAttach := ok && count > 0 // Container restarted, need to re-attach
  282. if !ok {
  283. // A new container has just been added to service by scale
  284. watched[container.ID] = 0
  285. expected.Add(container.ID)
  286. mustAttach = true
  287. }
  288. if mustAttach {
  289. // Container restarted, need to re-attach
  290. err := onStart(container, event.Timestamp)
  291. if err != nil {
  292. return err
  293. }
  294. }
  295. case "create":
  296. if id, ok := container.Labels[api.ContainerReplaceLabel]; ok {
  297. replaced = append(replaced, id)
  298. err = onRecreate(container, event.Timestamp)
  299. if err != nil {
  300. return err
  301. }
  302. if expected.Has(id) {
  303. expected.Add(inspected.ID)
  304. expected.Add(container.ID)
  305. }
  306. watched[container.ID] = 1
  307. } else if ofInterest(container) {
  308. watched[container.ID] = 1
  309. if isRequired(container) {
  310. expected.Add(container.ID)
  311. }
  312. }
  313. }
  314. return nil
  315. },
  316. })
  317. if errors.Is(ctx.Err(), context.Canceled) {
  318. return nil
  319. }
  320. return err
  321. }