compose.go 12 KB

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