up.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. "fmt"
  17. "os"
  18. "os/signal"
  19. "syscall"
  20. "github.com/docker/compose-cli/pkg/api"
  21. "github.com/docker/compose-cli/pkg/progress"
  22. "github.com/compose-spec/compose-go/types"
  23. "github.com/docker/cli/cli"
  24. "golang.org/x/sync/errgroup"
  25. )
  26. func (s *composeService) Up(ctx context.Context, project *types.Project, options api.UpOptions) error {
  27. err := progress.Run(ctx, func(ctx context.Context) error {
  28. err := s.create(ctx, project, options.Create)
  29. if err != nil {
  30. return err
  31. }
  32. return s.start(ctx, project, options.Start, nil)
  33. })
  34. if err != nil {
  35. return err
  36. }
  37. if options.Start.Attach == nil {
  38. return err
  39. }
  40. printer := newLogPrinter(options.Start.Attach)
  41. signalChan := make(chan os.Signal, 1)
  42. signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
  43. stopFunc := func() error {
  44. ctx := context.Background()
  45. return progress.Run(ctx, func(ctx context.Context) error {
  46. go func() {
  47. <-signalChan
  48. s.Kill(ctx, project, api.KillOptions{}) // nolint:errcheck
  49. }()
  50. return s.Stop(ctx, project, api.StopOptions{})
  51. })
  52. }
  53. go func() {
  54. <-signalChan
  55. printer.Cancel()
  56. fmt.Println("Gracefully stopping... (press Ctrl+C again to force)")
  57. stopFunc() // nolint:errcheck
  58. }()
  59. var exitCode int
  60. eg, ctx := errgroup.WithContext(ctx)
  61. eg.Go(func() error {
  62. code, err := printer.Run(options.Start.CascadeStop, options.Start.ExitCodeFrom, stopFunc)
  63. exitCode = code
  64. return err
  65. })
  66. err = s.start(ctx, project, options.Start, printer.HandleEvent)
  67. if err != nil {
  68. return err
  69. }
  70. err = eg.Wait()
  71. if exitCode != 0 {
  72. errMsg := ""
  73. if err != nil {
  74. errMsg = err.Error()
  75. }
  76. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  77. }
  78. return err
  79. }