convergence.go 23 KB

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