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