start.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. // predicate to tell if a container we receive event for should be considered or ignored
  136. ofInterest := func(c moby.Container) bool {
  137. if len(services) > 0 {
  138. // we only watch some services
  139. return utils.Contains(services, c.Labels[api.ServiceLabel])
  140. }
  141. return true
  142. }
  143. // predicate to tell if a container we receive event for should be watched until termination
  144. isRequired := func(c moby.Container) bool {
  145. if len(services) > 0 && len(required) > 0 {
  146. // we only watch some services
  147. return utils.Contains(required, c.Labels[api.ServiceLabel])
  148. }
  149. return true
  150. }
  151. var (
  152. expected []string
  153. watched = map[string]int{}
  154. replaced []string
  155. )
  156. for _, c := range containers {
  157. if isRequired(c) {
  158. expected = append(expected, c.ID)
  159. }
  160. watched[c.ID] = 0
  161. }
  162. ctx, stop := context.WithCancel(ctx)
  163. err := s.Events(ctx, projectName, api.EventsOptions{
  164. Services: services,
  165. Consumer: func(event api.Event) error {
  166. inspected, err := s.apiClient().ContainerInspect(ctx, event.Container)
  167. if err != nil {
  168. if errdefs.IsNotFound(err) {
  169. // it's possible to get "destroy" or "kill" events but not
  170. // be able to inspect in time before they're gone from the
  171. // API, so just remove the watch without erroring
  172. delete(watched, event.Container)
  173. expected = utils.Remove(expected, event.Container)
  174. return nil
  175. }
  176. return err
  177. }
  178. container := moby.Container{
  179. ID: inspected.ID,
  180. Names: []string{inspected.Name},
  181. Labels: inspected.Config.Labels,
  182. }
  183. name := getContainerNameWithoutProject(container)
  184. service := container.Labels[api.ServiceLabel]
  185. switch event.Status {
  186. case "stop":
  187. if _, ok := watched[container.ID]; ok {
  188. eType := api.ContainerEventStopped
  189. if utils.Contains(replaced, container.ID) {
  190. utils.Remove(replaced, container.ID)
  191. eType = api.ContainerEventRecreated
  192. }
  193. listener(api.ContainerEvent{
  194. Type: eType,
  195. Container: name,
  196. ID: container.ID,
  197. Service: service,
  198. })
  199. }
  200. delete(watched, container.ID)
  201. expected = utils.Remove(expected, container.ID)
  202. case "die":
  203. restarted := watched[container.ID]
  204. watched[container.ID] = restarted + 1
  205. // Container terminated.
  206. willRestart := inspected.State.Restarting
  207. eType := api.ContainerEventExit
  208. if utils.Contains(replaced, container.ID) {
  209. utils.Remove(replaced, container.ID)
  210. eType = api.ContainerEventRecreated
  211. }
  212. listener(api.ContainerEvent{
  213. Type: eType,
  214. Container: name,
  215. ID: container.ID,
  216. Service: service,
  217. ExitCode: inspected.State.ExitCode,
  218. Restarting: willRestart,
  219. })
  220. if !willRestart {
  221. // we're done with this one
  222. delete(watched, container.ID)
  223. expected = utils.Remove(expected, container.ID)
  224. }
  225. case "start":
  226. count, ok := watched[container.ID]
  227. mustAttach := ok && count > 0 // Container restarted, need to re-attach
  228. if !ok {
  229. // A new container has just been added to service by scale
  230. watched[container.ID] = 0
  231. expected = append(expected, container.ID)
  232. mustAttach = true
  233. }
  234. if mustAttach {
  235. // Container restarted, need to re-attach
  236. err := onStart(container, event.Timestamp)
  237. if err != nil {
  238. return err
  239. }
  240. }
  241. case "create":
  242. if id, ok := container.Labels[api.ContainerReplaceLabel]; ok {
  243. replaced = append(replaced, id)
  244. err = onRecreate(container, event.Timestamp)
  245. if err != nil {
  246. return err
  247. }
  248. if utils.StringContains(expected, id) {
  249. expected = append(expected, inspected.ID)
  250. }
  251. watched[container.ID] = 1
  252. if utils.Contains(expected, id) {
  253. expected = append(expected, container.ID)
  254. }
  255. } else if ofInterest(container) {
  256. watched[container.ID] = 1
  257. if isRequired(container) {
  258. expected = append(expected, container.ID)
  259. }
  260. }
  261. }
  262. if len(expected) == 0 {
  263. stop()
  264. }
  265. return nil
  266. },
  267. })
  268. if errors.Is(ctx.Err(), context.Canceled) {
  269. return nil
  270. }
  271. return err
  272. }