convergence.go 22 KB

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