up.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. // Start.AttachTo have been already curated with only the services to monitor
  153. monitor.withServices(options.Start.AttachTo)
  154. }
  155. monitor.withListener(printer.HandleEvent)
  156. var exitCode int
  157. if options.Start.OnExit != api.CascadeIgnore {
  158. once := true
  159. // detect first container to exit to trigger application shutdown
  160. monitor.withListener(func(event api.ContainerEvent) {
  161. if once && event.Type == api.ContainerEventExited {
  162. if options.Start.OnExit == api.CascadeFail && event.ExitCode == 0 {
  163. return
  164. }
  165. once = false
  166. exitCode = event.ExitCode
  167. _, _ = fmt.Fprintln(s.stdinfo(), progress.ErrorColor("Aborting on container exit..."))
  168. eg.Go(func() error {
  169. return progress.RunWithLog(context.WithoutCancel(ctx), func(ctx context.Context) error {
  170. return s.stop(ctx, project.Name, api.StopOptions{
  171. Services: options.Create.Services,
  172. Project: project,
  173. }, printer.HandleEvent)
  174. }, s.stdinfo(), logConsumer)
  175. })
  176. }
  177. })
  178. }
  179. if options.Start.ExitCodeFrom != "" {
  180. once := true
  181. // capture exit code from first container to exit with selected service
  182. monitor.withListener(func(event api.ContainerEvent) {
  183. if once && event.Type == api.ContainerEventExited && event.Service == options.Start.ExitCodeFrom {
  184. exitCode = event.ExitCode
  185. once = false
  186. }
  187. })
  188. }
  189. // use an independent context tied to the errgroup for background attach operations
  190. // the primary context is still used for other operations
  191. // this means that once any attach operation fails, all other attaches are cancelled,
  192. // but an attach failing won't interfere with the rest of the start
  193. _, attachCtx := errgroup.WithContext(ctx)
  194. containers, err := s.attach(attachCtx, project, printer.HandleEvent, options.Start.AttachTo)
  195. if err != nil {
  196. return err
  197. }
  198. attached := make([]string, len(containers))
  199. for i, ctr := range containers {
  200. attached[i] = ctr.ID
  201. }
  202. monitor.withListener(func(event api.ContainerEvent) {
  203. if event.Type != api.ContainerEventStarted {
  204. return
  205. }
  206. if slices.Contains(attached, event.ID) {
  207. return
  208. }
  209. eg.Go(func() error {
  210. ctr, err := s.apiClient().ContainerInspect(ctx, event.ID)
  211. if err != nil {
  212. return err
  213. }
  214. err = s.doLogContainer(ctx, options.Start.Attach, event.Source, ctr, api.LogOptions{
  215. Follow: true,
  216. Since: ctr.State.StartedAt,
  217. })
  218. if errdefs.IsNotImplemented(err) {
  219. // container may be configured with logging_driver: none
  220. // as container already started, we might miss the very first logs. But still better than none
  221. return s.doAttachContainer(ctx, event.Service, event.ID, event.Source, printer.HandleEvent)
  222. }
  223. return err
  224. })
  225. })
  226. eg.Go(func() error {
  227. err := monitor.Start(context.Background())
  228. // Signal for the signal-handler goroutines to stop
  229. close(doneCh)
  230. return err
  231. })
  232. // We use the parent context without cancellation as we manage sigterm to stop the stack
  233. err = s.start(context.WithoutCancel(ctx), project.Name, options.Start, printer.HandleEvent)
  234. if err != nil && !isTerminated.Load() { // Ignore error if the process is terminated
  235. return err
  236. }
  237. err = eg.Wait().ErrorOrNil()
  238. if exitCode != 0 {
  239. errMsg := ""
  240. if err != nil {
  241. errMsg = err.Error()
  242. }
  243. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  244. }
  245. return err
  246. }