compose.go 17 KB

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