convergence.go 23 KB

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