compose.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. "strings"
  20. "syscall"
  21. "github.com/compose-spec/compose-go/cli"
  22. "github.com/compose-spec/compose-go/types"
  23. dockercli "github.com/docker/cli/cli"
  24. "github.com/morikuni/aec"
  25. "github.com/pkg/errors"
  26. "github.com/spf13/cobra"
  27. "github.com/spf13/pflag"
  28. "github.com/docker/compose-cli/api/compose"
  29. "github.com/docker/compose-cli/api/context/store"
  30. "github.com/docker/compose-cli/api/errdefs"
  31. "github.com/docker/compose-cli/cli/formatter"
  32. "github.com/docker/compose-cli/cli/metrics"
  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 metrics.ComposeError
  53. if errdefs.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  54. err = dockercli.StatusError{
  55. StatusCode: 130,
  56. Status: metrics.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. func (o *projectOptions) addProjectFlags(f *pflag.FlagSet) {
  79. f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable")
  80. f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name")
  81. f.StringArrayVarP(&o.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  82. f.StringVar(&o.EnvFile, "env-file", "", "Specify an alternate environment file.")
  83. f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the Compose file)")
  84. f.StringVar(&o.WorkDir, "workdir", "", "DEPRECATED! USE --project-directory INSTEAD.\nSpecify an alternate working directory\n(default: the path of the Compose file)")
  85. _ = f.MarkHidden("workdir")
  86. }
  87. func (o *projectOptions) toProjectName() (string, error) {
  88. if o.ProjectName != "" {
  89. return o.ProjectName, nil
  90. }
  91. project, err := o.toProject(nil)
  92. if err != nil {
  93. return "", err
  94. }
  95. return project.Name, nil
  96. }
  97. func (o *projectOptions) toProject(services []string, po ...cli.ProjectOptionsFn) (*types.Project, error) {
  98. options, err := o.toProjectOptions(po...)
  99. if err != nil {
  100. return nil, metrics.WrapComposeError(err)
  101. }
  102. project, err := cli.ProjectFromOptions(options)
  103. if err != nil {
  104. return nil, metrics.WrapComposeError(err)
  105. }
  106. if len(services) > 0 {
  107. s, err := project.GetServices(services...)
  108. if err != nil {
  109. return nil, err
  110. }
  111. o.Profiles = append(o.Profiles, s.GetProfiles()...)
  112. }
  113. if profiles, ok := options.Environment["COMPOSE_PROFILES"]; ok {
  114. o.Profiles = append(o.Profiles, strings.Split(profiles, ",")...)
  115. }
  116. project.ApplyProfiles(o.Profiles)
  117. err = project.ForServices(services)
  118. return project, err
  119. }
  120. func (o *projectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
  121. return cli.NewProjectOptions(o.ConfigPaths,
  122. append(po,
  123. cli.WithEnvFile(o.EnvFile),
  124. cli.WithDotEnv,
  125. cli.WithOsEnv,
  126. cli.WithWorkingDirectory(o.ProjectDir),
  127. cli.WithConfigFileEnv,
  128. cli.WithDefaultConfigPath,
  129. cli.WithName(o.ProjectName))...)
  130. }
  131. // RootCommand returns the compose command with its child commands
  132. func RootCommand(contextType string, backend compose.Service) *cobra.Command {
  133. opts := projectOptions{}
  134. var ansi string
  135. var noAnsi bool
  136. command := &cobra.Command{
  137. Short: "Docker Compose",
  138. Use: "compose",
  139. TraverseChildren: true,
  140. // By default (no Run/RunE in parent command) for typos in subcommands, cobra displays the help of parent command but exit(0) !
  141. RunE: func(cmd *cobra.Command, args []string) error {
  142. if len(args) == 0 {
  143. return cmd.Help()
  144. }
  145. _ = cmd.Help()
  146. return dockercli.StatusError{
  147. StatusCode: metrics.CommandSyntaxFailure.ExitCode,
  148. Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
  149. }
  150. },
  151. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  152. parent := cmd.Root()
  153. parentPrerun := parent.PersistentPreRunE
  154. if parentPrerun != nil {
  155. err := parentPrerun(cmd, args)
  156. if err != nil {
  157. return err
  158. }
  159. }
  160. if noAnsi {
  161. if ansi != "auto" {
  162. return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`)
  163. }
  164. ansi = "never"
  165. fmt.Fprint(os.Stderr, aec.Apply("option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n", aec.RedF))
  166. }
  167. formatter.SetANSIMode(ansi)
  168. if opts.WorkDir != "" {
  169. if opts.ProjectDir != "" {
  170. return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`)
  171. }
  172. opts.ProjectDir = opts.WorkDir
  173. fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF))
  174. }
  175. if contextType == store.DefaultContextType || contextType == store.LocalContextType {
  176. Warning = "The new 'docker compose' command is currently experimental. " +
  177. "To provide feedback or request new features please open issues at https://github.com/docker/compose-cli"
  178. }
  179. return nil
  180. },
  181. }
  182. command.AddCommand(
  183. upCommand(&opts, contextType, backend),
  184. downCommand(&opts, contextType, backend),
  185. startCommand(&opts, backend),
  186. restartCommand(&opts, backend),
  187. stopCommand(&opts, backend),
  188. psCommand(&opts, backend),
  189. listCommand(contextType, backend),
  190. logsCommand(&opts, contextType, backend),
  191. convertCommand(&opts, backend),
  192. killCommand(&opts, backend),
  193. runCommand(&opts, backend),
  194. removeCommand(&opts, backend),
  195. execCommand(&opts, backend),
  196. pauseCommand(&opts, backend),
  197. unpauseCommand(&opts, backend),
  198. topCommand(&opts, backend),
  199. eventsCommand(&opts, backend),
  200. portCommand(&opts, backend),
  201. imagesCommand(&opts, backend),
  202. versionCommand(),
  203. )
  204. if contextType == store.LocalContextType || contextType == store.DefaultContextType {
  205. command.AddCommand(
  206. buildCommand(&opts, backend),
  207. pushCommand(&opts, backend),
  208. pullCommand(&opts, backend),
  209. createCommand(&opts, backend),
  210. copyCommand(&opts, backend),
  211. )
  212. }
  213. command.Flags().SetInterspersed(false)
  214. opts.addProjectFlags(command.Flags())
  215. command.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`)
  216. command.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`)
  217. command.Flags().MarkHidden("no-ansi") //nolint:errcheck
  218. return command
  219. }