convergence.go 22 KB

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