models.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. ArchType string `json:"archType,omitempty"`
  57. }
  58. // IsSpot determines whether or not a Node uses spot by usage type
  59. func (n *Node) IsSpot() bool {
  60. if n != nil {
  61. return strings.Contains(n.UsageType, "spot") || strings.Contains(n.UsageType, "emptible")
  62. } else {
  63. return false
  64. }
  65. }
  66. type OrphanedResource struct {
  67. Kind string `json:"resourceKind"`
  68. Region string `json:"region"`
  69. Description map[string]string `json:"description"`
  70. Size *int64 `json:"diskSizeInGB,omitempty"`
  71. DiskName string `json:"diskName,omitempty"`
  72. Url string `json:"url"`
  73. Address string `json:"ipAddress,omitempty"`
  74. MonthlyCost *float64 `json:"monthlyCost"`
  75. }
  76. // PV is the interface by which the provider and cost model communicate PV prices.
  77. // The provider will best-effort try to fill out this struct.
  78. type PV struct {
  79. Cost string `json:"hourlyCost"`
  80. CostPerIO string `json:"costPerIOOperation"`
  81. Class string `json:"storageClass"`
  82. Size string `json:"size"`
  83. Region string `json:"region"`
  84. ProviderID string `json:"providerID,omitempty"`
  85. Parameters map[string]string `json:"parameters"`
  86. }
  87. // Key represents a way for nodes to match between the k8s API and a pricing API
  88. type Key interface {
  89. ID() string // ID represents an exact match
  90. Features() string // Features are a comma separated string of node metadata that could match pricing
  91. GPUType() string // GPUType returns "" if no GPU exists or GPUs, but the name of the GPU otherwise
  92. GPUCount() int // GPUCount returns 0 if no GPU exists or GPUs, but the number of attached GPUs otherwise
  93. }
  94. type PVKey interface {
  95. Features() string
  96. GetStorageClass() string
  97. ID() string
  98. }
  99. // OutOfClusterAllocation represents a cloud provider cost not associated with kubernetes
  100. type OutOfClusterAllocation struct {
  101. Aggregator string `json:"aggregator"`
  102. Environment string `json:"environment"`
  103. Service string `json:"service"`
  104. Cost float64 `json:"cost"`
  105. Cluster string `json:"cluster"`
  106. }
  107. type CustomPricing struct {
  108. Provider string `json:"provider"`
  109. Description string `json:"description"`
  110. // CPU a string-encoded float describing cost per core-hour of CPU.
  111. CPU string `json:"CPU"`
  112. // CPU a string-encoded float describing cost per core-hour of CPU for spot
  113. // nodes.
  114. SpotCPU string `json:"spotCPU"`
  115. // RAM a string-encoded float describing cost per GiB-hour of RAM/memory.
  116. RAM string `json:"RAM"`
  117. // SpotRAM a string-encoded float describing cost per GiB-hour of RAM/memory
  118. // for spot nodes.
  119. SpotRAM string `json:"spotRAM"`
  120. GPU string `json:"GPU"`
  121. SpotGPU string `json:"spotGPU"`
  122. // Storage is a string-encoded float describing cost per GB-hour of storage
  123. // (e.g. PV, disk) resources.
  124. Storage string `json:"storage"`
  125. ZoneNetworkEgress string `json:"zoneNetworkEgress"`
  126. RegionNetworkEgress string `json:"regionNetworkEgress"`
  127. InternetNetworkEgress string `json:"internetNetworkEgress"`
  128. FirstFiveForwardingRulesCost string `json:"firstFiveForwardingRulesCost"`
  129. AdditionalForwardingRuleCost string `json:"additionalForwardingRuleCost"`
  130. LBIngressDataCost string `json:"LBIngressDataCost"`
  131. SpotLabel string `json:"spotLabel,omitempty"`
  132. SpotLabelValue string `json:"spotLabelValue,omitempty"`
  133. GpuLabel string `json:"gpuLabel,omitempty"`
  134. GpuLabelValue string `json:"gpuLabelValue,omitempty"`
  135. ServiceKeyName string `json:"awsServiceKeyName,omitempty"`
  136. ServiceKeySecret string `json:"awsServiceKeySecret,omitempty"`
  137. AlibabaServiceKeyName string `json:"alibabaServiceKeyName,omitempty"`
  138. AlibabaServiceKeySecret string `json:"alibabaServiceKeySecret,omitempty"`
  139. AlibabaClusterRegion string `json:"alibabaClusterRegion,omitempty"`
  140. SpotDataRegion string `json:"awsSpotDataRegion,omitempty"`
  141. SpotDataBucket string `json:"awsSpotDataBucket,omitempty"`
  142. SpotDataPrefix string `json:"awsSpotDataPrefix,omitempty"`
  143. ProjectID string `json:"projectID,omitempty"`
  144. AthenaProjectID string `json:"athenaProjectID,omitempty"`
  145. AthenaBucketName string `json:"athenaBucketName"`
  146. AthenaRegion string `json:"athenaRegion"`
  147. AthenaDatabase string `json:"athenaDatabase"`
  148. AthenaTable string `json:"athenaTable"`
  149. AthenaWorkgroup string `json:"athenaWorkgroup"`
  150. MasterPayerARN string `json:"masterPayerARN"`
  151. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  152. CustomPricesEnabled string `json:"customPricesEnabled"`
  153. DefaultIdle string `json:"defaultIdle"`
  154. AzureSubscriptionID string `json:"azureSubscriptionID"`
  155. AzureClientID string `json:"azureClientID"`
  156. AzureClientSecret string `json:"azureClientSecret"`
  157. AzureTenantID string `json:"azureTenantID"`
  158. AzureBillingRegion string `json:"azureBillingRegion"`
  159. AzureBillingAccount string `json:"azureBillingAccount"`
  160. AzureOfferDurableID string `json:"azureOfferDurableID"`
  161. AzureStorageSubscriptionID string `json:"azureStorageSubscriptionID"`
  162. AzureStorageAccount string `json:"azureStorageAccount"`
  163. AzureStorageAccessKey string `json:"azureStorageAccessKey"`
  164. AzureStorageContainer string `json:"azureStorageContainer"`
  165. AzureContainerPath string `json:"azureContainerPath"`
  166. AzureCloud string `json:"azureCloud"`
  167. CurrencyCode string `json:"currencyCode"`
  168. Discount string `json:"discount"`
  169. NegotiatedDiscount string `json:"negotiatedDiscount"`
  170. SharedOverhead string `json:"sharedOverhead"`
  171. ClusterName string `json:"clusterName"`
  172. ClusterAccountID string `json:"clusterAccount,omitempty"`
  173. SharedNamespaces string `json:"sharedNamespaces"`
  174. SharedLabelNames string `json:"sharedLabelNames"`
  175. SharedLabelValues string `json:"sharedLabelValues"`
  176. 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)
  177. ReadOnly string `json:"readOnly"`
  178. EditorAccess string `json:"editorAccess"`
  179. KubecostToken string `json:"kubecostToken"`
  180. GoogleAnalyticsTag string `json:"googleAnalyticsTag"`
  181. ExcludeProviderID string `json:"excludeProviderID"`
  182. DefaultLBPrice string `json:"defaultLBPrice"`
  183. }
  184. // GetSharedOverheadCostPerMonth parses and returns a float64 representation
  185. // of the configured monthly shared overhead cost. If the string version cannot
  186. // be parsed into a float, an error is logged and 0.0 is returned.
  187. func (cp *CustomPricing) GetSharedOverheadCostPerMonth() float64 {
  188. // Empty string should be interpreted as "no cost", i.e. 0.0
  189. if cp.SharedOverhead == "" {
  190. return 0.0
  191. }
  192. // Attempt to parse, but log and return 0.0 if that fails.
  193. sharedCostPerMonth, err := strconv.ParseFloat(cp.SharedOverhead, 64)
  194. if err != nil {
  195. log.Errorf("SharedOverhead: failed to parse shared overhead \"%s\": %s", cp.SharedOverhead, err)
  196. return 0.0
  197. }
  198. return sharedCostPerMonth
  199. }
  200. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  201. structValue := reflect.ValueOf(obj).Elem()
  202. structFieldValue := structValue.FieldByName(name)
  203. if !structFieldValue.IsValid() {
  204. return fmt.Errorf("No such field: %s in obj", name)
  205. }
  206. if !structFieldValue.CanSet() {
  207. return fmt.Errorf("Cannot set %s field value", name)
  208. }
  209. structFieldType := structFieldValue.Type()
  210. value = sanitizePolicy.Sanitize(value)
  211. val := reflect.ValueOf(value)
  212. if structFieldType != val.Type() {
  213. return fmt.Errorf("Provided value type didn't match custom pricing field type")
  214. }
  215. structFieldValue.Set(val)
  216. return nil
  217. }
  218. type PricingSources struct {
  219. PricingSources map[string]*PricingSource
  220. }
  221. type PricingSource struct {
  222. Name string `json:"name"`
  223. Enabled bool `json:"enabled"`
  224. Available bool `json:"available"`
  225. Error string `json:"error"`
  226. }
  227. type PricingType string
  228. const (
  229. Api PricingType = "api"
  230. Spot PricingType = "spot"
  231. Reserved PricingType = "reserved"
  232. SavingsPlan PricingType = "savingsPlan"
  233. CsvExact PricingType = "csvExact"
  234. CsvClass PricingType = "csvClass"
  235. DefaultPrices PricingType = "defaultPrices"
  236. )
  237. type PricingMatchMetadata struct {
  238. TotalNodes int `json:"TotalNodes"`
  239. PricingTypeCounts map[PricingType]int `json:"PricingType"`
  240. }
  241. // Provider represents a k8s provider.
  242. type Provider interface {
  243. ClusterInfo() (map[string]string, error)
  244. GetAddresses() ([]byte, error)
  245. GetDisks() ([]byte, error)
  246. GetOrphanedResources() ([]OrphanedResource, error)
  247. NodePricing(Key) (*Node, error)
  248. PVPricing(PVKey) (*PV, error)
  249. NetworkPricing() (*Network, error) // TODO: add key interface arg for dynamic price fetching
  250. LoadBalancerPricing() (*LoadBalancer, error) // TODO: add key interface arg for dynamic price fetching
  251. AllNodePricing() (interface{}, error)
  252. DownloadPricingData() error
  253. GetKey(map[string]string, *v1.Node) Key
  254. GetPVKey(*v1.PersistentVolume, map[string]string, string) PVKey
  255. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  256. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  257. GetConfig() (*CustomPricing, error)
  258. GetManagementPlatform() (string, error)
  259. GetLocalStorageQuery(time.Duration, time.Duration, bool, bool) string
  260. ApplyReservedInstancePricing(map[string]*Node)
  261. ServiceAccountStatus() *ServiceAccountStatus
  262. PricingSourceStatus() map[string]*PricingSource
  263. ClusterManagementPricing() (string, float64, error)
  264. CombinedDiscountForNode(string, bool, float64, float64) float64
  265. Regions() []string
  266. PricingSourceSummary() interface{}
  267. }
  268. // ProviderConfig describes config storage common to all providers.
  269. type ProviderConfig interface {
  270. ConfigFileManager() *config.ConfigFileManager
  271. GetCustomPricingData() (*CustomPricing, error)
  272. Update(func(*CustomPricing) error) (*CustomPricing, error)
  273. UpdateFromMap(map[string]string) (*CustomPricing, error)
  274. }