storefactory.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package storage
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/opencost/opencost/core/pkg/env"
  6. "github.com/opencost/opencost/core/pkg/log"
  7. )
  8. // GetDefaultStorage initializes the default shared storage which is required for kubecost. Panics
  9. // if the storage cannot be initialized.
  10. func GetDefaultStorage() Storage {
  11. store, err := InitializeStorage(env.GetDefaultStorageConfigFilePath())
  12. if err != nil {
  13. panic(fmt.Sprintf("failed to initialize default storage: %s", err.Error()))
  14. }
  15. return store
  16. }
  17. // GetConfiguredStorage retrieves the default shared storage which is required for running an opencost.
  18. func GetConfiguredStorage() Storage {
  19. const warningMessage = `Failed to create local directory '%s' - %s.
  20. Did you mean to enable the collector? For persistent storage, it's recommended to use Prometheus,
  21. or set a storage bucket configuration at %s.
  22. %s`
  23. // Try bucket storage if it exists
  24. store, err := TryGetDefaultStorage()
  25. if err == nil {
  26. return store
  27. }
  28. // Fallback to a local storage bucket
  29. dir := env.GetConfigPath()
  30. err = os.MkdirAll(dir, os.ModePerm)
  31. if err != nil {
  32. log.Warnf(
  33. warningMessage,
  34. dir,
  35. err.Error(),
  36. env.GetDefaultStorageConfigFilePath(),
  37. "Falling back to an in-memory file system for collector, which will lose any persistent storage upon restart.",
  38. )
  39. return NewMemoryStorage()
  40. }
  41. return NewFileStorage(dir)
  42. }
  43. // TryGetDefaultStorage will attempt to load the default bucket configuration, but will not panic
  44. // if the config file does not exist.
  45. func TryGetDefaultStorage() (Storage, error) {
  46. store, err := InitializeStorage(env.GetDefaultStorageConfigFilePath())
  47. if err != nil {
  48. return nil, fmt.Errorf("failed to initialize default storage: %w", err)
  49. }
  50. return store, nil
  51. }
  52. // InitializeStorage creates a storage from the config file at the given path
  53. func InitializeStorage(configPath string) (Storage, error) {
  54. storageConfig, err := os.ReadFile(configPath)
  55. if err != nil {
  56. return nil, fmt.Errorf("failed to read file '%s': %w", configPath, err)
  57. }
  58. store, err := NewBucketStorage(storageConfig)
  59. if err != nil {
  60. return nil, fmt.Errorf("failed to create storage from config '%s': %w", configPath, err)
  61. }
  62. return store, nil
  63. }