compose.go 13 KB

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