compose.go 15 KB

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