1
0

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