compose.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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/docker/compose/v2/cmd/formatter"
  23. "github.com/sirupsen/logrus"
  24. "github.com/compose-spec/compose-go/cli"
  25. "github.com/compose-spec/compose-go/types"
  26. dockercli "github.com/docker/cli/cli"
  27. "github.com/morikuni/aec"
  28. "github.com/pkg/errors"
  29. "github.com/spf13/cobra"
  30. "github.com/spf13/pflag"
  31. "github.com/docker/compose/v2/pkg/api"
  32. "github.com/docker/compose/v2/pkg/compose"
  33. )
  34. // Command defines a compose CLI command as a func with args
  35. type Command func(context.Context, []string) error
  36. type CobraCommand func(context.Context, *cobra.Command, []string) error
  37. // AdaptCmd adapt a CobraCommand func to cobra library
  38. func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error {
  39. return func(cmd *cobra.Command, args []string) error {
  40. ctx := cmd.Context()
  41. contextString := fmt.Sprintf("%s", ctx)
  42. if !strings.HasSuffix(contextString, ".WithCancel") { // need to handle cancel
  43. cancellableCtx, cancel := context.WithCancel(cmd.Context())
  44. ctx = cancellableCtx
  45. s := make(chan os.Signal, 1)
  46. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  47. go func() {
  48. <-s
  49. cancel()
  50. }()
  51. }
  52. err := fn(ctx, cmd, args)
  53. var composeErr compose.Error
  54. if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  55. err = dockercli.StatusError{
  56. StatusCode: 130,
  57. Status: compose.CanceledStatus,
  58. }
  59. }
  60. if errors.As(err, &composeErr) {
  61. err = dockercli.StatusError{
  62. StatusCode: composeErr.GetMetricsFailureCategory().ExitCode,
  63. Status: err.Error(),
  64. }
  65. }
  66. return err
  67. }
  68. }
  69. // Adapt a Command func to cobra library
  70. func Adapt(fn Command) func(cmd *cobra.Command, args []string) error {
  71. return AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  72. return fn(ctx, args)
  73. })
  74. }
  75. // Warning is a global warning to be displayed to user on command failure
  76. var Warning string
  77. type projectOptions struct {
  78. ProjectName string
  79. Profiles []string
  80. ConfigPaths []string
  81. WorkDir string
  82. ProjectDir string
  83. EnvFile string
  84. }
  85. // ProjectFunc does stuff within a types.Project
  86. type ProjectFunc func(ctx context.Context, project *types.Project) error
  87. // ProjectServicesFunc does stuff within a types.Project and a selection of services
  88. type ProjectServicesFunc func(ctx context.Context, project *types.Project, services []string) error
  89. // WithServices creates a cobra run command from a ProjectFunc based on configured project options and selected services
  90. func (o *projectOptions) WithProject(fn ProjectFunc) func(cmd *cobra.Command, args []string) error {
  91. return o.WithServices(func(ctx context.Context, project *types.Project, services []string) error {
  92. return fn(ctx, project)
  93. })
  94. }
  95. // WithServices creates a cobra run command from a ProjectFunc based on configured project options and selected services
  96. func (o *projectOptions) WithServices(fn ProjectServicesFunc) func(cmd *cobra.Command, args []string) error {
  97. return Adapt(func(ctx context.Context, args []string) error {
  98. project, err := o.toProject(args, cli.WithResolvedPaths(true))
  99. if err != nil {
  100. return err
  101. }
  102. if o.EnvFile != "" {
  103. var services types.Services
  104. for _, s := range project.Services {
  105. ef := o.EnvFile
  106. if ef != "" {
  107. if !filepath.IsAbs(ef) {
  108. ef = filepath.Join(project.WorkingDir, o.EnvFile)
  109. }
  110. if s.Labels == nil {
  111. s.Labels = make(map[string]string)
  112. }
  113. s.Labels[api.EnvironmentFileLabel] = ef
  114. services = append(services, s)
  115. }
  116. }
  117. project.Services = services
  118. }
  119. return fn(ctx, project, args)
  120. })
  121. }
  122. func (o *projectOptions) addProjectFlags(f *pflag.FlagSet) {
  123. f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
  124. f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")
  125. f.StringArrayVarP(&o.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  126. f.StringVar(&o.EnvFile, "env-file", "", "Specify an alternate environment file.")
  127. f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the Compose file)")
  128. f.StringVar(&o.WorkDir, "workdir", "", "DEPRECATED! USE --project-directory INSTEAD.\nSpecify an alternate working directory\n(default: the path of the Compose file)")
  129. f.Bool("compatibility", false, "DEPRECATED")
  130. _ = f.MarkHidden("workdir")
  131. _ = f.MarkHidden("compatibility")
  132. }
  133. func (o *projectOptions) toProjectName() (string, error) {
  134. if o.ProjectName != "" {
  135. return o.ProjectName, nil
  136. }
  137. project, err := o.toProject(nil)
  138. if err != nil {
  139. return "", err
  140. }
  141. return project.Name, nil
  142. }
  143. func (o *projectOptions) toProject(services []string, po ...cli.ProjectOptionsFn) (*types.Project, error) {
  144. options, err := o.toProjectOptions(po...)
  145. if err != nil {
  146. return nil, compose.WrapComposeError(err)
  147. }
  148. project, err := cli.ProjectFromOptions(options)
  149. if err != nil {
  150. return nil, compose.WrapComposeError(err)
  151. }
  152. if len(services) > 0 {
  153. s, err := project.GetServices(services...)
  154. if err != nil {
  155. return nil, err
  156. }
  157. o.Profiles = append(o.Profiles, s.GetProfiles()...)
  158. }
  159. if profiles, ok := options.Environment["COMPOSE_PROFILES"]; ok {
  160. o.Profiles = append(o.Profiles, strings.Split(profiles, ",")...)
  161. }
  162. project.ApplyProfiles(o.Profiles)
  163. project.WithoutUnnecessaryResources()
  164. err = project.ForServices(services)
  165. return project, err
  166. }
  167. func (o *projectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  168. return cli.NewProjectOptions(o.ConfigPaths,
  169. append(po,
  170. cli.WithEnvFile(o.EnvFile),
  171. cli.WithDotEnv,
  172. cli.WithOsEnv,
  173. cli.WithWorkingDirectory(o.ProjectDir),
  174. cli.WithConfigFileEnv,
  175. cli.WithDefaultConfigPath,
  176. cli.WithName(o.ProjectName))...)
  177. }
  178. // RootCommand returns the compose command with its child commands
  179. func RootCommand(backend api.Service) *cobra.Command {
  180. opts := projectOptions{}
  181. var (
  182. ansi string
  183. noAnsi bool
  184. verbose bool
  185. )
  186. command := &cobra.Command{
  187. Short: "Docker Compose",
  188. Use: "compose",
  189. TraverseChildren: true,
  190. // By default (no Run/RunE in parent command) for typos in subcommands, cobra displays the help of parent command but exit(0) !
  191. RunE: func(cmd *cobra.Command, args []string) error {
  192. if len(args) == 0 {
  193. return cmd.Help()
  194. }
  195. _ = cmd.Help()
  196. return dockercli.StatusError{
  197. StatusCode: compose.CommandSyntaxFailure.ExitCode,
  198. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  199. }
  200. },
  201. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  202. parent := cmd.Root()
  203. parentPrerun := parent.PersistentPreRunE
  204. if parentPrerun != nil {
  205. err := parentPrerun(cmd, args)
  206. if err != nil {
  207. return err
  208. }
  209. }
  210. if noAnsi {
  211. if ansi != "auto" {
  212. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  213. }
  214. ansi = "never"
  215. fmt.Fprint(os.Stderr, aec.Apply("option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n", aec.RedF))
  216. }
  217. if verbose {
  218. logrus.SetLevel(logrus.TraceLevel)
  219. }
  220. formatter.SetANSIMode(ansi)
  221. if opts.WorkDir != "" {
  222. if opts.ProjectDir != "" {
  223. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  224. }
  225. opts.ProjectDir = opts.WorkDir
  226. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  227. }
  228. return nil
  229. },
  230. }
  231. command.AddCommand(
  232. upCommand(&opts, backend),
  233. downCommand(&opts, backend),
  234. startCommand(&opts, backend),
  235. restartCommand(&opts, backend),
  236. stopCommand(&opts, backend),
  237. psCommand(&opts, backend),
  238. listCommand(backend),
  239. logsCommand(&opts, backend),
  240. convertCommand(&opts, backend),
  241. killCommand(&opts, backend),
  242. runCommand(&opts, backend),
  243. removeCommand(&opts, backend),
  244. execCommand(&opts, backend),
  245. pauseCommand(&opts, backend),
  246. unpauseCommand(&opts, backend),
  247. topCommand(&opts, backend),
  248. eventsCommand(&opts, backend),
  249. portCommand(&opts, backend),
  250. imagesCommand(&opts, backend),
  251. versionCommand(),
  252. buildCommand(&opts, backend),
  253. pushCommand(&opts, backend),
  254. pullCommand(&opts, backend),
  255. createCommand(&opts, backend),
  256. copyCommand(&opts, backend),
  257. )
  258. command.Flags().SetInterspersed(false)
  259. opts.addProjectFlags(command.Flags())
  260. command.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  261. command.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  262. command.Flags().MarkHidden("no-ansi") //nolint:errcheck
  263. command.Flags().BoolVar(&verbose, "verbose", false, "Show more output")
  264. command.Flags().MarkHidden("verbose") //nolint:errcheck
  265. return command
  266. }