up.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. stopFunc := func() error {
  248. ctx := context.Background()
  249. _, err := progress.Run(ctx, func(ctx context.Context) (string, error) {
  250. return "", c.ComposeService().Stop(ctx, project, compose.StopOptions{})
  251. })
  252. return err
  253. }
  254. signalChan := make(chan os.Signal, 1)
  255. signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
  256. go func() {
  257. <-signalChan
  258. queue <- compose.ContainerEvent{
  259. Type: compose.UserCancel,
  260. }
  261. fmt.Println("Gracefully stopping...")
  262. stopFunc() // nolint:errcheck
  263. }()
  264. consumer := formatter.NewLogConsumer(ctx, os.Stdout, !opts.noColor, !opts.noPrefix)
  265. var exitCode int
  266. eg, ctx := errgroup.WithContext(ctx)
  267. eg.Go(func() error {
  268. code, err := printer.run(ctx, opts.cascadeStop, opts.exitCodeFrom, consumer, stopFunc)
  269. exitCode = code
  270. return err
  271. })
  272. err = c.ComposeService().Start(ctx, project, compose.StartOptions{
  273. Attach: func(event compose.ContainerEvent) {
  274. queue <- event
  275. },
  276. Services: services,
  277. })
  278. if err != nil {
  279. return err
  280. }
  281. err = eg.Wait()
  282. if exitCode != 0 {
  283. return cmd.ExitCodeError{ExitCode: exitCode}
  284. }
  285. return err
  286. }
  287. func setServiceScale(project *types.Project, name string, replicas int) error {
  288. for i, s := range project.Services {
  289. if s.Name == name {
  290. service, err := project.GetService(name)
  291. if err != nil {
  292. return err
  293. }
  294. if service.Deploy == nil {
  295. service.Deploy = &types.DeployConfig{}
  296. }
  297. count := uint64(replicas)
  298. service.Deploy.Replicas = &count
  299. project.Services[i] = service
  300. return nil
  301. }
  302. }
  303. return fmt.Errorf("unknown service %q", name)
  304. }
  305. func setup(ctx context.Context, opts composeOptions, services []string) (*client.Client, *types.Project, error) {
  306. c, err := client.New(ctx)
  307. if err != nil {
  308. return nil, nil, err
  309. }
  310. project, err := opts.toProject(services)
  311. if err != nil {
  312. return nil, nil, err
  313. }
  314. if opts.DomainName != "" {
  315. // arbitrarily set the domain name on the first service ; ACI backend will expose the entire project
  316. project.Services[0].DomainName = opts.DomainName
  317. }
  318. if opts.Build {
  319. for i, service := range project.Services {
  320. service.PullPolicy = types.PullPolicyBuild
  321. project.Services[i] = service
  322. }
  323. }
  324. if opts.noBuild {
  325. for i, service := range project.Services {
  326. service.Build = nil
  327. project.Services[i] = service
  328. }
  329. }
  330. if opts.EnvFile != "" {
  331. var services types.Services
  332. for _, s := range project.Services {
  333. ef := opts.EnvFile
  334. if ef != "" {
  335. if !filepath.IsAbs(ef) {
  336. ef = filepath.Join(project.WorkingDir, opts.EnvFile)
  337. }
  338. if s.Labels == nil {
  339. s.Labels = make(map[string]string)
  340. }
  341. s.Labels[compose.EnvironmentFileLabel] = ef
  342. services = append(services, s)
  343. }
  344. }
  345. project.Services = services
  346. }
  347. return c, project, nil
  348. }
  349. type printer struct {
  350. queue chan compose.ContainerEvent
  351. }
  352. func (p printer) run(ctx context.Context, cascadeStop bool, exitCodeFrom string, consumer compose.LogConsumer, stopFn func() error) (int, error) { //nolint:unparam
  353. var aborting bool
  354. var count int
  355. for {
  356. event := <-p.queue
  357. switch event.Type {
  358. case compose.UserCancel:
  359. aborting = true
  360. case compose.ContainerEventAttach:
  361. consumer.Register(event.Container)
  362. count++
  363. case compose.ContainerEventExit:
  364. if !aborting {
  365. consumer.Status(event.Container, fmt.Sprintf("exited with code %d", event.ExitCode))
  366. }
  367. if cascadeStop {
  368. if !aborting {
  369. aborting = true
  370. fmt.Println("Aborting on container exit...")
  371. err := stopFn()
  372. if err != nil {
  373. return 0, err
  374. }
  375. }
  376. if exitCodeFrom == "" || exitCodeFrom == event.Service {
  377. logrus.Error(event.ExitCode)
  378. return event.ExitCode, nil
  379. }
  380. }
  381. count--
  382. if count == 0 {
  383. // Last container terminated, done
  384. return 0, nil
  385. }
  386. case compose.ContainerEventLog:
  387. if !aborting {
  388. consumer.Log(event.Container, event.Service, event.Line)
  389. }
  390. }
  391. }
  392. }