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