up.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. cerrdefs "github.com/containerd/errdefs"
  23. "github.com/docker/cli/cli"
  24. "github.com/docker/compose/v2/cmd/formatter"
  25. "github.com/docker/compose/v2/internal/tracing"
  26. "github.com/docker/compose/v2/pkg/api"
  27. "github.com/docker/compose/v2/pkg/progress"
  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. var (
  64. logConsumer = options.Start.Attach
  65. navigationMenu *formatter.LogKeyboard
  66. kEvents <-chan keyboard.KeyEvent
  67. )
  68. if options.Start.NavigationMenu {
  69. kEvents, err = keyboard.GetKeys(100)
  70. if err != nil {
  71. logrus.Warnf("could not start menu, an error occurred while starting: %v", err)
  72. options.Start.NavigationMenu = false
  73. } else {
  74. defer keyboard.Close() //nolint:errcheck
  75. isDockerDesktopActive := s.isDesktopIntegrationActive()
  76. tracing.KeyboardMetrics(ctx, options.Start.NavigationMenu, isDockerDesktopActive)
  77. navigationMenu = formatter.NewKeyboardManager(isDockerDesktopActive, signalChan)
  78. logConsumer = navigationMenu.Decorate(logConsumer)
  79. }
  80. }
  81. tui := formatter.NewStopping(logConsumer)
  82. defer tui.Close()
  83. logConsumer = tui
  84. watcher, err := NewWatcher(project, options, s.watch, logConsumer)
  85. if err != nil && options.Start.Watch {
  86. return err
  87. }
  88. if navigationMenu != nil && watcher != nil {
  89. navigationMenu.EnableWatch(options.Start.Watch, watcher)
  90. }
  91. printer := newLogPrinter(logConsumer)
  92. doneCh := make(chan bool)
  93. eg.Go(func() error {
  94. first := true
  95. gracefulTeardown := func() {
  96. tui.ApplicationTermination()
  97. eg.Go(func() error {
  98. return progress.RunWithLog(context.WithoutCancel(ctx), func(ctx context.Context) error {
  99. return s.stop(ctx, project.Name, api.StopOptions{
  100. Services: options.Create.Services,
  101. Project: project,
  102. }, printer.HandleEvent)
  103. }, s.stdinfo(), logConsumer)
  104. })
  105. isTerminated.Store(true)
  106. first = false
  107. }
  108. for {
  109. select {
  110. case <-doneCh:
  111. if watcher != nil {
  112. return watcher.Stop()
  113. }
  114. return nil
  115. case <-ctx.Done():
  116. if first {
  117. gracefulTeardown()
  118. }
  119. case <-signalChan:
  120. if first {
  121. keyboard.Close() //nolint:errcheck
  122. gracefulTeardown()
  123. break
  124. }
  125. eg.Go(func() error {
  126. err := s.kill(context.WithoutCancel(ctx), project.Name, api.KillOptions{
  127. Services: options.Create.Services,
  128. Project: project,
  129. All: true,
  130. })
  131. // Ignore errors indicating that some of the containers were already stopped or removed.
  132. if cerrdefs.IsNotFound(err) || cerrdefs.IsConflict(err) {
  133. return nil
  134. }
  135. return err
  136. })
  137. return nil
  138. case event := <-kEvents:
  139. navigationMenu.HandleKeyEvents(ctx, event, project, options)
  140. }
  141. }
  142. })
  143. var exitCode int
  144. eg.Go(func() error {
  145. code, err := printer.Run(options.Start.OnExit, options.Start.ExitCodeFrom, func() error {
  146. _, _ = fmt.Fprintln(s.stdinfo(), "Aborting on container exit...")
  147. eg.Go(func() error {
  148. return progress.RunWithLog(context.WithoutCancel(ctx), func(ctx context.Context) error {
  149. return s.stop(ctx, project.Name, api.StopOptions{
  150. Services: options.Create.Services,
  151. Project: project,
  152. }, printer.HandleEvent)
  153. }, s.stdinfo(), logConsumer)
  154. })
  155. return nil
  156. })
  157. exitCode = code
  158. return err
  159. })
  160. if options.Start.Watch && watcher != nil {
  161. err = watcher.Start(ctx)
  162. if err != nil {
  163. return err
  164. }
  165. }
  166. // We use the parent context without cancellation as we manage sigterm to stop the stack
  167. err = s.start(context.WithoutCancel(ctx), project.Name, options.Start, printer.HandleEvent)
  168. if err != nil && !isTerminated.Load() { // Ignore error if the process is terminated
  169. return err
  170. }
  171. // Signal for the signal-handler goroutines to stop
  172. close(doneCh)
  173. printer.Stop()
  174. err = eg.Wait().ErrorOrNil()
  175. if exitCode != 0 {
  176. errMsg := ""
  177. if err != nil {
  178. errMsg = err.Error()
  179. }
  180. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  181. }
  182. return err
  183. }