start.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. "github.com/docker/docker/errdefs"
  21. "github.com/docker/compose/v2/pkg/api"
  22. "github.com/docker/compose/v2/pkg/progress"
  23. "github.com/docker/compose/v2/pkg/utils"
  24. "github.com/compose-spec/compose-go/types"
  25. moby "github.com/docker/docker/api/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(container moby.Container, _ time.Time) error {
  73. svc := container.Labels[api.ServiceLabel]
  74. if attachTo.Has(svc) {
  75. return s.attachContainer(attachCtx, container, listener)
  76. }
  77. // HACK: simulate an "attach" event
  78. listener(api.ContainerEvent{
  79. Type: api.ContainerEventAttach,
  80. Container: getContainerNameWithoutProject(container),
  81. ID: container.ID,
  82. Service: svc,
  83. })
  84. return nil
  85. }, func(container moby.Container, _ time.Time) error {
  86. listener(api.ContainerEvent{
  87. Type: api.ContainerEventAttach,
  88. Container: "", // actual name will be set by start event
  89. ID: container.ID,
  90. Service: container.Labels[api.ServiceLabel],
  91. })
  92. return nil
  93. })
  94. })
  95. }
  96. var containers Containers
  97. containers, err := s.apiClient().ContainerList(ctx, moby.ContainerListOptions{
  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)
  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, depends, containers)
  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(container moby.Container, 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) error {
  158. if len(containers) == 0 {
  159. return nil
  160. }
  161. if len(required) == 0 {
  162. required = services
  163. }
  164. unexpected := utils.NewSet[string](required...).Diff(utils.NewSet[string](services...))
  165. if len(unexpected) != 0 {
  166. return fmt.Errorf(`required service(s) "%s" not present in watched service(s) "%s"`,
  167. strings.Join(unexpected.Elements(), ", "),
  168. strings.Join(services, ", "))
  169. }
  170. // predicate to tell if a container we receive event for should be considered or ignored
  171. ofInterest := func(c moby.Container) bool {
  172. if len(services) > 0 {
  173. // we only watch some services
  174. return utils.Contains(services, c.Labels[api.ServiceLabel])
  175. }
  176. return true
  177. }
  178. // predicate to tell if a container we receive event for should be watched until termination
  179. isRequired := func(c moby.Container) bool {
  180. if len(services) > 0 && len(required) > 0 {
  181. // we only watch some services
  182. return utils.Contains(required, c.Labels[api.ServiceLabel])
  183. }
  184. return true
  185. }
  186. var (
  187. expected []string
  188. watched = map[string]int{}
  189. replaced []string
  190. )
  191. for _, c := range containers {
  192. if isRequired(c) {
  193. expected = append(expected, c.ID)
  194. }
  195. watched[c.ID] = 0
  196. }
  197. ctx, stop := context.WithCancel(ctx)
  198. err := s.Events(ctx, projectName, api.EventsOptions{
  199. Services: services,
  200. Consumer: func(event api.Event) error {
  201. defer func() {
  202. // after consuming each event, check to see if we're done
  203. if len(expected) == 0 {
  204. stop()
  205. }
  206. }()
  207. inspected, err := s.apiClient().ContainerInspect(ctx, event.Container)
  208. if err != nil {
  209. if errdefs.IsNotFound(err) {
  210. // it's possible to get "destroy" or "kill" events but not
  211. // be able to inspect in time before they're gone from the
  212. // API, so just remove the watch without erroring
  213. delete(watched, event.Container)
  214. expected = utils.Remove(expected, event.Container)
  215. return nil
  216. }
  217. return err
  218. }
  219. container := moby.Container{
  220. ID: inspected.ID,
  221. Names: []string{inspected.Name},
  222. Labels: inspected.Config.Labels,
  223. }
  224. name := getContainerNameWithoutProject(container)
  225. service := container.Labels[api.ServiceLabel]
  226. switch event.Status {
  227. case "stop":
  228. if _, ok := watched[container.ID]; ok {
  229. eType := api.ContainerEventStopped
  230. if utils.Contains(replaced, container.ID) {
  231. utils.Remove(replaced, container.ID)
  232. eType = api.ContainerEventRecreated
  233. }
  234. listener(api.ContainerEvent{
  235. Type: eType,
  236. Container: name,
  237. ID: container.ID,
  238. Service: service,
  239. })
  240. }
  241. delete(watched, container.ID)
  242. expected = utils.Remove(expected, container.ID)
  243. case "die":
  244. restarted := watched[container.ID]
  245. watched[container.ID] = restarted + 1
  246. // Container terminated.
  247. willRestart := inspected.State.Restarting
  248. eType := api.ContainerEventExit
  249. if utils.Contains(replaced, container.ID) {
  250. utils.Remove(replaced, container.ID)
  251. eType = api.ContainerEventRecreated
  252. }
  253. listener(api.ContainerEvent{
  254. Type: eType,
  255. Container: name,
  256. ID: container.ID,
  257. Service: service,
  258. ExitCode: inspected.State.ExitCode,
  259. Restarting: willRestart,
  260. })
  261. if !willRestart {
  262. // we're done with this one
  263. delete(watched, container.ID)
  264. expected = utils.Remove(expected, container.ID)
  265. }
  266. case "start":
  267. count, ok := watched[container.ID]
  268. mustAttach := ok && count > 0 // Container restarted, need to re-attach
  269. if !ok {
  270. // A new container has just been added to service by scale
  271. watched[container.ID] = 0
  272. expected = append(expected, container.ID)
  273. mustAttach = true
  274. }
  275. if mustAttach {
  276. // Container restarted, need to re-attach
  277. err := onStart(container, event.Timestamp)
  278. if err != nil {
  279. return err
  280. }
  281. }
  282. case "create":
  283. if id, ok := container.Labels[api.ContainerReplaceLabel]; ok {
  284. replaced = append(replaced, id)
  285. err = onRecreate(container, event.Timestamp)
  286. if err != nil {
  287. return err
  288. }
  289. if utils.StringContains(expected, id) {
  290. expected = append(expected, inspected.ID)
  291. }
  292. watched[container.ID] = 1
  293. if utils.Contains(expected, id) {
  294. expected = append(expected, container.ID)
  295. }
  296. } else if ofInterest(container) {
  297. watched[container.ID] = 1
  298. if isRequired(container) {
  299. expected = append(expected, container.ID)
  300. }
  301. }
  302. }
  303. return nil
  304. },
  305. })
  306. if errors.Is(ctx.Err(), context.Canceled) {
  307. return nil
  308. }
  309. return err
  310. }