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. moby "github.com/docker/docker/api/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(container moby.Container, _ time.Time) error {
  74. svc := container.Labels[api.ServiceLabel]
  75. if attachTo.Has(svc) {
  76. return s.attachContainer(attachCtx, container, listener)
  77. }
  78. // HACK: simulate an "attach" event
  79. listener(api.ContainerEvent{
  80. Type: api.ContainerEventAttach,
  81. Container: getContainerNameWithoutProject(container),
  82. ID: container.ID,
  83. Service: svc,
  84. })
  85. return nil
  86. }, func(container moby.Container, _ time.Time) error {
  87. listener(api.ContainerEvent{
  88. Type: api.ContainerEventAttach,
  89. Container: "", // actual name will be set by start event
  90. ID: container.ID,
  91. Service: container.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(container moby.Container, 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) 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 moby.Container) 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 moby.Container) 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 := moby.Container{
  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. }