models.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. package models
  2. import (
  3. "fmt"
  4. "io"
  5. "math"
  6. "reflect"
  7. "strconv"
  8. "strings"
  9. "github.com/microcosm-cc/bluemonday"
  10. "github.com/opencost/opencost/core/pkg/clustercache"
  11. "github.com/opencost/opencost/core/pkg/log"
  12. "github.com/opencost/opencost/pkg/config"
  13. )
  14. var (
  15. sanitizePolicy = bluemonday.UGCPolicy()
  16. )
  17. const (
  18. AuthSecretPath = "/var/secrets/service-key.json"
  19. StorageConfigSecretPath = "/var/azure-storage-config/azure-storage-config.json"
  20. DefaultShareTenancyCost = "true"
  21. KarpenterCapacityTypeLabel = "karpenter.sh/capacity-type"
  22. KarpenterCapacitySpotTypeValue = "spot"
  23. )
  24. // ReservedInstanceData keeps record of resources on a node should be
  25. // priced at reserved rates
  26. type ReservedInstanceData struct {
  27. ReservedCPU int64 `json:"reservedCPU"`
  28. ReservedRAM int64 `json:"reservedRAM"`
  29. CPUCost float64 `json:"CPUHourlyCost"`
  30. RAMCost float64 `json:"RAMHourlyCost"`
  31. }
  32. // Node is the interface by which the provider and cost model communicate Node prices.
  33. // The provider will best-effort try to fill out this struct.
  34. type Node struct {
  35. Cost string `json:"hourlyCost"`
  36. VCPU string `json:"CPU"`
  37. VCPUCost string `json:"CPUHourlyCost"`
  38. RAM string `json:"RAM"`
  39. RAMBytes string `json:"RAMBytes"`
  40. RAMCost string `json:"RAMGBHourlyCost"`
  41. Storage string `json:"storage"`
  42. StorageCost string `json:"storageHourlyCost"`
  43. UsesBaseCPUPrice bool `json:"usesDefaultPrice"`
  44. BaseCPUPrice string `json:"baseCPUPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  45. BaseRAMPrice string `json:"baseRAMPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  46. BaseGPUPrice string `json:"baseGPUPrice"`
  47. UsageType string `json:"usageType"`
  48. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  49. GPUName string `json:"gpuName"`
  50. GPUCost string `json:"gpuCost"`
  51. VGPU string `json:"vgpu"` // virtualized gpu-- if we are using gpu replicas
  52. InstanceType string `json:"instanceType,omitempty"`
  53. Region string `json:"region,omitempty"`
  54. Reserved *ReservedInstanceData `json:"reserved,omitempty"`
  55. ProviderID string `json:"providerID,omitempty"`
  56. PricingType PricingType `json:"pricingType,omitempty"`
  57. ArchType string `json:"archType,omitempty"`
  58. }
  59. // IsSpot determines whether or not a Node uses spot by usage type
  60. func (n *Node) IsSpot() bool {
  61. if n != nil {
  62. return strings.Contains(n.UsageType, "spot") || strings.Contains(n.UsageType, "emptible")
  63. } else {
  64. return false
  65. }
  66. }
  67. type OrphanedResource struct {
  68. Kind string `json:"resourceKind"`
  69. Region string `json:"region"`
  70. Description map[string]string `json:"description"`
  71. Size *int64 `json:"diskSizeInGB,omitempty"`
  72. DiskName string `json:"diskName,omitempty"`
  73. Url string `json:"url"`
  74. Address string `json:"ipAddress,omitempty"`
  75. MonthlyCost *float64 `json:"monthlyCost"`
  76. }
  77. // PV is the interface by which the provider and cost model communicate PV prices.
  78. // The provider will best-effort try to fill out this struct.
  79. type PV struct {
  80. Cost string `json:"hourlyCost"`
  81. CostPerIO string `json:"costPerIOOperation"`
  82. Class string `json:"storageClass"`
  83. Size string `json:"size"`
  84. Region string `json:"region"`
  85. ProviderID string `json:"providerID,omitempty"`
  86. Parameters map[string]string `json:"parameters"`
  87. }
  88. // Key represents a way for nodes to match between the k8s API and a pricing API
  89. type Key interface {
  90. ID() string // ID represents an exact match
  91. Features() string // Features are a comma separated string of node metadata that could match pricing
  92. GPUType() string // GPUType returns "" if no GPU exists or GPUs, but the name of the GPU otherwise
  93. GPUCount() int // GPUCount returns 0 if no GPU exists or GPUs, but the number of attached GPUs otherwise
  94. }
  95. type PVKey interface {
  96. Features() string
  97. GetStorageClass() string
  98. ID() string
  99. }
  100. // OutOfClusterAllocation represents a cloud provider cost not associated with kubernetes
  101. type OutOfClusterAllocation struct {
  102. Aggregator string `json:"aggregator"`
  103. Environment string `json:"environment"`
  104. Service string `json:"service"`
  105. Cost float64 `json:"cost"`
  106. Cluster string `json:"cluster"`
  107. }
  108. type CustomPricing struct {
  109. Provider string `json:"provider"`
  110. Description string `json:"description"`
  111. // CPU a string-encoded float describing cost per core-hour of CPU.
  112. CPU string `json:"CPU"`
  113. // CPU a string-encoded float describing cost per core-hour of CPU for spot
  114. // nodes.
  115. SpotCPU string `json:"spotCPU"`
  116. // RAM a string-encoded float describing cost per GiB-hour of RAM/memory.
  117. RAM string `json:"RAM"`
  118. // SpotRAM a string-encoded float describing cost per GiB-hour of RAM/memory
  119. // for spot nodes.
  120. SpotRAM string `json:"spotRAM"`
  121. GPU string `json:"GPU"`
  122. SpotGPU string `json:"spotGPU"`
  123. // Storage is a string-encoded float describing cost per GB-hour of storage
  124. // (e.g. PV, disk) resources.
  125. Storage string `json:"storage"`
  126. ZoneNetworkEgress string `json:"zoneNetworkEgress"`
  127. RegionNetworkEgress string `json:"regionNetworkEgress"`
  128. InternetNetworkEgress string `json:"internetNetworkEgress"`
  129. FirstFiveForwardingRulesCost string `json:"firstFiveForwardingRulesCost"`
  130. AdditionalForwardingRuleCost string `json:"additionalForwardingRuleCost"`
  131. LBIngressDataCost string `json:"LBIngressDataCost"`
  132. SpotLabel string `json:"spotLabel,omitempty"`
  133. SpotLabelValue string `json:"spotLabelValue,omitempty"`
  134. GpuLabel string `json:"gpuLabel,omitempty"`
  135. GpuLabelValue string `json:"gpuLabelValue,omitempty"`
  136. ServiceKeyName string `json:"awsServiceKeyName,omitempty"`
  137. ServiceKeySecret string `json:"awsServiceKeySecret,omitempty"`
  138. AlibabaServiceKeyName string `json:"alibabaServiceKeyName,omitempty"`
  139. AlibabaServiceKeySecret string `json:"alibabaServiceKeySecret,omitempty"`
  140. AlibabaClusterRegion string `json:"alibabaClusterRegion,omitempty"`
  141. SpotDataRegion string `json:"awsSpotDataRegion,omitempty"`
  142. SpotDataBucket string `json:"awsSpotDataBucket,omitempty"`
  143. SpotDataPrefix string `json:"awsSpotDataPrefix,omitempty"`
  144. ProjectID string `json:"projectID,omitempty"`
  145. AthenaProjectID string `json:"athenaProjectID,omitempty"`
  146. AthenaBucketName string `json:"athenaBucketName"`
  147. AthenaRegion string `json:"athenaRegion"`
  148. AthenaDatabase string `json:"athenaDatabase"`
  149. AthenaCatalog string `json:"athenaCatalog"`
  150. AthenaTable string `json:"athenaTable"`
  151. AthenaWorkgroup string `json:"athenaWorkgroup"`
  152. MasterPayerARN string `json:"masterPayerARN"`
  153. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  154. CustomPricesEnabled string `json:"customPricesEnabled"`
  155. DefaultIdle string `json:"defaultIdle"`
  156. AzureSubscriptionID string `json:"azureSubscriptionID"`
  157. AzureClientID string `json:"azureClientID"`
  158. AzureClientSecret string `json:"azureClientSecret"`
  159. AzureTenantID string `json:"azureTenantID"`
  160. AzureBillingRegion string `json:"azureBillingRegion"`
  161. AzureBillingAccount string `json:"azureBillingAccount"`
  162. AzureOfferDurableID string `json:"azureOfferDurableID"`
  163. AzureStorageSubscriptionID string `json:"azureStorageSubscriptionID"`
  164. AzureStorageAccount string `json:"azureStorageAccount"`
  165. AzureStorageAccessKey string `json:"azureStorageAccessKey"`
  166. AzureStorageContainer string `json:"azureStorageContainer"`
  167. AzureContainerPath string `json:"azureContainerPath"`
  168. AzureCloud string `json:"azureCloud"`
  169. CurrencyCode string `json:"currencyCode"`
  170. Discount string `json:"discount"`
  171. NegotiatedDiscount string `json:"negotiatedDiscount"`
  172. SharedOverhead string `json:"sharedOverhead"`
  173. ClusterName string `json:"clusterName"`
  174. ClusterAccountID string `json:"clusterAccount,omitempty"`
  175. SharedNamespaces string `json:"sharedNamespaces"`
  176. SharedLabelNames string `json:"sharedLabelNames"`
  177. SharedLabelValues string `json:"sharedLabelValues"`
  178. ShareTenancyCosts string `json:"shareTenancyCosts"` // TODO clean up configuration so we can use a type other that string (this should be a bool, but the app panics if it's not a string)
  179. ReadOnly string `json:"readOnly"`
  180. EditorAccess string `json:"editorAccess"`
  181. KubecostToken string `json:"kubecostToken"`
  182. GoogleAnalyticsTag string `json:"googleAnalyticsTag"`
  183. ExcludeProviderID string `json:"excludeProviderID"`
  184. DefaultLBPrice string `json:"defaultLBPrice"`
  185. }
  186. // GetSharedOverheadCostPerMonth parses and returns a float64 representation
  187. // of the configured monthly shared overhead cost. If the string version cannot
  188. // be parsed into a float, an error is logged and 0.0 is returned.
  189. func (cp *CustomPricing) GetSharedOverheadCostPerMonth() float64 {
  190. // Empty string should be interpreted as "no cost", i.e. 0.0
  191. if cp.SharedOverhead == "" {
  192. return 0.0
  193. }
  194. // Attempt to parse, but log and return 0.0 if that fails.
  195. sharedCostPerMonth, err := strconv.ParseFloat(cp.SharedOverhead, 64)
  196. if err != nil {
  197. log.Errorf("SharedOverhead: failed to parse shared overhead \"%s\": %s", cp.SharedOverhead, err)
  198. return 0.0
  199. }
  200. return sharedCostPerMonth
  201. }
  202. func sanitizeFloatString(number string, allowNaN bool) (string, error) {
  203. num, err := strconv.ParseFloat(number, 64)
  204. if err != nil {
  205. return "", fmt.Errorf("expected a string representing a number; got '%s'", number)
  206. }
  207. if !allowNaN && math.IsNaN(num) {
  208. return "", fmt.Errorf("expected a string representing a number; got 'NaN'")
  209. }
  210. // Format the numerical string we just parsed.
  211. return strconv.FormatFloat(num, 'f', -1, 64), nil
  212. }
  213. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  214. structValue := reflect.ValueOf(obj).Elem()
  215. structFieldValue := structValue.FieldByName(name)
  216. if !structFieldValue.IsValid() {
  217. return fmt.Errorf("no such field: %s in obj", name)
  218. }
  219. if !structFieldValue.CanSet() {
  220. return fmt.Errorf("cannot set %s field value", name)
  221. }
  222. // If the custom pricing field is expected to be a string representation
  223. // of a floating point number, e.g. a resource price, then do some extra
  224. // validation work in order to prevent "NaN" and other invalid strings
  225. // from getting set here.
  226. switch strings.ToLower(name) {
  227. case "cpu", "gpu", "ram", "spotcpu", "spotgpu", "spotram", "storage", "zonenetworkegress", "regionnetworkegress", "internetnetworkegress":
  228. // If we are sent an empty string, ignore the key and don't change the value
  229. if value == "" {
  230. return nil
  231. } else {
  232. // Validate that "value" represents a real floating point number, and
  233. // set precision, bits, etc. Do not allow NaN.
  234. val, err := sanitizeFloatString(value, false)
  235. if err != nil {
  236. return fmt.Errorf("invalid numeric value for field '%s': %s", name, value)
  237. }
  238. value = val
  239. }
  240. default:
  241. }
  242. structFieldType := structFieldValue.Type()
  243. value = sanitizePolicy.Sanitize(value)
  244. val := reflect.ValueOf(value)
  245. if structFieldType != val.Type() {
  246. return fmt.Errorf("provided value type didn't match custom pricing field type")
  247. }
  248. structFieldValue.Set(val)
  249. return nil
  250. }
  251. type PricingSources struct {
  252. PricingSources map[string]*PricingSource
  253. }
  254. type PricingSource struct {
  255. Name string `json:"name"`
  256. Enabled bool `json:"enabled"`
  257. Available bool `json:"available"`
  258. Error string `json:"error"`
  259. }
  260. type PricingType string
  261. const (
  262. Api PricingType = "api"
  263. Spot PricingType = "spot"
  264. Reserved PricingType = "reserved"
  265. SavingsPlan PricingType = "savingsPlan"
  266. CsvExact PricingType = "csvExact"
  267. CsvClass PricingType = "csvClass"
  268. DefaultPrices PricingType = "defaultPrices"
  269. )
  270. type PricingMatchMetadata struct {
  271. TotalNodes int `json:"TotalNodes"`
  272. PricingTypeCounts map[PricingType]int `json:"PricingType"`
  273. }
  274. // Provider represents a k8s provider.
  275. type Provider interface {
  276. ClusterInfo() (map[string]string, error)
  277. GetAddresses() ([]byte, error)
  278. GetDisks() ([]byte, error)
  279. GetOrphanedResources() ([]OrphanedResource, error)
  280. NodePricing(Key) (*Node, PricingMetadata, error)
  281. GpuPricing(map[string]string) (string, error)
  282. PVPricing(PVKey) (*PV, error)
  283. NetworkPricing() (*Network, error) // TODO: add key interface arg for dynamic price fetching
  284. LoadBalancerPricing() (*LoadBalancer, error) // TODO: add key interface arg for dynamic price fetching
  285. AllNodePricing() (interface{}, error)
  286. DownloadPricingData() error
  287. GetKey(map[string]string, *clustercache.Node) Key
  288. GetPVKey(*clustercache.PersistentVolume, map[string]string, string) PVKey
  289. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  290. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  291. GetConfig() (*CustomPricing, error)
  292. GetManagementPlatform() (string, error)
  293. ApplyReservedInstancePricing(map[string]*Node)
  294. ServiceAccountStatus() *ServiceAccountStatus
  295. PricingSourceStatus() map[string]*PricingSource
  296. ClusterManagementPricing() (string, float64, error)
  297. CombinedDiscountForNode(string, bool, float64, float64) float64
  298. Regions() []string
  299. PricingSourceSummary() interface{}
  300. }
  301. // ProviderConfig describes config storage common to all providers.
  302. type ProviderConfig interface {
  303. ConfigFileManager() *config.ConfigFileManager
  304. GetCustomPricingData() (*CustomPricing, error)
  305. Update(func(*CustomPricing) error) (*CustomPricing, error)
  306. UpdateFromMap(map[string]string) (*CustomPricing, error)
  307. }