convergence.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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. "strconv"
  18. "strings"
  19. "sync"
  20. "time"
  21. "github.com/compose-spec/compose-go/types"
  22. "github.com/containerd/containerd/platforms"
  23. moby "github.com/docker/docker/api/types"
  24. "github.com/docker/docker/api/types/filters"
  25. "github.com/docker/docker/api/types/network"
  26. specs "github.com/opencontainers/image-spec/specs-go/v1"
  27. "github.com/sirupsen/logrus"
  28. "golang.org/x/sync/errgroup"
  29. "github.com/docker/compose/v2/pkg/api"
  30. "github.com/docker/compose/v2/pkg/progress"
  31. "github.com/docker/compose/v2/pkg/utils"
  32. )
  33. const (
  34. extLifecycle = "x-lifecycle"
  35. forceRecreate = "force_recreate"
  36. doubledContainerNameWarning = "WARNING: The %q service is using the custom container name %q. " +
  37. "Docker requires each container to have a unique name. " +
  38. "Remove the custom name to scale the service.\n"
  39. )
  40. // convergence manages service's container lifecycle.
  41. // Based on initially observed state, it reconciles the existing container with desired state, which might include
  42. // re-creating container, adding or removing replicas, or starting stopped containers.
  43. // Cross services dependencies are managed by creating services in expected order and updating `service:xx` reference
  44. // when a service has converged, so dependent ones can be managed with resolved containers references.
  45. type convergence struct {
  46. service *composeService
  47. observedState map[string]Containers
  48. stateMutex sync.Mutex
  49. }
  50. func (c *convergence) getObservedState(serviceName string) Containers {
  51. c.stateMutex.Lock()
  52. defer c.stateMutex.Unlock()
  53. return c.observedState[serviceName]
  54. }
  55. func (c *convergence) setObservedState(serviceName string, containers Containers) {
  56. c.stateMutex.Lock()
  57. defer c.stateMutex.Unlock()
  58. c.observedState[serviceName] = containers
  59. }
  60. func newConvergence(services []string, state Containers, s *composeService) *convergence {
  61. observedState := map[string]Containers{}
  62. for _, s := range services {
  63. observedState[s] = Containers{}
  64. }
  65. for _, c := range state.filter(isNotOneOff) {
  66. service := c.Labels[api.ServiceLabel]
  67. observedState[service] = append(observedState[service], c)
  68. }
  69. return &convergence{
  70. service: s,
  71. observedState: observedState,
  72. }
  73. }
  74. func (c *convergence) apply(ctx context.Context, project *types.Project, options api.CreateOptions) error {
  75. return InDependencyOrder(ctx, project, func(ctx context.Context, name string) error {
  76. service, err := project.GetService(name)
  77. if err != nil {
  78. return err
  79. }
  80. strategy := options.RecreateDependencies
  81. if utils.StringContains(options.Services, name) {
  82. strategy = options.Recreate
  83. }
  84. err = c.ensureService(ctx, project, service, strategy, options.Inherit, options.Timeout)
  85. if err != nil {
  86. return err
  87. }
  88. c.updateProject(project, name)
  89. return nil
  90. })
  91. }
  92. var mu sync.Mutex
  93. // updateProject updates project after service converged, so dependent services relying on `service:xx` can refer to actual containers.
  94. func (c *convergence) updateProject(project *types.Project, serviceName string) {
  95. // operation is protected by a Mutex so that we can safely update project.Services while running concurrent convergence on services
  96. mu.Lock()
  97. defer mu.Unlock()
  98. cnts := c.getObservedState(serviceName)
  99. for i, s := range project.Services {
  100. updateServices(&s, cnts)
  101. project.Services[i] = s
  102. }
  103. }
  104. func updateServices(service *types.ServiceConfig, cnts Containers) {
  105. if len(cnts) == 0 {
  106. return
  107. }
  108. cnt := cnts[0]
  109. serviceName := cnt.Labels[api.ServiceLabel]
  110. if d := getDependentServiceFromMode(service.NetworkMode); d == serviceName {
  111. service.NetworkMode = types.NetworkModeContainerPrefix + cnt.ID
  112. }
  113. if d := getDependentServiceFromMode(service.Ipc); d == serviceName {
  114. service.Ipc = types.NetworkModeContainerPrefix + cnt.ID
  115. }
  116. if d := getDependentServiceFromMode(service.Pid); d == serviceName {
  117. service.Pid = types.NetworkModeContainerPrefix + cnt.ID
  118. }
  119. var links []string
  120. for _, serviceLink := range service.Links {
  121. parts := strings.Split(serviceLink, ":")
  122. serviceName := serviceLink
  123. serviceAlias := ""
  124. if len(parts) == 2 {
  125. serviceName = parts[0]
  126. serviceAlias = parts[1]
  127. }
  128. if serviceName != service.Name {
  129. links = append(links, serviceLink)
  130. continue
  131. }
  132. for _, container := range cnts {
  133. name := getCanonicalContainerName(container)
  134. if serviceAlias != "" {
  135. links = append(links,
  136. fmt.Sprintf("%s:%s", name, serviceAlias))
  137. }
  138. links = append(links,
  139. fmt.Sprintf("%s:%s", name, name),
  140. fmt.Sprintf("%s:%s", name, getContainerNameWithoutProject(container)))
  141. }
  142. service.Links = links
  143. }
  144. }
  145. func (c *convergence) ensureService(ctx context.Context, project *types.Project, service types.ServiceConfig, recreate string, inherit bool, timeout *time.Duration) error {
  146. expected, err := getScale(service)
  147. if err != nil {
  148. return err
  149. }
  150. containers := c.getObservedState(service.Name)
  151. actual := len(containers)
  152. updated := make(Containers, expected)
  153. eg, _ := errgroup.WithContext(ctx)
  154. for i, container := range containers {
  155. if i >= expected {
  156. // Scale Down
  157. container := container
  158. eg.Go(func() error {
  159. err := c.service.apiClient.ContainerStop(ctx, container.ID, timeout)
  160. if err != nil {
  161. return err
  162. }
  163. return c.service.apiClient.ContainerRemove(ctx, container.ID, moby.ContainerRemoveOptions{})
  164. })
  165. continue
  166. }
  167. if recreate == api.RecreateNever {
  168. continue
  169. }
  170. // Re-create diverged containers
  171. configHash, err := ServiceHash(service)
  172. if err != nil {
  173. return err
  174. }
  175. name := getContainerProgressName(container)
  176. diverged := container.Labels[api.ConfigHashLabel] != configHash
  177. if diverged || recreate == api.RecreateForce || service.Extensions[extLifecycle] == forceRecreate {
  178. i, container := i, container
  179. eg.Go(func() error {
  180. recreated, err := c.service.recreateContainer(ctx, project, service, container, inherit, timeout)
  181. updated[i] = recreated
  182. return err
  183. })
  184. continue
  185. }
  186. // Enforce non-diverged containers are running
  187. w := progress.ContextWriter(ctx)
  188. switch container.State {
  189. case ContainerRunning:
  190. w.Event(progress.RunningEvent(name))
  191. case ContainerCreated:
  192. case ContainerRestarting:
  193. case ContainerExited:
  194. w.Event(progress.CreatedEvent(name))
  195. default:
  196. container := container
  197. eg.Go(func() error {
  198. return c.service.startContainer(ctx, container)
  199. })
  200. }
  201. updated[i] = container
  202. }
  203. next, err := nextContainerNumber(containers)
  204. if err != nil {
  205. return err
  206. }
  207. for i := 0; i < expected-actual; i++ {
  208. // Scale UP
  209. number := next + i
  210. name := getContainerName(project.Name, service, number)
  211. i := i
  212. eg.Go(func() error {
  213. container, err := c.service.createContainer(ctx, project, service, name, number, false, true, false)
  214. updated[actual+i] = container
  215. return err
  216. })
  217. continue
  218. }
  219. err = eg.Wait()
  220. c.setObservedState(service.Name, updated)
  221. return err
  222. }
  223. func getContainerName(projectName string, service types.ServiceConfig, number int) string {
  224. name := strings.Join([]string{projectName, service.Name, strconv.Itoa(number)}, Separator)
  225. if service.ContainerName != "" {
  226. name = service.ContainerName
  227. }
  228. return name
  229. }
  230. func getContainerProgressName(container moby.Container) string {
  231. return "Container " + getCanonicalContainerName(container)
  232. }
  233. func containerEvents(containers Containers, eventFunc func(string) progress.Event) []progress.Event {
  234. events := []progress.Event{}
  235. for _, container := range containers {
  236. events = append(events, eventFunc(getContainerProgressName(container)))
  237. }
  238. return events
  239. }
  240. // ServiceConditionRunningOrHealthy is a service condition on statys running or healthy
  241. const ServiceConditionRunningOrHealthy = "running_or_healthy"
  242. func (s *composeService) waitDependencies(ctx context.Context, project *types.Project, dependencies types.DependsOnConfig) error {
  243. eg, _ := errgroup.WithContext(ctx)
  244. w := progress.ContextWriter(ctx)
  245. for dep, config := range dependencies {
  246. if shouldWait, err := shouldWaitForDependency(dep, config, project); err != nil {
  247. return err
  248. } else if !shouldWait {
  249. continue
  250. }
  251. containers, err := s.getContainers(ctx, project.Name, oneOffExclude, false, dep)
  252. if err != nil {
  253. return err
  254. }
  255. w.Events(containerEvents(containers, progress.Waiting))
  256. dep, config := dep, config
  257. eg.Go(func() error {
  258. ticker := time.NewTicker(500 * time.Millisecond)
  259. defer ticker.Stop()
  260. for {
  261. <-ticker.C
  262. switch config.Condition {
  263. case ServiceConditionRunningOrHealthy:
  264. healthy, err := s.isServiceHealthy(ctx, project, dep, true)
  265. if err != nil {
  266. return err
  267. }
  268. if healthy {
  269. w.Events(containerEvents(containers, progress.Healthy))
  270. return nil
  271. }
  272. case types.ServiceConditionHealthy:
  273. healthy, err := s.isServiceHealthy(ctx, project, dep, false)
  274. if err != nil {
  275. return err
  276. }
  277. if healthy {
  278. w.Events(containerEvents(containers, progress.Healthy))
  279. return nil
  280. }
  281. case types.ServiceConditionCompletedSuccessfully:
  282. exited, code, err := s.isServiceCompleted(ctx, project, dep)
  283. if err != nil {
  284. return err
  285. }
  286. if exited {
  287. w.Events(containerEvents(containers, progress.Exited))
  288. if code != 0 {
  289. return fmt.Errorf("service %q didn't completed successfully: exit %d", dep, code)
  290. }
  291. return nil
  292. }
  293. default:
  294. logrus.Warnf("unsupported depends_on condition: %s", config.Condition)
  295. return nil
  296. }
  297. }
  298. })
  299. }
  300. return eg.Wait()
  301. }
  302. func shouldWaitForDependency(serviceName string, dependencyConfig types.ServiceDependency, project *types.Project) (bool, error) {
  303. if dependencyConfig.Condition == types.ServiceConditionStarted {
  304. // already managed by InDependencyOrder
  305. return false, nil
  306. }
  307. if service, err := project.GetService(serviceName); err != nil {
  308. return false, err
  309. } else if service.Scale == 0 {
  310. // don't wait for the dependency which configured to have 0 containers running
  311. return false, nil
  312. }
  313. return true, nil
  314. }
  315. func nextContainerNumber(containers []moby.Container) (int, error) {
  316. max := 0
  317. for _, c := range containers {
  318. n, err := strconv.Atoi(c.Labels[api.ContainerNumberLabel])
  319. if err != nil {
  320. return 0, err
  321. }
  322. if n > max {
  323. max = n
  324. }
  325. }
  326. return max + 1, nil
  327. }
  328. func getScale(config types.ServiceConfig) (int, error) {
  329. scale := 1
  330. if config.Deploy != nil && config.Deploy.Replicas != nil {
  331. scale = int(*config.Deploy.Replicas)
  332. }
  333. if scale > 1 && config.ContainerName != "" {
  334. return 0, fmt.Errorf(doubledContainerNameWarning,
  335. config.Name,
  336. config.ContainerName)
  337. }
  338. return scale, nil
  339. }
  340. func (s *composeService) createContainer(ctx context.Context, project *types.Project, service types.ServiceConfig,
  341. name string, number int, autoRemove bool, useNetworkAliases bool, attachStdin bool) (container moby.Container, err error) {
  342. w := progress.ContextWriter(ctx)
  343. eventName := "Container " + name
  344. w.Event(progress.CreatingEvent(eventName))
  345. container, err = s.createMobyContainer(ctx, project, service, name, number, nil, autoRemove, useNetworkAliases, attachStdin)
  346. if err != nil {
  347. return
  348. }
  349. w.Event(progress.CreatedEvent(eventName))
  350. return
  351. }
  352. func (s *composeService) recreateContainer(ctx context.Context, project *types.Project, service types.ServiceConfig,
  353. replaced moby.Container, inherit bool, timeout *time.Duration) (moby.Container, error) {
  354. var created moby.Container
  355. w := progress.ContextWriter(ctx)
  356. w.Event(progress.NewEvent(getContainerProgressName(replaced), progress.Working, "Recreate"))
  357. err := s.apiClient.ContainerStop(ctx, replaced.ID, timeout)
  358. if err != nil {
  359. return created, err
  360. }
  361. name := getCanonicalContainerName(replaced)
  362. tmpName := fmt.Sprintf("%s_%s", replaced.ID[:12], name)
  363. err = s.apiClient.ContainerRename(ctx, replaced.ID, tmpName)
  364. if err != nil {
  365. return created, err
  366. }
  367. number, err := strconv.Atoi(replaced.Labels[api.ContainerNumberLabel])
  368. if err != nil {
  369. return created, err
  370. }
  371. var inherited *moby.Container
  372. if inherit {
  373. inherited = &replaced
  374. }
  375. name = getContainerName(project.Name, service, number)
  376. created, err = s.createMobyContainer(ctx, project, service, name, number, inherited, false, true, false)
  377. if err != nil {
  378. return created, err
  379. }
  380. err = s.apiClient.ContainerRemove(ctx, replaced.ID, moby.ContainerRemoveOptions{})
  381. if err != nil {
  382. return created, err
  383. }
  384. w.Event(progress.NewEvent(getContainerProgressName(replaced), progress.Done, "Recreated"))
  385. setDependentLifecycle(project, service.Name, forceRecreate)
  386. return created, err
  387. }
  388. // setDependentLifecycle define the Lifecycle strategy for all services to depend on specified service
  389. func setDependentLifecycle(project *types.Project, service string, strategy string) {
  390. for i, s := range project.Services {
  391. if utils.StringContains(s.GetDependencies(), service) {
  392. if s.Extensions == nil {
  393. s.Extensions = map[string]interface{}{}
  394. }
  395. s.Extensions[extLifecycle] = strategy
  396. project.Services[i] = s
  397. }
  398. }
  399. }
  400. func (s *composeService) startContainer(ctx context.Context, container moby.Container) error {
  401. w := progress.ContextWriter(ctx)
  402. w.Event(progress.NewEvent(getContainerProgressName(container), progress.Working, "Restart"))
  403. err := s.apiClient.ContainerStart(ctx, container.ID, moby.ContainerStartOptions{})
  404. if err != nil {
  405. return err
  406. }
  407. w.Event(progress.NewEvent(getContainerProgressName(container), progress.Done, "Restarted"))
  408. return nil
  409. }
  410. func (s *composeService) createMobyContainer(ctx context.Context, project *types.Project, service types.ServiceConfig,
  411. name string, number int, inherit *moby.Container, autoRemove bool, useNetworkAliases bool, attachStdin bool) (moby.Container, error) {
  412. var created moby.Container
  413. containerConfig, hostConfig, networkingConfig, err := s.getCreateOptions(ctx, project, service, number, inherit, autoRemove, attachStdin)
  414. if err != nil {
  415. return created, err
  416. }
  417. var plat *specs.Platform
  418. if service.Platform != "" {
  419. var p specs.Platform
  420. p, err = platforms.Parse(service.Platform)
  421. if err != nil {
  422. return created, err
  423. }
  424. plat = &p
  425. }
  426. response, err := s.apiClient.ContainerCreate(ctx, containerConfig, hostConfig, networkingConfig, plat, name)
  427. if err != nil {
  428. return created, err
  429. }
  430. inspectedContainer, err := s.apiClient.ContainerInspect(ctx, response.ID)
  431. if err != nil {
  432. return created, err
  433. }
  434. created = moby.Container{
  435. ID: inspectedContainer.ID,
  436. Labels: inspectedContainer.Config.Labels,
  437. Names: []string{inspectedContainer.Name},
  438. NetworkSettings: &moby.SummaryNetworkSettings{
  439. Networks: inspectedContainer.NetworkSettings.Networks,
  440. },
  441. }
  442. links, err := s.getLinks(ctx, project.Name, service, number)
  443. if err != nil {
  444. return created, err
  445. }
  446. for _, netName := range service.NetworksByPriority() {
  447. netwrk := project.Networks[netName]
  448. cfg := service.Networks[netName]
  449. aliases := []string{getContainerName(project.Name, service, number)}
  450. if useNetworkAliases {
  451. aliases = append(aliases, service.Name)
  452. if cfg != nil {
  453. aliases = append(aliases, cfg.Aliases...)
  454. }
  455. }
  456. if val, ok := created.NetworkSettings.Networks[netwrk.Name]; ok {
  457. if shortIDAliasExists(created.ID, val.Aliases...) {
  458. continue
  459. }
  460. err = s.apiClient.NetworkDisconnect(ctx, netwrk.Name, created.ID, false)
  461. if err != nil {
  462. return created, err
  463. }
  464. }
  465. err = s.connectContainerToNetwork(ctx, created.ID, netwrk.Name, cfg, links, aliases...)
  466. if err != nil {
  467. return created, err
  468. }
  469. }
  470. return created, err
  471. }
  472. // getLinks mimics V1 compose/service.py::Service::_get_links()
  473. func (s composeService) getLinks(ctx context.Context, projectName string, service types.ServiceConfig, number int) ([]string, error) {
  474. var links []string
  475. format := func(k, v string) string {
  476. return fmt.Sprintf("%s:%s", k, v)
  477. }
  478. getServiceContainers := func(serviceName string) (Containers, error) {
  479. return s.getContainers(ctx, projectName, oneOffExclude, true, serviceName)
  480. }
  481. for _, rawLink := range service.Links {
  482. linkSplit := strings.Split(rawLink, ":")
  483. linkServiceName := linkSplit[0]
  484. linkName := linkServiceName
  485. if len(linkSplit) == 2 {
  486. linkName = linkSplit[1] // linkName if informed like in: "serviceName:linkName"
  487. }
  488. cnts, err := getServiceContainers(linkServiceName)
  489. if err != nil {
  490. return nil, err
  491. }
  492. for _, c := range cnts {
  493. containerName := getCanonicalContainerName(c)
  494. links = append(links,
  495. format(containerName, linkName),
  496. format(containerName, strings.Join([]string{linkServiceName, strconv.Itoa(number)}, Separator)),
  497. format(containerName, strings.Join([]string{projectName, linkServiceName, strconv.Itoa(number)}, Separator)),
  498. )
  499. }
  500. }
  501. if service.Labels[api.OneoffLabel] == "True" {
  502. cnts, err := getServiceContainers(service.Name)
  503. if err != nil {
  504. return nil, err
  505. }
  506. for _, c := range cnts {
  507. containerName := getCanonicalContainerName(c)
  508. links = append(links,
  509. format(containerName, service.Name),
  510. format(containerName, strings.TrimPrefix(containerName, projectName+Separator)),
  511. format(containerName, containerName),
  512. )
  513. }
  514. }
  515. for _, rawExtLink := range service.ExternalLinks {
  516. extLinkSplit := strings.Split(rawExtLink, ":")
  517. externalLink := extLinkSplit[0]
  518. linkName := externalLink
  519. if len(extLinkSplit) == 2 {
  520. linkName = extLinkSplit[1]
  521. }
  522. links = append(links, format(externalLink, linkName))
  523. }
  524. return links, nil
  525. }
  526. func shortIDAliasExists(containerID string, aliases ...string) bool {
  527. for _, alias := range aliases {
  528. if alias == containerID[:12] {
  529. return true
  530. }
  531. }
  532. return false
  533. }
  534. func (s *composeService) connectContainerToNetwork(ctx context.Context, id string, netwrk string, cfg *types.ServiceNetworkConfig, links []string, aliases ...string) error {
  535. var (
  536. ipv4Address string
  537. ipv6Address string
  538. ipam *network.EndpointIPAMConfig
  539. )
  540. if cfg != nil {
  541. ipv4Address = cfg.Ipv4Address
  542. ipv6Address = cfg.Ipv6Address
  543. ipam = &network.EndpointIPAMConfig{
  544. IPv4Address: ipv4Address,
  545. IPv6Address: ipv6Address,
  546. }
  547. }
  548. err := s.apiClient.NetworkConnect(ctx, netwrk, id, &network.EndpointSettings{
  549. Aliases: aliases,
  550. IPAddress: ipv4Address,
  551. GlobalIPv6Address: ipv6Address,
  552. Links: links,
  553. IPAMConfig: ipam,
  554. })
  555. if err != nil {
  556. return err
  557. }
  558. return nil
  559. }
  560. func (s *composeService) isServiceHealthy(ctx context.Context, project *types.Project, service string, fallbackRunning bool) (bool, error) {
  561. containers, err := s.getContainers(ctx, project.Name, oneOffExclude, false, service)
  562. if err != nil {
  563. return false, err
  564. }
  565. if len(containers) == 0 {
  566. return false, nil
  567. }
  568. for _, c := range containers {
  569. container, err := s.apiClient.ContainerInspect(ctx, c.ID)
  570. if err != nil {
  571. return false, err
  572. }
  573. if container.Config.Healthcheck == nil && fallbackRunning {
  574. // Container does not define a health check, but we can fall back to "running" state
  575. return container.State != nil && container.State.Status == "running", nil
  576. }
  577. if container.State == nil || container.State.Health == nil {
  578. return false, fmt.Errorf("container for service %q has no healthcheck configured", service)
  579. }
  580. switch container.State.Health.Status {
  581. case moby.Healthy:
  582. // Continue by checking the next container.
  583. case moby.Unhealthy:
  584. return false, fmt.Errorf("container for service %q is unhealthy", service)
  585. case moby.Starting:
  586. return false, nil
  587. default:
  588. return false, fmt.Errorf("container for service %q had unexpected health status %q", service, container.State.Health.Status)
  589. }
  590. }
  591. return true, nil
  592. }
  593. func (s *composeService) isServiceCompleted(ctx context.Context, project *types.Project, dep string) (bool, int, error) {
  594. containers, err := s.getContainers(ctx, project.Name, oneOffExclude, true, dep)
  595. if err != nil {
  596. return false, 0, err
  597. }
  598. for _, c := range containers {
  599. container, err := s.apiClient.ContainerInspect(ctx, c.ID)
  600. if err != nil {
  601. return false, 0, err
  602. }
  603. if container.State != nil && container.State.Status == "exited" {
  604. return true, container.State.ExitCode, nil
  605. }
  606. }
  607. return false, 0, nil
  608. }
  609. func (s *composeService) startService(ctx context.Context, project *types.Project, service types.ServiceConfig) error {
  610. if service.Deploy != nil && service.Deploy.Replicas != nil && *service.Deploy.Replicas == 0 {
  611. return nil
  612. }
  613. err := s.waitDependencies(ctx, project, service.DependsOn)
  614. if err != nil {
  615. return err
  616. }
  617. containers, err := s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
  618. Filters: filters.NewArgs(
  619. projectFilter(project.Name),
  620. serviceFilter(service.Name),
  621. oneOffFilter(false),
  622. ),
  623. All: true,
  624. })
  625. if err != nil {
  626. return err
  627. }
  628. if len(containers) == 0 {
  629. if scale, err := getScale(service); err != nil && scale == 0 {
  630. return nil
  631. }
  632. return fmt.Errorf("service %q has no container to start", service.Name)
  633. }
  634. w := progress.ContextWriter(ctx)
  635. eg, ctx := errgroup.WithContext(ctx)
  636. for _, container := range containers {
  637. if container.State == ContainerRunning {
  638. continue
  639. }
  640. container := container
  641. eg.Go(func() error {
  642. eventName := getContainerProgressName(container)
  643. w.Event(progress.StartingEvent(eventName))
  644. err := s.apiClient.ContainerStart(ctx, container.ID, moby.ContainerStartOptions{})
  645. if err == nil {
  646. w.Event(progress.StartedEvent(eventName))
  647. }
  648. return err
  649. })
  650. }
  651. return eg.Wait()
  652. }