compose.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. "strings"
  21. "syscall"
  22. "github.com/compose-spec/compose-go/cli"
  23. "github.com/compose-spec/compose-go/types"
  24. dockercli "github.com/docker/cli/cli"
  25. "github.com/docker/cli/cli-plugins/manager"
  26. "github.com/docker/cli/cli/command"
  27. "github.com/morikuni/aec"
  28. "github.com/pkg/errors"
  29. "github.com/sirupsen/logrus"
  30. "github.com/spf13/cobra"
  31. "github.com/spf13/pflag"
  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. "github.com/docker/compose/v2/pkg/progress"
  36. "github.com/docker/compose/v2/pkg/utils"
  37. )
  38. // Command defines a compose CLI command as a func with args
  39. type Command func(context.Context, []string) error
  40. // CobraCommand defines a cobra command function
  41. type CobraCommand func(context.Context, *cobra.Command, []string) error
  42. // AdaptCmd adapt a CobraCommand func to cobra library
  43. func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error {
  44. return func(cmd *cobra.Command, args []string) error {
  45. ctx := cmd.Context()
  46. contextString := fmt.Sprintf("%s", ctx)
  47. if !strings.HasSuffix(contextString, ".WithCancel") { // need to handle cancel
  48. cancellableCtx, cancel := context.WithCancel(cmd.Context())
  49. ctx = cancellableCtx
  50. s := make(chan os.Signal, 1)
  51. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  52. go func() {
  53. <-s
  54. cancel()
  55. }()
  56. }
  57. err := fn(ctx, cmd, args)
  58. var composeErr compose.Error
  59. if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  60. err = dockercli.StatusError{
  61. StatusCode: 130,
  62. Status: compose.CanceledStatus,
  63. }
  64. }
  65. if errors.As(err, &composeErr) {
  66. err = dockercli.StatusError{
  67. StatusCode: composeErr.GetMetricsFailureCategory().ExitCode,
  68. Status: err.Error(),
  69. }
  70. }
  71. return err
  72. }
  73. }
  74. // Adapt a Command func to cobra library
  75. func Adapt(fn Command) func(cmd *cobra.Command, args []string) error {
  76. return AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  77. return fn(ctx, args)
  78. })
  79. }
  80. // Warning is a global warning to be displayed to user on command failure
  81. var Warning string
  82. type projectOptions struct {
  83. ProjectName string
  84. Profiles []string
  85. ConfigPaths []string
  86. WorkDir string
  87. ProjectDir string
  88. EnvFile string
  89. Compatibility bool
  90. }
  91. // ProjectFunc does stuff within a types.Project
  92. type ProjectFunc func(ctx context.Context, project *types.Project) error
  93. // ProjectServicesFunc does stuff within a types.Project and a selection of services
  94. type ProjectServicesFunc func(ctx context.Context, project *types.Project, services []string) error
  95. // WithProject creates a cobra run command from a ProjectFunc based on configured project options and selected services
  96. func (o *projectOptions) WithProject(fn ProjectFunc) func(cmd *cobra.Command, args []string) error {
  97. return o.WithServices(func(ctx context.Context, project *types.Project, services []string) error {
  98. return fn(ctx, project)
  99. })
  100. }
  101. // WithServices creates a cobra run command from a ProjectFunc based on configured project options and selected services
  102. func (o *projectOptions) WithServices(fn ProjectServicesFunc) func(cmd *cobra.Command, args []string) error {
  103. return Adapt(func(ctx context.Context, args []string) error {
  104. project, err := o.toProject(args, cli.WithResolvedPaths(true))
  105. if err != nil {
  106. return err
  107. }
  108. return fn(ctx, project, args)
  109. })
  110. }
  111. func (o *projectOptions) addProjectFlags(f *pflag.FlagSet) {
  112. f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
  113. f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")
  114. f.StringArrayVarP(&o.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  115. f.StringVar(&o.EnvFile, "env-file", "", "Specify an alternate environment file.")
  116. f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the Compose file)")
  117. f.StringVar(&o.WorkDir, "workdir", "", "DEPRECATED! USE --project-directory INSTEAD.\nSpecify an alternate working directory\n(default: the path of the Compose file)")
  118. f.BoolVar(&o.Compatibility, "compatibility", false, "Run compose in backward compatibility mode")
  119. _ = f.MarkHidden("workdir")
  120. }
  121. func (o *projectOptions) toProjectName() (string, error) {
  122. if o.ProjectName != "" {
  123. return o.ProjectName, nil
  124. }
  125. envProjectName := os.Getenv("COMPOSE_PROJECT_NAME")
  126. if envProjectName != "" {
  127. return envProjectName, nil
  128. }
  129. project, err := o.toProject(nil)
  130. if err != nil {
  131. return "", err
  132. }
  133. return project.Name, nil
  134. }
  135. func (o *projectOptions) toProject(services []string, po ...cli.ProjectOptionsFn) (*types.Project, error) {
  136. options, err := o.toProjectOptions(po...)
  137. if err != nil {
  138. return nil, compose.WrapComposeError(err)
  139. }
  140. project, err := cli.ProjectFromOptions(options)
  141. if err != nil {
  142. return nil, compose.WrapComposeError(err)
  143. }
  144. if o.Compatibility || utils.StringToBool(project.Environment["COMPOSE_COMPATIBILITY"]) {
  145. compose.Separator = "_"
  146. }
  147. ef := o.EnvFile
  148. if ef != "" && !filepath.IsAbs(ef) {
  149. ef = filepath.Join(project.WorkingDir, o.EnvFile)
  150. }
  151. for i, s := range project.Services {
  152. s.CustomLabels = map[string]string{
  153. api.ProjectLabel: project.Name,
  154. api.ServiceLabel: s.Name,
  155. api.VersionLabel: api.ComposeVersion,
  156. api.WorkingDirLabel: project.WorkingDir,
  157. api.ConfigFilesLabel: strings.Join(project.ComposeFiles, ","),
  158. api.OneoffLabel: "False", // default, will be overridden by `run` command
  159. }
  160. if ef != "" {
  161. s.CustomLabels[api.EnvironmentFileLabel] = ef
  162. }
  163. project.Services[i] = s
  164. }
  165. if len(services) > 0 {
  166. s, err := project.GetServices(services...)
  167. if err != nil {
  168. return nil, err
  169. }
  170. o.Profiles = append(o.Profiles, s.GetProfiles()...)
  171. }
  172. if profiles, ok := options.Environment["COMPOSE_PROFILES"]; ok {
  173. o.Profiles = append(o.Profiles, strings.Split(profiles, ",")...)
  174. }
  175. project.ApplyProfiles(o.Profiles)
  176. project.WithoutUnnecessaryResources()
  177. err = project.ForServices(services)
  178. return project, err
  179. }
  180. func (o *projectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  181. return cli.NewProjectOptions(o.ConfigPaths,
  182. append(po,
  183. cli.WithWorkingDirectory(o.ProjectDir),
  184. cli.WithEnvFile(o.EnvFile),
  185. cli.WithDotEnv,
  186. cli.WithOsEnv,
  187. cli.WithConfigFileEnv,
  188. cli.WithDefaultConfigPath,
  189. cli.WithName(o.ProjectName))...)
  190. }
  191. // PluginName is the name of the plugin
  192. const PluginName = "compose"
  193. // RunningAsStandalone detects when running as a standalone program
  194. func RunningAsStandalone() bool {
  195. return len(os.Args) < 2 || os.Args[1] != manager.MetadataSubcommandName && os.Args[1] != PluginName
  196. }
  197. // RootCommand returns the compose command with its child commands
  198. func RootCommand(dockerCli command.Cli, backend api.Service) *cobra.Command {
  199. opts := projectOptions{}
  200. var (
  201. ansi string
  202. noAnsi bool
  203. verbose bool
  204. version bool
  205. )
  206. command := &cobra.Command{
  207. Short: "Docker Compose",
  208. Use: PluginName,
  209. TraverseChildren: true,
  210. // By default (no Run/RunE in parent command) for typos in subcommands, cobra displays the help of parent command but exit(0) !
  211. RunE: func(cmd *cobra.Command, args []string) error {
  212. if len(args) == 0 {
  213. return cmd.Help()
  214. }
  215. if version {
  216. return versionCommand().Execute()
  217. }
  218. _ = cmd.Help()
  219. return dockercli.StatusError{
  220. StatusCode: compose.CommandSyntaxFailure.ExitCode,
  221. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  222. }
  223. },
  224. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  225. parent := cmd.Root()
  226. if parent != nil {
  227. parentPrerun := parent.PersistentPreRunE
  228. if parentPrerun != nil {
  229. err := parentPrerun(cmd, args)
  230. if err != nil {
  231. return err
  232. }
  233. }
  234. }
  235. if noAnsi {
  236. if ansi != "auto" {
  237. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  238. }
  239. ansi = "never"
  240. fmt.Fprint(os.Stderr, aec.Apply("option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n", aec.RedF))
  241. }
  242. if verbose {
  243. logrus.SetLevel(logrus.TraceLevel)
  244. }
  245. formatter.SetANSIMode(ansi)
  246. switch ansi {
  247. case "never":
  248. progress.Mode = progress.ModePlain
  249. case "tty":
  250. progress.Mode = progress.ModeTTY
  251. }
  252. if opts.WorkDir != "" {
  253. if opts.ProjectDir != "" {
  254. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  255. }
  256. opts.ProjectDir = opts.WorkDir
  257. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  258. }
  259. return nil
  260. },
  261. }
  262. command.AddCommand(
  263. upCommand(&opts, backend),
  264. downCommand(&opts, backend),
  265. startCommand(&opts, backend),
  266. restartCommand(&opts, backend),
  267. stopCommand(&opts, backend),
  268. psCommand(&opts, backend),
  269. listCommand(backend),
  270. logsCommand(&opts, backend),
  271. convertCommand(&opts, backend),
  272. killCommand(&opts, backend),
  273. runCommand(&opts, dockerCli, backend),
  274. removeCommand(&opts, backend),
  275. execCommand(&opts, dockerCli, backend),
  276. pauseCommand(&opts, backend),
  277. unpauseCommand(&opts, backend),
  278. topCommand(&opts, backend),
  279. eventsCommand(&opts, backend),
  280. portCommand(&opts, backend),
  281. imagesCommand(&opts, backend),
  282. versionCommand(),
  283. buildCommand(&opts, backend),
  284. pushCommand(&opts, backend),
  285. pullCommand(&opts, backend),
  286. createCommand(&opts, backend),
  287. copyCommand(&opts, backend),
  288. )
  289. command.Flags().SetInterspersed(false)
  290. opts.addProjectFlags(command.Flags())
  291. command.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  292. command.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  293. command.Flags().MarkHidden("version") //nolint:errcheck
  294. command.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  295. command.Flags().MarkHidden("no-ansi") //nolint:errcheck
  296. command.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  297. command.Flags().MarkHidden("verbose") //nolint:errcheck
  298. return command
  299. }