models.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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/pkg/config"
  12. )
  13. var (
  14. sanitizePolicy = bluemonday.UGCPolicy()
  15. )
  16. const (
  17. AuthSecretPath = "/var/secrets/service-key.json"
  18. StorageConfigSecretPath = "/var/azure-storage-config/azure-storage-config.json"
  19. KarpenterCapacityTypeLabel = "karpenter.sh/capacity-type"
  20. KarpenterCapacitySpotTypeValue = "spot"
  21. )
  22. // ReservedInstanceData keeps record of resources on a node should be
  23. // priced at reserved rates
  24. type ReservedInstanceData struct {
  25. ReservedCPU int64 `json:"reservedCPU"`
  26. ReservedRAM int64 `json:"reservedRAM"`
  27. CPUCost float64 `json:"CPUHourlyCost"`
  28. RAMCost float64 `json:"RAMHourlyCost"`
  29. }
  30. // Node is the interface by which the provider and cost model communicate Node prices.
  31. // The provider will best-effort try to fill out this struct.
  32. type Node struct {
  33. Cost string `json:"hourlyCost"`
  34. VCPU string `json:"CPU"`
  35. VCPUCost string `json:"CPUHourlyCost"`
  36. RAM string `json:"RAM"`
  37. RAMBytes string `json:"RAMBytes"`
  38. RAMCost string `json:"RAMGBHourlyCost"`
  39. Storage string `json:"storage"`
  40. StorageCost string `json:"storageHourlyCost"`
  41. UsesBaseCPUPrice bool `json:"usesDefaultPrice"`
  42. BaseCPUPrice string `json:"baseCPUPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  43. BaseRAMPrice string `json:"baseRAMPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  44. BaseGPUPrice string `json:"baseGPUPrice"`
  45. UsageType string `json:"usageType"`
  46. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  47. GPUName string `json:"gpuName"`
  48. GPUCost string `json:"gpuCost"`
  49. VGPU string `json:"vgpu"` // virtualized gpu-- if we are using gpu replicas
  50. InstanceType string `json:"instanceType,omitempty"`
  51. Region string `json:"region,omitempty"`
  52. Reserved *ReservedInstanceData `json:"reserved,omitempty"`
  53. ProviderID string `json:"providerID,omitempty"`
  54. PricingType PricingType `json:"pricingType,omitempty"`
  55. ArchType string `json:"archType,omitempty"`
  56. }
  57. // IsSpot determines whether or not a Node uses spot by usage type
  58. func (n *Node) IsSpot() bool {
  59. if n != nil {
  60. return strings.Contains(n.UsageType, "spot") || strings.Contains(n.UsageType, "emptible")
  61. } else {
  62. return false
  63. }
  64. }
  65. type OrphanedResource struct {
  66. Kind string `json:"resourceKind"`
  67. Region string `json:"region"`
  68. Description map[string]string `json:"description"`
  69. Size *int64 `json:"diskSizeInGB,omitempty"`
  70. DiskName string `json:"diskName,omitempty"`
  71. Url string `json:"url"`
  72. Address string `json:"ipAddress,omitempty"`
  73. MonthlyCost *float64 `json:"monthlyCost"`
  74. }
  75. // PV is the interface by which the provider and cost model communicate PV prices.
  76. // The provider will best-effort try to fill out this struct.
  77. type PV struct {
  78. Cost string `json:"hourlyCost"`
  79. CostPerIO string `json:"costPerIOOperation"`
  80. Class string `json:"storageClass"`
  81. Size string `json:"size"`
  82. Region string `json:"region"`
  83. ProviderID string `json:"providerID,omitempty"`
  84. Parameters map[string]string `json:"parameters"`
  85. }
  86. // Key represents a way for nodes to match between the k8s API and a pricing API
  87. type Key interface {
  88. ID() string // ID represents an exact match
  89. Features() string // Features are a comma separated string of node metadata that could match pricing
  90. GPUType() string // GPUType returns "" if no GPU exists or GPUs, but the name of the GPU otherwise
  91. GPUCount() int // GPUCount returns 0 if no GPU exists or GPUs, but the number of attached GPUs otherwise
  92. }
  93. type PVKey interface {
  94. Features() string
  95. GetStorageClass() string
  96. ID() string
  97. }
  98. // OutOfClusterAllocation represents a cloud provider cost not associated with kubernetes
  99. type OutOfClusterAllocation struct {
  100. Aggregator string `json:"aggregator"`
  101. Environment string `json:"environment"`
  102. Service string `json:"service"`
  103. Cost float64 `json:"cost"`
  104. Cluster string `json:"cluster"`
  105. }
  106. type CustomPricing struct {
  107. Provider string `json:"provider"`
  108. Description string `json:"description"`
  109. // CPU a string-encoded float describing cost per core-hour of CPU.
  110. CPU string `json:"CPU"`
  111. // CPU a string-encoded float describing cost per core-hour of CPU for spot
  112. // nodes.
  113. SpotCPU string `json:"spotCPU"`
  114. // RAM a string-encoded float describing cost per GiB-hour of RAM/memory.
  115. RAM string `json:"RAM"`
  116. // SpotRAM a string-encoded float describing cost per GiB-hour of RAM/memory
  117. // for spot nodes.
  118. SpotRAM string `json:"spotRAM"`
  119. GPU string `json:"GPU"`
  120. SpotGPU string `json:"spotGPU"`
  121. // Storage is a string-encoded float describing cost per GB-hour of storage
  122. // (e.g. PV, disk) resources.
  123. Storage string `json:"storage"`
  124. ZoneNetworkEgress string `json:"zoneNetworkEgress"`
  125. RegionNetworkEgress string `json:"regionNetworkEgress"`
  126. InternetNetworkEgress string `json:"internetNetworkEgress"`
  127. NatGatewayEgress string `json:"natGatewayEgress"`
  128. NatGatewayIngress string `json:"natGatewayIngress"`
  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. AwsServiceKeyName string `json:"awsServiceKeyName,omitempty"`
  137. AwsServiceKeySecret string `json:"awsServiceKeySecret,omitempty"`
  138. AlibabaServiceKeyName string `json:"alibabaServiceKeyName,omitempty"`
  139. AlibabaServiceKeySecret string `json:"alibabaServiceKeySecret,omitempty"`
  140. AlibabaClusterRegion string `json:"alibabaClusterRegion,omitempty"`
  141. AwsSpotDataRegion string `json:"awsSpotDataRegion,omitempty"`
  142. AwsSpotDataBucket string `json:"awsSpotDataBucket,omitempty"`
  143. AwsSpotDataPrefix string `json:"awsSpotDataPrefix,omitempty"`
  144. SpotDataFeedEnabled string `json:"spotDataFeedEnabled,omitempty"`
  145. ProjectID string `json:"projectID,omitempty"`
  146. AthenaProjectID string `json:"athenaProjectID,omitempty"`
  147. AthenaBucketName string `json:"athenaBucketName"`
  148. AthenaRegion string `json:"athenaRegion"`
  149. AthenaDatabase string `json:"athenaDatabase"`
  150. AthenaCatalog string `json:"athenaCatalog"`
  151. AthenaTable string `json:"athenaTable"`
  152. AthenaWorkgroup string `json:"athenaWorkgroup"`
  153. MasterPayerARN string `json:"masterPayerARN"`
  154. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  155. CustomPricesEnabled string `json:"customPricesEnabled"`
  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. ClusterName string `json:"clusterName"`
  173. ClusterAccountID string `json:"clusterAccount,omitempty"`
  174. DefaultLBPrice string `json:"defaultLBPrice"`
  175. }
  176. func sanitizeFloatString(number string, allowNaN bool) (string, error) {
  177. num, err := strconv.ParseFloat(number, 64)
  178. if err != nil {
  179. return "", fmt.Errorf("expected a string representing a number; got '%s'", number)
  180. }
  181. if !allowNaN && math.IsNaN(num) {
  182. return "", fmt.Errorf("expected a string representing a number; got 'NaN'")
  183. }
  184. // Format the numerical string we just parsed.
  185. return strconv.FormatFloat(num, 'f', -1, 64), nil
  186. }
  187. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  188. structValue := reflect.ValueOf(obj).Elem()
  189. structFieldValue := structValue.FieldByName(name)
  190. if !structFieldValue.IsValid() {
  191. return fmt.Errorf("no such field: %s in obj", name)
  192. }
  193. if !structFieldValue.CanSet() {
  194. return fmt.Errorf("cannot set %s field value", name)
  195. }
  196. // If the custom pricing field is expected to be a string representation
  197. // of a floating point number, e.g. a resource price, then do some extra
  198. // validation work in order to prevent "NaN" and other invalid strings
  199. // from getting set here.
  200. switch strings.ToLower(name) {
  201. case "cpu", "gpu", "ram", "spotcpu", "spotgpu", "spotram", "storage", "zonenetworkegress", "regionnetworkegress", "internetnetworkegress", "natgatewayegress", "natgatewayingress":
  202. // If we are sent an empty string, ignore the key and don't change the value
  203. if value == "" {
  204. return nil
  205. } else {
  206. // Validate that "value" represents a real floating point number, and
  207. // set precision, bits, etc. Do not allow NaN.
  208. val, err := sanitizeFloatString(value, false)
  209. if err != nil {
  210. return fmt.Errorf("invalid numeric value for field '%s': %s", name, value)
  211. }
  212. value = val
  213. }
  214. default:
  215. }
  216. structFieldType := structFieldValue.Type()
  217. value = sanitizePolicy.Sanitize(value)
  218. val := reflect.ValueOf(value)
  219. if structFieldType != val.Type() {
  220. return fmt.Errorf("provided value type didn't match custom pricing field type")
  221. }
  222. structFieldValue.Set(val)
  223. return nil
  224. }
  225. type PricingSources struct {
  226. PricingSources map[string]*PricingSource
  227. }
  228. type PricingSource struct {
  229. Name string `json:"name"`
  230. Enabled bool `json:"enabled"`
  231. Available bool `json:"available"`
  232. Error string `json:"error"`
  233. }
  234. type PricingType string
  235. const (
  236. Api PricingType = "api"
  237. Spot PricingType = "spot"
  238. Reserved PricingType = "reserved"
  239. SavingsPlan PricingType = "savingsPlan"
  240. CsvExact PricingType = "csvExact"
  241. CsvClass PricingType = "csvClass"
  242. DefaultPrices PricingType = "defaultPrices"
  243. )
  244. type PricingMatchMetadata struct {
  245. TotalNodes int `json:"TotalNodes"`
  246. PricingTypeCounts map[PricingType]int `json:"PricingType"`
  247. }
  248. // Provider represents a k8s provider.
  249. type Provider interface {
  250. ClusterInfo() (map[string]string, error)
  251. GetAddresses() ([]byte, error)
  252. GetDisks() ([]byte, error)
  253. GetOrphanedResources() ([]OrphanedResource, error)
  254. NodePricing(Key) (*Node, PricingMetadata, error)
  255. GpuPricing(map[string]string) (string, error)
  256. PVPricing(PVKey) (*PV, error)
  257. NetworkPricing() (*Network, error) // TODO: add key interface arg for dynamic price fetching
  258. LoadBalancerPricing() (*LoadBalancer, error) // TODO: add key interface arg for dynamic price fetching
  259. AllNodePricing() (interface{}, error)
  260. DownloadPricingData() error
  261. GetKey(map[string]string, *clustercache.Node) Key
  262. GetPVKey(*clustercache.PersistentVolume, map[string]string, string) PVKey
  263. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  264. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  265. GetConfig() (*CustomPricing, error)
  266. GetManagementPlatform() (string, error)
  267. ApplyReservedInstancePricing(map[string]*Node)
  268. ServiceAccountStatus() *ServiceAccountStatus
  269. PricingSourceStatus() map[string]*PricingSource
  270. ClusterManagementPricing() (string, float64, error)
  271. CombinedDiscountForNode(string, bool, float64, float64) float64
  272. Regions() []string
  273. PricingSourceSummary() interface{}
  274. }
  275. // ProviderConfig describes config storage common to all providers.
  276. type ProviderConfig interface {
  277. ConfigFileManager() *config.ConfigFileManager
  278. GetCustomPricingData() (*CustomPricing, error)
  279. Update(func(*CustomPricing) error) (*CustomPricing, error)
  280. UpdateFromMap(map[string]string) (*CustomPricing, error)
  281. }