up.go 11 KB

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