up.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. "slices"
  20. "sync/atomic"
  21. "syscall"
  22. "github.com/compose-spec/compose-go/v2/types"
  23. "github.com/containerd/errdefs"
  24. "github.com/docker/cli/cli"
  25. "github.com/docker/compose/v2/cmd/formatter"
  26. "github.com/docker/compose/v2/internal/tracing"
  27. "github.com/docker/compose/v2/pkg/api"
  28. "github.com/docker/compose/v2/pkg/progress"
  29. "github.com/eiannone/keyboard"
  30. "github.com/hashicorp/go-multierror"
  31. "github.com/sirupsen/logrus"
  32. "golang.org/x/sync/errgroup"
  33. )
  34. func (s *composeService) Up(ctx context.Context, project *types.Project, options api.UpOptions) error { //nolint:gocyclo
  35. err := progress.Run(ctx, tracing.SpanWrapFunc("project/up", tracing.ProjectOptions(ctx, project), func(ctx context.Context) error {
  36. err := s.create(ctx, project, options.Create)
  37. if err != nil {
  38. return err
  39. }
  40. if options.Start.Attach == nil {
  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. defer close(signalChan)
  62. signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
  63. defer signal.Stop(signalChan)
  64. var isTerminated atomic.Bool
  65. var (
  66. logConsumer = options.Start.Attach
  67. navigationMenu *formatter.LogKeyboard
  68. kEvents <-chan keyboard.KeyEvent
  69. )
  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)
  79. navigationMenu = formatter.NewKeyboardManager(isDockerDesktopActive, signalChan)
  80. logConsumer = navigationMenu.Decorate(logConsumer)
  81. }
  82. }
  83. watcher, err := NewWatcher(project, options, s.watch, logConsumer)
  84. if err != nil && options.Start.Watch {
  85. return err
  86. }
  87. if navigationMenu != nil && watcher != nil {
  88. navigationMenu.EnableWatch(options.Start.Watch, watcher)
  89. }
  90. printer := newLogPrinter(logConsumer)
  91. doneCh := make(chan bool)
  92. eg.Go(func() error {
  93. first := true
  94. gracefulTeardown := func() {
  95. first = false
  96. fmt.Println("Gracefully Stopping... press Ctrl+C again to force")
  97. eg.Go(func() error {
  98. return progress.RunWithLog(context.WithoutCancel(ctx), func(ctx context.Context) error {
  99. return s.stop(ctx, project.Name, api.StopOptions{
  100. Services: options.Create.Services,
  101. Project: project,
  102. }, printer.HandleEvent)
  103. }, s.stdinfo(), logConsumer)
  104. })
  105. isTerminated.Store(true)
  106. }
  107. for {
  108. select {
  109. case <-doneCh:
  110. if watcher != nil {
  111. return watcher.Stop()
  112. }
  113. return nil
  114. case <-ctx.Done():
  115. if first {
  116. gracefulTeardown()
  117. }
  118. case <-signalChan:
  119. if first {
  120. keyboard.Close() //nolint:errcheck
  121. gracefulTeardown()
  122. break
  123. }
  124. eg.Go(func() error {
  125. err := s.kill(context.WithoutCancel(ctx), project.Name, api.KillOptions{
  126. Services: options.Create.Services,
  127. Project: project,
  128. All: true,
  129. })
  130. // Ignore errors indicating that some of the containers were already stopped or removed.
  131. if errdefs.IsNotFound(err) || errdefs.IsConflict(err) {
  132. return nil
  133. }
  134. return err
  135. })
  136. return nil
  137. case event := <-kEvents:
  138. navigationMenu.HandleKeyEvents(ctx, event, project, options)
  139. }
  140. }
  141. })
  142. if options.Start.Watch && watcher != nil {
  143. err = watcher.Start(ctx)
  144. if err != nil {
  145. return err
  146. }
  147. }
  148. monitor := newMonitor(s.apiClient(), project.Name)
  149. if len(options.Start.Services) > 0 {
  150. monitor.withServices(options.Start.Services)
  151. } else {
  152. monitor.withServices(project.ServiceNames())
  153. }
  154. monitor.withListener(printer.HandleEvent)
  155. var exitCode int
  156. if options.Start.OnExit != api.CascadeIgnore {
  157. once := true
  158. // detect first container to exit to trigger application shutdown
  159. monitor.withListener(func(event api.ContainerEvent) {
  160. if once && event.Type == api.ContainerEventExited {
  161. if options.Start.OnExit == api.CascadeFail && event.ExitCode == 0 {
  162. return
  163. }
  164. once = false
  165. exitCode = event.ExitCode
  166. _, _ = fmt.Fprintln(s.stdinfo(), progress.ErrorColor("Aborting on container exit..."))
  167. eg.Go(func() error {
  168. return progress.RunWithLog(context.WithoutCancel(ctx), func(ctx context.Context) error {
  169. return s.stop(ctx, project.Name, api.StopOptions{
  170. Services: options.Create.Services,
  171. Project: project,
  172. }, printer.HandleEvent)
  173. }, s.stdinfo(), logConsumer)
  174. })
  175. }
  176. })
  177. }
  178. if options.Start.ExitCodeFrom != "" {
  179. once := true
  180. // capture exit code from first container to exit with selected service
  181. monitor.withListener(func(event api.ContainerEvent) {
  182. if once && event.Type == api.ContainerEventExited && event.Service == options.Start.ExitCodeFrom {
  183. exitCode = event.ExitCode
  184. once = false
  185. }
  186. })
  187. }
  188. // use an independent context tied to the errgroup for background attach operations
  189. // the primary context is still used for other operations
  190. // this means that once any attach operation fails, all other attaches are cancelled,
  191. // but an attach failing won't interfere with the rest of the start
  192. _, attachCtx := errgroup.WithContext(ctx)
  193. containers, err := s.attach(attachCtx, project, printer.HandleEvent, options.Start.AttachTo)
  194. if err != nil {
  195. return err
  196. }
  197. attached := make([]string, len(containers))
  198. for i, ctr := range containers {
  199. attached[i] = ctr.ID
  200. }
  201. monitor.withListener(func(event api.ContainerEvent) {
  202. if event.Type != api.ContainerEventStarted {
  203. return
  204. }
  205. if slices.Contains(attached, event.ID) {
  206. return
  207. }
  208. eg.Go(func() error {
  209. ctr, err := s.apiClient().ContainerInspect(ctx, event.ID)
  210. if err != nil {
  211. return err
  212. }
  213. err = s.doLogContainer(ctx, options.Start.Attach, event.Source, ctr, api.LogOptions{
  214. Follow: true,
  215. Since: ctr.State.StartedAt,
  216. })
  217. if errdefs.IsNotImplemented(err) {
  218. // container may be configured with logging_driver: none
  219. // as container already started, we might miss the very first logs. But still better than none
  220. return s.doAttachContainer(ctx, event.Service, event.ID, event.Source, printer.HandleEvent)
  221. }
  222. return err
  223. })
  224. })
  225. eg.Go(func() error {
  226. err := monitor.Start(context.Background())
  227. // Signal for the signal-handler goroutines to stop
  228. close(doneCh)
  229. return err
  230. })
  231. // We use the parent context without cancellation as we manage sigterm to stop the stack
  232. err = s.start(context.WithoutCancel(ctx), project.Name, options.Start, printer.HandleEvent)
  233. if err != nil && !isTerminated.Load() { // Ignore error if the process is terminated
  234. return err
  235. }
  236. err = eg.Wait().ErrorOrNil()
  237. if exitCode != 0 {
  238. errMsg := ""
  239. if err != nil {
  240. errMsg = err.Error()
  241. }
  242. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  243. }
  244. return err
  245. }