utils.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package config
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "strings"
  8. "github.com/opencost/opencost/pkg/cloud"
  9. "github.com/opencost/opencost/pkg/cloud/aws"
  10. "github.com/opencost/opencost/pkg/cloud/azure"
  11. "github.com/opencost/opencost/pkg/cloud/gcp"
  12. )
  13. func ParseConfig(configType string, body io.Reader) (cloud.KeyedConfig, error) {
  14. buf := new(bytes.Buffer)
  15. _, err := buf.ReadFrom(body)
  16. if err != nil {
  17. return nil, fmt.Errorf("failed to read body: %w", err)
  18. }
  19. return ParseConfigBytes(configType, buf.Bytes())
  20. }
  21. func ParseConfigBytes(configType string, configBytes []byte) (cloud.KeyedConfig, error) {
  22. var config cloud.KeyedConfig
  23. var err error
  24. switch strings.ToLower(configType) {
  25. case S3ConfigType:
  26. config = &aws.S3Configuration{}
  27. case AthenaConfigType:
  28. config = &aws.AthenaConfiguration{}
  29. case BigQueryConfigType:
  30. config = &gcp.BigQueryConfiguration{}
  31. case AzureStorageConfigType:
  32. config = &azure.StorageConfiguration{}
  33. default:
  34. return nil, fmt.Errorf("provided config type was not recognized %s", configType)
  35. }
  36. err = json.Unmarshal(configBytes, config)
  37. if err != nil {
  38. return nil, fmt.Errorf("error unmarshalling configuration of type %s: %w", configType, err)
  39. }
  40. return config, nil
  41. }
  42. func ParseConfigString(configType string, configStr string) (cloud.KeyedConfig, error) {
  43. return ParseConfigBytes(configType, []byte(configStr))
  44. }