compose.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. for i, s := range project.Services {
  166. s.CustomLabels = map[string]string{
  167. api.ProjectLabel: project.Name,
  168. api.ServiceLabel: s.Name,
  169. api.VersionLabel: api.ComposeVersion,
  170. api.WorkingDirLabel: project.WorkingDir,
  171. api.ConfigFilesLabel: strings.Join(project.ComposeFiles, ","),
  172. api.OneoffLabel: "False", // default, will be overridden by `run` command
  173. }
  174. if len(o.EnvFiles) != 0 {
  175. s.CustomLabels[api.EnvironmentFileLabel] = strings.Join(o.EnvFiles, ",")
  176. }
  177. project.Services[i] = s
  178. }
  179. if profiles, ok := options.Environment["COMPOSE_PROFILES"]; ok && len(o.Profiles) == 0 {
  180. o.Profiles = append(o.Profiles, strings.Split(profiles, ",")...)
  181. }
  182. if len(services) > 0 {
  183. s, err := project.GetServices(services...)
  184. if err != nil {
  185. return nil, err
  186. }
  187. o.Profiles = append(o.Profiles, s.GetProfiles()...)
  188. }
  189. project.ApplyProfiles(o.Profiles)
  190. project.WithoutUnnecessaryResources()
  191. err = project.ForServices(services)
  192. return project, err
  193. }
  194. func (o *ProjectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  195. return cli.NewProjectOptions(o.ConfigPaths,
  196. append(po,
  197. cli.WithWorkingDirectory(o.ProjectDir),
  198. cli.WithOsEnv,
  199. cli.WithEnvFiles(o.EnvFiles...),
  200. cli.WithDotEnv,
  201. cli.WithConfigFileEnv,
  202. cli.WithDefaultConfigPath,
  203. cli.WithName(o.ProjectName))...)
  204. }
  205. // PluginName is the name of the plugin
  206. const PluginName = "compose"
  207. // RunningAsStandalone detects when running as a standalone program
  208. func RunningAsStandalone() bool {
  209. return len(os.Args) < 2 || os.Args[1] != manager.MetadataSubcommandName && os.Args[1] != PluginName
  210. }
  211. // RootCommand returns the compose command with its child commands
  212. func RootCommand(streams command.Cli, backend api.Service) *cobra.Command { //nolint:gocyclo
  213. // filter out useless commandConn.CloseWrite warning message that can occur
  214. // when using a remote context that is unreachable: "commandConn.CloseWrite: commandconn: failed to wait: signal: killed"
  215. // https://github.com/docker/cli/blob/e1f24d3c93df6752d3c27c8d61d18260f141310c/cli/connhelper/commandconn/commandconn.go#L203-L215
  216. logrus.AddHook(logutil.NewFilter([]logrus.Level{
  217. logrus.WarnLevel,
  218. },
  219. "commandConn.CloseWrite:",
  220. "commandConn.CloseRead:",
  221. ))
  222. opts := ProjectOptions{}
  223. var (
  224. ansi string
  225. noAnsi bool
  226. verbose bool
  227. version bool
  228. parallel int
  229. dryRun bool
  230. )
  231. c := &cobra.Command{
  232. Short: "Docker Compose",
  233. Use: PluginName,
  234. TraverseChildren: true,
  235. // By default (no Run/RunE in parent c) for typos in subcommands, cobra displays the help of parent c but exit(0) !
  236. RunE: func(cmd *cobra.Command, args []string) error {
  237. if len(args) == 0 {
  238. return cmd.Help()
  239. }
  240. if version {
  241. return versionCommand().Execute()
  242. }
  243. _ = cmd.Help()
  244. return dockercli.StatusError{
  245. StatusCode: compose.CommandSyntaxFailure.ExitCode,
  246. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  247. }
  248. },
  249. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  250. err := setEnvWithDotEnv(&opts)
  251. if err != nil {
  252. return err
  253. }
  254. parent := cmd.Root()
  255. if parent != nil {
  256. parentPrerun := parent.PersistentPreRunE
  257. if parentPrerun != nil {
  258. err := parentPrerun(cmd, args)
  259. if err != nil {
  260. return err
  261. }
  262. }
  263. }
  264. if noAnsi {
  265. if ansi != "auto" {
  266. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  267. }
  268. ansi = "never"
  269. fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n")
  270. }
  271. if verbose {
  272. logrus.SetLevel(logrus.TraceLevel)
  273. }
  274. formatter.SetANSIMode(streams, ansi)
  275. switch ansi {
  276. case "never":
  277. progress.Mode = progress.ModePlain
  278. case "tty":
  279. progress.Mode = progress.ModeTTY
  280. }
  281. if opts.WorkDir != "" {
  282. if opts.ProjectDir != "" {
  283. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  284. }
  285. opts.ProjectDir = opts.WorkDir
  286. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  287. }
  288. for i, file := range opts.EnvFiles {
  289. if !filepath.IsAbs(file) {
  290. file, err = filepath.Abs(file)
  291. if err != nil {
  292. return err
  293. }
  294. opts.EnvFiles[i] = file
  295. }
  296. }
  297. if v, ok := os.LookupEnv("COMPOSE_PARALLEL_LIMIT"); ok && !cmd.Flags().Changed("parallel") {
  298. i, err := strconv.Atoi(v)
  299. if err != nil {
  300. return fmt.Errorf("COMPOSE_PARALLEL_LIMIT must be an integer (found: %q)", v)
  301. }
  302. parallel = i
  303. }
  304. if parallel > 0 {
  305. backend.MaxConcurrency(parallel)
  306. }
  307. ctx, err := backend.DryRunMode(cmd.Context(), dryRun)
  308. if err != nil {
  309. return err
  310. }
  311. cmd.SetContext(ctx)
  312. return nil
  313. },
  314. }
  315. c.AddCommand(
  316. upCommand(&opts, streams, backend),
  317. downCommand(&opts, backend),
  318. startCommand(&opts, backend),
  319. restartCommand(&opts, backend),
  320. stopCommand(&opts, backend),
  321. psCommand(&opts, streams, backend),
  322. listCommand(streams, backend),
  323. logsCommand(&opts, streams, backend),
  324. convertCommand(&opts, streams, backend),
  325. killCommand(&opts, backend),
  326. runCommand(&opts, streams, backend),
  327. removeCommand(&opts, backend),
  328. execCommand(&opts, streams, backend),
  329. pauseCommand(&opts, backend),
  330. unpauseCommand(&opts, backend),
  331. topCommand(&opts, streams, backend),
  332. eventsCommand(&opts, streams, backend),
  333. portCommand(&opts, streams, backend),
  334. imagesCommand(&opts, streams, backend),
  335. versionCommand(),
  336. buildCommand(&opts, streams, backend),
  337. pushCommand(&opts, backend),
  338. pullCommand(&opts, backend),
  339. createCommand(&opts, backend),
  340. copyCommand(&opts, backend),
  341. alphaCommand(&opts, backend),
  342. )
  343. c.Flags().SetInterspersed(false)
  344. opts.addProjectFlags(c.Flags())
  345. c.RegisterFlagCompletionFunc( //nolint:errcheck
  346. "project-name",
  347. completeProjectNames(backend),
  348. )
  349. c.RegisterFlagCompletionFunc( //nolint:errcheck
  350. "file",
  351. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  352. return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt
  353. },
  354. )
  355. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  356. c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`)
  357. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  358. c.Flags().MarkHidden("version") //nolint:errcheck
  359. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  360. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  361. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  362. c.Flags().MarkHidden("verbose") //nolint:errcheck
  363. c.Flags().BoolVar(&dryRun, "dry-run", false, "Execute command in dry run mode")
  364. c.Flags().MarkHidden("dry-run") //nolint:errcheck
  365. return c
  366. }
  367. func setEnvWithDotEnv(prjOpts *ProjectOptions) error {
  368. options, err := prjOpts.toProjectOptions()
  369. if err != nil {
  370. return compose.WrapComposeError(err)
  371. }
  372. workingDir, err := options.GetWorkingDir()
  373. if err != nil {
  374. return err
  375. }
  376. envFromFile, err := cli.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), workingDir, options.EnvFiles)
  377. if err != nil {
  378. return err
  379. }
  380. for k, v := range envFromFile {
  381. if _, ok := os.LookupEnv(k); !ok { // Precedence to OS Env
  382. if err := os.Setenv(k, v); err != nil {
  383. return err
  384. }
  385. }
  386. }
  387. return nil
  388. }