compose.go 9.5 KB

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