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. "time"
  10. "github.com/microcosm-cc/bluemonday"
  11. "github.com/opencost/opencost/core/pkg/log"
  12. "github.com/opencost/opencost/pkg/clustercache"
  13. "github.com/opencost/opencost/pkg/config"
  14. )
  15. var (
  16. sanitizePolicy = bluemonday.UGCPolicy()
  17. )
  18. const (
  19. AuthSecretPath = "/var/secrets/service-key.json"
  20. StorageConfigSecretPath = "/var/azure-storage-config/azure-storage-config.json"
  21. DefaultShareTenancyCost = "true"
  22. KarpenterCapacityTypeLabel = "karpenter.sh/capacity-type"
  23. KarpenterCapacitySpotTypeValue = "spot"
  24. )
  25. // ReservedInstanceData keeps record of resources on a node should be
  26. // priced at reserved rates
  27. type ReservedInstanceData struct {
  28. ReservedCPU int64 `json:"reservedCPU"`
  29. ReservedRAM int64 `json:"reservedRAM"`
  30. CPUCost float64 `json:"CPUHourlyCost"`
  31. RAMCost float64 `json:"RAMHourlyCost"`
  32. }
  33. // Node is the interface by which the provider and cost model communicate Node prices.
  34. // The provider will best-effort try to fill out this struct.
  35. type Node struct {
  36. Cost string `json:"hourlyCost"`
  37. VCPU string `json:"CPU"`
  38. VCPUCost string `json:"CPUHourlyCost"`
  39. RAM string `json:"RAM"`
  40. RAMBytes string `json:"RAMBytes"`
  41. RAMCost string `json:"RAMGBHourlyCost"`
  42. Storage string `json:"storage"`
  43. StorageCost string `json:"storageHourlyCost"`
  44. UsesBaseCPUPrice bool `json:"usesDefaultPrice"`
  45. BaseCPUPrice string `json:"baseCPUPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  46. BaseRAMPrice string `json:"baseRAMPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  47. BaseGPUPrice string `json:"baseGPUPrice"`
  48. UsageType string `json:"usageType"`
  49. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  50. GPUName string `json:"gpuName"`
  51. GPUCost string `json:"gpuCost"`
  52. VGPU string `json:"vgpu"` // virtualized gpu-- if we are using gpu replicas
  53. InstanceType string `json:"instanceType,omitempty"`
  54. Region string `json:"region,omitempty"`
  55. Reserved *ReservedInstanceData `json:"reserved,omitempty"`
  56. ProviderID string `json:"providerID,omitempty"`
  57. PricingType PricingType `json:"pricingType,omitempty"`
  58. ArchType string `json:"archType,omitempty"`
  59. }
  60. // IsSpot determines whether or not a Node uses spot by usage type
  61. func (n *Node) IsSpot() bool {
  62. if n != nil {
  63. return strings.Contains(n.UsageType, "spot") || strings.Contains(n.UsageType, "emptible")
  64. } else {
  65. return false
  66. }
  67. }
  68. type OrphanedResource struct {
  69. Kind string `json:"resourceKind"`
  70. Region string `json:"region"`
  71. Description map[string]string `json:"description"`
  72. Size *int64 `json:"diskSizeInGB,omitempty"`
  73. DiskName string `json:"diskName,omitempty"`
  74. Url string `json:"url"`
  75. Address string `json:"ipAddress,omitempty"`
  76. MonthlyCost *float64 `json:"monthlyCost"`
  77. }
  78. // PV is the interface by which the provider and cost model communicate PV prices.
  79. // The provider will best-effort try to fill out this struct.
  80. type PV struct {
  81. Cost string `json:"hourlyCost"`
  82. CostPerIO string `json:"costPerIOOperation"`
  83. Class string `json:"storageClass"`
  84. Size string `json:"size"`
  85. Region string `json:"region"`
  86. ProviderID string `json:"providerID,omitempty"`
  87. Parameters map[string]string `json:"parameters"`
  88. }
  89. // Key represents a way for nodes to match between the k8s API and a pricing API
  90. type Key interface {
  91. ID() string // ID represents an exact match
  92. Features() string // Features are a comma separated string of node metadata that could match pricing
  93. GPUType() string // GPUType returns "" if no GPU exists or GPUs, but the name of the GPU otherwise
  94. GPUCount() int // GPUCount returns 0 if no GPU exists or GPUs, but the number of attached GPUs otherwise
  95. }
  96. type PVKey interface {
  97. Features() string
  98. GetStorageClass() string
  99. ID() string
  100. }
  101. // OutOfClusterAllocation represents a cloud provider cost not associated with kubernetes
  102. type OutOfClusterAllocation struct {
  103. Aggregator string `json:"aggregator"`
  104. Environment string `json:"environment"`
  105. Service string `json:"service"`
  106. Cost float64 `json:"cost"`
  107. Cluster string `json:"cluster"`
  108. }
  109. type CustomPricing struct {
  110. Provider string `json:"provider"`
  111. Description string `json:"description"`
  112. // CPU a string-encoded float describing cost per core-hour of CPU.
  113. CPU string `json:"CPU"`
  114. // CPU a string-encoded float describing cost per core-hour of CPU for spot
  115. // nodes.
  116. SpotCPU string `json:"spotCPU"`
  117. // RAM a string-encoded float describing cost per GiB-hour of RAM/memory.
  118. RAM string `json:"RAM"`
  119. // SpotRAM a string-encoded float describing cost per GiB-hour of RAM/memory
  120. // for spot nodes.
  121. SpotRAM string `json:"spotRAM"`
  122. GPU string `json:"GPU"`
  123. SpotGPU string `json:"spotGPU"`
  124. // Storage is a string-encoded float describing cost per GB-hour of storage
  125. // (e.g. PV, disk) resources.
  126. Storage string `json:"storage"`
  127. ZoneNetworkEgress string `json:"zoneNetworkEgress"`
  128. RegionNetworkEgress string `json:"regionNetworkEgress"`
  129. InternetNetworkEgress string `json:"internetNetworkEgress"`
  130. FirstFiveForwardingRulesCost string `json:"firstFiveForwardingRulesCost"`
  131. AdditionalForwardingRuleCost string `json:"additionalForwardingRuleCost"`
  132. LBIngressDataCost string `json:"LBIngressDataCost"`
  133. SpotLabel string `json:"spotLabel,omitempty"`
  134. SpotLabelValue string `json:"spotLabelValue,omitempty"`
  135. GpuLabel string `json:"gpuLabel,omitempty"`
  136. GpuLabelValue string `json:"gpuLabelValue,omitempty"`
  137. ServiceKeyName string `json:"awsServiceKeyName,omitempty"`
  138. ServiceKeySecret string `json:"awsServiceKeySecret,omitempty"`
  139. AlibabaServiceKeyName string `json:"alibabaServiceKeyName,omitempty"`
  140. AlibabaServiceKeySecret string `json:"alibabaServiceKeySecret,omitempty"`
  141. AlibabaClusterRegion string `json:"alibabaClusterRegion,omitempty"`
  142. SpotDataRegion string `json:"awsSpotDataRegion,omitempty"`
  143. SpotDataBucket string `json:"awsSpotDataBucket,omitempty"`
  144. SpotDataPrefix string `json:"awsSpotDataPrefix,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. 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. 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. GetLocalStorageQuery(time.Duration, time.Duration, bool, bool) string
  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. }