compose.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. if o.EnvFile != "" {
  106. var services types.Services
  107. for _, s := range project.Services {
  108. ef := o.EnvFile
  109. if ef != "" {
  110. if !filepath.IsAbs(ef) {
  111. ef = filepath.Join(project.WorkingDir, o.EnvFile)
  112. }
  113. if s.Labels == nil {
  114. s.Labels = make(map[string]string)
  115. }
  116. s.Labels[api.EnvironmentFileLabel] = ef
  117. services = append(services, s)
  118. }
  119. }
  120. project.Services = services
  121. }
  122. return fn(ctx, project, args)
  123. })
  124. }
  125. func (o *projectOptions) addProjectFlags(f *pflag.FlagSet) {
  126. f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
  127. f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")
  128. f.StringArrayVarP(&o.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  129. f.StringVar(&o.EnvFile, "env-file", "", "Specify an alternate environment file.")
  130. f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the Compose file)")
  131. f.StringVar(&o.WorkDir, "workdir", "", "DEPRECATED! USE --project-directory INSTEAD.\nSpecify an alternate working directory\n(default: the path of the Compose file)")
  132. f.BoolVar(&o.Compatibility, "compatibility", false, "Run compose in backward compatibility mode")
  133. _ = f.MarkHidden("workdir")
  134. }
  135. func (o *projectOptions) toProjectName() (string, error) {
  136. if o.ProjectName != "" {
  137. return o.ProjectName, nil
  138. }
  139. project, err := o.toProject(nil)
  140. if err != nil {
  141. return "", err
  142. }
  143. return project.Name, nil
  144. }
  145. func (o *projectOptions) toProject(services []string, po ...cli.ProjectOptionsFn) (*types.Project, error) {
  146. options, err := o.toProjectOptions(po...)
  147. if err != nil {
  148. return nil, compose.WrapComposeError(err)
  149. }
  150. project, err := cli.ProjectFromOptions(options)
  151. if err != nil {
  152. return nil, compose.WrapComposeError(err)
  153. }
  154. if len(services) > 0 {
  155. s, err := project.GetServices(services...)
  156. if err != nil {
  157. return nil, err
  158. }
  159. o.Profiles = append(o.Profiles, s.GetProfiles()...)
  160. }
  161. if profiles, ok := options.Environment["COMPOSE_PROFILES"]; ok {
  162. o.Profiles = append(o.Profiles, strings.Split(profiles, ",")...)
  163. }
  164. project.ApplyProfiles(o.Profiles)
  165. project.WithoutUnnecessaryResources()
  166. err = project.ForServices(services)
  167. return project, err
  168. }
  169. func (o *projectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  170. return cli.NewProjectOptions(o.ConfigPaths,
  171. append(po,
  172. cli.WithEnvFile(o.EnvFile),
  173. cli.WithDotEnv,
  174. cli.WithOsEnv,
  175. cli.WithWorkingDirectory(o.ProjectDir),
  176. cli.WithConfigFileEnv,
  177. cli.WithDefaultConfigPath,
  178. cli.WithName(o.ProjectName))...)
  179. }
  180. const pluginName = "compose"
  181. // RunningAsStandalone detects when running as a standalone program
  182. func RunningAsStandalone() bool {
  183. return len(os.Args) < 2 || os.Args[1] != manager.MetadataSubcommandName && os.Args[1] != pluginName
  184. }
  185. // RootCommand returns the compose command with its child commands
  186. func RootCommand(backend api.Service) *cobra.Command {
  187. opts := projectOptions{}
  188. var (
  189. ansi string
  190. noAnsi bool
  191. verbose bool
  192. )
  193. command := &cobra.Command{
  194. Short: "Docker Compose",
  195. Use: pluginName,
  196. TraverseChildren: true,
  197. // By default (no Run/RunE in parent command) for typos in subcommands, cobra displays the help of parent command but exit(0) !
  198. RunE: func(cmd *cobra.Command, args []string) error {
  199. if len(args) == 0 {
  200. return cmd.Help()
  201. }
  202. _ = cmd.Help()
  203. return dockercli.StatusError{
  204. StatusCode: compose.CommandSyntaxFailure.ExitCode,
  205. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  206. }
  207. },
  208. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  209. parent := cmd.Root()
  210. if parent != nil {
  211. parentPrerun := parent.PersistentPreRunE
  212. if parentPrerun != nil {
  213. err := parentPrerun(cmd, args)
  214. if err != nil {
  215. return err
  216. }
  217. }
  218. }
  219. if noAnsi {
  220. if ansi != "auto" {
  221. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  222. }
  223. ansi = "never"
  224. fmt.Fprint(os.Stderr, aec.Apply("option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n", aec.RedF))
  225. }
  226. if verbose {
  227. logrus.SetLevel(logrus.TraceLevel)
  228. }
  229. formatter.SetANSIMode(ansi)
  230. if opts.WorkDir != "" {
  231. if opts.ProjectDir != "" {
  232. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  233. }
  234. opts.ProjectDir = opts.WorkDir
  235. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  236. }
  237. if opts.Compatibility || os.Getenv("COMPOSE_COMPATIBILITY") == "true" {
  238. compose.Separator = "_"
  239. }
  240. return nil
  241. },
  242. }
  243. command.AddCommand(
  244. upCommand(&opts, backend),
  245. downCommand(&opts, backend),
  246. startCommand(&opts, backend),
  247. restartCommand(&opts, backend),
  248. stopCommand(&opts, backend),
  249. psCommand(&opts, backend),
  250. listCommand(backend),
  251. logsCommand(&opts, backend),
  252. convertCommand(&opts, backend),
  253. killCommand(&opts, backend),
  254. runCommand(&opts, backend),
  255. removeCommand(&opts, backend),
  256. execCommand(&opts, backend),
  257. pauseCommand(&opts, backend),
  258. unpauseCommand(&opts, backend),
  259. topCommand(&opts, backend),
  260. eventsCommand(&opts, backend),
  261. portCommand(&opts, backend),
  262. imagesCommand(&opts, backend),
  263. versionCommand(),
  264. buildCommand(&opts, backend),
  265. pushCommand(&opts, backend),
  266. pullCommand(&opts, backend),
  267. createCommand(&opts, backend),
  268. copyCommand(&opts, backend),
  269. )
  270. command.Flags().SetInterspersed(false)
  271. opts.addProjectFlags(command.Flags())
  272. command.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  273. command.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  274. command.Flags().MarkHidden("no-ansi") //nolint:errcheck
  275. command.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  276. command.Flags().MarkHidden("verbose") //nolint:errcheck
  277. return command
  278. }