convergence.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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,
  362. autoRemove, useNetworkAliases, attachStdin, w, mergeLabels(service.Labels, service.CustomLabels))
  363. if err != nil {
  364. return
  365. }
  366. w.Event(progress.CreatedEvent(eventName))
  367. return
  368. }
  369. func (s *composeService) recreateContainer(ctx context.Context, project *types.Project, service types.ServiceConfig,
  370. replaced moby.Container, inherit bool, timeout *time.Duration) (moby.Container, error) {
  371. var created moby.Container
  372. w := progress.ContextWriter(ctx)
  373. w.Event(progress.NewEvent(getContainerProgressName(replaced), progress.Working, "Recreate"))
  374. number, err := strconv.Atoi(replaced.Labels[api.ContainerNumberLabel])
  375. if err != nil {
  376. return created, err
  377. }
  378. var inherited *moby.Container
  379. if inherit {
  380. inherited = &replaced
  381. }
  382. name := getContainerName(project.Name, service, number)
  383. tmpName := fmt.Sprintf("%s_%s", replaced.ID[:12], name)
  384. created, err = s.createMobyContainer(ctx, project, service, tmpName, number, inherited,
  385. false, true, false, w,
  386. mergeLabels(service.Labels, service.CustomLabels).Add(api.ContainerReplaceLabel, replaced.ID))
  387. if err != nil {
  388. return created, err
  389. }
  390. timeoutInSecond := utils.DurationSecondToInt(timeout)
  391. err = s.apiClient().ContainerStop(ctx, replaced.ID, containerType.StopOptions{Timeout: timeoutInSecond})
  392. if err != nil {
  393. return created, err
  394. }
  395. err = s.apiClient().ContainerRemove(ctx, replaced.ID, moby.ContainerRemoveOptions{})
  396. if err != nil {
  397. return created, err
  398. }
  399. err = s.apiClient().ContainerRename(ctx, created.ID, name)
  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,
  430. project *types.Project,
  431. service types.ServiceConfig,
  432. name string,
  433. number int,
  434. inherit *moby.Container,
  435. autoRemove, useNetworkAliases, attachStdin bool,
  436. w progress.Writer,
  437. labels types.Labels,
  438. ) (moby.Container, error) {
  439. var created moby.Container
  440. containerConfig, hostConfig, networkingConfig, err := s.getCreateOptions(ctx, project, service, number, inherit,
  441. autoRemove, attachStdin, labels)
  442. if err != nil {
  443. return created, err
  444. }
  445. platform := service.Platform
  446. if platform == "" {
  447. platform = project.Environment["DOCKER_DEFAULT_PLATFORM"]
  448. }
  449. var plat *specs.Platform
  450. if platform != "" {
  451. var p specs.Platform
  452. p, err = platforms.Parse(platform)
  453. if err != nil {
  454. return created, err
  455. }
  456. plat = &p
  457. }
  458. response, err := s.apiClient().ContainerCreate(ctx, containerConfig, hostConfig, networkingConfig, plat, name)
  459. if err != nil {
  460. return created, err
  461. }
  462. for _, warning := range response.Warnings {
  463. w.Event(progress.Event{
  464. ID: service.Name,
  465. Status: progress.Warning,
  466. Text: warning,
  467. })
  468. }
  469. inspectedContainer, err := s.apiClient().ContainerInspect(ctx, response.ID)
  470. if err != nil {
  471. return created, err
  472. }
  473. created = moby.Container{
  474. ID: inspectedContainer.ID,
  475. Labels: inspectedContainer.Config.Labels,
  476. Names: []string{inspectedContainer.Name},
  477. NetworkSettings: &moby.SummaryNetworkSettings{
  478. Networks: inspectedContainer.NetworkSettings.Networks,
  479. },
  480. }
  481. links, err := s.getLinks(ctx, project.Name, service, number)
  482. if err != nil {
  483. return created, err
  484. }
  485. for _, netName := range service.NetworksByPriority() {
  486. netwrk := project.Networks[netName]
  487. cfg := service.Networks[netName]
  488. aliases := []string{getContainerName(project.Name, service, number)}
  489. if useNetworkAliases {
  490. aliases = append(aliases, service.Name)
  491. if cfg != nil {
  492. aliases = append(aliases, cfg.Aliases...)
  493. }
  494. }
  495. if val, ok := created.NetworkSettings.Networks[netwrk.Name]; ok {
  496. if shortIDAliasExists(created.ID, val.Aliases...) {
  497. continue
  498. }
  499. err = s.apiClient().NetworkDisconnect(ctx, netwrk.Name, created.ID, false)
  500. if err != nil {
  501. return created, err
  502. }
  503. }
  504. err = s.connectContainerToNetwork(ctx, created.ID, netwrk.Name, cfg, links, aliases...)
  505. if err != nil {
  506. return created, err
  507. }
  508. }
  509. err = s.injectSecrets(ctx, project, service, created.ID)
  510. return created, err
  511. }
  512. // getLinks mimics V1 compose/service.py::Service::_get_links()
  513. func (s *composeService) getLinks(ctx context.Context, projectName string, service types.ServiceConfig, number int) ([]string, error) {
  514. var links []string
  515. format := func(k, v string) string {
  516. return fmt.Sprintf("%s:%s", k, v)
  517. }
  518. getServiceContainers := func(serviceName string) (Containers, error) {
  519. return s.getContainers(ctx, projectName, oneOffExclude, true, serviceName)
  520. }
  521. for _, rawLink := range service.Links {
  522. linkSplit := strings.Split(rawLink, ":")
  523. linkServiceName := linkSplit[0]
  524. linkName := linkServiceName
  525. if len(linkSplit) == 2 {
  526. linkName = linkSplit[1] // linkName if informed like in: "serviceName:linkName"
  527. }
  528. cnts, err := getServiceContainers(linkServiceName)
  529. if err != nil {
  530. return nil, err
  531. }
  532. for _, c := range cnts {
  533. containerName := getCanonicalContainerName(c)
  534. links = append(links,
  535. format(containerName, linkName),
  536. format(containerName, linkServiceName+api.Separator+strconv.Itoa(number)),
  537. format(containerName, strings.Join([]string{projectName, linkServiceName, strconv.Itoa(number)}, api.Separator)),
  538. )
  539. }
  540. }
  541. if service.Labels[api.OneoffLabel] == "True" {
  542. cnts, err := getServiceContainers(service.Name)
  543. if err != nil {
  544. return nil, err
  545. }
  546. for _, c := range cnts {
  547. containerName := getCanonicalContainerName(c)
  548. links = append(links,
  549. format(containerName, service.Name),
  550. format(containerName, strings.TrimPrefix(containerName, projectName+api.Separator)),
  551. format(containerName, containerName),
  552. )
  553. }
  554. }
  555. for _, rawExtLink := range service.ExternalLinks {
  556. extLinkSplit := strings.Split(rawExtLink, ":")
  557. externalLink := extLinkSplit[0]
  558. linkName := externalLink
  559. if len(extLinkSplit) == 2 {
  560. linkName = extLinkSplit[1]
  561. }
  562. links = append(links, format(externalLink, linkName))
  563. }
  564. return links, nil
  565. }
  566. func shortIDAliasExists(containerID string, aliases ...string) bool {
  567. for _, alias := range aliases {
  568. if alias == containerID[:12] {
  569. return true
  570. }
  571. }
  572. return false
  573. }
  574. func (s *composeService) connectContainerToNetwork(ctx context.Context, id string, netwrk string, cfg *types.ServiceNetworkConfig, links []string, aliases ...string) error {
  575. var (
  576. ipv4Address string
  577. ipv6Address string
  578. ipam *network.EndpointIPAMConfig
  579. )
  580. if cfg != nil {
  581. ipv4Address = cfg.Ipv4Address
  582. ipv6Address = cfg.Ipv6Address
  583. ipam = &network.EndpointIPAMConfig{
  584. IPv4Address: ipv4Address,
  585. IPv6Address: ipv6Address,
  586. LinkLocalIPs: cfg.LinkLocalIPs,
  587. }
  588. }
  589. err := s.apiClient().NetworkConnect(ctx, netwrk, id, &network.EndpointSettings{
  590. Aliases: aliases,
  591. IPAddress: ipv4Address,
  592. GlobalIPv6Address: ipv6Address,
  593. Links: links,
  594. IPAMConfig: ipam,
  595. })
  596. if err != nil {
  597. return err
  598. }
  599. return nil
  600. }
  601. func (s *composeService) isServiceHealthy(ctx context.Context, containers Containers, fallbackRunning bool) (bool, error) {
  602. for _, c := range containers {
  603. container, err := s.apiClient().ContainerInspect(ctx, c.ID)
  604. if err != nil {
  605. return false, err
  606. }
  607. name := container.Name[1:]
  608. if container.State.Status == "exited" {
  609. return false, fmt.Errorf("container %s exited (%d)", name, container.State.ExitCode)
  610. }
  611. if container.Config.Healthcheck == nil && fallbackRunning {
  612. // Container does not define a health check, but we can fall back to "running" state
  613. return container.State != nil && container.State.Status == "running", nil
  614. }
  615. if container.State == nil || container.State.Health == nil {
  616. return false, fmt.Errorf("container %s has no healthcheck configured", name)
  617. }
  618. switch container.State.Health.Status {
  619. case moby.Healthy:
  620. // Continue by checking the next container.
  621. case moby.Unhealthy:
  622. return false, fmt.Errorf("container %s is unhealthy", name)
  623. case moby.Starting:
  624. return false, nil
  625. default:
  626. return false, fmt.Errorf("container %s had unexpected health status %q", name, container.State.Health.Status)
  627. }
  628. }
  629. return true, nil
  630. }
  631. func (s *composeService) isServiceCompleted(ctx context.Context, containers Containers) (bool, int, error) {
  632. for _, c := range containers {
  633. container, err := s.apiClient().ContainerInspect(ctx, c.ID)
  634. if err != nil {
  635. return false, 0, err
  636. }
  637. if container.State != nil && container.State.Status == "exited" {
  638. return true, container.State.ExitCode, nil
  639. }
  640. }
  641. return false, 0, nil
  642. }
  643. func (s *composeService) startService(ctx context.Context, project *types.Project, service types.ServiceConfig, containers Containers) error {
  644. if service.Deploy != nil && service.Deploy.Replicas != nil && *service.Deploy.Replicas == 0 {
  645. return nil
  646. }
  647. err := s.waitDependencies(ctx, project, service.DependsOn, containers)
  648. if err != nil {
  649. return err
  650. }
  651. if len(containers) == 0 {
  652. if scale, err := getScale(service); err != nil && scale == 0 {
  653. return nil
  654. }
  655. return fmt.Errorf("service %q has no container to start", service.Name)
  656. }
  657. w := progress.ContextWriter(ctx)
  658. for _, container := range containers.filter(isService(service.Name)) {
  659. if container.State == ContainerRunning {
  660. continue
  661. }
  662. eventName := getContainerProgressName(container)
  663. w.Event(progress.StartingEvent(eventName))
  664. err := s.apiClient().ContainerStart(ctx, container.ID, moby.ContainerStartOptions{})
  665. if err != nil {
  666. return err
  667. }
  668. w.Event(progress.StartedEvent(eventName))
  669. }
  670. return nil
  671. }
  672. func mergeLabels(ls ...types.Labels) types.Labels {
  673. merged := types.Labels{}
  674. for _, l := range ls {
  675. for k, v := range l {
  676. merged[k] = v
  677. }
  678. }
  679. return merged
  680. }