main.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "github.com/opencost/opencost/core/pkg/log"
  7. "github.com/opencost/opencost/core/pkg/pricing"
  8. "github.com/opencost/opencost/core/pkg/unit"
  9. "github.com/opencost/opencost/modules/pricing/public"
  10. "github.com/spf13/cobra"
  11. )
  12. var (
  13. provider string
  14. currency string
  15. output string
  16. )
  17. func main() {
  18. if err := rootCmd.Execute(); err != nil {
  19. fmt.Fprintf(os.Stderr, "Error: %v\n", err)
  20. os.Exit(1)
  21. }
  22. }
  23. var rootCmd = &cobra.Command{
  24. Use: "fetch-pricing",
  25. Short: "Fetch cloud provider pricing data",
  26. Long: `Fetch pricing data from a cloud provider and output as JSON.`,
  27. RunE: run,
  28. }
  29. func init() {
  30. rootCmd.Flags().StringVarP(&provider, "provider", "p", "aws", "Cloud provider (aws, azure, gcp, all). Default: aws")
  31. rootCmd.Flags().StringVarP(&currency, "currency", "c", "USD", "Currency code (e.g. USD, EUR, CNY). Default: USD")
  32. rootCmd.Flags().StringVarP(&output, "output", "o", "", "Output file path. Default: /pricing-data/{provider}-{currency}.json. Use 'stdout' to print to console")
  33. }
  34. func run(cmd *cobra.Command, args []string) error {
  35. curr, err := unit.ParseCurrency(currency)
  36. if err != nil {
  37. return fmt.Errorf("invalid currency '%s': %w", currency, err)
  38. }
  39. var prov pricing.Provider
  40. switch provider {
  41. case "all":
  42. prov = pricing.AllProvider
  43. case "aws":
  44. prov = pricing.AWSProvider
  45. case "azure":
  46. prov = pricing.AzureProvider
  47. case "gcp":
  48. prov = pricing.GCPProvider
  49. default:
  50. return fmt.Errorf("unsupported provider: %s", provider)
  51. }
  52. log.Infof("Generating pricing for %s in %s", prov, curr)
  53. pricingSet, err := public.GeneratePricingForProvider(prov, curr)
  54. if err != nil {
  55. return fmt.Errorf("failed to generate pricing: %w", err)
  56. }
  57. data, err := json.MarshalIndent(pricingSet, "", " ")
  58. if err != nil {
  59. return fmt.Errorf("failed to marshal JSON: %w", err)
  60. }
  61. log.Infof("Generated %d node pricing entries and %d volume pricing entries",
  62. len(pricingSet.Nodes), len(pricingSet.Volumes))
  63. // Set default output path if not specified
  64. if output == "" {
  65. output = fmt.Sprintf("pricing-data/%s/%s-%s.json", provider, provider, currency)
  66. }
  67. // Check if user wants stdout
  68. if output == "stdout" {
  69. fmt.Println(string(data))
  70. return nil
  71. }
  72. // Write to file
  73. if err := os.WriteFile(output, data, 0644); err != nil {
  74. return fmt.Errorf("failed to write output file: %w", err)
  75. }
  76. log.Infof("Wrote pricing data to %s", output)
  77. return nil
  78. }