compose.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. "errors"
  17. "fmt"
  18. "os"
  19. "os/signal"
  20. "path/filepath"
  21. "strconv"
  22. "strings"
  23. "syscall"
  24. "github.com/compose-spec/compose-go/cli"
  25. "github.com/compose-spec/compose-go/dotenv"
  26. "github.com/compose-spec/compose-go/types"
  27. composegoutils "github.com/compose-spec/compose-go/utils"
  28. "github.com/docker/buildx/util/logutil"
  29. buildx "github.com/docker/buildx/util/progress"
  30. dockercli "github.com/docker/cli/cli"
  31. "github.com/docker/cli/cli-plugins/manager"
  32. "github.com/docker/cli/cli/command"
  33. "github.com/docker/compose/v2/pkg/remote"
  34. "github.com/morikuni/aec"
  35. "github.com/sirupsen/logrus"
  36. "github.com/spf13/cobra"
  37. "github.com/spf13/pflag"
  38. "github.com/docker/compose/v2/cmd/formatter"
  39. "github.com/docker/compose/v2/pkg/api"
  40. "github.com/docker/compose/v2/pkg/compose"
  41. ui "github.com/docker/compose/v2/pkg/progress"
  42. "github.com/docker/compose/v2/pkg/utils"
  43. )
  44. const (
  45. // ComposeParallelLimit set the limit running concurrent operation on docker engine
  46. ComposeParallelLimit = "COMPOSE_PARALLEL_LIMIT"
  47. // ComposeProjectName define the project name to be used, instead of guessing from parent directory
  48. ComposeProjectName = "COMPOSE_PROJECT_NAME"
  49. // ComposeCompatibility try to mimic compose v1 as much as possible
  50. ComposeCompatibility = "COMPOSE_COMPATIBILITY"
  51. // ComposeRemoveOrphans remove “orphaned" containers, i.e. containers tagged for current project but not declared as service
  52. ComposeRemoveOrphans = "COMPOSE_REMOVE_ORPHANS"
  53. // ComposeIgnoreOrphans ignore "orphaned" containers
  54. ComposeIgnoreOrphans = "COMPOSE_IGNORE_ORPHANS"
  55. // ComposeEnvFiles defines the env files to use if --env-file isn't used
  56. ComposeEnvFiles = "COMPOSE_ENV_FILES"
  57. )
  58. // Command defines a compose CLI command as a func with args
  59. type Command func(context.Context, []string) error
  60. // CobraCommand defines a cobra command function
  61. type CobraCommand func(context.Context, *cobra.Command, []string) error
  62. // AdaptCmd adapt a CobraCommand func to cobra library
  63. func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error {
  64. return func(cmd *cobra.Command, args []string) error {
  65. ctx := cmd.Context()
  66. contextString := fmt.Sprintf("%s", ctx)
  67. if !strings.HasSuffix(contextString, ".WithCancel") { // need to handle cancel
  68. cancellableCtx, cancel := context.WithCancel(cmd.Context())
  69. ctx = cancellableCtx
  70. s := make(chan os.Signal, 1)
  71. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  72. go func() {
  73. <-s
  74. cancel()
  75. signal.Stop(s)
  76. close(s)
  77. }()
  78. }
  79. err := fn(ctx, cmd, args)
  80. var composeErr compose.Error
  81. if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  82. err = dockercli.StatusError{
  83. StatusCode: 130,
  84. Status: compose.CanceledStatus,
  85. }
  86. }
  87. if errors.As(err, &composeErr) {
  88. err = dockercli.StatusError{
  89. StatusCode: composeErr.GetMetricsFailureCategory().ExitCode,
  90. Status: err.Error(),
  91. }
  92. }
  93. return err
  94. }
  95. }
  96. // Adapt a Command func to cobra library
  97. func Adapt(fn Command) func(cmd *cobra.Command, args []string) error {
  98. return AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  99. return fn(ctx, args)
  100. })
  101. }
  102. type ProjectOptions struct {
  103. ProjectName string
  104. Profiles []string
  105. ConfigPaths []string
  106. WorkDir string
  107. ProjectDir string
  108. EnvFiles []string
  109. Compatibility bool
  110. Progress string
  111. Offline bool
  112. }
  113. // ProjectFunc does stuff within a types.Project
  114. type ProjectFunc func(ctx context.Context, project *types.Project) error
  115. // ProjectServicesFunc does stuff within a types.Project and a selection of services
  116. type ProjectServicesFunc func(ctx context.Context, project *types.Project, services []string) error
  117. // WithProject creates a cobra run command from a ProjectFunc based on configured project options and selected services
  118. func (o *ProjectOptions) WithProject(fn ProjectFunc, dockerCli command.Cli) func(cmd *cobra.Command, args []string) error {
  119. return o.WithServices(dockerCli, func(ctx context.Context, project *types.Project, services []string) error {
  120. return fn(ctx, project)
  121. })
  122. }
  123. // WithServices creates a cobra run command from a ProjectFunc based on configured project options and selected services
  124. func (o *ProjectOptions) WithServices(dockerCli command.Cli, fn ProjectServicesFunc) func(cmd *cobra.Command, args []string) error {
  125. return Adapt(func(ctx context.Context, args []string) error {
  126. options := []cli.ProjectOptionsFn{
  127. cli.WithResolvedPaths(true),
  128. cli.WithDiscardEnvFile,
  129. cli.WithContext(ctx),
  130. }
  131. project, err := o.ToProject(dockerCli, args, options...)
  132. if err != nil {
  133. return err
  134. }
  135. return fn(ctx, project, args)
  136. })
  137. }
  138. func (o *ProjectOptions) addProjectFlags(f *pflag.FlagSet) {
  139. f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
  140. f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")
  141. f.StringArrayVarP(&o.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  142. f.StringArrayVar(&o.EnvFiles, "env-file", nil, "Specify an alternate environment file.")
  143. f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the, first specified, Compose file)")
  144. f.StringVar(&o.WorkDir, "workdir", "", "DEPRECATED! USE --project-directory INSTEAD.\nSpecify an alternate working directory\n(default: the path of the, first specified, Compose file)")
  145. f.BoolVar(&o.Compatibility, "compatibility", false, "Run compose in backward compatibility mode")
  146. f.StringVar(&o.Progress, "progress", buildx.PrinterModeAuto, fmt.Sprintf(`Set type of progress output (%s)`, strings.Join(printerModes, ", ")))
  147. _ = f.MarkHidden("workdir")
  148. }
  149. func (o *ProjectOptions) projectOrName(dockerCli command.Cli, services ...string) (*types.Project, string, error) {
  150. name := o.ProjectName
  151. var project *types.Project
  152. if len(o.ConfigPaths) > 0 || o.ProjectName == "" {
  153. p, err := o.ToProject(dockerCli, services, cli.WithDiscardEnvFile)
  154. if err != nil {
  155. envProjectName := os.Getenv(ComposeProjectName)
  156. if envProjectName != "" {
  157. return nil, envProjectName, nil
  158. }
  159. return nil, "", err
  160. }
  161. project = p
  162. name = p.Name
  163. }
  164. return project, name, nil
  165. }
  166. func (o *ProjectOptions) toProjectName(dockerCli command.Cli) (string, error) {
  167. if o.ProjectName != "" {
  168. return o.ProjectName, nil
  169. }
  170. envProjectName := os.Getenv(ComposeProjectName)
  171. if envProjectName != "" {
  172. return envProjectName, nil
  173. }
  174. project, err := o.ToProject(dockerCli, nil)
  175. if err != nil {
  176. return "", err
  177. }
  178. return project.Name, nil
  179. }
  180. func (o *ProjectOptions) ToProject(dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (*types.Project, error) {
  181. if !o.Offline {
  182. var err error
  183. po, err = o.configureRemoteLoaders(dockerCli, po)
  184. if err != nil {
  185. return nil, err
  186. }
  187. }
  188. options, err := o.toProjectOptions(po...)
  189. if err != nil {
  190. return nil, compose.WrapComposeError(err)
  191. }
  192. if o.Compatibility || utils.StringToBool(options.Environment[ComposeCompatibility]) {
  193. api.Separator = "_"
  194. }
  195. project, err := cli.ProjectFromOptions(options)
  196. if err != nil {
  197. return nil, compose.WrapComposeError(err)
  198. }
  199. if project.Name == "" {
  200. return nil, errors.New("project name can't be empty. Use `--project-name` to set a valid name")
  201. }
  202. err = project.EnableServices(services...)
  203. if err != nil {
  204. return nil, err
  205. }
  206. for i, s := range project.Services {
  207. s.CustomLabels = map[string]string{
  208. api.ProjectLabel: project.Name,
  209. api.ServiceLabel: s.Name,
  210. api.VersionLabel: api.ComposeVersion,
  211. api.WorkingDirLabel: project.WorkingDir,
  212. api.ConfigFilesLabel: strings.Join(project.ComposeFiles, ","),
  213. api.OneoffLabel: "False", // default, will be overridden by `run` command
  214. }
  215. if len(o.EnvFiles) != 0 {
  216. s.CustomLabels[api.EnvironmentFileLabel] = strings.Join(o.EnvFiles, ",")
  217. }
  218. project.Services[i] = s
  219. }
  220. project.WithoutUnnecessaryResources()
  221. err = project.ForServices(services)
  222. return project, err
  223. }
  224. func (o *ProjectOptions) configureRemoteLoaders(dockerCli command.Cli, po []cli.ProjectOptionsFn) ([]cli.ProjectOptionsFn, error) {
  225. git, err := remote.NewGitRemoteLoader(o.Offline)
  226. if err != nil {
  227. return nil, err
  228. }
  229. oci, err := remote.NewOCIRemoteLoader(dockerCli, o.Offline)
  230. if err != nil {
  231. return nil, err
  232. }
  233. po = append(po, cli.WithResourceLoader(git), cli.WithResourceLoader(oci))
  234. return po, nil
  235. }
  236. func (o *ProjectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  237. return cli.NewProjectOptions(o.ConfigPaths,
  238. append(po,
  239. cli.WithWorkingDirectory(o.ProjectDir),
  240. cli.WithOsEnv,
  241. cli.WithEnvFiles(o.EnvFiles...),
  242. cli.WithDotEnv,
  243. cli.WithConfigFileEnv,
  244. cli.WithDefaultConfigPath,
  245. cli.WithDefaultProfiles(o.Profiles...),
  246. cli.WithName(o.ProjectName))...)
  247. }
  248. // PluginName is the name of the plugin
  249. const PluginName = "compose"
  250. // RunningAsStandalone detects when running as a standalone program
  251. func RunningAsStandalone() bool {
  252. return len(os.Args) < 2 || os.Args[1] != manager.MetadataSubcommandName && os.Args[1] != PluginName
  253. }
  254. // RootCommand returns the compose command with its child commands
  255. func RootCommand(dockerCli command.Cli, backend api.Service) *cobra.Command { //nolint:gocyclo
  256. // filter out useless commandConn.CloseWrite warning message that can occur
  257. // when using a remote context that is unreachable: "commandConn.CloseWrite: commandconn: failed to wait: signal: killed"
  258. // https://github.com/docker/cli/blob/e1f24d3c93df6752d3c27c8d61d18260f141310c/cli/connhelper/commandconn/commandconn.go#L203-L215
  259. logrus.AddHook(logutil.NewFilter([]logrus.Level{
  260. logrus.WarnLevel,
  261. },
  262. "commandConn.CloseWrite:",
  263. "commandConn.CloseRead:",
  264. ))
  265. opts := ProjectOptions{}
  266. var (
  267. ansi string
  268. noAnsi bool
  269. verbose bool
  270. version bool
  271. parallel int
  272. dryRun bool
  273. )
  274. c := &cobra.Command{
  275. Short: "Docker Compose",
  276. Long: "Define and run multi-container applications with Docker.",
  277. Use: PluginName,
  278. TraverseChildren: true,
  279. // By default (no Run/RunE in parent c) for typos in subcommands, cobra displays the help of parent c but exit(0) !
  280. RunE: func(cmd *cobra.Command, args []string) error {
  281. if len(args) == 0 {
  282. return cmd.Help()
  283. }
  284. if version {
  285. return versionCommand(dockerCli).Execute()
  286. }
  287. _ = cmd.Help()
  288. return dockercli.StatusError{
  289. StatusCode: compose.CommandSyntaxFailure.ExitCode,
  290. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  291. }
  292. },
  293. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  294. err := setEnvWithDotEnv(&opts)
  295. if err != nil {
  296. return err
  297. }
  298. parent := cmd.Root()
  299. if parent != nil {
  300. parentPrerun := parent.PersistentPreRunE
  301. if parentPrerun != nil {
  302. err := parentPrerun(cmd, args)
  303. if err != nil {
  304. return err
  305. }
  306. }
  307. }
  308. if noAnsi {
  309. if ansi != "auto" {
  310. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  311. }
  312. ansi = "never"
  313. fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n")
  314. }
  315. if verbose {
  316. logrus.SetLevel(logrus.TraceLevel)
  317. }
  318. if v, ok := os.LookupEnv("COMPOSE_ANSI"); ok && !cmd.Flags().Changed("ansi") {
  319. ansi = v
  320. }
  321. formatter.SetANSIMode(dockerCli, ansi)
  322. if noColor, ok := os.LookupEnv("NO_COLOR"); ok && noColor != "" {
  323. ui.NoColor()
  324. formatter.SetANSIMode(dockerCli, formatter.Never)
  325. }
  326. switch ansi {
  327. case "never":
  328. ui.Mode = ui.ModePlain
  329. case "always":
  330. ui.Mode = ui.ModeTTY
  331. }
  332. switch opts.Progress {
  333. case ui.ModeAuto:
  334. ui.Mode = ui.ModeAuto
  335. case ui.ModeTTY:
  336. if ansi == "never" {
  337. return fmt.Errorf("can't use --progress tty while ANSI support is disabled")
  338. }
  339. ui.Mode = ui.ModeTTY
  340. case ui.ModePlain:
  341. if ansi == "always" {
  342. return fmt.Errorf("can't use --progress plain while ANSI support is forced")
  343. }
  344. ui.Mode = ui.ModePlain
  345. case ui.ModeQuiet, "none":
  346. ui.Mode = ui.ModeQuiet
  347. default:
  348. return fmt.Errorf("unsupported --progress value %q", opts.Progress)
  349. }
  350. if opts.WorkDir != "" {
  351. if opts.ProjectDir != "" {
  352. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  353. }
  354. opts.ProjectDir = opts.WorkDir
  355. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  356. }
  357. for i, file := range opts.EnvFiles {
  358. if !filepath.IsAbs(file) {
  359. file, err = filepath.Abs(file)
  360. if err != nil {
  361. return err
  362. }
  363. opts.EnvFiles[i] = file
  364. }
  365. }
  366. composeCmd := cmd
  367. for {
  368. if composeCmd.Name() == PluginName {
  369. break
  370. }
  371. if !composeCmd.HasParent() {
  372. return fmt.Errorf("error parsing command line, expected %q", PluginName)
  373. }
  374. composeCmd = composeCmd.Parent()
  375. }
  376. if v, ok := os.LookupEnv(ComposeParallelLimit); ok && !composeCmd.Flags().Changed("parallel") {
  377. i, err := strconv.Atoi(v)
  378. if err != nil {
  379. return fmt.Errorf("%s must be an integer (found: %q)", ComposeParallelLimit, v)
  380. }
  381. parallel = i
  382. }
  383. if parallel > 0 {
  384. backend.MaxConcurrency(parallel)
  385. }
  386. ctx, err := backend.DryRunMode(cmd.Context(), dryRun)
  387. if err != nil {
  388. return err
  389. }
  390. cmd.SetContext(ctx)
  391. return nil
  392. },
  393. }
  394. c.AddCommand(
  395. upCommand(&opts, dockerCli, backend),
  396. downCommand(&opts, dockerCli, backend),
  397. startCommand(&opts, dockerCli, backend),
  398. restartCommand(&opts, dockerCli, backend),
  399. stopCommand(&opts, dockerCli, backend),
  400. psCommand(&opts, dockerCli, backend),
  401. listCommand(dockerCli, backend),
  402. logsCommand(&opts, dockerCli, backend),
  403. configCommand(&opts, dockerCli, backend),
  404. killCommand(&opts, dockerCli, backend),
  405. runCommand(&opts, dockerCli, backend),
  406. removeCommand(&opts, dockerCli, backend),
  407. execCommand(&opts, dockerCli, backend),
  408. pauseCommand(&opts, dockerCli, backend),
  409. unpauseCommand(&opts, dockerCli, backend),
  410. topCommand(&opts, dockerCli, backend),
  411. eventsCommand(&opts, dockerCli, backend),
  412. portCommand(&opts, dockerCli, backend),
  413. imagesCommand(&opts, dockerCli, backend),
  414. versionCommand(dockerCli),
  415. buildCommand(&opts, dockerCli, backend),
  416. pushCommand(&opts, dockerCli, backend),
  417. pullCommand(&opts, dockerCli, backend),
  418. createCommand(&opts, dockerCli, backend),
  419. copyCommand(&opts, dockerCli, backend),
  420. waitCommand(&opts, dockerCli, backend),
  421. scaleCommand(&opts, dockerCli, backend),
  422. watchCommand(&opts, dockerCli, backend),
  423. alphaCommand(&opts, dockerCli, backend),
  424. )
  425. c.Flags().SetInterspersed(false)
  426. opts.addProjectFlags(c.Flags())
  427. c.RegisterFlagCompletionFunc( //nolint:errcheck
  428. "project-name",
  429. completeProjectNames(backend),
  430. )
  431. c.RegisterFlagCompletionFunc( //nolint:errcheck
  432. "project-directory",
  433. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  434. return []string{}, cobra.ShellCompDirectiveFilterDirs
  435. },
  436. )
  437. c.RegisterFlagCompletionFunc( //nolint:errcheck
  438. "file",
  439. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  440. return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt
  441. },
  442. )
  443. c.RegisterFlagCompletionFunc( //nolint:errcheck
  444. "profile",
  445. completeProfileNames(dockerCli, &opts),
  446. )
  447. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  448. c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`)
  449. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  450. c.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Execute command in dry run mode")
  451. c.Flags().MarkHidden("version") //nolint:errcheck
  452. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  453. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  454. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  455. c.Flags().MarkHidden("verbose") //nolint:errcheck
  456. return c
  457. }
  458. func setEnvWithDotEnv(prjOpts *ProjectOptions) error {
  459. if len(prjOpts.EnvFiles) == 0 {
  460. if envFiles := os.Getenv(ComposeEnvFiles); envFiles != "" {
  461. prjOpts.EnvFiles = strings.Split(envFiles, ",")
  462. }
  463. }
  464. options, err := prjOpts.toProjectOptions()
  465. if err != nil {
  466. return compose.WrapComposeError(err)
  467. }
  468. workingDir, err := options.GetWorkingDir()
  469. if err != nil {
  470. return err
  471. }
  472. envFromFile, err := dotenv.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), workingDir, options.EnvFiles)
  473. if err != nil {
  474. return err
  475. }
  476. for k, v := range envFromFile {
  477. if _, ok := os.LookupEnv(k); !ok { // Precedence to OS Env
  478. if err := os.Setenv(k, v); err != nil {
  479. return err
  480. }
  481. }
  482. }
  483. return nil
  484. }
  485. var printerModes = []string{
  486. ui.ModeAuto,
  487. ui.ModeTTY,
  488. ui.ModePlain,
  489. ui.ModeQuiet,
  490. }