compose.go 16 KB

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