up.go 5.3 KB

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