storefactory.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package storage
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/opencost/opencost/core/pkg/env"
  6. )
  7. // GetDefaultStorage initializes the default shared storage which is required for kubecost. Panics
  8. // if the storage cannot be initialized.
  9. func GetDefaultStorage() Storage {
  10. store, err := InitializeStorage(env.GetDefaultStorageConfigFilePath())
  11. if err != nil {
  12. panic(fmt.Sprintf("failed to initialize default storage: %s", err.Error()))
  13. }
  14. return store
  15. }
  16. // TryGetDefaultStorage will attempt to load the default bucket configuration, but will not panic
  17. // if the config file does not exist.
  18. func TryGetDefaultStorage() (Storage, error) {
  19. store, err := InitializeStorage(env.GetDefaultStorageConfigFilePath())
  20. if err != nil {
  21. return nil, fmt.Errorf("failed to initialize default storage: %w", err)
  22. }
  23. return store, nil
  24. }
  25. // InitializeStorage creates a storage from the config file at the given path
  26. func InitializeStorage(configPath string) (Storage, error) {
  27. storageConfig, err := os.ReadFile(configPath)
  28. if err != nil {
  29. return nil, fmt.Errorf("failed to read file '%s': %w", configPath, err)
  30. }
  31. store, err := NewBucketStorage(storageConfig)
  32. if err != nil {
  33. return nil, fmt.Errorf("failed to create storage from config '%s': %w", configPath, err)
  34. }
  35. return store, nil
  36. }