up.go 12 KB

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