convergence.go 22 KB

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