compose.go 12 KB

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