up.go 8.3 KB

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