start.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. Required: true,
  95. }
  96. }
  97. if options.WaitTimeout > 0 {
  98. withTimeout, cancel := context.WithTimeout(ctx, options.WaitTimeout)
  99. ctx = withTimeout
  100. defer cancel()
  101. }
  102. err = s.waitDependencies(ctx, project, depends, containers)
  103. if err != nil {
  104. if ctx.Err() == context.DeadlineExceeded {
  105. return fmt.Errorf("application not healthy after %s", options.WaitTimeout)
  106. }
  107. return err
  108. }
  109. }
  110. return eg.Wait()
  111. }
  112. // getDependencyCondition checks if service is depended on by other services
  113. // with service_completed_successfully condition, and applies that condition
  114. // instead, or --wait will never finish waiting for one-shot containers
  115. func getDependencyCondition(service types.ServiceConfig, project *types.Project) string {
  116. for _, services := range project.Services {
  117. for dependencyService, dependencyConfig := range services.DependsOn {
  118. if dependencyService == service.Name && dependencyConfig.Condition == types.ServiceConditionCompletedSuccessfully {
  119. return types.ServiceConditionCompletedSuccessfully
  120. }
  121. }
  122. }
  123. return ServiceConditionRunningOrHealthy
  124. }
  125. type containerWatchFn func(container moby.Container, t time.Time) error
  126. // watchContainers uses engine events to capture container start/die and notify ContainerEventListener
  127. func (s *composeService) watchContainers(ctx context.Context, //nolint:gocyclo
  128. projectName string, services, required []string,
  129. listener api.ContainerEventListener, containers Containers, onStart, onRecreate containerWatchFn) error {
  130. if len(containers) == 0 {
  131. return nil
  132. }
  133. if len(required) == 0 {
  134. required = services
  135. }
  136. // predicate to tell if a container we receive event for should be considered or ignored
  137. ofInterest := func(c moby.Container) bool {
  138. if len(services) > 0 {
  139. // we only watch some services
  140. return utils.Contains(services, c.Labels[api.ServiceLabel])
  141. }
  142. return true
  143. }
  144. // predicate to tell if a container we receive event for should be watched until termination
  145. isRequired := func(c moby.Container) bool {
  146. if len(services) > 0 && len(required) > 0 {
  147. // we only watch some services
  148. return utils.Contains(required, c.Labels[api.ServiceLabel])
  149. }
  150. return true
  151. }
  152. var (
  153. expected []string
  154. watched = map[string]int{}
  155. replaced []string
  156. )
  157. for _, c := range containers {
  158. if isRequired(c) {
  159. expected = append(expected, c.ID)
  160. }
  161. watched[c.ID] = 0
  162. }
  163. ctx, stop := context.WithCancel(ctx)
  164. err := s.Events(ctx, projectName, api.EventsOptions{
  165. Services: services,
  166. Consumer: func(event api.Event) error {
  167. inspected, err := s.apiClient().ContainerInspect(ctx, event.Container)
  168. if err != nil {
  169. if errdefs.IsNotFound(err) {
  170. // it's possible to get "destroy" or "kill" events but not
  171. // be able to inspect in time before they're gone from the
  172. // API, so just remove the watch without erroring
  173. delete(watched, event.Container)
  174. expected = utils.Remove(expected, event.Container)
  175. return nil
  176. }
  177. return err
  178. }
  179. container := moby.Container{
  180. ID: inspected.ID,
  181. Names: []string{inspected.Name},
  182. Labels: inspected.Config.Labels,
  183. }
  184. name := getContainerNameWithoutProject(container)
  185. service := container.Labels[api.ServiceLabel]
  186. switch event.Status {
  187. case "stop":
  188. if _, ok := watched[container.ID]; ok {
  189. eType := api.ContainerEventStopped
  190. if utils.Contains(replaced, container.ID) {
  191. utils.Remove(replaced, container.ID)
  192. eType = api.ContainerEventRecreated
  193. }
  194. listener(api.ContainerEvent{
  195. Type: eType,
  196. Container: name,
  197. ID: container.ID,
  198. Service: service,
  199. })
  200. }
  201. delete(watched, container.ID)
  202. expected = utils.Remove(expected, container.ID)
  203. case "die":
  204. restarted := watched[container.ID]
  205. watched[container.ID] = restarted + 1
  206. // Container terminated.
  207. willRestart := inspected.State.Restarting
  208. eType := api.ContainerEventExit
  209. if utils.Contains(replaced, container.ID) {
  210. utils.Remove(replaced, container.ID)
  211. eType = api.ContainerEventRecreated
  212. }
  213. listener(api.ContainerEvent{
  214. Type: eType,
  215. Container: name,
  216. ID: container.ID,
  217. Service: service,
  218. ExitCode: inspected.State.ExitCode,
  219. Restarting: willRestart,
  220. })
  221. if !willRestart {
  222. // we're done with this one
  223. delete(watched, container.ID)
  224. expected = utils.Remove(expected, container.ID)
  225. }
  226. case "start":
  227. count, ok := watched[container.ID]
  228. mustAttach := ok && count > 0 // Container restarted, need to re-attach
  229. if !ok {
  230. // A new container has just been added to service by scale
  231. watched[container.ID] = 0
  232. expected = append(expected, container.ID)
  233. mustAttach = true
  234. }
  235. if mustAttach {
  236. // Container restarted, need to re-attach
  237. err := onStart(container, event.Timestamp)
  238. if err != nil {
  239. return err
  240. }
  241. }
  242. case "create":
  243. if id, ok := container.Labels[api.ContainerReplaceLabel]; ok {
  244. replaced = append(replaced, id)
  245. err = onRecreate(container, event.Timestamp)
  246. if err != nil {
  247. return err
  248. }
  249. if utils.StringContains(expected, id) {
  250. expected = append(expected, inspected.ID)
  251. }
  252. watched[container.ID] = 1
  253. if utils.Contains(expected, id) {
  254. expected = append(expected, container.ID)
  255. }
  256. } else if ofInterest(container) {
  257. watched[container.ID] = 1
  258. if isRequired(container) {
  259. expected = append(expected, container.ID)
  260. }
  261. }
  262. }
  263. if len(expected) == 0 {
  264. stop()
  265. }
  266. return nil
  267. },
  268. })
  269. if errors.Is(ctx.Err(), context.Canceled) {
  270. return nil
  271. }
  272. return err
  273. }