main.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. compose.Command(ctype, service.ComposeService()),
  192. volume.Command(ctype),
  193. )
  194. if err = root.ExecuteContext(ctx); err != nil {
  195. handleError(ctx, err, ctype, currentContext, cc, root)
  196. }
  197. metrics.Track(ctype, os.Args[1:], metrics.SuccessStatus)
  198. }
  199. func getBackend(ctype string, configDir string, opts cliopts.GlobalOpts) (backend.Service, error) {
  200. switch ctype {
  201. case store.DefaultContextType, store.LocalContextType:
  202. return local.GetLocalBackend(configDir, opts)
  203. }
  204. service, err := backend.Get(ctype)
  205. if errdefs.IsNotFoundError(err) {
  206. return service, nil
  207. }
  208. return service, err
  209. }
  210. func handleError(ctx context.Context, err error, ctype string, currentContext string, cc *store.DockerContext, root *cobra.Command) {
  211. // if user canceled request, simply exit without any error message
  212. if errdefs.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  213. metrics.Track(ctype, os.Args[1:], metrics.CanceledStatus)
  214. os.Exit(130)
  215. }
  216. if ctype == store.AwsContextType {
  217. exit(currentContext, errors.Errorf(`%q context type has been renamed. Recreate the context by running:
  218. $ docker context create %s <name>`, cc.Type(), store.EcsContextType), ctype)
  219. }
  220. // Context should always be handled by new CLI
  221. requiredCmd, _, _ := root.Find(os.Args[1:])
  222. if requiredCmd != nil && isContextAgnosticCommand(requiredCmd) {
  223. exit(currentContext, err, ctype)
  224. }
  225. mobycli.ExecIfDefaultCtxType(ctx, root)
  226. checkIfUnknownCommandExistInDefaultContext(err, currentContext, ctype)
  227. exit(currentContext, err, ctype)
  228. }
  229. func exit(ctx string, err error, ctype string) {
  230. if exit, ok := err.(cli.StatusError); ok {
  231. metrics.Track(ctype, os.Args[1:], metrics.SuccessStatus)
  232. os.Exit(exit.StatusCode)
  233. }
  234. var composeErr metrics.ComposeError
  235. metricsStatus := metrics.FailureStatus
  236. exitCode := 1
  237. if errors.As(err, &composeErr) {
  238. metricsStatus = composeErr.GetMetricsFailureCategory().MetricsStatus
  239. exitCode = composeErr.GetMetricsFailureCategory().ExitCode
  240. }
  241. if strings.HasPrefix(err.Error(), "unknown shorthand flag:") || strings.HasPrefix(err.Error(), "unknown flag:") || strings.HasPrefix(err.Error(), "unknown docker command:") {
  242. metricsStatus = metrics.CommandSyntaxFailure.MetricsStatus
  243. exitCode = metrics.CommandSyntaxFailure.ExitCode
  244. }
  245. metrics.Track(ctype, os.Args[1:], metricsStatus)
  246. if errors.Is(err, errdefs.ErrLoginRequired) {
  247. fmt.Fprintln(os.Stderr, err)
  248. os.Exit(errdefs.ExitCodeLoginRequired)
  249. }
  250. if compose.Warning != "" {
  251. logrus.Warn(err)
  252. fmt.Fprintln(os.Stderr, compose.Warning)
  253. }
  254. if errors.Is(err, errdefs.ErrNotImplemented) {
  255. name := metrics.GetCommand(os.Args[1:])
  256. fmt.Fprintf(os.Stderr, "Command %q not available in current context (%s)\n", name, ctx)
  257. os.Exit(1)
  258. }
  259. fmt.Fprintln(os.Stderr, err)
  260. os.Exit(exitCode)
  261. }
  262. func fatal(err error) {
  263. fmt.Fprintln(os.Stderr, err)
  264. os.Exit(1)
  265. }
  266. func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string, contextType string) {
  267. submatch := unknownCommandRegexp.FindSubmatch([]byte(err.Error()))
  268. if len(submatch) == 2 {
  269. dockerCommand := string(submatch[1])
  270. if mobycli.IsDefaultContextCommand(dockerCommand) {
  271. 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)
  272. metrics.Track(contextType, os.Args[1:], metrics.FailureStatus)
  273. os.Exit(1)
  274. }
  275. }
  276. }
  277. func newSigContext() (context.Context, func()) {
  278. ctx, cancel := context.WithCancel(context.Background())
  279. s := make(chan os.Signal, 1)
  280. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  281. go func() {
  282. <-s
  283. cancel()
  284. }()
  285. return ctx, cancel
  286. }
  287. func walk(c *cobra.Command, f func(*cobra.Command)) {
  288. f(c)
  289. for _, c := range c.Commands() {
  290. walk(c, f)
  291. }
  292. }