models.go 14 KB

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