compose.go 10 KB

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