main.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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/pkg/errors"
  26. "github.com/sirupsen/logrus"
  27. "github.com/spf13/cobra"
  28. "github.com/docker/compose-cli/api/config"
  29. apicontext "github.com/docker/compose-cli/api/context"
  30. "github.com/docker/compose-cli/api/context/store"
  31. "github.com/docker/compose-cli/api/errdefs"
  32. "github.com/docker/compose-cli/cli/cmd"
  33. "github.com/docker/compose-cli/cli/cmd/compose"
  34. contextcmd "github.com/docker/compose-cli/cli/cmd/context"
  35. "github.com/docker/compose-cli/cli/cmd/login"
  36. "github.com/docker/compose-cli/cli/cmd/logout"
  37. "github.com/docker/compose-cli/cli/cmd/run"
  38. "github.com/docker/compose-cli/cli/cmd/volume"
  39. "github.com/docker/compose-cli/cli/metrics"
  40. "github.com/docker/compose-cli/cli/mobycli"
  41. cliopts "github.com/docker/compose-cli/cli/options"
  42. // Backend registrations
  43. _ "github.com/docker/compose-cli/aci"
  44. _ "github.com/docker/compose-cli/ecs"
  45. _ "github.com/docker/compose-cli/ecs/local"
  46. _ "github.com/docker/compose-cli/local"
  47. )
  48. var (
  49. contextAgnosticCommands = map[string]struct{}{
  50. "compose": {},
  51. "context": {},
  52. "login": {},
  53. "logout": {},
  54. "serve": {},
  55. "version": {},
  56. "backend-metadata": {},
  57. }
  58. unknownCommandRegexp = regexp.MustCompile(`unknown command "([^"]*)"`)
  59. )
  60. func init() {
  61. // initial hack to get the path of the project's bin dir
  62. // into the env of this cli for development
  63. path, err := filepath.Abs(filepath.Dir(os.Args[0]))
  64. if err != nil {
  65. fatal(errors.Wrap(err, "unable to get absolute bin path"))
  66. }
  67. if err := os.Setenv("PATH", appendPaths(os.Getenv("PATH"), path)); err != nil {
  68. panic(err)
  69. }
  70. // Seed random
  71. rand.Seed(time.Now().UnixNano())
  72. }
  73. func appendPaths(envPath string, path string) string {
  74. if envPath == "" {
  75. return path
  76. }
  77. return strings.Join([]string{envPath, path}, string(os.PathListSeparator))
  78. }
  79. func isContextAgnosticCommand(cmd *cobra.Command) bool {
  80. if cmd == nil {
  81. return false
  82. }
  83. if _, ok := contextAgnosticCommands[cmd.Name()]; ok {
  84. return true
  85. }
  86. return isContextAgnosticCommand(cmd.Parent())
  87. }
  88. func main() {
  89. var opts cliopts.GlobalOpts
  90. root := &cobra.Command{
  91. Use: "docker",
  92. SilenceErrors: true,
  93. SilenceUsage: true,
  94. TraverseChildren: true,
  95. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  96. if !isContextAgnosticCommand(cmd) {
  97. mobycli.ExecIfDefaultCtxType(cmd.Context(), cmd.Root())
  98. }
  99. return nil
  100. },
  101. RunE: func(cmd *cobra.Command, args []string) error {
  102. if len(args) == 0 {
  103. return cmd.Help()
  104. }
  105. return fmt.Errorf("unknown command %q", args[0])
  106. },
  107. }
  108. root.AddCommand(
  109. contextcmd.Command(),
  110. cmd.PsCommand(),
  111. cmd.ServeCommand(),
  112. cmd.ExecCommand(),
  113. cmd.LogsCommand(),
  114. cmd.RmCommand(),
  115. cmd.StartCommand(),
  116. cmd.InspectCommand(),
  117. login.Command(),
  118. logout.Command(),
  119. cmd.VersionCommand(),
  120. cmd.StopCommand(),
  121. cmd.KillCommand(),
  122. cmd.SecretCommand(),
  123. cmd.PruneCommand(),
  124. cmd.MetadataCommand(),
  125. // Place holders
  126. cmd.EcsCommand(),
  127. )
  128. helpFunc := root.HelpFunc()
  129. root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  130. if !isContextAgnosticCommand(cmd) {
  131. mobycli.ExecIfDefaultCtxType(cmd.Context(), cmd.Root())
  132. }
  133. helpFunc(cmd, args)
  134. })
  135. flags := root.Flags()
  136. flags.StringVarP(&opts.LogLevel, "log-level", "l", "info", "Set the logging level (\"debug\"|\"info\"|\"warn\"|\"error\"|\"fatal\")")
  137. flags.BoolVarP(&opts.Debug, "debug", "D", false, "Enable debug output in the logs")
  138. flags.StringVarP(&opts.Host, "host", "H", "", "Daemon socket(s) to connect to")
  139. opts.AddContextFlags(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. // --host and --version should immediately be forwarded to the original cli
  164. if opts.Host != "" || 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. ctx = config.WithDir(ctx, configDir)
  172. currentContext := determineCurrentContext(opts.Context, configDir)
  173. s, err := store.New(configDir)
  174. if err != nil {
  175. mobycli.Exec(root)
  176. }
  177. ctype := store.DefaultContextType
  178. cc, _ := s.Get(currentContext)
  179. if cc != nil {
  180. ctype = cc.Type()
  181. }
  182. root.AddCommand(
  183. run.Command(ctype),
  184. compose.Command(ctype),
  185. volume.Command(ctype),
  186. )
  187. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  188. ctx = store.WithContextStore(ctx, s)
  189. if err = root.ExecuteContext(ctx); err != nil {
  190. handleError(ctx, err, ctype, currentContext, cc, root)
  191. }
  192. metrics.Track(ctype, os.Args[1:], metrics.SuccessStatus)
  193. }
  194. func handleError(ctx context.Context, err error, ctype string, currentContext string, cc *store.DockerContext, root *cobra.Command) {
  195. // if user canceled request, simply exit without any error message
  196. if errdefs.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
  197. metrics.Track(ctype, os.Args[1:], metrics.CanceledStatus)
  198. os.Exit(130)
  199. }
  200. if ctype == store.AwsContextType {
  201. exit(currentContext, errors.Errorf(`%q context type has been renamed. Recreate the context by running:
  202. $ docker context create %s <name>`, cc.Type(), store.EcsContextType), ctype)
  203. }
  204. // Context should always be handled by new CLI
  205. requiredCmd, _, _ := root.Find(os.Args[1:])
  206. if requiredCmd != nil && isContextAgnosticCommand(requiredCmd) {
  207. exit(currentContext, err, ctype)
  208. }
  209. mobycli.ExecIfDefaultCtxType(ctx, root)
  210. checkIfUnknownCommandExistInDefaultContext(err, currentContext, ctype)
  211. exit(currentContext, err, ctype)
  212. }
  213. func exit(ctx string, err error, ctype string) {
  214. if exit, ok := err.(cmd.ExitCodeError); ok {
  215. metrics.Track(ctype, os.Args[1:], metrics.SuccessStatus)
  216. os.Exit(exit.ExitCode)
  217. }
  218. metrics.Track(ctype, os.Args[1:], metrics.FailureStatus)
  219. if errors.Is(err, errdefs.ErrLoginRequired) {
  220. fmt.Fprintln(os.Stderr, err)
  221. os.Exit(errdefs.ExitCodeLoginRequired)
  222. }
  223. if compose.Warning != "" {
  224. fmt.Fprintln(os.Stderr, compose.Warning)
  225. }
  226. if errors.Is(err, errdefs.ErrNotImplemented) {
  227. name := metrics.GetCommand(os.Args[1:])
  228. fmt.Fprintf(os.Stderr, "Command %q not available in current context (%s)\n", name, ctx)
  229. os.Exit(1)
  230. }
  231. fatal(err)
  232. }
  233. func fatal(err error) {
  234. fmt.Fprintln(os.Stderr, err)
  235. os.Exit(1)
  236. }
  237. func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string, contextType string) {
  238. submatch := unknownCommandRegexp.FindSubmatch([]byte(err.Error()))
  239. if len(submatch) == 2 {
  240. dockerCommand := string(submatch[1])
  241. if mobycli.IsDefaultContextCommand(dockerCommand) {
  242. 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)
  243. metrics.Track(contextType, os.Args[1:], metrics.FailureStatus)
  244. os.Exit(1)
  245. }
  246. }
  247. }
  248. func newSigContext() (context.Context, func()) {
  249. ctx, cancel := context.WithCancel(context.Background())
  250. s := make(chan os.Signal, 1)
  251. signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
  252. go func() {
  253. <-s
  254. cancel()
  255. }()
  256. return ctx, cancel
  257. }
  258. func determineCurrentContext(flag string, configDir string) string {
  259. res := flag
  260. if res == "" {
  261. config, err := config.LoadFile(configDir)
  262. if err != nil {
  263. fmt.Fprintln(os.Stderr, errors.Wrap(err, "WARNING"))
  264. return "default"
  265. }
  266. res = config.CurrentContext
  267. }
  268. if res == "" {
  269. res = "default"
  270. }
  271. return res
  272. }
  273. func walk(c *cobra.Command, f func(*cobra.Command)) {
  274. f(c)
  275. for _, c := range c.Commands() {
  276. walk(c, f)
  277. }
  278. }