convergence.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. mustRecreate, err := mustRecreate(service, container, recreate)
  168. if err != nil {
  169. return err
  170. }
  171. if mustRecreate {
  172. i, container := i, container
  173. eg.Go(func() error {
  174. recreated, err := c.service.recreateContainer(ctx, project, service, container, inherit, timeout)
  175. updated[i] = recreated
  176. return err
  177. })
  178. continue
  179. }
  180. // Enforce non-diverged containers are running
  181. w := progress.ContextWriter(ctx)
  182. name := getContainerProgressName(container)
  183. switch container.State {
  184. case ContainerRunning:
  185. w.Event(progress.RunningEvent(name))
  186. case ContainerCreated:
  187. case ContainerRestarting:
  188. case ContainerExited:
  189. w.Event(progress.CreatedEvent(name))
  190. default:
  191. container := container
  192. eg.Go(func() error {
  193. return c.service.startContainer(ctx, container)
  194. })
  195. }
  196. updated[i] = container
  197. }
  198. next, err := nextContainerNumber(containers)
  199. if err != nil {
  200. return err
  201. }
  202. for i := 0; i < expected-actual; i++ {
  203. // Scale UP
  204. number := next + i
  205. name := getContainerName(project.Name, service, number)
  206. i := i
  207. eg.Go(func() error {
  208. container, err := c.service.createContainer(ctx, project, service, name, number, false, true, false)
  209. updated[actual+i] = container
  210. return err
  211. })
  212. continue
  213. }
  214. err = eg.Wait()
  215. c.setObservedState(service.Name, updated)
  216. return err
  217. }
  218. func mustRecreate(expected types.ServiceConfig, actual moby.Container, policy string) (bool, error) {
  219. if policy == api.RecreateNever {
  220. return false, nil
  221. }
  222. if policy == api.RecreateForce || expected.Extensions[extLifecycle] == forceRecreate {
  223. return true, nil
  224. }
  225. configHash, err := ServiceHash(expected)
  226. if err != nil {
  227. return false, err
  228. }
  229. configChanged := actual.Labels[api.ConfigHashLabel] != configHash
  230. imageUpdated := actual.Labels[api.ImageDigestLabel] != expected.CustomLabels[api.ImageDigestLabel]
  231. return configChanged || imageUpdated, nil
  232. }
  233. func getContainerName(projectName string, service types.ServiceConfig, number int) string {
  234. name := strings.Join([]string{projectName, service.Name, strconv.Itoa(number)}, Separator)
  235. if service.ContainerName != "" {
  236. name = service.ContainerName
  237. }
  238. return name
  239. }
  240. func getContainerProgressName(container moby.Container) string {
  241. return "Container " + getCanonicalContainerName(container)
  242. }
  243. func containerEvents(containers Containers, eventFunc func(string) progress.Event) []progress.Event {
  244. events := []progress.Event{}
  245. for _, container := range containers {
  246. events = append(events, eventFunc(getContainerProgressName(container)))
  247. }
  248. return events
  249. }
  250. // ServiceConditionRunningOrHealthy is a service condition on statys running or healthy
  251. const ServiceConditionRunningOrHealthy = "running_or_healthy"
  252. func (s *composeService) waitDependencies(ctx context.Context, project *types.Project, dependencies types.DependsOnConfig) error {
  253. eg, _ := errgroup.WithContext(ctx)
  254. w := progress.ContextWriter(ctx)
  255. for dep, config := range dependencies {
  256. if shouldWait, err := shouldWaitForDependency(dep, config, project); err != nil {
  257. return err
  258. } else if !shouldWait {
  259. continue
  260. }
  261. containers, err := s.getContainers(ctx, project.Name, oneOffExclude, false, dep)
  262. if err != nil {
  263. return err
  264. }
  265. w.Events(containerEvents(containers, progress.Waiting))
  266. dep, config := dep, config
  267. eg.Go(func() error {
  268. ticker := time.NewTicker(500 * time.Millisecond)
  269. defer ticker.Stop()
  270. for {
  271. <-ticker.C
  272. switch config.Condition {
  273. case ServiceConditionRunningOrHealthy:
  274. healthy, err := s.isServiceHealthy(ctx, project, dep, true)
  275. if err != nil {
  276. return err
  277. }
  278. if healthy {
  279. w.Events(containerEvents(containers, progress.Healthy))
  280. return nil
  281. }
  282. case types.ServiceConditionHealthy:
  283. healthy, err := s.isServiceHealthy(ctx, project, dep, false)
  284. if err != nil {
  285. return err
  286. }
  287. if healthy {
  288. w.Events(containerEvents(containers, progress.Healthy))
  289. return nil
  290. }
  291. case types.ServiceConditionCompletedSuccessfully:
  292. exited, code, err := s.isServiceCompleted(ctx, project, dep)
  293. if err != nil {
  294. return err
  295. }
  296. if exited {
  297. w.Events(containerEvents(containers, progress.Exited))
  298. if code != 0 {
  299. return fmt.Errorf("service %q didn't completed successfully: exit %d", dep, code)
  300. }
  301. return nil
  302. }
  303. default:
  304. logrus.Warnf("unsupported depends_on condition: %s", config.Condition)
  305. return nil
  306. }
  307. }
  308. })
  309. }
  310. return eg.Wait()
  311. }
  312. func shouldWaitForDependency(serviceName string, dependencyConfig types.ServiceDependency, project *types.Project) (bool, error) {
  313. if dependencyConfig.Condition == types.ServiceConditionStarted {
  314. // already managed by InDependencyOrder
  315. return false, nil
  316. }
  317. if service, err := project.GetService(serviceName); err != nil {
  318. return false, err
  319. } else if service.Scale == 0 {
  320. // don't wait for the dependency which configured to have 0 containers running
  321. return false, nil
  322. }
  323. return true, nil
  324. }
  325. func nextContainerNumber(containers []moby.Container) (int, error) {
  326. max := 0
  327. for _, c := range containers {
  328. n, err := strconv.Atoi(c.Labels[api.ContainerNumberLabel])
  329. if err != nil {
  330. return 0, err
  331. }
  332. if n > max {
  333. max = n
  334. }
  335. }
  336. return max + 1, nil
  337. }
  338. func getScale(config types.ServiceConfig) (int, error) {
  339. scale := 1
  340. if config.Deploy != nil && config.Deploy.Replicas != nil {
  341. scale = int(*config.Deploy.Replicas)
  342. }
  343. if scale > 1 && config.ContainerName != "" {
  344. return 0, fmt.Errorf(doubledContainerNameWarning,
  345. config.Name,
  346. config.ContainerName)
  347. }
  348. return scale, nil
  349. }
  350. func (s *composeService) createContainer(ctx context.Context, project *types.Project, service types.ServiceConfig,
  351. name string, number int, autoRemove bool, useNetworkAliases bool, attachStdin bool) (container moby.Container, err error) {
  352. w := progress.ContextWriter(ctx)
  353. eventName := "Container " + name
  354. w.Event(progress.CreatingEvent(eventName))
  355. container, err = s.createMobyContainer(ctx, project, service, name, number, nil, autoRemove, useNetworkAliases, attachStdin)
  356. if err != nil {
  357. return
  358. }
  359. w.Event(progress.CreatedEvent(eventName))
  360. return
  361. }
  362. func (s *composeService) recreateContainer(ctx context.Context, project *types.Project, service types.ServiceConfig,
  363. replaced moby.Container, inherit bool, timeout *time.Duration) (moby.Container, error) {
  364. var created moby.Container
  365. w := progress.ContextWriter(ctx)
  366. w.Event(progress.NewEvent(getContainerProgressName(replaced), progress.Working, "Recreate"))
  367. err := s.apiClient().ContainerStop(ctx, replaced.ID, timeout)
  368. if err != nil {
  369. return created, err
  370. }
  371. name := getCanonicalContainerName(replaced)
  372. tmpName := fmt.Sprintf("%s_%s", replaced.ID[:12], name)
  373. err = s.apiClient().ContainerRename(ctx, replaced.ID, tmpName)
  374. if err != nil {
  375. return created, err
  376. }
  377. number, err := strconv.Atoi(replaced.Labels[api.ContainerNumberLabel])
  378. if err != nil {
  379. return created, err
  380. }
  381. var inherited *moby.Container
  382. if inherit {
  383. inherited = &replaced
  384. }
  385. name = getContainerName(project.Name, service, number)
  386. created, err = s.createMobyContainer(ctx, project, service, name, number, inherited, false, true, false)
  387. if err != nil {
  388. return created, err
  389. }
  390. err = s.apiClient().ContainerRemove(ctx, replaced.ID, moby.ContainerRemoveOptions{})
  391. if err != nil {
  392. return created, err
  393. }
  394. w.Event(progress.NewEvent(getContainerProgressName(replaced), progress.Done, "Recreated"))
  395. setDependentLifecycle(project, service.Name, forceRecreate)
  396. return created, err
  397. }
  398. // setDependentLifecycle define the Lifecycle strategy for all services to depend on specified service
  399. func setDependentLifecycle(project *types.Project, service string, strategy string) {
  400. for i, s := range project.Services {
  401. if utils.StringContains(s.GetDependencies(), service) {
  402. if s.Extensions == nil {
  403. s.Extensions = map[string]interface{}{}
  404. }
  405. s.Extensions[extLifecycle] = strategy
  406. project.Services[i] = s
  407. }
  408. }
  409. }
  410. func (s *composeService) startContainer(ctx context.Context, container moby.Container) error {
  411. w := progress.ContextWriter(ctx)
  412. w.Event(progress.NewEvent(getContainerProgressName(container), progress.Working, "Restart"))
  413. err := s.apiClient().ContainerStart(ctx, container.ID, moby.ContainerStartOptions{})
  414. if err != nil {
  415. return err
  416. }
  417. w.Event(progress.NewEvent(getContainerProgressName(container), progress.Done, "Restarted"))
  418. return nil
  419. }
  420. func (s *composeService) createMobyContainer(ctx context.Context, project *types.Project, service types.ServiceConfig,
  421. name string, number int, inherit *moby.Container, autoRemove bool, useNetworkAliases bool, attachStdin bool) (moby.Container, error) {
  422. var created moby.Container
  423. containerConfig, hostConfig, networkingConfig, err := s.getCreateOptions(ctx, project, service, number, inherit, autoRemove, attachStdin)
  424. if err != nil {
  425. return created, err
  426. }
  427. var plat *specs.Platform
  428. if service.Platform != "" {
  429. var p specs.Platform
  430. p, err = platforms.Parse(service.Platform)
  431. if err != nil {
  432. return created, err
  433. }
  434. plat = &p
  435. }
  436. response, err := s.apiClient().ContainerCreate(ctx, containerConfig, hostConfig, networkingConfig, plat, name)
  437. if err != nil {
  438. return created, err
  439. }
  440. inspectedContainer, err := s.apiClient().ContainerInspect(ctx, response.ID)
  441. if err != nil {
  442. return created, err
  443. }
  444. created = moby.Container{
  445. ID: inspectedContainer.ID,
  446. Labels: inspectedContainer.Config.Labels,
  447. Names: []string{inspectedContainer.Name},
  448. NetworkSettings: &moby.SummaryNetworkSettings{
  449. Networks: inspectedContainer.NetworkSettings.Networks,
  450. },
  451. }
  452. links, err := s.getLinks(ctx, project.Name, service, number)
  453. if err != nil {
  454. return created, err
  455. }
  456. for _, netName := range service.NetworksByPriority() {
  457. netwrk := project.Networks[netName]
  458. cfg := service.Networks[netName]
  459. aliases := []string{getContainerName(project.Name, service, number)}
  460. if useNetworkAliases {
  461. aliases = append(aliases, service.Name)
  462. if cfg != nil {
  463. aliases = append(aliases, cfg.Aliases...)
  464. }
  465. }
  466. if val, ok := created.NetworkSettings.Networks[netwrk.Name]; ok {
  467. if shortIDAliasExists(created.ID, val.Aliases...) {
  468. continue
  469. }
  470. err = s.apiClient().NetworkDisconnect(ctx, netwrk.Name, created.ID, false)
  471. if err != nil {
  472. return created, err
  473. }
  474. }
  475. err = s.connectContainerToNetwork(ctx, created.ID, netwrk.Name, cfg, links, aliases...)
  476. if err != nil {
  477. return created, err
  478. }
  479. }
  480. return created, err
  481. }
  482. // getLinks mimics V1 compose/service.py::Service::_get_links()
  483. func (s composeService) getLinks(ctx context.Context, projectName string, service types.ServiceConfig, number int) ([]string, error) {
  484. var links []string
  485. format := func(k, v string) string {
  486. return fmt.Sprintf("%s:%s", k, v)
  487. }
  488. getServiceContainers := func(serviceName string) (Containers, error) {
  489. return s.getContainers(ctx, projectName, oneOffExclude, true, serviceName)
  490. }
  491. for _, rawLink := range service.Links {
  492. linkSplit := strings.Split(rawLink, ":")
  493. linkServiceName := linkSplit[0]
  494. linkName := linkServiceName
  495. if len(linkSplit) == 2 {
  496. linkName = linkSplit[1] // linkName if informed like in: "serviceName:linkName"
  497. }
  498. cnts, err := getServiceContainers(linkServiceName)
  499. if err != nil {
  500. return nil, err
  501. }
  502. for _, c := range cnts {
  503. containerName := getCanonicalContainerName(c)
  504. links = append(links,
  505. format(containerName, linkName),
  506. format(containerName, strings.Join([]string{linkServiceName, strconv.Itoa(number)}, Separator)),
  507. format(containerName, strings.Join([]string{projectName, linkServiceName, strconv.Itoa(number)}, Separator)),
  508. )
  509. }
  510. }
  511. if service.Labels[api.OneoffLabel] == "True" {
  512. cnts, err := getServiceContainers(service.Name)
  513. if err != nil {
  514. return nil, err
  515. }
  516. for _, c := range cnts {
  517. containerName := getCanonicalContainerName(c)
  518. links = append(links,
  519. format(containerName, service.Name),
  520. format(containerName, strings.TrimPrefix(containerName, projectName+Separator)),
  521. format(containerName, containerName),
  522. )
  523. }
  524. }
  525. for _, rawExtLink := range service.ExternalLinks {
  526. extLinkSplit := strings.Split(rawExtLink, ":")
  527. externalLink := extLinkSplit[0]
  528. linkName := externalLink
  529. if len(extLinkSplit) == 2 {
  530. linkName = extLinkSplit[1]
  531. }
  532. links = append(links, format(externalLink, linkName))
  533. }
  534. return links, nil
  535. }
  536. func shortIDAliasExists(containerID string, aliases ...string) bool {
  537. for _, alias := range aliases {
  538. if alias == containerID[:12] {
  539. return true
  540. }
  541. }
  542. return false
  543. }
  544. func (s *composeService) connectContainerToNetwork(ctx context.Context, id string, netwrk string, cfg *types.ServiceNetworkConfig, links []string, aliases ...string) error {
  545. var (
  546. ipv4Address string
  547. ipv6Address string
  548. ipam *network.EndpointIPAMConfig
  549. )
  550. if cfg != nil {
  551. ipv4Address = cfg.Ipv4Address
  552. ipv6Address = cfg.Ipv6Address
  553. ipam = &network.EndpointIPAMConfig{
  554. IPv4Address: ipv4Address,
  555. IPv6Address: ipv6Address,
  556. }
  557. }
  558. err := s.apiClient().NetworkConnect(ctx, netwrk, id, &network.EndpointSettings{
  559. Aliases: aliases,
  560. IPAddress: ipv4Address,
  561. GlobalIPv6Address: ipv6Address,
  562. Links: links,
  563. IPAMConfig: ipam,
  564. })
  565. if err != nil {
  566. return err
  567. }
  568. return nil
  569. }
  570. func (s *composeService) isServiceHealthy(ctx context.Context, project *types.Project, service string, fallbackRunning bool) (bool, error) {
  571. containers, err := s.getContainers(ctx, project.Name, oneOffExclude, false, service)
  572. if err != nil {
  573. return false, err
  574. }
  575. if len(containers) == 0 {
  576. return false, nil
  577. }
  578. for _, c := range containers {
  579. container, err := s.apiClient().ContainerInspect(ctx, c.ID)
  580. if err != nil {
  581. return false, err
  582. }
  583. if container.Config.Healthcheck == nil && fallbackRunning {
  584. // Container does not define a health check, but we can fall back to "running" state
  585. return container.State != nil && container.State.Status == "running", nil
  586. }
  587. if container.State == nil || container.State.Health == nil {
  588. return false, fmt.Errorf("container for service %q has no healthcheck configured", service)
  589. }
  590. switch container.State.Health.Status {
  591. case moby.Healthy:
  592. // Continue by checking the next container.
  593. case moby.Unhealthy:
  594. return false, fmt.Errorf("container for service %q is unhealthy", service)
  595. case moby.Starting:
  596. return false, nil
  597. default:
  598. return false, fmt.Errorf("container for service %q had unexpected health status %q", service, container.State.Health.Status)
  599. }
  600. }
  601. return true, nil
  602. }
  603. func (s *composeService) isServiceCompleted(ctx context.Context, project *types.Project, dep string) (bool, int, error) {
  604. containers, err := s.getContainers(ctx, project.Name, oneOffExclude, true, dep)
  605. if err != nil {
  606. return false, 0, err
  607. }
  608. for _, c := range containers {
  609. container, err := s.apiClient().ContainerInspect(ctx, c.ID)
  610. if err != nil {
  611. return false, 0, err
  612. }
  613. if container.State != nil && container.State.Status == "exited" {
  614. return true, container.State.ExitCode, nil
  615. }
  616. }
  617. return false, 0, nil
  618. }
  619. func (s *composeService) startService(ctx context.Context, project *types.Project, service types.ServiceConfig) error {
  620. if service.Deploy != nil && service.Deploy.Replicas != nil && *service.Deploy.Replicas == 0 {
  621. return nil
  622. }
  623. err := s.waitDependencies(ctx, project, service.DependsOn)
  624. if err != nil {
  625. return err
  626. }
  627. containers, err := s.apiClient().ContainerList(ctx, moby.ContainerListOptions{
  628. Filters: filters.NewArgs(
  629. projectFilter(project.Name),
  630. serviceFilter(service.Name),
  631. oneOffFilter(false),
  632. ),
  633. All: true,
  634. })
  635. if err != nil {
  636. return err
  637. }
  638. if len(containers) == 0 {
  639. if scale, err := getScale(service); err != nil && scale == 0 {
  640. return nil
  641. }
  642. return fmt.Errorf("service %q has no container to start", service.Name)
  643. }
  644. w := progress.ContextWriter(ctx)
  645. eg, ctx := errgroup.WithContext(ctx)
  646. for _, container := range containers {
  647. if container.State == ContainerRunning {
  648. continue
  649. }
  650. container := container
  651. eg.Go(func() error {
  652. eventName := getContainerProgressName(container)
  653. w.Event(progress.StartingEvent(eventName))
  654. err := s.apiClient().ContainerStart(ctx, container.ID, moby.ContainerStartOptions{})
  655. if err == nil {
  656. w.Event(progress.StartedEvent(eventName))
  657. }
  658. return err
  659. })
  660. }
  661. return eg.Wait()
  662. }