1
0

compose.go 16 KB

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