up.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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/docker/compose-cli/utils"
  27. "github.com/sirupsen/logrus"
  28. "github.com/spf13/cobra"
  29. "golang.org/x/sync/errgroup"
  30. "github.com/docker/compose-cli/api/client"
  31. "github.com/docker/compose-cli/api/compose"
  32. "github.com/docker/compose-cli/api/context/store"
  33. "github.com/docker/compose-cli/api/progress"
  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. if len(project.Services) == 0 {
  214. return fmt.Errorf("no service selected")
  215. }
  216. _, err = progress.Run(ctx, func(ctx context.Context) (string, error) {
  217. err := c.ComposeService().Create(ctx, project, compose.CreateOptions{
  218. Services: services,
  219. RemoveOrphans: opts.removeOrphans,
  220. Recreate: opts.recreateStrategy(),
  221. RecreateDependencies: opts.dependenciesRecreateStrategy(),
  222. Inherit: !opts.noInherit,
  223. Timeout: opts.GetTimeout(),
  224. QuietPull: opts.quietPull,
  225. })
  226. if err != nil {
  227. return "", err
  228. }
  229. if opts.Detach {
  230. err = c.ComposeService().Start(ctx, project, compose.StartOptions{})
  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. queue := make(chan compose.ContainerEvent)
  247. printer := printer{
  248. queue: queue,
  249. }
  250. signalChan := make(chan os.Signal, 1)
  251. signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
  252. stopFunc := func() error {
  253. ctx := context.Background()
  254. _, err := progress.Run(ctx, func(ctx context.Context) (string, error) {
  255. go func() {
  256. <-signalChan
  257. c.ComposeService().Kill(ctx, project, compose.KillOptions{}) // nolint:errcheck
  258. }()
  259. return "", c.ComposeService().Stop(ctx, project, compose.StopOptions{})
  260. })
  261. return err
  262. }
  263. go func() {
  264. <-signalChan
  265. queue <- compose.ContainerEvent{
  266. Type: compose.UserCancel,
  267. }
  268. fmt.Println("Gracefully stopping... (press Ctrl+C again to force)")
  269. stopFunc() // nolint:errcheck
  270. }()
  271. consumer := formatter.NewLogConsumer(ctx, os.Stdout, !opts.noColor, !opts.noPrefix)
  272. var exitCode int
  273. eg, ctx := errgroup.WithContext(ctx)
  274. eg.Go(func() error {
  275. code, err := printer.run(opts.cascadeStop, opts.exitCodeFrom, consumer, stopFunc)
  276. exitCode = code
  277. return err
  278. })
  279. err = c.ComposeService().Start(ctx, project, compose.StartOptions{
  280. Attach: func(event compose.ContainerEvent) {
  281. queue <- event
  282. },
  283. Services: services,
  284. })
  285. if err != nil {
  286. return err
  287. }
  288. err = eg.Wait()
  289. if exitCode != 0 {
  290. errMsg := ""
  291. if err != nil {
  292. errMsg = err.Error()
  293. }
  294. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  295. }
  296. return err
  297. }
  298. func setServiceScale(project *types.Project, name string, replicas int) error {
  299. for i, s := range project.Services {
  300. if s.Name == name {
  301. service, err := project.GetService(name)
  302. if err != nil {
  303. return err
  304. }
  305. if service.Deploy == nil {
  306. service.Deploy = &types.DeployConfig{}
  307. }
  308. count := uint64(replicas)
  309. service.Deploy.Replicas = &count
  310. project.Services[i] = service
  311. return nil
  312. }
  313. }
  314. return fmt.Errorf("unknown service %q", name)
  315. }
  316. func setup(ctx context.Context, opts composeOptions, services []string) (*client.Client, *types.Project, error) {
  317. c, err := client.New(ctx)
  318. if err != nil {
  319. return nil, nil, err
  320. }
  321. project, err := opts.toProject(services)
  322. if err != nil {
  323. return nil, nil, err
  324. }
  325. if opts.DomainName != "" {
  326. // arbitrarily set the domain name on the first service ; ACI backend will expose the entire project
  327. project.Services[0].DomainName = opts.DomainName
  328. }
  329. if opts.Build {
  330. for i, service := range project.Services {
  331. service.PullPolicy = types.PullPolicyBuild
  332. project.Services[i] = service
  333. }
  334. }
  335. if opts.noBuild {
  336. for i, service := range project.Services {
  337. service.Build = nil
  338. project.Services[i] = service
  339. }
  340. }
  341. if opts.EnvFile != "" {
  342. var services types.Services
  343. for _, s := range project.Services {
  344. ef := opts.EnvFile
  345. if ef != "" {
  346. if !filepath.IsAbs(ef) {
  347. ef = filepath.Join(project.WorkingDir, opts.EnvFile)
  348. }
  349. if s.Labels == nil {
  350. s.Labels = make(map[string]string)
  351. }
  352. s.Labels[compose.EnvironmentFileLabel] = ef
  353. services = append(services, s)
  354. }
  355. }
  356. project.Services = services
  357. }
  358. return c, project, nil
  359. }
  360. type printer struct {
  361. queue chan compose.ContainerEvent
  362. }
  363. func (p printer) run(cascadeStop bool, exitCodeFrom string, consumer compose.LogConsumer, stopFn func() error) (int, error) {
  364. var aborting bool
  365. var count int
  366. for {
  367. event := <-p.queue
  368. switch event.Type {
  369. case compose.UserCancel:
  370. aborting = true
  371. case compose.ContainerEventAttach:
  372. consumer.Register(event.Container)
  373. count++
  374. case compose.ContainerEventExit:
  375. if !aborting {
  376. consumer.Status(event.Container, fmt.Sprintf("exited with code %d", event.ExitCode))
  377. }
  378. if cascadeStop {
  379. if !aborting {
  380. aborting = true
  381. fmt.Println("Aborting on container exit...")
  382. err := stopFn()
  383. if err != nil {
  384. return 0, err
  385. }
  386. }
  387. if exitCodeFrom == "" || exitCodeFrom == event.Service {
  388. logrus.Error(event.ExitCode)
  389. return event.ExitCode, nil
  390. }
  391. }
  392. count--
  393. if count == 0 {
  394. // Last container terminated, done
  395. return 0, nil
  396. }
  397. case compose.ContainerEventLog:
  398. if !aborting {
  399. consumer.Log(event.Container, event.Service, event.Line)
  400. }
  401. }
  402. }
  403. }