main.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 main
  14. import (
  15. "context"
  16. "fmt"
  17. "math/rand"
  18. "os"
  19. "os/signal"
  20. "path/filepath"
  21. "regexp"
  22. "strings"
  23. "syscall"
  24. "time"
  25. "github.com/docker/cli/cli"
  26. "github.com/pkg/errors"
  27. "github.com/sirupsen/logrus"
  28. "github.com/spf13/cobra"
  29. "github.com/docker/compose-cli/api/backend"
  30. "github.com/docker/compose-cli/api/config"
  31. apicontext "github.com/docker/compose-cli/api/context"
  32. "github.com/docker/compose-cli/api/context/store"
  33. "github.com/docker/compose-cli/api/errdefs"
  34. "github.com/docker/compose-cli/cli/cmd"
  35. "github.com/docker/compose-cli/cli/cmd/compose"
  36. contextcmd "github.com/docker/compose-cli/cli/cmd/context"
  37. "github.com/docker/compose-cli/cli/cmd/login"
  38. "github.com/docker/compose-cli/cli/cmd/logout"
  39. "github.com/docker/compose-cli/cli/cmd/run"
  40. "github.com/docker/compose-cli/cli/cmd/volume"
  41. cliconfig "github.com/docker/compose-cli/cli/config"
  42. "github.com/docker/compose-cli/cli/metrics"
  43. "github.com/docker/compose-cli/cli/mobycli"
  44. cliopts "github.com/docker/compose-cli/cli/options"
  45. "github.com/docker/compose-cli/local"
  46. // Backend registrations
  47. _ "github.com/docker/compose-cli/aci"
  48. _ "github.com/docker/compose-cli/ecs"
  49. _ "github.com/docker/compose-cli/ecs/local"
  50. _ "github.com/docker/compose-cli/local"
  51. )
  52. var (
  53. contextAgnosticCommands = map[string]struct{}{
  54. "context": {},
  55. "login": {},
  56. "logout": {},
  57. "serve": {},
  58. "version": {},
  59. "backend-metadata": {},
  60. }
  61. unknownCommandRegexp = regexp.MustCompile(`unknown docker command: "([^"]*)"`)
  62. )
  63. func init() {
  64. // initial hack to get the path of the project's bin dir
  65. // into the env of this cli for development
  66. path, err := filepath.Abs(filepath.Dir(os.Args[0]))
  67. if err != nil {
  68. fatal(errors.Wrap(err, "unable to get absolute bin path"))
  69. }
  70. if err := os.Setenv("PATH", appendPaths(os.Getenv("PATH"), path)); err != nil {
  71. panic(err)
  72. }
  73. // Seed random
  74. rand.Seed(time.Now().UnixNano())
  75. }
  76. func appendPaths(envPath string, path string) string {
  77. if envPath == "" {
  78. return path
  79. }
  80. return strings.Join([]string{envPath, path}, string(os.PathListSeparator))
  81. }
  82. func isContextAgnosticCommand(cmd *cobra.Command) bool {
  83. if cmd == nil {
  84. return false
  85. }
  86. if _, ok := contextAgnosticCommands[cmd.Name()]; ok {
  87. return true
  88. }
  89. return isContextAgnosticCommand(cmd.Parent())
  90. }
  91. func main() {
  92. var opts cliopts.GlobalOpts
  93. root := &cobra.Command{
  94. Use: "docker",
  95. SilenceErrors: true,
  96. SilenceUsage: true,
  97. TraverseChildren: true,
  98. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  99. if !isContextAgnosticCommand(cmd) {
  100. mobycli.ExecIfDefaultCtxType(cmd.Context(), cmd.Root())
  101. }
  102. return nil
  103. },
  104. RunE: func(cmd *cobra.Command, args []string) error {
  105. if len(args) == 0 {
  106. return cmd.Help()
  107. }
  108. return fmt.Errorf("unknown docker command: %q", args[0])
  109. },
  110. }
  111. root.AddCommand(
  112. contextcmd.Command(),
  113. cmd.PsCommand(),
  114. cmd.ServeCommand(),
  115. cmd.ExecCommand(),
  116. cmd.LogsCommand(),
  117. cmd.RmCommand(),
  118. cmd.StartCommand(),
  119. cmd.InspectCommand(),
  120. login.Command(),
  121. logout.Command(),
  122. cmd.VersionCommand(),
  123. cmd.StopCommand(),
  124. cmd.KillCommand(),
  125. cmd.SecretCommand(),
  126. cmd.PruneCommand(),
  127. cmd.MetadataCommand(),
  128. // Place holders
  129. cmd.EcsCommand(),
  130. )
  131. helpFunc := root.HelpFunc()
  132. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  133. if !isContextAgnosticCommand(cmd) {
  134. mobycli.ExecIfDefaultCtxType(cmd.Context(), cmd.Root())
  135. }
  136. helpFunc(cmd, args)
  137. })
  138. flags := root.Flags()
  139. opts.InstallFlags(flags)
  140. opts.AddConfigFlags(flags)
  141. flags.BoolVarP(&opts.Version, "version", "v", false, "Print version information and quit")
  142. flags.SetInterspersed(false)
  143. walk(root, func(c *cobra.Command) {
  144. c.Flags().BoolP("help", "h", false, "Help for "+c.Name())
  145. })
  146. // populate the opts with the global flags
  147. flags.Parse(os.Args[1:]) //nolint: errcheck
  148. level, err := logrus.ParseLevel(opts.LogLevel)
  149. if err != nil {
  150. fmt.Fprintf(os.Stderr, "Unable to parse logging level: %s\n", opts.LogLevel)
  151. os.Exit(1)
  152. }
  153. logrus.SetFormatter(&logrus.TextFormatter{
  154. DisableTimestamp: true,
  155. DisableLevelTruncation: true,
  156. })
  157. logrus.SetLevel(level)
  158. if opts.Debug {
  159. logrus.SetLevel(logrus.DebugLevel)
  160. }
  161. ctx, cancel := newSigContext()
  162. defer cancel()
  163. // --version should immediately be forwarded to the original cli
  164. if opts.Version {
  165. mobycli.Exec(root)
  166. }
  167. if opts.Config == "" {
  168. fatal(errors.New("config path cannot be empty"))
  169. }
  170. configDir := opts.Config
  171. config.WithDir(configDir)
  172. currentContext := cliconfig.GetCurrentContext(opts.Context, configDir, opts.Hosts)
  173. apicontext.WithCurrentContext(currentContext)
  174. s, err := store.New(configDir)
  175. if err != nil {
  176. mobycli.Exec(root)
  177. }
  178. store.WithContextStore(s)
  179. ctype := store.DefaultContextType
  180. cc, _ := s.Get(currentContext)
  181. if cc != nil {
  182. ctype = cc.Type()
  183. }
  184. service, err := getBackend(ctype, configDir, opts)
  185. if err != nil {
  186. fatal(err)
  187. }
  188. backend.WithBackend(service)
  189. root.AddCommand(
  190. run.Command(ctype),
  191. volume.Command(ctype),
  192. )
  193. if ctype != store.DefaultContextType {
  194. // On default context, "compose" is implemented by CLI Plugin
  195. root.AddCommand(compose.RootCommand(ctype, service.ComposeService()))
  196. }
  197. if err = root.ExecuteContext(ctx); err != nil {
  198. handleError(ctx, err, ctype, currentContext, cc, root)
  199. }
  200. metrics.Track(ctype, os.Args[1:], metrics.SuccessStatus)
  201. }
  202. func getBackend(ctype string, configDir string, opts cliopts.GlobalOpts) (backend.Service, error) {
  203. switch ctype {
  204. case store.DefaultContextType, store.LocalContextType:
  205. return local.GetLocalBackend(configDir, opts)
  206. }
  207. service, err := backend.Get(ctype)
  208. if errdefs.IsNotFoundError(err) {
  209. return service, nil
  210. }
  211. return service, err
  212. }
  213. func handleError(ctx context.Context, err error, ctype string, currentContext string, cc *store.DockerContext, root *cobra.Command) {
  214. // if user canceled request, simply exit without any error message
  215. if errdefs.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  216. metrics.Track(ctype, os.Args[1:], metrics.CanceledStatus)
  217. os.Exit(130)
  218. }
  219. if ctype == store.AwsContextType {
  220. exit(currentContext, errors.Errorf(`%q context type has been renamed. Recreate the context by running:
  221. $ docker context create %s <name>`, cc.Type(), store.EcsContextType), ctype)
  222. }
  223. // Context should always be handled by new CLI
  224. requiredCmd, _, _ := root.Find(os.Args[1:])
  225. if requiredCmd != nil && isContextAgnosticCommand(requiredCmd) {
  226. exit(currentContext, err, ctype)
  227. }
  228. mobycli.ExecIfDefaultCtxType(ctx, root)
  229. checkIfUnknownCommandExistInDefaultContext(err, currentContext, ctype)
  230. exit(currentContext, err, ctype)
  231. }
  232. func exit(ctx string, err error, ctype string) {
  233. if exit, ok := err.(cli.StatusError); ok {
  234. metrics.Track(ctype, os.Args[1:], metrics.SuccessStatus)
  235. os.Exit(exit.StatusCode)
  236. }
  237. var composeErr metrics.ComposeError
  238. metricsStatus := metrics.FailureStatus
  239. exitCode := 1
  240. if errors.As(err, &composeErr) {
  241. metricsStatus = composeErr.GetMetricsFailureCategory().MetricsStatus
  242. exitCode = composeErr.GetMetricsFailureCategory().ExitCode
  243. }
  244. if strings.HasPrefix(err.Error(), "unknown shorthand flag:") || strings.HasPrefix(err.Error(), "unknown flag:") || strings.HasPrefix(err.Error(), "unknown docker command:") {
  245. metricsStatus = metrics.CommandSyntaxFailure.MetricsStatus
  246. exitCode = metrics.CommandSyntaxFailure.ExitCode
  247. }
  248. metrics.Track(ctype, os.Args[1:], metricsStatus)
  249. if errors.Is(err, errdefs.ErrLoginRequired) {
  250. fmt.Fprintln(os.Stderr, err)
  251. os.Exit(errdefs.ExitCodeLoginRequired)
  252. }
  253. if compose.Warning != "" {
  254. logrus.Warn(err)
  255. fmt.Fprintln(os.Stderr, compose.Warning)
  256. }
  257. if errors.Is(err, errdefs.ErrNotImplemented) {
  258. name := metrics.GetCommand(os.Args[1:])
  259. fmt.Fprintf(os.Stderr, "Command %q not available in current context (%s)\n", name, ctx)
  260. os.Exit(1)
  261. }
  262. fmt.Fprintln(os.Stderr, err)
  263. os.Exit(exitCode)
  264. }
  265. func fatal(err error) {
  266. fmt.Fprintln(os.Stderr, err)
  267. os.Exit(1)
  268. }
  269. func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string, contextType string) {
  270. submatch := unknownCommandRegexp.FindSubmatch([]byte(err.Error()))
  271. if len(submatch) == 2 {
  272. dockerCommand := string(submatch[1])
  273. if mobycli.IsDefaultContextCommand(dockerCommand) {
  274. fmt.Fprintf(os.Stderr, "Command %q not available in current context (%s), you can use the \"default\" context to run this command\n", dockerCommand, currentContext)
  275. metrics.Track(contextType, os.Args[1:], metrics.FailureStatus)
  276. os.Exit(1)
  277. }
  278. }
  279. }
  280. func newSigContext() (context.Context, func()) {
  281. ctx, cancel := context.WithCancel(context.Background())
  282. s := make(chan os.Signal, 1)
  283. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  284. go func() {
  285. <-s
  286. cancel()
  287. }()
  288. return ctx, cancel
  289. }
  290. func walk(c *cobra.Command, f func(*cobra.Command)) {
  291. f(c)
  292. for _, c := range c.Commands() {
  293. walk(c, f)
  294. }
  295. }