compose.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. composegoutils "github.com/compose-spec/compose-go/utils"
  25. dockercli "github.com/docker/cli/cli"
  26. "github.com/docker/cli/cli-plugins/manager"
  27. "github.com/docker/cli/cli/command"
  28. "github.com/morikuni/aec"
  29. "github.com/pkg/errors"
  30. "github.com/sirupsen/logrus"
  31. "github.com/spf13/cobra"
  32. "github.com/spf13/pflag"
  33. "github.com/docker/compose/v2/cmd/formatter"
  34. "github.com/docker/compose/v2/pkg/api"
  35. "github.com/docker/compose/v2/pkg/compose"
  36. "github.com/docker/compose/v2/pkg/progress"
  37. "github.com/docker/compose/v2/pkg/utils"
  38. )
  39. // Command defines a compose CLI command as a func with args
  40. type Command func(context.Context, []string) error
  41. // CobraCommand defines a cobra command function
  42. type CobraCommand func(context.Context, *cobra.Command, []string) error
  43. // AdaptCmd adapt a CobraCommand func to cobra library
  44. func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error {
  45. return func(cmd *cobra.Command, args []string) error {
  46. ctx := cmd.Context()
  47. contextString := fmt.Sprintf("%s", ctx)
  48. if !strings.HasSuffix(contextString, ".WithCancel") { // need to handle cancel
  49. cancellableCtx, cancel := context.WithCancel(cmd.Context())
  50. ctx = cancellableCtx
  51. s := make(chan os.Signal, 1)
  52. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  53. go func() {
  54. <-s
  55. cancel()
  56. }()
  57. }
  58. err := fn(ctx, cmd, args)
  59. var composeErr compose.Error
  60. if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  61. err = dockercli.StatusError{
  62. StatusCode: 130,
  63. Status: compose.CanceledStatus,
  64. }
  65. }
  66. if errors.As(err, &composeErr) {
  67. err = dockercli.StatusError{
  68. StatusCode: composeErr.GetMetricsFailureCategory().ExitCode,
  69. Status: err.Error(),
  70. }
  71. }
  72. return err
  73. }
  74. }
  75. // Adapt a Command func to cobra library
  76. func Adapt(fn Command) func(cmd *cobra.Command, args []string) error {
  77. return AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  78. return fn(ctx, args)
  79. })
  80. }
  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, first specified, Compose file)")
  116. 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)")
  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. envProjectName := os.Getenv("COMPOSE_PROJECT_NAME")
  125. if envProjectName != "" {
  126. return envProjectName, nil
  127. }
  128. project, err := o.toProject(nil)
  129. if err != nil {
  130. return "", err
  131. }
  132. return project.Name, nil
  133. }
  134. func (o *projectOptions) toProject(services []string, po ...cli.ProjectOptionsFn) (*types.Project, error) {
  135. options, err := o.toProjectOptions(po...)
  136. if err != nil {
  137. return nil, compose.WrapComposeError(err)
  138. }
  139. if o.Compatibility || utils.StringToBool(options.Environment["COMPOSE_COMPATIBILITY"]) {
  140. api.Separator = "_"
  141. }
  142. project, err := cli.ProjectFromOptions(options)
  143. if err != nil {
  144. return nil, compose.WrapComposeError(err)
  145. }
  146. ef := o.EnvFile
  147. if ef != "" && !filepath.IsAbs(ef) {
  148. ef, err = filepath.Abs(ef)
  149. if err != nil {
  150. return nil, err
  151. }
  152. }
  153. for i, s := range project.Services {
  154. s.CustomLabels = map[string]string{
  155. api.ProjectLabel: project.Name,
  156. api.ServiceLabel: s.Name,
  157. api.VersionLabel: api.ComposeVersion,
  158. api.WorkingDirLabel: project.WorkingDir,
  159. api.ConfigFilesLabel: strings.Join(project.ComposeFiles, ","),
  160. api.OneoffLabel: "False", // default, will be overridden by `run` command
  161. }
  162. if ef != "" {
  163. s.CustomLabels[api.EnvironmentFileLabel] = ef
  164. }
  165. project.Services[i] = s
  166. }
  167. if len(services) > 0 {
  168. s, err := project.GetServices(services...)
  169. if err != nil {
  170. return nil, err
  171. }
  172. o.Profiles = append(o.Profiles, s.GetProfiles()...)
  173. }
  174. if profiles, ok := options.Environment["COMPOSE_PROFILES"]; ok {
  175. o.Profiles = append(o.Profiles, strings.Split(profiles, ",")...)
  176. }
  177. project.ApplyProfiles(o.Profiles)
  178. project.WithoutUnnecessaryResources()
  179. err = project.ForServices(services)
  180. return project, err
  181. }
  182. func (o *projectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  183. return cli.NewProjectOptions(o.ConfigPaths,
  184. append(po,
  185. cli.WithWorkingDirectory(o.ProjectDir),
  186. cli.WithOsEnv,
  187. cli.WithEnvFile(o.EnvFile),
  188. cli.WithDotEnv,
  189. cli.WithConfigFileEnv,
  190. cli.WithDefaultConfigPath,
  191. cli.WithName(o.ProjectName))...)
  192. }
  193. // PluginName is the name of the plugin
  194. const PluginName = "compose"
  195. // RunningAsStandalone detects when running as a standalone program
  196. func RunningAsStandalone() bool {
  197. return len(os.Args) < 2 || os.Args[1] != manager.MetadataSubcommandName && os.Args[1] != PluginName
  198. }
  199. // RootCommand returns the compose command with its child commands
  200. func RootCommand(dockerCli command.Cli, backend api.Service) *cobra.Command {
  201. opts := projectOptions{}
  202. var (
  203. ansi string
  204. noAnsi bool
  205. verbose bool
  206. version bool
  207. )
  208. c := &cobra.Command{
  209. Short: "Docker Compose",
  210. Use: PluginName,
  211. TraverseChildren: true,
  212. // By default (no Run/RunE in parent c) for typos in subcommands, cobra displays the help of parent c but exit(0) !
  213. RunE: func(cmd *cobra.Command, args []string) error {
  214. if len(args) == 0 {
  215. return cmd.Help()
  216. }
  217. if version {
  218. return versionCommand().Execute()
  219. }
  220. _ = cmd.Help()
  221. return dockercli.StatusError{
  222. StatusCode: compose.CommandSyntaxFailure.ExitCode,
  223. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  224. }
  225. },
  226. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  227. err := setEnvWithDotEnv(&opts)
  228. if err != nil {
  229. return err
  230. }
  231. parent := cmd.Root()
  232. if parent != nil {
  233. parentPrerun := parent.PersistentPreRunE
  234. if parentPrerun != nil {
  235. err := parentPrerun(cmd, args)
  236. if err != nil {
  237. return err
  238. }
  239. }
  240. }
  241. if noAnsi {
  242. if ansi != "auto" {
  243. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  244. }
  245. ansi = "never"
  246. fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n")
  247. }
  248. if verbose {
  249. logrus.SetLevel(logrus.TraceLevel)
  250. }
  251. formatter.SetANSIMode(ansi)
  252. switch ansi {
  253. case "never":
  254. progress.Mode = progress.ModePlain
  255. case "tty":
  256. progress.Mode = progress.ModeTTY
  257. }
  258. if opts.WorkDir != "" {
  259. if opts.ProjectDir != "" {
  260. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  261. }
  262. opts.ProjectDir = opts.WorkDir
  263. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  264. }
  265. return nil
  266. },
  267. }
  268. c.AddCommand(
  269. upCommand(&opts, backend),
  270. downCommand(&opts, backend),
  271. startCommand(&opts, backend),
  272. restartCommand(&opts, backend),
  273. stopCommand(&opts, backend),
  274. psCommand(&opts, backend),
  275. listCommand(backend),
  276. logsCommand(&opts, backend),
  277. convertCommand(&opts, backend),
  278. killCommand(&opts, backend),
  279. runCommand(&opts, dockerCli, backend),
  280. removeCommand(&opts, backend),
  281. execCommand(&opts, dockerCli, backend),
  282. pauseCommand(&opts, backend),
  283. unpauseCommand(&opts, backend),
  284. topCommand(&opts, backend),
  285. eventsCommand(&opts, backend),
  286. portCommand(&opts, backend),
  287. imagesCommand(&opts, backend),
  288. versionCommand(),
  289. buildCommand(&opts, backend),
  290. pushCommand(&opts, backend),
  291. pullCommand(&opts, backend),
  292. createCommand(&opts, backend),
  293. copyCommand(&opts, backend),
  294. )
  295. c.Flags().SetInterspersed(false)
  296. opts.addProjectFlags(c.Flags())
  297. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  298. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  299. c.Flags().MarkHidden("version") //nolint:errcheck
  300. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  301. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  302. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  303. c.Flags().MarkHidden("verbose") //nolint:errcheck
  304. return c
  305. }
  306. func setEnvWithDotEnv(prjOpts *projectOptions) error {
  307. options, err := prjOpts.toProjectOptions()
  308. if err != nil {
  309. return compose.WrapComposeError(err)
  310. }
  311. workingDir, err := options.GetWorkingDir()
  312. if err != nil {
  313. return err
  314. }
  315. envFromFile, err := cli.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), workingDir, options.EnvFile)
  316. if err != nil {
  317. return err
  318. }
  319. for k, v := range envFromFile {
  320. if _, ok := os.LookupEnv(k); !ok {
  321. if err := os.Setenv(k, v); err != nil {
  322. return err
  323. }
  324. }
  325. }
  326. return nil
  327. }