models.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. package models
  2. import (
  3. "fmt"
  4. "io"
  5. "reflect"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/microcosm-cc/bluemonday"
  10. v1 "k8s.io/api/core/v1"
  11. "github.com/opencost/opencost/pkg/config"
  12. "github.com/opencost/opencost/pkg/log"
  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. InstanceType string `json:"instanceType,omitempty"`
  52. Region string `json:"region,omitempty"`
  53. Reserved *ReservedInstanceData `json:"reserved,omitempty"`
  54. ProviderID string `json:"providerID,omitempty"`
  55. PricingType PricingType `json:"pricingType,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. AthenaTable string `json:"athenaTable"`
  148. AthenaWorkgroup string `json:"athenaWorkgroup"`
  149. MasterPayerARN string `json:"masterPayerARN"`
  150. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  151. CustomPricesEnabled string `json:"customPricesEnabled"`
  152. DefaultIdle string `json:"defaultIdle"`
  153. AzureSubscriptionID string `json:"azureSubscriptionID"`
  154. AzureClientID string `json:"azureClientID"`
  155. AzureClientSecret string `json:"azureClientSecret"`
  156. AzureTenantID string `json:"azureTenantID"`
  157. AzureBillingRegion string `json:"azureBillingRegion"`
  158. AzureBillingAccount string `json:"azureBillingAccount"`
  159. AzureOfferDurableID string `json:"azureOfferDurableID"`
  160. AzureStorageSubscriptionID string `json:"azureStorageSubscriptionID"`
  161. AzureStorageAccount string `json:"azureStorageAccount"`
  162. AzureStorageAccessKey string `json:"azureStorageAccessKey"`
  163. AzureStorageContainer string `json:"azureStorageContainer"`
  164. AzureContainerPath string `json:"azureContainerPath"`
  165. AzureCloud string `json:"azureCloud"`
  166. CurrencyCode string `json:"currencyCode"`
  167. Discount string `json:"discount"`
  168. NegotiatedDiscount string `json:"negotiatedDiscount"`
  169. SharedOverhead string `json:"sharedOverhead"`
  170. ClusterName string `json:"clusterName"`
  171. ClusterAccountID string `json:"clusterAccount,omitempty"`
  172. SharedNamespaces string `json:"sharedNamespaces"`
  173. SharedLabelNames string `json:"sharedLabelNames"`
  174. SharedLabelValues string `json:"sharedLabelValues"`
  175. 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)
  176. ReadOnly string `json:"readOnly"`
  177. EditorAccess string `json:"editorAccess"`
  178. KubecostToken string `json:"kubecostToken"`
  179. GoogleAnalyticsTag string `json:"googleAnalyticsTag"`
  180. ExcludeProviderID string `json:"excludeProviderID"`
  181. DefaultLBPrice string `json:"defaultLBPrice"`
  182. }
  183. // GetSharedOverheadCostPerMonth parses and returns a float64 representation
  184. // of the configured monthly shared overhead cost. If the string version cannot
  185. // be parsed into a float, an error is logged and 0.0 is returned.
  186. func (cp *CustomPricing) GetSharedOverheadCostPerMonth() float64 {
  187. // Empty string should be interpreted as "no cost", i.e. 0.0
  188. if cp.SharedOverhead == "" {
  189. return 0.0
  190. }
  191. // Attempt to parse, but log and return 0.0 if that fails.
  192. sharedCostPerMonth, err := strconv.ParseFloat(cp.SharedOverhead, 64)
  193. if err != nil {
  194. log.Errorf("SharedOverhead: failed to parse shared overhead \"%s\": %s", cp.SharedOverhead, err)
  195. return 0.0
  196. }
  197. return sharedCostPerMonth
  198. }
  199. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  200. structValue := reflect.ValueOf(obj).Elem()
  201. structFieldValue := structValue.FieldByName(name)
  202. if !structFieldValue.IsValid() {
  203. return fmt.Errorf("No such field: %s in obj", name)
  204. }
  205. if !structFieldValue.CanSet() {
  206. return fmt.Errorf("Cannot set %s field value", name)
  207. }
  208. structFieldType := structFieldValue.Type()
  209. value = sanitizePolicy.Sanitize(value)
  210. val := reflect.ValueOf(value)
  211. if structFieldType != val.Type() {
  212. return fmt.Errorf("Provided value type didn't match custom pricing field type")
  213. }
  214. structFieldValue.Set(val)
  215. return nil
  216. }
  217. type PricingSources struct {
  218. PricingSources map[string]*PricingSource
  219. }
  220. type PricingSource struct {
  221. Name string `json:"name"`
  222. Enabled bool `json:"enabled"`
  223. Available bool `json:"available"`
  224. Error string `json:"error"`
  225. }
  226. type PricingType string
  227. const (
  228. Api PricingType = "api"
  229. Spot PricingType = "spot"
  230. Reserved PricingType = "reserved"
  231. SavingsPlan PricingType = "savingsPlan"
  232. CsvExact PricingType = "csvExact"
  233. CsvClass PricingType = "csvClass"
  234. DefaultPrices PricingType = "defaultPrices"
  235. )
  236. type PricingMatchMetadata struct {
  237. TotalNodes int `json:"TotalNodes"`
  238. PricingTypeCounts map[PricingType]int `json:"PricingType"`
  239. }
  240. // Provider represents a k8s provider.
  241. type Provider interface {
  242. ClusterInfo() (map[string]string, error)
  243. GetAddresses() ([]byte, error)
  244. GetDisks() ([]byte, error)
  245. GetOrphanedResources() ([]OrphanedResource, error)
  246. NodePricing(Key) (*Node, error)
  247. PVPricing(PVKey) (*PV, error)
  248. NetworkPricing() (*Network, error) // TODO: add key interface arg for dynamic price fetching
  249. LoadBalancerPricing() (*LoadBalancer, error) // TODO: add key interface arg for dynamic price fetching
  250. AllNodePricing() (interface{}, error)
  251. DownloadPricingData() error
  252. GetKey(map[string]string, *v1.Node) Key
  253. GetPVKey(*v1.PersistentVolume, map[string]string, string) PVKey
  254. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  255. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  256. GetConfig() (*CustomPricing, error)
  257. GetManagementPlatform() (string, error)
  258. GetLocalStorageQuery(time.Duration, time.Duration, bool, bool) string
  259. ApplyReservedInstancePricing(map[string]*Node)
  260. ServiceAccountStatus() *ServiceAccountStatus
  261. PricingSourceStatus() map[string]*PricingSource
  262. ClusterManagementPricing() (string, float64, error)
  263. CombinedDiscountForNode(string, bool, float64, float64) float64
  264. Regions() []string
  265. PricingSourceSummary() interface{}
  266. }
  267. // ProviderConfig describes config storage common to all providers.
  268. type ProviderConfig interface {
  269. ConfigFileManager() *config.ConfigFileManager
  270. GetCustomPricingData() (*CustomPricing, error)
  271. Update(func(*CustomPricing) error) (*CustomPricing, error)
  272. UpdateFromMap(map[string]string) (*CustomPricing, error)
  273. }