1
0

up.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. "errors"
  17. "fmt"
  18. "os"
  19. "os/signal"
  20. "slices"
  21. "sync"
  22. "sync/atomic"
  23. "syscall"
  24. "github.com/compose-spec/compose-go/v2/types"
  25. "github.com/containerd/errdefs"
  26. "github.com/docker/cli/cli"
  27. "github.com/docker/compose/v2/cmd/formatter"
  28. "github.com/docker/compose/v2/internal/tracing"
  29. "github.com/docker/compose/v2/pkg/api"
  30. "github.com/docker/compose/v2/pkg/progress"
  31. "github.com/eiannone/keyboard"
  32. "github.com/sirupsen/logrus"
  33. "golang.org/x/sync/errgroup"
  34. )
  35. func (s *composeService) Up(ctx context.Context, project *types.Project, options api.UpOptions) error { //nolint:gocyclo
  36. err := progress.Run(ctx, tracing.SpanWrapFunc("project/up", tracing.ProjectOptions(ctx, project), func(ctx context.Context) error {
  37. err := s.create(ctx, project, options.Create)
  38. if err != nil {
  39. return err
  40. }
  41. if options.Start.Attach == nil {
  42. return s.start(ctx, project.Name, options.Start, nil)
  43. }
  44. return nil
  45. }), "up", s.events)
  46. if err != nil {
  47. return err
  48. }
  49. if options.Start.Attach == nil {
  50. return err
  51. }
  52. if s.dryRun {
  53. _, _ = fmt.Fprintln(s.stdout(), "end of 'compose up' output, interactive run is not supported in dry-run mode")
  54. return err
  55. }
  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. signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
  62. defer signal.Stop(signalChan)
  63. var isTerminated atomic.Bool
  64. var (
  65. logConsumer = options.Start.Attach
  66. navigationMenu *formatter.LogKeyboard
  67. kEvents <-chan keyboard.KeyEvent
  68. )
  69. if options.Start.NavigationMenu {
  70. kEvents, err = keyboard.GetKeys(100)
  71. if err != nil {
  72. logrus.Warnf("could not start menu, an error occurred while starting: %v", err)
  73. options.Start.NavigationMenu = false
  74. } else {
  75. defer keyboard.Close() //nolint:errcheck
  76. isDockerDesktopActive, err := s.isDesktopIntegrationActive(ctx)
  77. if err != nil {
  78. return err
  79. }
  80. tracing.KeyboardMetrics(ctx, options.Start.NavigationMenu, isDockerDesktopActive)
  81. navigationMenu = formatter.NewKeyboardManager(isDockerDesktopActive, signalChan)
  82. logConsumer = navigationMenu.Decorate(logConsumer)
  83. }
  84. }
  85. watcher, err := NewWatcher(project, options, s.watch, logConsumer)
  86. if err != nil && options.Start.Watch {
  87. return err
  88. }
  89. if navigationMenu != nil && watcher != nil {
  90. navigationMenu.EnableWatch(options.Start.Watch, watcher)
  91. }
  92. printer := newLogPrinter(logConsumer)
  93. // global context to handle canceling goroutines
  94. globalCtx, cancel := context.WithCancel(ctx)
  95. defer cancel()
  96. var (
  97. eg errgroup.Group
  98. mu sync.Mutex
  99. errs []error
  100. )
  101. appendErr := func(err error) {
  102. if err != nil {
  103. mu.Lock()
  104. errs = append(errs, err)
  105. mu.Unlock()
  106. }
  107. }
  108. eg.Go(func() error {
  109. first := true
  110. gracefulTeardown := func() {
  111. first = false
  112. fmt.Println("Gracefully Stopping... press Ctrl+C again to force")
  113. eg.Go(func() error {
  114. err = s.stop(context.WithoutCancel(globalCtx), project.Name, api.StopOptions{
  115. Services: options.Create.Services,
  116. Project: project,
  117. }, printer.HandleEvent)
  118. appendErr(err)
  119. return nil
  120. })
  121. isTerminated.Store(true)
  122. }
  123. for {
  124. select {
  125. case <-globalCtx.Done():
  126. if watcher != nil {
  127. return watcher.Stop()
  128. }
  129. return nil
  130. case <-ctx.Done():
  131. if first {
  132. gracefulTeardown()
  133. }
  134. case <-signalChan:
  135. if first {
  136. _ = keyboard.Close()
  137. gracefulTeardown()
  138. break
  139. }
  140. eg.Go(func() error {
  141. err := s.kill(context.WithoutCancel(globalCtx), project.Name, api.KillOptions{
  142. Services: options.Create.Services,
  143. Project: project,
  144. All: true,
  145. })
  146. // Ignore errors indicating that some of the containers were already stopped or removed.
  147. if errdefs.IsNotFound(err) || errdefs.IsConflict(err) {
  148. return nil
  149. }
  150. appendErr(err)
  151. return nil
  152. })
  153. return nil
  154. case event := <-kEvents:
  155. navigationMenu.HandleKeyEvents(globalCtx, event, project, options)
  156. }
  157. }
  158. })
  159. if options.Start.Watch && watcher != nil {
  160. if err := watcher.Start(globalCtx); err != nil {
  161. // cancel the global context to terminate background goroutines
  162. cancel()
  163. _ = eg.Wait()
  164. return err
  165. }
  166. }
  167. monitor := newMonitor(s.apiClient(), project.Name)
  168. if len(options.Start.Services) > 0 {
  169. monitor.withServices(options.Start.Services)
  170. } else {
  171. // Start.AttachTo have been already curated with only the services to monitor
  172. monitor.withServices(options.Start.AttachTo)
  173. }
  174. monitor.withListener(printer.HandleEvent)
  175. var exitCode int
  176. if options.Start.OnExit != api.CascadeIgnore {
  177. once := true
  178. // detect first container to exit to trigger application shutdown
  179. monitor.withListener(func(event api.ContainerEvent) {
  180. if once && event.Type == api.ContainerEventExited {
  181. if options.Start.OnExit == api.CascadeFail && event.ExitCode == 0 {
  182. return
  183. }
  184. once = false
  185. exitCode = event.ExitCode
  186. _, _ = fmt.Fprintln(s.stdinfo(), progress.ErrorColor("Aborting on container exit..."))
  187. eg.Go(func() error {
  188. err = s.stop(context.WithoutCancel(globalCtx), project.Name, api.StopOptions{
  189. Services: options.Create.Services,
  190. Project: project,
  191. }, printer.HandleEvent)
  192. appendErr(err)
  193. return nil
  194. })
  195. }
  196. })
  197. }
  198. if options.Start.ExitCodeFrom != "" {
  199. once := true
  200. // capture exit code from first container to exit with selected service
  201. monitor.withListener(func(event api.ContainerEvent) {
  202. if once && event.Type == api.ContainerEventExited && event.Service == options.Start.ExitCodeFrom {
  203. exitCode = event.ExitCode
  204. once = false
  205. }
  206. })
  207. }
  208. containers, err := s.attach(globalCtx, project, printer.HandleEvent, options.Start.AttachTo)
  209. if err != nil {
  210. cancel()
  211. _ = eg.Wait()
  212. return err
  213. }
  214. attached := make([]string, len(containers))
  215. for i, ctr := range containers {
  216. attached[i] = ctr.ID
  217. }
  218. monitor.withListener(func(event api.ContainerEvent) {
  219. if event.Type != api.ContainerEventStarted {
  220. return
  221. }
  222. if slices.Contains(attached, event.ID) && !event.Restarting {
  223. return
  224. }
  225. eg.Go(func() error {
  226. ctr, err := s.apiClient().ContainerInspect(globalCtx, event.ID)
  227. if err != nil {
  228. appendErr(err)
  229. return nil
  230. }
  231. err = s.doLogContainer(globalCtx, options.Start.Attach, event.Source, ctr, api.LogOptions{
  232. Follow: true,
  233. Since: ctr.State.StartedAt,
  234. })
  235. if errdefs.IsNotImplemented(err) {
  236. // container may be configured with logging_driver: none
  237. // as container already started, we might miss the very first logs. But still better than none
  238. err := s.doAttachContainer(globalCtx, event.Service, event.ID, event.Source, printer.HandleEvent)
  239. appendErr(err)
  240. return nil
  241. }
  242. appendErr(err)
  243. return nil
  244. })
  245. })
  246. eg.Go(func() error {
  247. err := monitor.Start(globalCtx)
  248. // cancel the global context to terminate signal-handler goroutines
  249. cancel()
  250. appendErr(err)
  251. return nil
  252. })
  253. // We use the parent context without cancellation as we manage sigterm to stop the stack
  254. err = s.start(context.WithoutCancel(ctx), project.Name, options.Start, printer.HandleEvent)
  255. if err != nil && !isTerminated.Load() { // Ignore error if the process is terminated
  256. cancel()
  257. _ = eg.Wait()
  258. return err
  259. }
  260. _ = eg.Wait()
  261. err = errors.Join(errs...)
  262. if exitCode != 0 {
  263. errMsg := ""
  264. if err != nil {
  265. errMsg = err.Error()
  266. }
  267. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  268. }
  269. return err
  270. }