up.go 10 KB

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