costconfiguration.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package stackit
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/opencost/opencost/core/pkg/opencost"
  6. "github.com/opencost/opencost/pkg/cloud"
  7. )
  8. // CostConfiguration holds the configuration needed to connect to STACKIT Cost API
  9. type CostConfiguration struct {
  10. CustomerAccountID string `json:"customerAccountId"`
  11. ProjectID string `json:"projectId"`
  12. ServiceAccountKeyPath string `json:"serviceAccountKeyPath,omitempty"`
  13. }
  14. func (c *CostConfiguration) Validate() error {
  15. if c.CustomerAccountID == "" {
  16. return fmt.Errorf("CostConfiguration: missing customerAccountId")
  17. }
  18. if c.ProjectID == "" {
  19. return fmt.Errorf("CostConfiguration: missing projectId")
  20. }
  21. return nil
  22. }
  23. func (c *CostConfiguration) Equals(config cloud.Config) bool {
  24. if config == nil {
  25. return false
  26. }
  27. thatConfig, ok := config.(*CostConfiguration)
  28. if !ok {
  29. return false
  30. }
  31. return c.CustomerAccountID == thatConfig.CustomerAccountID &&
  32. c.ProjectID == thatConfig.ProjectID &&
  33. c.ServiceAccountKeyPath == thatConfig.ServiceAccountKeyPath
  34. }
  35. func (c *CostConfiguration) Sanitize() cloud.Config {
  36. sanitized := &CostConfiguration{
  37. CustomerAccountID: c.CustomerAccountID,
  38. ProjectID: c.ProjectID,
  39. }
  40. if c.ServiceAccountKeyPath != "" {
  41. sanitized.ServiceAccountKeyPath = cloud.Redacted
  42. }
  43. return sanitized
  44. }
  45. func (c *CostConfiguration) Key() string {
  46. return c.CustomerAccountID + "/" + c.ProjectID
  47. }
  48. func (c *CostConfiguration) Provider() string {
  49. return opencost.STACKITProvider
  50. }
  51. func (c *CostConfiguration) UnmarshalJSON(b []byte) error {
  52. var f interface{}
  53. err := json.Unmarshal(b, &f)
  54. if err != nil {
  55. return err
  56. }
  57. fmap, ok := f.(map[string]interface{})
  58. if !ok {
  59. return fmt.Errorf("CostConfiguration: UnmarshalJSON: expected object")
  60. }
  61. customerAccountID, err := cloud.GetInterfaceValue[string](fmap, "customerAccountId")
  62. if err != nil {
  63. return fmt.Errorf("CostConfiguration: UnmarshalJSON: %w", err)
  64. }
  65. c.CustomerAccountID = customerAccountID
  66. projectID, err := cloud.GetInterfaceValue[string](fmap, "projectId")
  67. if err != nil {
  68. return fmt.Errorf("CostConfiguration: UnmarshalJSON: %w", err)
  69. }
  70. c.ProjectID = projectID
  71. if saKeyPath, ok := fmap["serviceAccountKeyPath"]; ok {
  72. if s, ok := saKeyPath.(string); ok {
  73. c.ServiceAccountKeyPath = s
  74. }
  75. }
  76. return nil
  77. }