1
0

compose.go 10 KB

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