up.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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/eiannone/keyboard"
  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 := 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. }), "up", s.events)
  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. // if we get a second signal during shutdown, we kill the services
  56. // immediately, so the channel needs to have sufficient capacity or
  57. // we might miss a signal while setting up the second channel read
  58. // (this is also why signal.Notify is used vs signal.NotifyContext)
  59. signalChan := make(chan os.Signal, 2)
  60. signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
  61. defer signal.Stop(signalChan)
  62. var isTerminated atomic.Bool
  63. var (
  64. logConsumer = options.Start.Attach
  65. navigationMenu *formatter.LogKeyboard
  66. kEvents <-chan keyboard.KeyEvent
  67. )
  68. if options.Start.NavigationMenu {
  69. kEvents, err = keyboard.GetKeys(100)
  70. if err != nil {
  71. logrus.Warnf("could not start menu, an error occurred while starting: %v", err)
  72. options.Start.NavigationMenu = false
  73. } else {
  74. defer keyboard.Close() //nolint:errcheck
  75. isDockerDesktopActive, err := s.isDesktopIntegrationActive(ctx)
  76. if err != nil {
  77. return err
  78. }
  79. tracing.KeyboardMetrics(ctx, options.Start.NavigationMenu, isDockerDesktopActive)
  80. navigationMenu = formatter.NewKeyboardManager(isDockerDesktopActive, signalChan)
  81. logConsumer = navigationMenu.Decorate(logConsumer)
  82. }
  83. }
  84. watcher, err := NewWatcher(project, options, s.watch, logConsumer)
  85. if err != nil && options.Start.Watch {
  86. return err
  87. }
  88. if navigationMenu != nil && watcher != nil {
  89. navigationMenu.EnableWatch(options.Start.Watch, watcher)
  90. }
  91. printer := newLogPrinter(logConsumer)
  92. // global context to handle canceling goroutines
  93. globalCtx, cancel := context.WithCancel(ctx)
  94. defer cancel()
  95. if navigationMenu != nil {
  96. navigationMenu.EnableDetach(cancel)
  97. }
  98. var (
  99. eg errgroup.Group
  100. mu sync.Mutex
  101. errs []error
  102. )
  103. appendErr := func(err error) {
  104. if err != nil {
  105. mu.Lock()
  106. errs = append(errs, err)
  107. mu.Unlock()
  108. }
  109. }
  110. eg.Go(func() error {
  111. first := true
  112. gracefulTeardown := func() {
  113. first = false
  114. s.events.On(newEvent(api.ResourceCompose, api.Working, api.StatusStopping, "Gracefully Stopping... press Ctrl+C again to force"))
  115. eg.Go(func() error {
  116. err = s.stop(context.WithoutCancel(globalCtx), project.Name, api.StopOptions{
  117. Services: options.Create.Services,
  118. Project: project,
  119. }, printer.HandleEvent)
  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) || errors.Is(err, api.ErrNoResources) {
  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. s.events.On(newEvent(api.ResourceCompose, api.Working, api.StatusStopping, "Aborting on container exit..."))
  189. eg.Go(func() error {
  190. err = s.stop(context.WithoutCancel(globalCtx), project.Name, api.StopOptions{
  191. Services: options.Create.Services,
  192. Project: project,
  193. }, printer.HandleEvent)
  194. appendErr(err)
  195. return nil
  196. })
  197. }
  198. })
  199. }
  200. if options.Start.ExitCodeFrom != "" {
  201. once := true
  202. // capture exit code from first container to exit with selected service
  203. monitor.withListener(func(event api.ContainerEvent) {
  204. if once && event.Type == api.ContainerEventExited && event.Service == options.Start.ExitCodeFrom {
  205. exitCode = event.ExitCode
  206. once = false
  207. }
  208. })
  209. }
  210. containers, err := s.attach(globalCtx, project, printer.HandleEvent, options.Start.AttachTo)
  211. if err != nil {
  212. cancel()
  213. _ = eg.Wait()
  214. return err
  215. }
  216. attached := make([]string, len(containers))
  217. for i, ctr := range containers {
  218. attached[i] = ctr.ID
  219. }
  220. monitor.withListener(func(event api.ContainerEvent) {
  221. if event.Type != api.ContainerEventStarted {
  222. return
  223. }
  224. if slices.Contains(attached, event.ID) && !event.Restarting {
  225. return
  226. }
  227. eg.Go(func() error {
  228. ctr, err := s.apiClient().ContainerInspect(globalCtx, event.ID)
  229. if err != nil {
  230. appendErr(err)
  231. return nil
  232. }
  233. err = s.doLogContainer(globalCtx, options.Start.Attach, event.Source, ctr, api.LogOptions{
  234. Follow: true,
  235. Since: ctr.State.StartedAt,
  236. })
  237. if errdefs.IsNotImplemented(err) {
  238. // container may be configured with logging_driver: none
  239. // as container already started, we might miss the very first logs. But still better than none
  240. err := s.doAttachContainer(globalCtx, event.Service, event.ID, event.Source, printer.HandleEvent)
  241. appendErr(err)
  242. return nil
  243. }
  244. appendErr(err)
  245. return nil
  246. })
  247. })
  248. eg.Go(func() error {
  249. err := monitor.Start(globalCtx)
  250. // cancel the global context to terminate signal-handler goroutines
  251. cancel()
  252. appendErr(err)
  253. return nil
  254. })
  255. // We use the parent context without cancellation as we manage sigterm to stop the stack
  256. err = s.start(context.WithoutCancel(ctx), project.Name, options.Start, printer.HandleEvent)
  257. if err != nil && !isTerminated.Load() { // Ignore error if the process is terminated
  258. cancel()
  259. _ = eg.Wait()
  260. return err
  261. }
  262. _ = eg.Wait()
  263. err = errors.Join(errs...)
  264. if exitCode != 0 {
  265. errMsg := ""
  266. if err != nil {
  267. errMsg = err.Error()
  268. }
  269. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  270. }
  271. return err
  272. }