up.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. }), s.stdinfo())
  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 := progress.RunWithLog(context.WithoutCancel(globalCtx), func(c context.Context) error {
  115. return s.stop(c, project.Name, api.StopOptions{
  116. Services: options.Create.Services,
  117. Project: project,
  118. }, printer.HandleEvent)
  119. }, s.stdinfo(), logConsumer)
  120. appendErr(err)
  121. return nil
  122. })
  123. isTerminated.Store(true)
  124. }
  125. for {
  126. select {
  127. case <-globalCtx.Done():
  128. if watcher != nil {
  129. return watcher.Stop()
  130. }
  131. return nil
  132. case <-ctx.Done():
  133. if first {
  134. gracefulTeardown()
  135. }
  136. case <-signalChan:
  137. if first {
  138. _ = keyboard.Close()
  139. gracefulTeardown()
  140. break
  141. }
  142. eg.Go(func() error {
  143. err := s.kill(context.WithoutCancel(globalCtx), project.Name, api.KillOptions{
  144. Services: options.Create.Services,
  145. Project: project,
  146. All: true,
  147. })
  148. // Ignore errors indicating that some of the containers were already stopped or removed.
  149. if errdefs.IsNotFound(err) || errdefs.IsConflict(err) {
  150. return nil
  151. }
  152. appendErr(err)
  153. return nil
  154. })
  155. return nil
  156. case event := <-kEvents:
  157. navigationMenu.HandleKeyEvents(globalCtx, event, project, options)
  158. }
  159. }
  160. })
  161. if options.Start.Watch && watcher != nil {
  162. if err := watcher.Start(globalCtx); err != nil {
  163. // cancel the global context to terminate background goroutines
  164. cancel()
  165. _ = eg.Wait()
  166. return err
  167. }
  168. }
  169. monitor := newMonitor(s.apiClient(), project.Name)
  170. if len(options.Start.Services) > 0 {
  171. monitor.withServices(options.Start.Services)
  172. } else {
  173. // Start.AttachTo have been already curated with only the services to monitor
  174. monitor.withServices(options.Start.AttachTo)
  175. }
  176. monitor.withListener(printer.HandleEvent)
  177. var exitCode int
  178. if options.Start.OnExit != api.CascadeIgnore {
  179. once := true
  180. // detect first container to exit to trigger application shutdown
  181. monitor.withListener(func(event api.ContainerEvent) {
  182. if once && event.Type == api.ContainerEventExited {
  183. if options.Start.OnExit == api.CascadeFail && event.ExitCode == 0 {
  184. return
  185. }
  186. once = false
  187. exitCode = event.ExitCode
  188. _, _ = fmt.Fprintln(s.stdinfo(), progress.ErrorColor("Aborting on container exit..."))
  189. eg.Go(func() error {
  190. err := progress.RunWithLog(context.WithoutCancel(globalCtx), func(c context.Context) error {
  191. return s.stop(c, project.Name, api.StopOptions{
  192. Services: options.Create.Services,
  193. Project: project,
  194. }, printer.HandleEvent)
  195. }, s.stdinfo(), logConsumer)
  196. appendErr(err)
  197. return nil
  198. })
  199. }
  200. })
  201. }
  202. if options.Start.ExitCodeFrom != "" {
  203. once := true
  204. // capture exit code from first container to exit with selected service
  205. monitor.withListener(func(event api.ContainerEvent) {
  206. if once && event.Type == api.ContainerEventExited && event.Service == options.Start.ExitCodeFrom {
  207. exitCode = event.ExitCode
  208. once = false
  209. }
  210. })
  211. }
  212. containers, err := s.attach(globalCtx, project, printer.HandleEvent, options.Start.AttachTo)
  213. if err != nil {
  214. cancel()
  215. _ = eg.Wait()
  216. return err
  217. }
  218. attached := make([]string, len(containers))
  219. for i, ctr := range containers {
  220. attached[i] = ctr.ID
  221. }
  222. monitor.withListener(func(event api.ContainerEvent) {
  223. if event.Type != api.ContainerEventStarted {
  224. return
  225. }
  226. if slices.Contains(attached, event.ID) && !event.Restarting {
  227. return
  228. }
  229. eg.Go(func() error {
  230. ctr, err := s.apiClient().ContainerInspect(globalCtx, event.ID)
  231. if err != nil {
  232. appendErr(err)
  233. return nil
  234. }
  235. err = s.doLogContainer(globalCtx, options.Start.Attach, event.Source, ctr, api.LogOptions{
  236. Follow: true,
  237. Since: ctr.State.StartedAt,
  238. })
  239. if errdefs.IsNotImplemented(err) {
  240. // container may be configured with logging_driver: none
  241. // as container already started, we might miss the very first logs. But still better than none
  242. err := s.doAttachContainer(globalCtx, event.Service, event.ID, event.Source, printer.HandleEvent)
  243. appendErr(err)
  244. return nil
  245. }
  246. appendErr(err)
  247. return nil
  248. })
  249. })
  250. eg.Go(func() error {
  251. err := monitor.Start(globalCtx)
  252. // cancel the global context to terminate signal-handler goroutines
  253. cancel()
  254. appendErr(err)
  255. return nil
  256. })
  257. // We use the parent context without cancellation as we manage sigterm to stop the stack
  258. err = s.start(context.WithoutCancel(ctx), project.Name, options.Start, printer.HandleEvent)
  259. if err != nil && !isTerminated.Load() { // Ignore error if the process is terminated
  260. cancel()
  261. _ = eg.Wait()
  262. return err
  263. }
  264. _ = eg.Wait()
  265. err = errors.Join(errs...)
  266. if exitCode != 0 {
  267. errMsg := ""
  268. if err != nil {
  269. errMsg = err.Error()
  270. }
  271. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  272. }
  273. return err
  274. }