compose.go 17 KB

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