models.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. FirstFiveForwardingRulesCost string `json:"firstFiveForwardingRulesCost"`
  128. AdditionalForwardingRuleCost string `json:"additionalForwardingRuleCost"`
  129. LBIngressDataCost string `json:"LBIngressDataCost"`
  130. SpotLabel string `json:"spotLabel,omitempty"`
  131. SpotLabelValue string `json:"spotLabelValue,omitempty"`
  132. GpuLabel string `json:"gpuLabel,omitempty"`
  133. GpuLabelValue string `json:"gpuLabelValue,omitempty"`
  134. ServiceKeyName string `json:"awsServiceKeyName,omitempty"`
  135. ServiceKeySecret string `json:"awsServiceKeySecret,omitempty"`
  136. AlibabaServiceKeyName string `json:"alibabaServiceKeyName,omitempty"`
  137. AlibabaServiceKeySecret string `json:"alibabaServiceKeySecret,omitempty"`
  138. AlibabaClusterRegion string `json:"alibabaClusterRegion,omitempty"`
  139. SpotDataRegion string `json:"awsSpotDataRegion,omitempty"`
  140. SpotDataBucket string `json:"awsSpotDataBucket,omitempty"`
  141. SpotDataPrefix string `json:"awsSpotDataPrefix,omitempty"`
  142. ProjectID string `json:"projectID,omitempty"`
  143. AthenaProjectID string `json:"athenaProjectID,omitempty"`
  144. AthenaBucketName string `json:"athenaBucketName"`
  145. AthenaRegion string `json:"athenaRegion"`
  146. AthenaDatabase string `json:"athenaDatabase"`
  147. AthenaCatalog string `json:"athenaCatalog"`
  148. AthenaTable string `json:"athenaTable"`
  149. AthenaWorkgroup string `json:"athenaWorkgroup"`
  150. MasterPayerARN string `json:"masterPayerARN"`
  151. AthenaCURVersion string `json:"athenaCURVersion,omitempty"` // "1.0" or "2.0", defaults to "2.0"
  152. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  153. CustomPricesEnabled string `json:"customPricesEnabled"`
  154. AzureSubscriptionID string `json:"azureSubscriptionID"`
  155. AzureClientID string `json:"azureClientID"`
  156. AzureClientSecret string `json:"azureClientSecret"`
  157. AzureTenantID string `json:"azureTenantID"`
  158. AzureBillingRegion string `json:"azureBillingRegion"`
  159. AzureBillingAccount string `json:"azureBillingAccount"`
  160. AzureOfferDurableID string `json:"azureOfferDurableID"`
  161. AzureStorageSubscriptionID string `json:"azureStorageSubscriptionID"`
  162. AzureStorageAccount string `json:"azureStorageAccount"`
  163. AzureStorageAccessKey string `json:"azureStorageAccessKey"`
  164. AzureStorageContainer string `json:"azureStorageContainer"`
  165. AzureContainerPath string `json:"azureContainerPath"`
  166. AzureCloud string `json:"azureCloud"`
  167. CurrencyCode string `json:"currencyCode"`
  168. Discount string `json:"discount"`
  169. NegotiatedDiscount string `json:"negotiatedDiscount"`
  170. ClusterName string `json:"clusterName"`
  171. ClusterAccountID string `json:"clusterAccount,omitempty"`
  172. DefaultLBPrice string `json:"defaultLBPrice"`
  173. }
  174. func sanitizeFloatString(number string, allowNaN bool) (string, error) {
  175. num, err := strconv.ParseFloat(number, 64)
  176. if err != nil {
  177. return "", fmt.Errorf("expected a string representing a number; got '%s'", number)
  178. }
  179. if !allowNaN && math.IsNaN(num) {
  180. return "", fmt.Errorf("expected a string representing a number; got 'NaN'")
  181. }
  182. // Format the numerical string we just parsed.
  183. return strconv.FormatFloat(num, 'f', -1, 64), nil
  184. }
  185. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  186. structValue := reflect.ValueOf(obj).Elem()
  187. structFieldValue := structValue.FieldByName(name)
  188. if !structFieldValue.IsValid() {
  189. return fmt.Errorf("no such field: %s in obj", name)
  190. }
  191. if !structFieldValue.CanSet() {
  192. return fmt.Errorf("cannot set %s field value", name)
  193. }
  194. // If the custom pricing field is expected to be a string representation
  195. // of a floating point number, e.g. a resource price, then do some extra
  196. // validation work in order to prevent "NaN" and other invalid strings
  197. // from getting set here.
  198. switch strings.ToLower(name) {
  199. case "cpu", "gpu", "ram", "spotcpu", "spotgpu", "spotram", "storage", "zonenetworkegress", "regionnetworkegress", "internetnetworkegress":
  200. // If we are sent an empty string, ignore the key and don't change the value
  201. if value == "" {
  202. return nil
  203. } else {
  204. // Validate that "value" represents a real floating point number, and
  205. // set precision, bits, etc. Do not allow NaN.
  206. val, err := sanitizeFloatString(value, false)
  207. if err != nil {
  208. return fmt.Errorf("invalid numeric value for field '%s': %s", name, value)
  209. }
  210. value = val
  211. }
  212. default:
  213. }
  214. structFieldType := structFieldValue.Type()
  215. value = sanitizePolicy.Sanitize(value)
  216. val := reflect.ValueOf(value)
  217. if structFieldType != val.Type() {
  218. return fmt.Errorf("provided value type didn't match custom pricing field type")
  219. }
  220. structFieldValue.Set(val)
  221. return nil
  222. }
  223. type PricingSources struct {
  224. PricingSources map[string]*PricingSource
  225. }
  226. type PricingSource struct {
  227. Name string `json:"name"`
  228. Enabled bool `json:"enabled"`
  229. Available bool `json:"available"`
  230. Error string `json:"error"`
  231. }
  232. type PricingType string
  233. const (
  234. Api PricingType = "api"
  235. Spot PricingType = "spot"
  236. Reserved PricingType = "reserved"
  237. SavingsPlan PricingType = "savingsPlan"
  238. CsvExact PricingType = "csvExact"
  239. CsvClass PricingType = "csvClass"
  240. DefaultPrices PricingType = "defaultPrices"
  241. )
  242. type PricingMatchMetadata struct {
  243. TotalNodes int `json:"TotalNodes"`
  244. PricingTypeCounts map[PricingType]int `json:"PricingType"`
  245. }
  246. // Provider represents a k8s provider.
  247. type Provider interface {
  248. ClusterInfo() (map[string]string, error)
  249. GetAddresses() ([]byte, error)
  250. GetDisks() ([]byte, error)
  251. GetOrphanedResources() ([]OrphanedResource, error)
  252. NodePricing(Key) (*Node, PricingMetadata, error)
  253. GpuPricing(map[string]string) (string, error)
  254. PVPricing(PVKey) (*PV, error)
  255. NetworkPricing() (*Network, error) // TODO: add key interface arg for dynamic price fetching
  256. LoadBalancerPricing() (*LoadBalancer, error) // TODO: add key interface arg for dynamic price fetching
  257. AllNodePricing() (interface{}, error)
  258. DownloadPricingData() error
  259. GetKey(map[string]string, *clustercache.Node) Key
  260. GetPVKey(*clustercache.PersistentVolume, map[string]string, string) PVKey
  261. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  262. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  263. GetConfig() (*CustomPricing, error)
  264. GetManagementPlatform() (string, error)
  265. ApplyReservedInstancePricing(map[string]*Node)
  266. ServiceAccountStatus() *ServiceAccountStatus
  267. PricingSourceStatus() map[string]*PricingSource
  268. ClusterManagementPricing() (string, float64, error)
  269. CombinedDiscountForNode(string, bool, float64, float64) float64
  270. Regions() []string
  271. PricingSourceSummary() interface{}
  272. }
  273. // ProviderConfig describes config storage common to all providers.
  274. type ProviderConfig interface {
  275. ConfigFileManager() *config.ConfigFileManager
  276. GetCustomPricingData() (*CustomPricing, error)
  277. Update(func(*CustomPricing) error) (*CustomPricing, error)
  278. UpdateFromMap(map[string]string) (*CustomPricing, error)
  279. }