up.go 8.9 KB

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