up.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. "os"
  18. "os/signal"
  19. "sync/atomic"
  20. "syscall"
  21. "github.com/compose-spec/compose-go/v2/types"
  22. "github.com/docker/cli/cli"
  23. "github.com/docker/compose/v2/cmd/formatter"
  24. "github.com/docker/compose/v2/internal/tracing"
  25. "github.com/docker/compose/v2/pkg/api"
  26. "github.com/docker/compose/v2/pkg/progress"
  27. "github.com/docker/docker/errdefs"
  28. "github.com/eiannone/keyboard"
  29. "github.com/hashicorp/go-multierror"
  30. "github.com/sirupsen/logrus"
  31. )
  32. func (s *composeService) Up(ctx context.Context, project *types.Project, options api.UpOptions) error { //nolint:gocyclo
  33. err := progress.Run(ctx, tracing.SpanWrapFunc("project/up", tracing.ProjectOptions(ctx, project), func(ctx context.Context) error {
  34. err := s.create(ctx, project, options.Create)
  35. if err != nil {
  36. return err
  37. }
  38. if options.Start.Attach == nil {
  39. return s.start(ctx, project.Name, options.Start, nil)
  40. }
  41. return nil
  42. }), s.stdinfo())
  43. if err != nil {
  44. return err
  45. }
  46. if options.Start.Attach == nil {
  47. return err
  48. }
  49. if s.dryRun {
  50. _, _ = fmt.Fprintln(s.stdout(), "end of 'compose up' output, interactive run is not supported in dry-run mode")
  51. return err
  52. }
  53. var eg multierror.Group
  54. // if we get a second signal during shutdown, we kill the services
  55. // immediately, so the channel needs to have sufficient capacity or
  56. // we might miss a signal while setting up the second channel read
  57. // (this is also why signal.Notify is used vs signal.NotifyContext)
  58. signalChan := make(chan os.Signal, 2)
  59. defer close(signalChan)
  60. signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
  61. defer signal.Stop(signalChan)
  62. var isTerminated atomic.Bool
  63. printer := newLogPrinter(options.Start.Attach)
  64. doneCh := make(chan bool)
  65. eg.Go(func() error {
  66. first := true
  67. gracefulTeardown := func() {
  68. printer.Cancel()
  69. _, _ = fmt.Fprintln(s.stdinfo(), "Gracefully stopping... (press Ctrl+C again to force)")
  70. eg.Go(func() error {
  71. err := s.Stop(context.WithoutCancel(ctx), project.Name, api.StopOptions{
  72. Services: options.Create.Services,
  73. Project: project,
  74. })
  75. isTerminated.Store(true)
  76. return err
  77. })
  78. first = false
  79. }
  80. var kEvents <-chan keyboard.KeyEvent
  81. if options.Start.NavigationMenu {
  82. kEvents, err = keyboard.GetKeys(100)
  83. if err != nil {
  84. logrus.Warn("could not start menu, an error occurred while starting.")
  85. } else {
  86. defer keyboard.Close() //nolint:errcheck
  87. isWatchConfigured := s.shouldWatch(project)
  88. isDockerDesktopActive := s.isDesktopIntegrationActive()
  89. tracing.KeyboardMetrics(ctx, options.Start.NavigationMenu, isDockerDesktopActive, isWatchConfigured)
  90. formatter.NewKeyboardManager(ctx, isDockerDesktopActive, isWatchConfigured, signalChan, s.watch)
  91. if options.Start.Watch {
  92. formatter.KeyboardManager.StartWatch(ctx, doneCh, project, options)
  93. }
  94. }
  95. }
  96. for {
  97. select {
  98. case <-doneCh:
  99. return nil
  100. case <-ctx.Done():
  101. if first {
  102. gracefulTeardown()
  103. }
  104. case <-signalChan:
  105. if first {
  106. gracefulTeardown()
  107. break
  108. }
  109. eg.Go(func() error {
  110. err := s.kill(context.WithoutCancel(ctx), project.Name, api.KillOptions{
  111. Services: options.Create.Services,
  112. Project: project,
  113. All: true,
  114. })
  115. // Ignore errors indicating that some of the containers were already stopped or removed.
  116. if errdefs.IsNotFound(err) || errdefs.IsConflict(err) {
  117. return nil
  118. }
  119. return err
  120. })
  121. return nil
  122. case event := <-kEvents:
  123. formatter.KeyboardManager.HandleKeyEvents(event, ctx, doneCh, project, options)
  124. }
  125. }
  126. })
  127. var exitCode int
  128. eg.Go(func() error {
  129. code, err := printer.Run(options.Start.OnExit, options.Start.ExitCodeFrom, func() error {
  130. _, _ = fmt.Fprintln(s.stdinfo(), "Aborting on container exit...")
  131. return progress.Run(ctx, func(ctx context.Context) error {
  132. return s.Stop(ctx, project.Name, api.StopOptions{
  133. Services: options.Create.Services,
  134. Project: project,
  135. })
  136. }, s.stdinfo())
  137. })
  138. exitCode = code
  139. return err
  140. })
  141. if options.Start.Watch && !options.Start.NavigationMenu {
  142. eg.Go(func() error {
  143. buildOpts := *options.Create.Build
  144. buildOpts.Quiet = true
  145. return s.watch(ctx, doneCh, project, options.Start.Services, api.WatchOptions{
  146. Build: &buildOpts,
  147. LogTo: options.Start.Attach,
  148. })
  149. })
  150. }
  151. // We use the parent context without cancellation as we manage sigterm to stop the stack
  152. err = s.start(context.WithoutCancel(ctx), project.Name, options.Start, printer.HandleEvent)
  153. if err != nil && !isTerminated.Load() { // Ignore error if the process is terminated
  154. return err
  155. }
  156. // Signal for the signal-handler goroutines to stop
  157. close(doneCh)
  158. printer.Stop()
  159. err = eg.Wait().ErrorOrNil()
  160. if exitCode != 0 {
  161. errMsg := ""
  162. if err != nil {
  163. errMsg = err.Error()
  164. }
  165. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  166. }
  167. return err
  168. }