up.go 12 KB

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