compose.go 14 KB

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