up.go 8.2 KB

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