convergence.go 24 KB

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