2
0

commands.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. package cmd
  2. import (
  3. "fmt"
  4. "os"
  5. "strings"
  6. "github.com/opencost/opencost/core/pkg/log"
  7. "github.com/opencost/opencost/pkg/cmd/agent"
  8. "github.com/opencost/opencost/pkg/cmd/costmodel"
  9. "github.com/spf13/cobra"
  10. "github.com/spf13/viper"
  11. )
  12. const (
  13. // commandRoot is the root command used to route to sub-commands
  14. commandRoot string = "root"
  15. // CommandCostModel is the command used to execute the metrics emission and ETL pipeline
  16. CommandCostModel string = "cost-model"
  17. // CommandAgent executes the application in agent mode, which provides only metrics exporting.
  18. CommandAgent string = "agent"
  19. )
  20. // Execute runs the root command for the application. By default, if no command argument is provided,
  21. // on the command line, the cost-model is executed by default.
  22. //
  23. // This function accepts a costModelCmd and agentCmd parameters to provide support for alternate
  24. // implementations for cost-model and/or agent. If the passed in costModelCmd and/or agentCmd are nil,
  25. // then the respective defaults from opencost will be used.
  26. //
  27. // Any additional commands passed in will be added to the root command.
  28. func Execute(costModelCmd *cobra.Command, cmds ...*cobra.Command) error {
  29. // use the open-source cost-model if a command is not provided
  30. if costModelCmd == nil {
  31. costModelCmd = newCostModelCommand()
  32. }
  33. // validate the commands being passed
  34. if err := validate(costModelCmd, CommandCostModel); err != nil {
  35. return err
  36. }
  37. // prepend the -agent command and create a new root command
  38. rootCmd := newRootCommand(costModelCmd, cmds...)
  39. // in the event that no directive/command is passed, we want to default to using the cost-model command
  40. // cobra doesn't provide a way within the API to do this, so we'll prepend the command if it is omitted.
  41. if len(os.Args) > 1 {
  42. // try to find the sub-command from the arguments, if there's an error or the command _is_ the
  43. // root command, prepend the default command
  44. pCmd, _, err := rootCmd.Find(os.Args[1:])
  45. if err != nil || pCmd.Use == rootCmd.Use {
  46. rootCmd.SetArgs(append([]string{CommandCostModel}, os.Args[1:]...))
  47. }
  48. } else {
  49. rootCmd.SetArgs([]string{CommandCostModel})
  50. }
  51. return rootCmd.Execute()
  52. }
  53. // newRootCommand creates a new root command which will act as a sub-command router for the
  54. // cost-model application.
  55. func newRootCommand(costModelCmd *cobra.Command, cmds ...*cobra.Command) *cobra.Command {
  56. cmd := &cobra.Command{
  57. Use: commandRoot,
  58. SilenceUsage: true,
  59. }
  60. // Add our persistent flags, these are global and available anywhere
  61. cmd.PersistentFlags().String("log-level", "info", "Set the log level")
  62. cmd.PersistentFlags().String("log-format", "pretty", "Set the log format - Can be either 'JSON' or 'pretty'")
  63. cmd.PersistentFlags().Bool("disable-log-color", false, "Disable coloring of log output")
  64. viper.BindPFlag("log-level", cmd.PersistentFlags().Lookup("log-level"))
  65. viper.BindPFlag("log-format", cmd.PersistentFlags().Lookup("log-format"))
  66. viper.BindPFlag("disable-log-color", cmd.PersistentFlags().Lookup("disable-log-color"))
  67. // Setup viper to read from the env, this allows reading flags from the command line or the env
  68. // using the format 'LOG_LEVEL'
  69. viper.AutomaticEnv()
  70. viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
  71. // add the modes of operation
  72. cmd.AddCommand(
  73. append([]*cobra.Command{
  74. costModelCmd,
  75. newAgentCommand(),
  76. }, cmds...)...,
  77. )
  78. return cmd
  79. }
  80. // default open-source cost-model command
  81. func newCostModelCommand() *cobra.Command {
  82. opts := &costmodel.CostModelOpts{}
  83. cmCmd := &cobra.Command{
  84. Use: CommandCostModel,
  85. Short: "Cost-Model metric exporter and data aggregator.",
  86. RunE: func(cmd *cobra.Command, args []string) error {
  87. // Init logging here so cobra/viper has processed the command line args and flags
  88. // otherwise only envvars are available during init
  89. log.InitLogging(true)
  90. return costmodel.Execute(opts)
  91. },
  92. }
  93. // TODO: We could introduce a way of mapping input command-line parameters to a configuration
  94. // TODO: object, and pass that object to the agent Execute()
  95. // cmCmd.Flags().<Type>VarP(&opts.<Property>, "<flag>", "<short>", <default>, "<usage>")
  96. return cmCmd
  97. }
  98. func newAgentCommand() *cobra.Command {
  99. opts := &agent.AgentOpts{}
  100. agentCmd := &cobra.Command{
  101. Use: CommandAgent,
  102. Short: "Agent mode operates as a metric exporter only.",
  103. RunE: func(cmd *cobra.Command, args []string) error {
  104. // Init logging here so cobra/viper has processed the command line args and flags
  105. // otherwise only envvars are available during init
  106. log.InitLogging(true)
  107. return agent.Execute(opts)
  108. },
  109. }
  110. // TODO: We could introduce a way of mapping input command-line parameters to a configuration
  111. // TODO: object, and pass that object to the agent Execute()
  112. // agentCmd.Flags().<Type>VarP(&opts.<Property>, "<flag>", "<short>", <default>, "<usage>")
  113. return agentCmd
  114. }
  115. // validate checks the command's use to see if it matches an expected command name.
  116. func validate(cmd *cobra.Command, command string) error {
  117. if cmd.Use != command {
  118. return fmt.Errorf("Incompatible '%s' command provided to run-time.", command)
  119. }
  120. return nil
  121. }