up.go 9.4 KB

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