2
0

models.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. AthenaCURVersion string `json:"athenaCURVersion,omitempty"` // "1.0" or "2.0", defaults to "2.0"
  154. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  155. CustomPricesEnabled string `json:"customPricesEnabled"`
  156. DefaultIdle string `json:"defaultIdle"`
  157. AzureSubscriptionID string `json:"azureSubscriptionID"`
  158. AzureClientID string `json:"azureClientID"`
  159. AzureClientSecret string `json:"azureClientSecret"`
  160. AzureTenantID string `json:"azureTenantID"`
  161. AzureBillingRegion string `json:"azureBillingRegion"`
  162. AzureBillingAccount string `json:"azureBillingAccount"`
  163. AzureOfferDurableID string `json:"azureOfferDurableID"`
  164. AzureStorageSubscriptionID string `json:"azureStorageSubscriptionID"`
  165. AzureStorageAccount string `json:"azureStorageAccount"`
  166. AzureStorageAccessKey string `json:"azureStorageAccessKey"`
  167. AzureStorageContainer string `json:"azureStorageContainer"`
  168. AzureContainerPath string `json:"azureContainerPath"`
  169. AzureCloud string `json:"azureCloud"`
  170. CurrencyCode string `json:"currencyCode"`
  171. Discount string `json:"discount"`
  172. NegotiatedDiscount string `json:"negotiatedDiscount"`
  173. SharedOverhead string `json:"sharedOverhead"`
  174. ClusterName string `json:"clusterName"`
  175. ClusterAccountID string `json:"clusterAccount,omitempty"`
  176. SharedNamespaces string `json:"sharedNamespaces"`
  177. SharedLabelNames string `json:"sharedLabelNames"`
  178. SharedLabelValues string `json:"sharedLabelValues"`
  179. 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)
  180. ReadOnly string `json:"readOnly"`
  181. EditorAccess string `json:"editorAccess"`
  182. KubecostToken string `json:"kubecostToken"`
  183. GoogleAnalyticsTag string `json:"googleAnalyticsTag"`
  184. ExcludeProviderID string `json:"excludeProviderID"`
  185. DefaultLBPrice string `json:"defaultLBPrice"`
  186. }
  187. // GetSharedOverheadCostPerMonth parses and returns a float64 representation
  188. // of the configured monthly shared overhead cost. If the string version cannot
  189. // be parsed into a float, an error is logged and 0.0 is returned.
  190. func (cp *CustomPricing) GetSharedOverheadCostPerMonth() float64 {
  191. // Empty string should be interpreted as "no cost", i.e. 0.0
  192. if cp.SharedOverhead == "" {
  193. return 0.0
  194. }
  195. // Attempt to parse, but log and return 0.0 if that fails.
  196. sharedCostPerMonth, err := strconv.ParseFloat(cp.SharedOverhead, 64)
  197. if err != nil {
  198. log.Errorf("SharedOverhead: failed to parse shared overhead \"%s\": %s", cp.SharedOverhead, err)
  199. return 0.0
  200. }
  201. return sharedCostPerMonth
  202. }
  203. func sanitizeFloatString(number string, allowNaN bool) (string, error) {
  204. num, err := strconv.ParseFloat(number, 64)
  205. if err != nil {
  206. return "", fmt.Errorf("expected a string representing a number; got '%s'", number)
  207. }
  208. if !allowNaN && math.IsNaN(num) {
  209. return "", fmt.Errorf("expected a string representing a number; got 'NaN'")
  210. }
  211. // Format the numerical string we just parsed.
  212. return strconv.FormatFloat(num, 'f', -1, 64), nil
  213. }
  214. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  215. structValue := reflect.ValueOf(obj).Elem()
  216. structFieldValue := structValue.FieldByName(name)
  217. if !structFieldValue.IsValid() {
  218. return fmt.Errorf("no such field: %s in obj", name)
  219. }
  220. if !structFieldValue.CanSet() {
  221. return fmt.Errorf("cannot set %s field value", name)
  222. }
  223. // If the custom pricing field is expected to be a string representation
  224. // of a floating point number, e.g. a resource price, then do some extra
  225. // validation work in order to prevent "NaN" and other invalid strings
  226. // from getting set here.
  227. switch strings.ToLower(name) {
  228. case "cpu", "gpu", "ram", "spotcpu", "spotgpu", "spotram", "storage", "zonenetworkegress", "regionnetworkegress", "internetnetworkegress":
  229. // If we are sent an empty string, ignore the key and don't change the value
  230. if value == "" {
  231. return nil
  232. } else {
  233. // Validate that "value" represents a real floating point number, and
  234. // set precision, bits, etc. Do not allow NaN.
  235. val, err := sanitizeFloatString(value, false)
  236. if err != nil {
  237. return fmt.Errorf("invalid numeric value for field '%s': %s", name, value)
  238. }
  239. value = val
  240. }
  241. default:
  242. }
  243. structFieldType := structFieldValue.Type()
  244. value = sanitizePolicy.Sanitize(value)
  245. val := reflect.ValueOf(value)
  246. if structFieldType != val.Type() {
  247. return fmt.Errorf("provided value type didn't match custom pricing field type")
  248. }
  249. structFieldValue.Set(val)
  250. return nil
  251. }
  252. type PricingSources struct {
  253. PricingSources map[string]*PricingSource
  254. }
  255. type PricingSource struct {
  256. Name string `json:"name"`
  257. Enabled bool `json:"enabled"`
  258. Available bool `json:"available"`
  259. Error string `json:"error"`
  260. }
  261. type PricingType string
  262. const (
  263. Api PricingType = "api"
  264. Spot PricingType = "spot"
  265. Reserved PricingType = "reserved"
  266. SavingsPlan PricingType = "savingsPlan"
  267. CsvExact PricingType = "csvExact"
  268. CsvClass PricingType = "csvClass"
  269. DefaultPrices PricingType = "defaultPrices"
  270. )
  271. type PricingMatchMetadata struct {
  272. TotalNodes int `json:"TotalNodes"`
  273. PricingTypeCounts map[PricingType]int `json:"PricingType"`
  274. }
  275. // Provider represents a k8s provider.
  276. type Provider interface {
  277. ClusterInfo() (map[string]string, error)
  278. GetAddresses() ([]byte, error)
  279. GetDisks() ([]byte, error)
  280. GetOrphanedResources() ([]OrphanedResource, error)
  281. NodePricing(Key) (*Node, PricingMetadata, error)
  282. GpuPricing(map[string]string) (string, 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(*clustercache.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. ApplyReservedInstancePricing(map[string]*Node)
  295. ServiceAccountStatus() *ServiceAccountStatus
  296. PricingSourceStatus() map[string]*PricingSource
  297. ClusterManagementPricing() (string, float64, error)
  298. CombinedDiscountForNode(string, bool, float64, float64) float64
  299. Regions() []string
  300. PricingSourceSummary() interface{}
  301. }
  302. // ProviderConfig describes config storage common to all providers.
  303. type ProviderConfig interface {
  304. ConfigFileManager() *config.ConfigFileManager
  305. GetCustomPricingData() (*CustomPricing, error)
  306. Update(func(*CustomPricing) error) (*CustomPricing, error)
  307. UpdateFromMap(map[string]string) (*CustomPricing, error)
  308. }