compose.go 10 KB

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