compose.go 15 KB

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