compose.go 9.4 KB

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