compose.go 8.9 KB

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