up.go 12 KB

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