convergence.go 23 KB

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