up.go 12 KB

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