up.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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/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. watcher, err := NewWatcher(project, options, s.watch, logConsumer)
  82. if err != nil && options.Start.Watch {
  83. return err
  84. }
  85. if navigationMenu != nil && watcher != nil {
  86. navigationMenu.EnableWatch(options.Start.Watch, watcher)
  87. }
  88. printer := newLogPrinter(logConsumer)
  89. doneCh := make(chan bool)
  90. eg.Go(func() error {
  91. first := true
  92. gracefulTeardown := func() {
  93. first = false
  94. fmt.Println("Gracefully Stopping... press Ctrl+C again to force")
  95. eg.Go(func() error {
  96. return progress.RunWithLog(context.WithoutCancel(ctx), func(ctx context.Context) error {
  97. return s.stop(ctx, project.Name, api.StopOptions{
  98. Services: options.Create.Services,
  99. Project: project,
  100. }, printer.HandleEvent)
  101. }, s.stdinfo(), logConsumer)
  102. })
  103. isTerminated.Store(true)
  104. }
  105. for {
  106. select {
  107. case <-doneCh:
  108. if watcher != nil {
  109. return watcher.Stop()
  110. }
  111. return nil
  112. case <-ctx.Done():
  113. if first {
  114. gracefulTeardown()
  115. }
  116. case <-signalChan:
  117. if first {
  118. keyboard.Close() //nolint:errcheck
  119. gracefulTeardown()
  120. break
  121. }
  122. eg.Go(func() error {
  123. err := s.kill(context.WithoutCancel(ctx), project.Name, api.KillOptions{
  124. Services: options.Create.Services,
  125. Project: project,
  126. All: true,
  127. })
  128. // Ignore errors indicating that some of the containers were already stopped or removed.
  129. if errdefs.IsNotFound(err) || errdefs.IsConflict(err) {
  130. return nil
  131. }
  132. return err
  133. })
  134. return nil
  135. case event := <-kEvents:
  136. navigationMenu.HandleKeyEvents(ctx, event, project, options)
  137. }
  138. }
  139. })
  140. if options.Start.Watch && watcher != nil {
  141. err = watcher.Start(ctx)
  142. if err != nil {
  143. return err
  144. }
  145. }
  146. monitor := newMonitor(s.apiClient(), project.Name)
  147. if len(options.Start.Services) > 0 {
  148. monitor.withServices(options.Start.Services)
  149. } else {
  150. monitor.withServices(project.ServiceNames())
  151. }
  152. monitor.withListener(printer.HandleEvent)
  153. var exitCode int
  154. if options.Start.OnExit != api.CascadeIgnore {
  155. once := true
  156. // detect first container to exit to trigger application shutdown
  157. monitor.withListener(func(event api.ContainerEvent) {
  158. if once && event.Type == api.ContainerEventExited {
  159. if options.Start.OnExit == api.CascadeFail && event.ExitCode == 0 {
  160. return
  161. }
  162. once = false
  163. exitCode = event.ExitCode
  164. _, _ = fmt.Fprintln(s.stdinfo(), progress.ErrorColor("Aborting on container exit..."))
  165. eg.Go(func() error {
  166. return progress.RunWithLog(context.WithoutCancel(ctx), func(ctx context.Context) error {
  167. return s.stop(ctx, project.Name, api.StopOptions{
  168. Services: options.Create.Services,
  169. Project: project,
  170. }, printer.HandleEvent)
  171. }, s.stdinfo(), logConsumer)
  172. })
  173. }
  174. })
  175. }
  176. if options.Start.ExitCodeFrom != "" {
  177. once := true
  178. // capture exit code from first container to exit with selected service
  179. monitor.withListener(func(event api.ContainerEvent) {
  180. if once && event.Type == api.ContainerEventExited && event.Service == options.Start.ExitCodeFrom {
  181. exitCode = event.ExitCode
  182. once = false
  183. }
  184. })
  185. }
  186. monitor.withListener(func(event api.ContainerEvent) {
  187. if event.Type != api.ContainerEventStarted {
  188. return
  189. }
  190. if event.Restarting || event.Container.Labels[api.ContainerReplaceLabel] != "" {
  191. eg.Go(func() error {
  192. ctr, err := s.apiClient().ContainerInspect(ctx, event.ID)
  193. if err != nil {
  194. return err
  195. }
  196. err = s.doLogContainer(ctx, options.Start.Attach, event.Source, ctr, api.LogOptions{
  197. Follow: true,
  198. Since: ctr.State.StartedAt,
  199. })
  200. if errdefs.IsNotImplemented(err) {
  201. // container may be configured with logging_driver: none
  202. // as container already started, we might miss the very first logs. But still better than none
  203. return s.doAttachContainer(ctx, event.Service, event.ID, event.Source, printer.HandleEvent)
  204. }
  205. return err
  206. })
  207. }
  208. })
  209. eg.Go(func() error {
  210. err := monitor.Start(context.Background())
  211. // Signal for the signal-handler goroutines to stop
  212. close(doneCh)
  213. return err
  214. })
  215. // We use the parent context without cancellation as we manage sigterm to stop the stack
  216. err = s.start(context.WithoutCancel(ctx), project.Name, options.Start, printer.HandleEvent)
  217. if err != nil && !isTerminated.Load() { // Ignore error if the process is terminated
  218. return err
  219. }
  220. err = eg.Wait().ErrorOrNil()
  221. if exitCode != 0 {
  222. errMsg := ""
  223. if err != nil {
  224. errMsg = err.Error()
  225. }
  226. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  227. }
  228. return err
  229. }