up.go 5.7 KB

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