compose.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. "github.com/docker/buildx/util/logutil"
  26. dockercli "github.com/docker/cli/cli"
  27. "github.com/docker/cli/cli-plugins/manager"
  28. "github.com/docker/cli/cli/command"
  29. "github.com/morikuni/aec"
  30. "github.com/pkg/errors"
  31. "github.com/sirupsen/logrus"
  32. "github.com/spf13/cobra"
  33. "github.com/spf13/pflag"
  34. "github.com/docker/compose/v2/cmd/formatter"
  35. "github.com/docker/compose/v2/pkg/api"
  36. "github.com/docker/compose/v2/pkg/compose"
  37. "github.com/docker/compose/v2/pkg/progress"
  38. "github.com/docker/compose/v2/pkg/utils"
  39. )
  40. // Command defines a compose CLI command as a func with args
  41. type Command func(context.Context, []string) error
  42. // CobraCommand defines a cobra command function
  43. type CobraCommand func(context.Context, *cobra.Command, []string) error
  44. // AdaptCmd adapt a CobraCommand func to cobra library
  45. func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error {
  46. return func(cmd *cobra.Command, args []string) error {
  47. ctx := cmd.Context()
  48. contextString := fmt.Sprintf("%s", ctx)
  49. if !strings.HasSuffix(contextString, ".WithCancel") { // need to handle cancel
  50. cancellableCtx, cancel := context.WithCancel(cmd.Context())
  51. ctx = cancellableCtx
  52. s := make(chan os.Signal, 1)
  53. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  54. go func() {
  55. <-s
  56. cancel()
  57. }()
  58. }
  59. err := fn(ctx, cmd, args)
  60. var composeErr compose.Error
  61. if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  62. err = dockercli.StatusError{
  63. StatusCode: 130,
  64. Status: compose.CanceledStatus,
  65. }
  66. }
  67. if errors.As(err, &composeErr) {
  68. err = dockercli.StatusError{
  69. StatusCode: composeErr.GetMetricsFailureCategory().ExitCode,
  70. Status: err.Error(),
  71. }
  72. }
  73. return err
  74. }
  75. }
  76. // Adapt a Command func to cobra library
  77. func Adapt(fn Command) func(cmd *cobra.Command, args []string) error {
  78. return AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  79. return fn(ctx, args)
  80. })
  81. }
  82. type projectOptions struct {
  83. ProjectName string
  84. Profiles []string
  85. ConfigPaths []string
  86. WorkDir string
  87. ProjectDir string
  88. EnvFile string
  89. Compatibility bool
  90. }
  91. // ProjectFunc does stuff within a types.Project
  92. type ProjectFunc func(ctx context.Context, project *types.Project) error
  93. // ProjectServicesFunc does stuff within a types.Project and a selection of services
  94. type ProjectServicesFunc func(ctx context.Context, project *types.Project, services []string) error
  95. // WithProject creates a cobra run command from a ProjectFunc based on configured project options and selected services
  96. func (o *projectOptions) WithProject(fn ProjectFunc) func(cmd *cobra.Command, args []string) error {
  97. return o.WithServices(func(ctx context.Context, project *types.Project, services []string) error {
  98. return fn(ctx, project)
  99. })
  100. }
  101. // WithServices creates a cobra run command from a ProjectFunc based on configured project options and selected services
  102. func (o *projectOptions) WithServices(fn ProjectServicesFunc) func(cmd *cobra.Command, args []string) error {
  103. return Adapt(func(ctx context.Context, args []string) error {
  104. project, err := o.toProject(args, cli.WithResolvedPaths(true))
  105. if err != nil {
  106. return err
  107. }
  108. return fn(ctx, project, args)
  109. })
  110. }
  111. func (o *projectOptions) addProjectFlags(f *pflag.FlagSet) {
  112. f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
  113. f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")
  114. f.StringArrayVarP(&o.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  115. f.StringVar(&o.EnvFile, "env-file", "", "Specify an alternate environment file.")
  116. f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the, first specified, Compose file)")
  117. 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)")
  118. f.BoolVar(&o.Compatibility, "compatibility", false, "Run compose in backward compatibility mode")
  119. _ = f.MarkHidden("workdir")
  120. }
  121. func (o *projectOptions) projectOrName(services ...string) (*types.Project, string, error) {
  122. name := o.ProjectName
  123. var project *types.Project
  124. if len(o.ConfigPaths) > 0 || o.ProjectName == "" {
  125. p, err := o.toProject(services)
  126. if err != nil {
  127. envProjectName := os.Getenv("COMPOSE_PROJECT_NAME")
  128. if envProjectName != "" {
  129. return nil, envProjectName, nil
  130. }
  131. return nil, "", err
  132. }
  133. project = p
  134. name = p.Name
  135. }
  136. return project, name, nil
  137. }
  138. func (o *projectOptions) toProjectName() (string, error) {
  139. if o.ProjectName != "" {
  140. return o.ProjectName, nil
  141. }
  142. envProjectName := os.Getenv("COMPOSE_PROJECT_NAME")
  143. if envProjectName != "" {
  144. return envProjectName, nil
  145. }
  146. project, err := o.toProject(nil)
  147. if err != nil {
  148. return "", err
  149. }
  150. return project.Name, nil
  151. }
  152. func (o *projectOptions) toProject(services []string, po ...cli.ProjectOptionsFn) (*types.Project, error) {
  153. options, err := o.toProjectOptions(po...)
  154. if err != nil {
  155. return nil, compose.WrapComposeError(err)
  156. }
  157. if o.Compatibility || utils.StringToBool(options.Environment["COMPOSE_COMPATIBILITY"]) {
  158. api.Separator = "_"
  159. }
  160. project, err := cli.ProjectFromOptions(options)
  161. if err != nil {
  162. return nil, compose.WrapComposeError(err)
  163. }
  164. for i, s := range project.Services {
  165. s.CustomLabels = map[string]string{
  166. api.ProjectLabel: project.Name,
  167. api.ServiceLabel: s.Name,
  168. api.VersionLabel: api.ComposeVersion,
  169. api.WorkingDirLabel: project.WorkingDir,
  170. api.ConfigFilesLabel: strings.Join(project.ComposeFiles, ","),
  171. api.OneoffLabel: "False", // default, will be overridden by `run` command
  172. }
  173. if o.EnvFile != "" {
  174. s.CustomLabels[api.EnvironmentFileLabel] = o.EnvFile
  175. }
  176. project.Services[i] = s
  177. }
  178. if profiles, ok := options.Environment["COMPOSE_PROFILES"]; ok && len(o.Profiles) == 0 {
  179. o.Profiles = append(o.Profiles, strings.Split(profiles, ",")...)
  180. }
  181. if len(services) > 0 {
  182. s, err := project.GetServices(services...)
  183. if err != nil {
  184. return nil, err
  185. }
  186. o.Profiles = append(o.Profiles, s.GetProfiles()...)
  187. }
  188. project.ApplyProfiles(o.Profiles)
  189. project.WithoutUnnecessaryResources()
  190. err = project.ForServices(services)
  191. return project, err
  192. }
  193. func (o *projectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  194. return cli.NewProjectOptions(o.ConfigPaths,
  195. append(po,
  196. cli.WithWorkingDirectory(o.ProjectDir),
  197. cli.WithOsEnv,
  198. cli.WithEnvFile(o.EnvFile),
  199. cli.WithDotEnv,
  200. cli.WithConfigFileEnv,
  201. cli.WithDefaultConfigPath,
  202. cli.WithName(o.ProjectName))...)
  203. }
  204. // PluginName is the name of the plugin
  205. const PluginName = "compose"
  206. // RunningAsStandalone detects when running as a standalone program
  207. func RunningAsStandalone() bool {
  208. return len(os.Args) < 2 || os.Args[1] != manager.MetadataSubcommandName && os.Args[1] != PluginName
  209. }
  210. // RootCommand returns the compose command with its child commands
  211. func RootCommand(dockerCli command.Cli, backend api.Service) *cobra.Command { //nolint:gocyclo
  212. // filter out useless commandConn.CloseWrite warning message that can occur
  213. // when using a remote context that is unreachable: "commandConn.CloseWrite: commandconn: failed to wait: signal: killed"
  214. // https://github.com/docker/cli/blob/e1f24d3c93df6752d3c27c8d61d18260f141310c/cli/connhelper/commandconn/commandconn.go#L203-L215
  215. logrus.AddHook(logutil.NewFilter([]logrus.Level{
  216. logrus.WarnLevel,
  217. },
  218. "commandConn.CloseWrite:",
  219. "commandConn.CloseRead:",
  220. ))
  221. opts := projectOptions{}
  222. var (
  223. ansi string
  224. noAnsi bool
  225. verbose bool
  226. version bool
  227. parallel int
  228. )
  229. c := &cobra.Command{
  230. Short: "Docker Compose",
  231. Use: PluginName,
  232. TraverseChildren: true,
  233. // By default (no Run/RunE in parent c) for typos in subcommands, cobra displays the help of parent c but exit(0) !
  234. RunE: func(cmd *cobra.Command, args []string) error {
  235. if len(args) == 0 {
  236. return cmd.Help()
  237. }
  238. if version {
  239. return versionCommand().Execute()
  240. }
  241. _ = cmd.Help()
  242. return dockercli.StatusError{
  243. StatusCode: compose.CommandSyntaxFailure.ExitCode,
  244. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  245. }
  246. },
  247. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  248. err := setEnvWithDotEnv(&opts)
  249. if err != nil {
  250. return err
  251. }
  252. parent := cmd.Root()
  253. if parent != nil {
  254. parentPrerun := parent.PersistentPreRunE
  255. if parentPrerun != nil {
  256. err := parentPrerun(cmd, args)
  257. if err != nil {
  258. return err
  259. }
  260. }
  261. }
  262. if noAnsi {
  263. if ansi != "auto" {
  264. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  265. }
  266. ansi = "never"
  267. fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n")
  268. }
  269. if verbose {
  270. logrus.SetLevel(logrus.TraceLevel)
  271. }
  272. formatter.SetANSIMode(ansi)
  273. switch ansi {
  274. case "never":
  275. progress.Mode = progress.ModePlain
  276. case "tty":
  277. progress.Mode = progress.ModeTTY
  278. }
  279. if opts.WorkDir != "" {
  280. if opts.ProjectDir != "" {
  281. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  282. }
  283. opts.ProjectDir = opts.WorkDir
  284. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  285. }
  286. if opts.EnvFile != "" && !filepath.IsAbs(opts.EnvFile) {
  287. opts.EnvFile, err = filepath.Abs(opts.EnvFile)
  288. if err != nil {
  289. return err
  290. }
  291. }
  292. if parallel > 0 {
  293. backend.MaxConcurrency(parallel)
  294. }
  295. return nil
  296. },
  297. }
  298. c.AddCommand(
  299. upCommand(&opts, backend),
  300. downCommand(&opts, backend),
  301. startCommand(&opts, backend),
  302. restartCommand(&opts, backend),
  303. stopCommand(&opts, backend),
  304. psCommand(&opts, backend),
  305. listCommand(backend),
  306. logsCommand(&opts, backend),
  307. convertCommand(&opts, backend),
  308. killCommand(&opts, backend),
  309. runCommand(&opts, dockerCli, backend),
  310. removeCommand(&opts, backend),
  311. execCommand(&opts, dockerCli, backend),
  312. pauseCommand(&opts, backend),
  313. unpauseCommand(&opts, backend),
  314. topCommand(&opts, backend),
  315. eventsCommand(&opts, backend),
  316. portCommand(&opts, backend),
  317. imagesCommand(&opts, backend),
  318. versionCommand(),
  319. buildCommand(&opts, backend),
  320. pushCommand(&opts, backend),
  321. pullCommand(&opts, backend),
  322. createCommand(&opts, backend),
  323. copyCommand(&opts, backend),
  324. )
  325. c.Flags().SetInterspersed(false)
  326. opts.addProjectFlags(c.Flags())
  327. c.RegisterFlagCompletionFunc( //nolint:errcheck
  328. "project-name",
  329. completeProjectNames(backend),
  330. )
  331. c.RegisterFlagCompletionFunc( //nolint:errcheck
  332. "file",
  333. func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  334. return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt
  335. },
  336. )
  337. c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  338. c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`)
  339. c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information")
  340. c.Flags().MarkHidden("version") //nolint:errcheck
  341. c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  342. c.Flags().MarkHidden("no-ansi") //nolint:errcheck
  343. c.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  344. c.Flags().MarkHidden("verbose") //nolint:errcheck
  345. return c
  346. }
  347. func setEnvWithDotEnv(prjOpts *projectOptions) error {
  348. options, err := prjOpts.toProjectOptions()
  349. if err != nil {
  350. return compose.WrapComposeError(err)
  351. }
  352. workingDir, err := options.GetWorkingDir()
  353. if err != nil {
  354. return err
  355. }
  356. envFromFile, err := cli.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), workingDir, options.EnvFile)
  357. if err != nil {
  358. return err
  359. }
  360. for k, v := range envFromFile {
  361. if _, ok := os.LookupEnv(k); !ok { // Precedence to OS Env
  362. if err := os.Setenv(k, v); err != nil {
  363. return err
  364. }
  365. }
  366. }
  367. return nil
  368. }