convergence.go 23 KB

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