up.go 12 KB

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