start.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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/compose/v2/pkg/api"
  20. "github.com/docker/compose/v2/pkg/progress"
  21. "github.com/docker/compose/v2/pkg/utils"
  22. "github.com/compose-spec/compose-go/types"
  23. moby "github.com/docker/docker/api/types"
  24. "github.com/docker/docker/api/types/filters"
  25. "github.com/pkg/errors"
  26. "golang.org/x/sync/errgroup"
  27. )
  28. func (s *composeService) Start(ctx context.Context, projectName string, options api.StartOptions) error {
  29. return progress.Run(ctx, func(ctx context.Context) error {
  30. return s.start(ctx, strings.ToLower(projectName), options, nil)
  31. })
  32. }
  33. func (s *composeService) start(ctx context.Context, projectName string, options api.StartOptions, listener api.ContainerEventListener) error {
  34. project := options.Project
  35. if project == nil {
  36. var containers Containers
  37. containers, err := s.getContainers(ctx, projectName, oneOffExclude, true)
  38. if err != nil {
  39. return err
  40. }
  41. project, err = s.projectFromName(containers, projectName, options.AttachTo...)
  42. if err != nil {
  43. return err
  44. }
  45. }
  46. eg, ctx := errgroup.WithContext(ctx)
  47. if listener != nil {
  48. attached, err := s.attach(ctx, project, listener, options.AttachTo)
  49. if err != nil {
  50. return err
  51. }
  52. eg.Go(func() error {
  53. return s.watchContainers(context.Background(), project.Name, options.AttachTo, options.Services, listener, attached,
  54. func(container moby.Container, _ time.Time) error {
  55. return s.attachContainer(ctx, container, listener)
  56. }, func(container moby.Container, _ time.Time) error {
  57. listener(api.ContainerEvent{
  58. Type: api.ContainerEventAttach,
  59. Container: "", // actual name will be set by start event
  60. ID: container.ID,
  61. Service: container.Labels[api.ServiceLabel],
  62. })
  63. return nil
  64. })
  65. })
  66. }
  67. var containers Containers
  68. containers, err := s.apiClient().ContainerList(ctx, moby.ContainerListOptions{
  69. Filters: filters.NewArgs(
  70. projectFilter(project.Name),
  71. oneOffFilter(false),
  72. ),
  73. All: true,
  74. })
  75. if err != nil {
  76. return err
  77. }
  78. err = InDependencyOrder(ctx, project, func(c context.Context, name string) error {
  79. service, err := project.GetService(name)
  80. if err != nil {
  81. return err
  82. }
  83. return s.startService(ctx, project, service, containers)
  84. })
  85. if err != nil {
  86. return err
  87. }
  88. if options.Wait {
  89. depends := types.DependsOnConfig{}
  90. for _, s := range project.Services {
  91. depends[s.Name] = types.ServiceDependency{
  92. Condition: getDependencyCondition(s, project),
  93. }
  94. }
  95. if options.WaitTimeout > 0 {
  96. withTimeout, cancel := context.WithTimeout(ctx, options.WaitTimeout)
  97. ctx = withTimeout
  98. defer cancel()
  99. }
  100. err = s.waitDependencies(ctx, project, depends, containers)
  101. if err != nil {
  102. if ctx.Err() == context.DeadlineExceeded {
  103. return fmt.Errorf("application not healthy after %s", options.WaitTimeout)
  104. }
  105. return err
  106. }
  107. }
  108. return eg.Wait()
  109. }
  110. // getDependencyCondition checks if service is depended on by other services
  111. // with service_completed_successfully condition, and applies that condition
  112. // instead, or --wait will never finish waiting for one-shot containers
  113. func getDependencyCondition(service types.ServiceConfig, project *types.Project) string {
  114. for _, services := range project.Services {
  115. for dependencyService, dependencyConfig := range services.DependsOn {
  116. if dependencyService == service.Name && dependencyConfig.Condition == types.ServiceConditionCompletedSuccessfully {
  117. return types.ServiceConditionCompletedSuccessfully
  118. }
  119. }
  120. }
  121. return ServiceConditionRunningOrHealthy
  122. }
  123. type containerWatchFn func(container moby.Container, t time.Time) error
  124. // watchContainers uses engine events to capture container start/die and notify ContainerEventListener
  125. func (s *composeService) watchContainers(ctx context.Context, //nolint:gocyclo
  126. projectName string, services, required []string,
  127. listener api.ContainerEventListener, containers Containers, onStart, onRecreate containerWatchFn) error {
  128. if len(containers) == 0 {
  129. return nil
  130. }
  131. if len(required) == 0 {
  132. required = services
  133. }
  134. var (
  135. expected []string
  136. watched = map[string]int{}
  137. replaced []string
  138. )
  139. for _, c := range containers {
  140. if utils.Contains(required, c.Labels[api.ServiceLabel]) {
  141. expected = append(expected, c.ID)
  142. }
  143. watched[c.ID] = 0
  144. }
  145. ctx, stop := context.WithCancel(ctx)
  146. err := s.Events(ctx, projectName, api.EventsOptions{
  147. Services: services,
  148. Consumer: func(event api.Event) error {
  149. if event.Status == "destroy" {
  150. // This container can't be inspected, because it's gone.
  151. // It's already been removed from the watched map.
  152. return nil
  153. }
  154. inspected, err := s.apiClient().ContainerInspect(ctx, event.Container)
  155. if err != nil {
  156. return err
  157. }
  158. container := moby.Container{
  159. ID: inspected.ID,
  160. Names: []string{inspected.Name},
  161. Labels: inspected.Config.Labels,
  162. }
  163. name := getContainerNameWithoutProject(container)
  164. service := container.Labels[api.ServiceLabel]
  165. switch event.Status {
  166. case "stop":
  167. if _, ok := watched[container.ID]; ok {
  168. eType := api.ContainerEventStopped
  169. if utils.Contains(replaced, container.ID) {
  170. utils.Remove(replaced, container.ID)
  171. eType = api.ContainerEventRecreated
  172. }
  173. listener(api.ContainerEvent{
  174. Type: eType,
  175. Container: name,
  176. ID: container.ID,
  177. Service: service,
  178. })
  179. }
  180. delete(watched, container.ID)
  181. expected = utils.Remove(expected, container.ID)
  182. case "die":
  183. restarted := watched[container.ID]
  184. watched[container.ID] = restarted + 1
  185. // Container terminated.
  186. willRestart := inspected.State.Restarting
  187. eType := api.ContainerEventExit
  188. if utils.Contains(replaced, container.ID) {
  189. utils.Remove(replaced, container.ID)
  190. eType = api.ContainerEventRecreated
  191. }
  192. listener(api.ContainerEvent{
  193. Type: eType,
  194. Container: name,
  195. ID: container.ID,
  196. Service: service,
  197. ExitCode: inspected.State.ExitCode,
  198. Restarting: willRestart,
  199. })
  200. if !willRestart {
  201. // we're done with this one
  202. delete(watched, container.ID)
  203. expected = utils.Remove(expected, container.ID)
  204. }
  205. case "start":
  206. count, ok := watched[container.ID]
  207. mustAttach := ok && count > 0 // Container restarted, need to re-attach
  208. if !ok {
  209. // A new container has just been added to service by scale
  210. watched[container.ID] = 0
  211. expected = append(expected, container.ID)
  212. mustAttach = true
  213. }
  214. if mustAttach {
  215. // Container restarted, need to re-attach
  216. err := onStart(container, event.Timestamp)
  217. if err != nil {
  218. return err
  219. }
  220. }
  221. case "create":
  222. if id, ok := container.Labels[api.ContainerReplaceLabel]; ok {
  223. replaced = append(replaced, id)
  224. err = onRecreate(container, event.Timestamp)
  225. if err != nil {
  226. return err
  227. }
  228. if utils.StringContains(expected, id) {
  229. expected = append(expected, inspected.ID)
  230. }
  231. watched[container.ID] = 1
  232. if utils.Contains(expected, id) {
  233. expected = append(expected, container.ID)
  234. }
  235. }
  236. }
  237. if len(expected) == 0 {
  238. stop()
  239. }
  240. return nil
  241. },
  242. })
  243. if errors.Is(ctx.Err(), context.Canceled) {
  244. return nil
  245. }
  246. return err
  247. }