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