up.go 11 KB

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