compose.go 13 KB

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