up.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. fmt.Println("Gracefully stopping...")
  185. stopFunc() // nolint:errcheck
  186. }()
  187. consumer := formatter.NewLogConsumer(ctx, os.Stdout, !opts.noColor, !opts.noPrefix)
  188. var exitCode int
  189. eg, ctx := errgroup.WithContext(ctx)
  190. eg.Go(func() error {
  191. code, err := printer.run(ctx, opts.cascadeStop, opts.exitCodeFrom, consumer, stopFunc)
  192. exitCode = code
  193. return err
  194. })
  195. err = c.ComposeService().Start(ctx, project, compose.StartOptions{
  196. Attach: func(event compose.ContainerEvent) {
  197. queue <- event
  198. },
  199. })
  200. if err != nil {
  201. return err
  202. }
  203. err = eg.Wait()
  204. if exitCode != 0 {
  205. return cmd.ExitCodeError{ExitCode: exitCode}
  206. }
  207. return err
  208. }
  209. func applyScaleOpt(opts []string, project *types.Project) error {
  210. for _, scale := range opts {
  211. split := strings.Split(scale, "=")
  212. if len(split) != 2 {
  213. return fmt.Errorf("invalid --scale option %q. Should be SERVICE=NUM", scale)
  214. }
  215. name := split[0]
  216. replicas, err := strconv.Atoi(split[1])
  217. if err != nil {
  218. return err
  219. }
  220. err = setServiceScale(project, name, replicas)
  221. if err != nil {
  222. return err
  223. }
  224. }
  225. return nil
  226. }
  227. func setServiceScale(project *types.Project, name string, replicas int) error {
  228. for i, s := range project.Services {
  229. if s.Name == name {
  230. service, err := project.GetService(name)
  231. if err != nil {
  232. return err
  233. }
  234. if service.Deploy == nil {
  235. service.Deploy = &types.DeployConfig{}
  236. }
  237. count := uint64(replicas)
  238. service.Deploy.Replicas = &count
  239. project.Services[i] = service
  240. return nil
  241. }
  242. }
  243. return fmt.Errorf("unknown service %q", name)
  244. }
  245. func setup(ctx context.Context, opts composeOptions, services []string) (*client.Client, *types.Project, error) {
  246. c, err := client.NewWithDefaultLocalBackend(ctx)
  247. if err != nil {
  248. return nil, nil, err
  249. }
  250. project, err := opts.toProject(services)
  251. if err != nil {
  252. return nil, nil, err
  253. }
  254. if opts.DomainName != "" {
  255. // arbitrarily set the domain name on the first service ; ACI backend will expose the entire project
  256. project.Services[0].DomainName = opts.DomainName
  257. }
  258. if opts.Build {
  259. for i, service := range project.Services {
  260. service.PullPolicy = types.PullPolicyBuild
  261. project.Services[i] = service
  262. }
  263. }
  264. if opts.noBuild {
  265. for i, service := range project.Services {
  266. service.Build = nil
  267. project.Services[i] = service
  268. }
  269. }
  270. if opts.EnvFile != "" {
  271. var services types.Services
  272. for _, s := range project.Services {
  273. ef := opts.EnvFile
  274. if ef != "" {
  275. if !filepath.IsAbs(ef) {
  276. ef = filepath.Join(project.WorkingDir, opts.EnvFile)
  277. }
  278. if s.Labels == nil {
  279. s.Labels = make(map[string]string)
  280. }
  281. s.Labels[compose.EnvironmentFileLabel] = ef
  282. services = append(services, s)
  283. }
  284. }
  285. project.Services = services
  286. }
  287. return c, project, nil
  288. }
  289. type printer struct {
  290. queue chan compose.ContainerEvent
  291. }
  292. func (p printer) run(ctx context.Context, cascadeStop bool, exitCodeFrom string, consumer compose.LogConsumer, stopFn func() error) (int, error) { //nolint:unparam
  293. var aborting bool
  294. var count int
  295. for {
  296. event := <-p.queue
  297. switch event.Type {
  298. case compose.ContainerEventAttach:
  299. consumer.Register(event.Name, event.Source)
  300. count++
  301. case compose.ContainerEventExit:
  302. if !aborting {
  303. consumer.Status(event.Name, event.Source, fmt.Sprintf("exited with code %d", event.ExitCode))
  304. }
  305. if cascadeStop {
  306. if !aborting {
  307. aborting = true
  308. fmt.Println("Aborting on container exit...")
  309. err := stopFn()
  310. if err != nil {
  311. return 0, err
  312. }
  313. }
  314. if exitCodeFrom == "" || exitCodeFrom == event.Service {
  315. logrus.Error(event.ExitCode)
  316. return event.ExitCode, nil
  317. }
  318. }
  319. count--
  320. if count == 0 {
  321. // Last container terminated, done
  322. return 0, nil
  323. }
  324. case compose.ContainerEventLog:
  325. if !aborting {
  326. consumer.Log(event.Name, event.Service, event.Source, event.Line)
  327. }
  328. }
  329. }
  330. }