up.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. "path/filepath"
  20. "strconv"
  21. "strings"
  22. "syscall"
  23. "time"
  24. "github.com/compose-spec/compose-go/types"
  25. "github.com/docker/cli/cli"
  26. "github.com/spf13/cobra"
  27. "golang.org/x/sync/errgroup"
  28. "github.com/docker/compose-cli/api/compose"
  29. "github.com/docker/compose-cli/api/context/store"
  30. "github.com/docker/compose-cli/api/progress"
  31. "github.com/docker/compose-cli/cli/formatter"
  32. "github.com/docker/compose-cli/utils"
  33. )
  34. // composeOptions hold options common to `up` and `run` to run compose project
  35. type composeOptions struct {
  36. *projectOptions
  37. Build bool
  38. noBuild bool
  39. }
  40. type upOptions struct {
  41. *composeOptions
  42. Detach bool
  43. Environment []string
  44. removeOrphans bool
  45. forceRecreate bool
  46. noRecreate bool
  47. recreateDeps bool
  48. noStart bool
  49. noDeps bool
  50. cascadeStop bool
  51. exitCodeFrom string
  52. scale []string
  53. noColor bool
  54. noPrefix bool
  55. timeChanged bool
  56. timeout int
  57. noInherit bool
  58. attachDependencies bool
  59. quietPull bool
  60. }
  61. func (opts upOptions) recreateStrategy() string {
  62. if opts.noRecreate {
  63. return compose.RecreateNever
  64. }
  65. if opts.forceRecreate {
  66. return compose.RecreateForce
  67. }
  68. return compose.RecreateDiverged
  69. }
  70. func (opts upOptions) dependenciesRecreateStrategy() string {
  71. if opts.noRecreate {
  72. return compose.RecreateNever
  73. }
  74. if opts.recreateDeps {
  75. return compose.RecreateForce
  76. }
  77. return compose.RecreateDiverged
  78. }
  79. func (opts upOptions) GetTimeout() *time.Duration {
  80. if opts.timeChanged {
  81. t := time.Duration(opts.timeout) * time.Second
  82. return &t
  83. }
  84. return nil
  85. }
  86. func (opts upOptions) apply(project *types.Project, services []string) error {
  87. if opts.noDeps {
  88. enabled, err := project.GetServices(services...)
  89. if err != nil {
  90. return err
  91. }
  92. for _, s := range project.Services {
  93. if !utils.StringContains(services, s.Name) {
  94. project.DisabledServices = append(project.DisabledServices, s)
  95. }
  96. }
  97. project.Services = enabled
  98. }
  99. if opts.exitCodeFrom != "" {
  100. _, err := project.GetService(opts.exitCodeFrom)
  101. if err != nil {
  102. return err
  103. }
  104. }
  105. for _, scale := range opts.scale {
  106. split := strings.Split(scale, "=")
  107. if len(split) != 2 {
  108. return fmt.Errorf("invalid --scale option %q. Should be SERVICE=NUM", scale)
  109. }
  110. name := split[0]
  111. replicas, err := strconv.Atoi(split[1])
  112. if err != nil {
  113. return err
  114. }
  115. err = setServiceScale(project, name, replicas)
  116. if err != nil {
  117. return err
  118. }
  119. }
  120. return nil
  121. }
  122. func upCommand(p *projectOptions, contextType string, backend compose.Service) *cobra.Command {
  123. opts := upOptions{
  124. composeOptions: &composeOptions{
  125. projectOptions: p,
  126. },
  127. }
  128. upCmd := &cobra.Command{
  129. Use: "up [SERVICE...]",
  130. Short: "Create and start containers",
  131. PreRun: func(cmd *cobra.Command, args []string) {
  132. opts.timeChanged = cmd.Flags().Changed("timeout")
  133. },
  134. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  135. if opts.exitCodeFrom != "" {
  136. opts.cascadeStop = true
  137. }
  138. if opts.Build && opts.noBuild {
  139. return fmt.Errorf("--build and --no-build are incompatible")
  140. }
  141. if opts.Detach && (opts.attachDependencies || opts.cascadeStop) {
  142. return fmt.Errorf("--detach cannot be combined with --abort-on-container-exit or --attach-dependencies")
  143. }
  144. if opts.forceRecreate && opts.noRecreate {
  145. return fmt.Errorf("--force-recreate and --no-recreate are incompatible")
  146. }
  147. if opts.recreateDeps && opts.noRecreate {
  148. return fmt.Errorf("--always-recreate-deps and --no-recreate are incompatible")
  149. }
  150. return nil
  151. }),
  152. RunE: Adapt(func(ctx context.Context, args []string) error {
  153. switch contextType {
  154. case store.LocalContextType, store.DefaultContextType, store.EcsLocalSimulationContextType:
  155. return runCreateStart(ctx, backend, opts, args)
  156. default:
  157. return runUp(ctx, backend, opts, args)
  158. }
  159. }),
  160. }
  161. flags := upCmd.Flags()
  162. flags.StringArrayVarP(&opts.Environment, "environment", "e", []string{}, "Environment variables")
  163. flags.BoolVarP(&opts.Detach, "detach", "d", false, "Detached mode: Run containers in the background")
  164. flags.BoolVar(&opts.Build, "build", false, "Build images before starting containers.")
  165. flags.BoolVar(&opts.noBuild, "no-build", false, "Don't build an image, even if it's missing.")
  166. flags.BoolVar(&opts.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file.")
  167. flags.StringArrayVar(&opts.scale, "scale", []string{}, "Scale SERVICE to NUM instances. Overrides the `scale` setting in the Compose file if present.")
  168. flags.BoolVar(&opts.noColor, "no-color", false, "Produce monochrome output.")
  169. flags.BoolVar(&opts.noPrefix, "no-log-prefix", false, "Don't print prefix in logs.")
  170. switch contextType {
  171. case store.LocalContextType, store.DefaultContextType, store.EcsLocalSimulationContextType:
  172. flags.BoolVar(&opts.forceRecreate, "force-recreate", false, "Recreate containers even if their configuration and image haven't changed.")
  173. flags.BoolVar(&opts.noRecreate, "no-recreate", false, "If containers already exist, don't recreate them. Incompatible with --force-recreate.")
  174. flags.BoolVar(&opts.noStart, "no-start", false, "Don't start the services after creating them.")
  175. flags.BoolVar(&opts.cascadeStop, "abort-on-container-exit", false, "Stops all containers if any container was stopped. Incompatible with -d")
  176. flags.StringVar(&opts.exitCodeFrom, "exit-code-from", "", "Return the exit code of the selected service container. Implies --abort-on-container-exit")
  177. flags.IntVarP(&opts.timeout, "timeout", "t", 10, "Use this timeout in seconds for container shutdown when attached or when containers are already running.")
  178. flags.BoolVar(&opts.noDeps, "no-deps", false, "Don't start linked services.")
  179. flags.BoolVar(&opts.recreateDeps, "always-recreate-deps", false, "Recreate dependent containers. Incompatible with --no-recreate.")
  180. flags.BoolVarP(&opts.noInherit, "renew-anon-volumes", "V", false, "Recreate anonymous volumes instead of retrieving data from the previous containers.")
  181. flags.BoolVar(&opts.attachDependencies, "attach-dependencies", false, "Attach to dependent containers.")
  182. flags.BoolVar(&opts.quietPull, "quiet-pull", false, "Pull without printing progress information.")
  183. }
  184. return upCmd
  185. }
  186. func runUp(ctx context.Context, backend compose.Service, opts upOptions, services []string) error {
  187. project, err := setup(*opts.composeOptions, services)
  188. if err != nil {
  189. return err
  190. }
  191. err = opts.apply(project, services)
  192. if err != nil {
  193. return err
  194. }
  195. return progress.Run(ctx, func(ctx context.Context) error {
  196. return backend.Up(ctx, project, compose.UpOptions{
  197. Detach: opts.Detach,
  198. QuietPull: opts.quietPull,
  199. })
  200. })
  201. }
  202. func runCreateStart(ctx context.Context, backend compose.Service, opts upOptions, services []string) error {
  203. project, err := setup(*opts.composeOptions, services)
  204. if err != nil {
  205. return err
  206. }
  207. err = opts.apply(project, services)
  208. if err != nil {
  209. return err
  210. }
  211. if len(project.Services) == 0 {
  212. return fmt.Errorf("no service selected")
  213. }
  214. err = progress.Run(ctx, func(ctx context.Context) error {
  215. err := backend.Create(ctx, project, compose.CreateOptions{
  216. Services: services,
  217. RemoveOrphans: opts.removeOrphans,
  218. Recreate: opts.recreateStrategy(),
  219. RecreateDependencies: opts.dependenciesRecreateStrategy(),
  220. Inherit: !opts.noInherit,
  221. Timeout: opts.GetTimeout(),
  222. QuietPull: opts.quietPull,
  223. })
  224. if err != nil {
  225. return err
  226. }
  227. if opts.Detach {
  228. err = backend.Start(ctx, project, compose.StartOptions{
  229. Services: services,
  230. })
  231. }
  232. return err
  233. })
  234. if err != nil {
  235. return err
  236. }
  237. if opts.noStart {
  238. return nil
  239. }
  240. if opts.attachDependencies {
  241. services = nil
  242. }
  243. if opts.Detach {
  244. return nil
  245. }
  246. consumer := formatter.NewLogConsumer(ctx, os.Stdout, !opts.noColor, !opts.noPrefix)
  247. printer := compose.NewLogPrinter(consumer)
  248. signalChan := make(chan os.Signal, 1)
  249. signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
  250. stopFunc := func() error {
  251. ctx := context.Background()
  252. return progress.Run(ctx, func(ctx context.Context) error {
  253. go func() {
  254. <-signalChan
  255. backend.Kill(ctx, project, compose.KillOptions{}) // nolint:errcheck
  256. }()
  257. return backend.Stop(ctx, project, compose.StopOptions{})
  258. })
  259. }
  260. go func() {
  261. <-signalChan
  262. printer.Cancel()
  263. fmt.Println("Gracefully stopping... (press Ctrl+C again to force)")
  264. stopFunc() // nolint:errcheck
  265. }()
  266. var exitCode int
  267. eg, ctx := errgroup.WithContext(ctx)
  268. eg.Go(func() error {
  269. code, err := printer.Run(opts.cascadeStop, opts.exitCodeFrom, stopFunc)
  270. exitCode = code
  271. return err
  272. })
  273. err = backend.Start(ctx, project, compose.StartOptions{
  274. Attach: printer.HandleEvent,
  275. Services: services,
  276. })
  277. if err != nil {
  278. return err
  279. }
  280. err = eg.Wait()
  281. if exitCode != 0 {
  282. errMsg := ""
  283. if err != nil {
  284. errMsg = err.Error()
  285. }
  286. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  287. }
  288. return err
  289. }
  290. func setServiceScale(project *types.Project, name string, replicas int) error {
  291. for i, s := range project.Services {
  292. if s.Name == name {
  293. service, err := project.GetService(name)
  294. if err != nil {
  295. return err
  296. }
  297. service.Scale = replicas
  298. project.Services[i] = service
  299. return nil
  300. }
  301. }
  302. return fmt.Errorf("unknown service %q", name)
  303. }
  304. func setup(opts composeOptions, services []string) (*types.Project, error) {
  305. project, err := opts.toProject(services)
  306. if err != nil {
  307. return nil, err
  308. }
  309. if opts.Build {
  310. for i, service := range project.Services {
  311. service.PullPolicy = types.PullPolicyBuild
  312. project.Services[i] = service
  313. }
  314. }
  315. if opts.noBuild {
  316. for i, service := range project.Services {
  317. service.Build = nil
  318. project.Services[i] = service
  319. }
  320. }
  321. if opts.EnvFile != "" {
  322. var services types.Services
  323. for _, s := range project.Services {
  324. ef := opts.EnvFile
  325. if ef != "" {
  326. if !filepath.IsAbs(ef) {
  327. ef = filepath.Join(project.WorkingDir, opts.EnvFile)
  328. }
  329. if s.Labels == nil {
  330. s.Labels = make(map[string]string)
  331. }
  332. s.Labels[compose.EnvironmentFileLabel] = ef
  333. services = append(services, s)
  334. }
  335. }
  336. project.Services = services
  337. }
  338. return project, nil
  339. }