models.go 14 KB

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