convergence.go 25 KB

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