types.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. package types
  2. import (
  3. "fmt"
  4. "io"
  5. "reflect"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/microcosm-cc/bluemonday"
  11. v1 "k8s.io/api/core/v1"
  12. "github.com/opencost/opencost/pkg/log"
  13. )
  14. var sanitizePolicy = bluemonday.UGCPolicy()
  15. // ReservedInstanceData keeps record of resources on a node should be
  16. // priced at reserved rates
  17. type ReservedInstanceData struct {
  18. ReservedCPU int64 `json:"reservedCPU"`
  19. ReservedRAM int64 `json:"reservedRAM"`
  20. CPUCost float64 `json:"CPUHourlyCost"`
  21. RAMCost float64 `json:"RAMHourlyCost"`
  22. }
  23. // Node is the interface by which the provider and cost model communicate Node prices.
  24. // The provider will best-effort try to fill out this struct.
  25. type Node struct {
  26. Cost string `json:"hourlyCost"`
  27. VCPU string `json:"CPU"`
  28. VCPUCost string `json:"CPUHourlyCost"`
  29. RAM string `json:"RAM"`
  30. RAMBytes string `json:"RAMBytes"`
  31. RAMCost string `json:"RAMGBHourlyCost"`
  32. Storage string `json:"storage"`
  33. StorageCost string `json:"storageHourlyCost"`
  34. UsesBaseCPUPrice bool `json:"usesDefaultPrice"`
  35. BaseCPUPrice string `json:"baseCPUPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  36. BaseRAMPrice string `json:"baseRAMPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  37. BaseGPUPrice string `json:"baseGPUPrice"`
  38. UsageType string `json:"usageType"`
  39. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  40. GPUName string `json:"gpuName"`
  41. GPUCost string `json:"gpuCost"`
  42. InstanceType string `json:"instanceType,omitempty"`
  43. Region string `json:"region,omitempty"`
  44. Reserved *ReservedInstanceData `json:"reserved,omitempty"`
  45. ProviderID string `json:"providerID,omitempty"`
  46. PricingType PricingType `json:"pricingType,omitempty"`
  47. }
  48. // IsSpot determines whether or not a Node uses spot by usage type
  49. func (n *Node) IsSpot() bool {
  50. if n != nil {
  51. return strings.Contains(n.UsageType, "spot") || strings.Contains(n.UsageType, "emptible")
  52. } else {
  53. return false
  54. }
  55. }
  56. // LoadBalancer is the interface by which the provider and cost model communicate LoadBalancer prices.
  57. // The provider will best-effort try to fill out this struct.
  58. type LoadBalancer struct {
  59. IngressIPAddresses []string `json:"IngressIPAddresses"`
  60. Cost float64 `json:"hourlyCost"`
  61. }
  62. // TODO: used for dynamic cloud provider price fetching.
  63. // determine what identifies a load balancer in the json returned from the cloud provider pricing API call
  64. // type LBKey interface {
  65. // }
  66. // Network is the interface by which the provider and cost model communicate network egress prices.
  67. // The provider will best-effort try to fill out this struct.
  68. type Network struct {
  69. ZoneNetworkEgressCost float64
  70. RegionNetworkEgressCost float64
  71. InternetNetworkEgressCost float64
  72. }
  73. type OrphanedResource struct {
  74. Kind string `json:"resourceKind"`
  75. Region string `json:"region"`
  76. Description map[string]string `json:"description"`
  77. Size *int64 `json:"diskSizeInGB,omitempty"`
  78. DiskName string `json:"diskName,omitempty"`
  79. Url string `json:"url"`
  80. Address string `json:"ipAddress,omitempty"`
  81. MonthlyCost *float64 `json:"monthlyCost"`
  82. }
  83. // PV is the interface by which the provider and cost model communicate PV prices.
  84. // The provider will best-effort try to fill out this struct.
  85. type PV struct {
  86. Cost string `json:"hourlyCost"`
  87. CostPerIO string `json:"costPerIOOperation"`
  88. Class string `json:"storageClass"`
  89. Size string `json:"size"`
  90. Region string `json:"region"`
  91. ProviderID string `json:"providerID,omitempty"`
  92. Parameters map[string]string `json:"parameters"`
  93. }
  94. // Key represents a way for nodes to match between the k8s API and a pricing API
  95. type Key interface {
  96. ID() string // ID represents an exact match
  97. Features() string // Features are a comma separated string of node metadata that could match pricing
  98. GPUType() string // GPUType returns "" if no GPU exists or GPUs, but the name of the GPU otherwise
  99. GPUCount() int // GPUCount returns 0 if no GPU exists or GPUs, but the number of attached GPUs otherwise
  100. }
  101. type PVKey interface {
  102. Features() string
  103. GetStorageClass() string
  104. ID() string
  105. }
  106. // OutOfClusterAllocation represents a cloud provider cost not associated with kubernetes
  107. type OutOfClusterAllocation struct {
  108. Aggregator string `json:"aggregator"`
  109. Environment string `json:"environment"`
  110. Service string `json:"service"`
  111. Cost float64 `json:"cost"`
  112. Cluster string `json:"cluster"`
  113. }
  114. type CustomPricing struct {
  115. Provider string `json:"provider"`
  116. Description string `json:"description"`
  117. // CPU a string-encoded float describing cost per core-hour of CPU.
  118. CPU string `json:"CPU"`
  119. // CPU a string-encoded float describing cost per core-hour of CPU for spot
  120. // nodes.
  121. SpotCPU string `json:"spotCPU"`
  122. // RAM a string-encoded float describing cost per GiB-hour of RAM/memory.
  123. RAM string `json:"RAM"`
  124. // SpotRAM a string-encoded float describing cost per GiB-hour of RAM/memory
  125. // for spot nodes.
  126. SpotRAM string `json:"spotRAM"`
  127. GPU string `json:"GPU"`
  128. SpotGPU string `json:"spotGPU"`
  129. // Storage is a string-encoded float describing cost per GB-hour of storage
  130. // (e.g. PV, disk) resources.
  131. Storage string `json:"storage"`
  132. ZoneNetworkEgress string `json:"zoneNetworkEgress"`
  133. RegionNetworkEgress string `json:"regionNetworkEgress"`
  134. InternetNetworkEgress string `json:"internetNetworkEgress"`
  135. FirstFiveForwardingRulesCost string `json:"firstFiveForwardingRulesCost"`
  136. AdditionalForwardingRuleCost string `json:"additionalForwardingRuleCost"`
  137. LBIngressDataCost string `json:"LBIngressDataCost"`
  138. SpotLabel string `json:"spotLabel,omitempty"`
  139. SpotLabelValue string `json:"spotLabelValue,omitempty"`
  140. GpuLabel string `json:"gpuLabel,omitempty"`
  141. GpuLabelValue string `json:"gpuLabelValue,omitempty"`
  142. ServiceKeyName string `json:"awsServiceKeyName,omitempty"`
  143. ServiceKeySecret string `json:"awsServiceKeySecret,omitempty"`
  144. AlibabaServiceKeyName string `json:"alibabaServiceKeyName,omitempty"`
  145. AlibabaServiceKeySecret string `json:"alibabaServiceKeySecret,omitempty"`
  146. AlibabaClusterRegion string `json:"alibabaClusterRegion,omitempty"`
  147. SpotDataRegion string `json:"awsSpotDataRegion,omitempty"`
  148. SpotDataBucket string `json:"awsSpotDataBucket,omitempty"`
  149. SpotDataPrefix string `json:"awsSpotDataPrefix,omitempty"`
  150. ProjectID string `json:"projectID,omitempty"`
  151. AthenaProjectID string `json:"athenaProjectID,omitempty"`
  152. AthenaBucketName string `json:"athenaBucketName"`
  153. AthenaRegion string `json:"athenaRegion"`
  154. AthenaDatabase string `json:"athenaDatabase"`
  155. AthenaTable string `json:"athenaTable"`
  156. AthenaWorkgroup string `json:"athenaWorkgroup"`
  157. MasterPayerARN string `json:"masterPayerARN"`
  158. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  159. CustomPricesEnabled string `json:"customPricesEnabled"`
  160. DefaultIdle string `json:"defaultIdle"`
  161. AzureSubscriptionID string `json:"azureSubscriptionID"`
  162. AzureClientID string `json:"azureClientID"`
  163. AzureClientSecret string `json:"azureClientSecret"`
  164. AzureTenantID string `json:"azureTenantID"`
  165. AzureBillingRegion string `json:"azureBillingRegion"`
  166. AzureBillingAccount string `json:"azureBillingAccount"`
  167. AzureOfferDurableID string `json:"azureOfferDurableID"`
  168. AzureStorageSubscriptionID string `json:"azureStorageSubscriptionID"`
  169. AzureStorageAccount string `json:"azureStorageAccount"`
  170. AzureStorageAccessKey string `json:"azureStorageAccessKey"`
  171. AzureStorageContainer string `json:"azureStorageContainer"`
  172. AzureContainerPath string `json:"azureContainerPath"`
  173. AzureCloud string `json:"azureCloud"`
  174. CurrencyCode string `json:"currencyCode"`
  175. Discount string `json:"discount"`
  176. NegotiatedDiscount string `json:"negotiatedDiscount"`
  177. SharedOverhead string `json:"sharedOverhead"`
  178. ClusterName string `json:"clusterName"`
  179. ClusterAccountID string `json:"clusterAccount,omitempty"`
  180. SharedNamespaces string `json:"sharedNamespaces"`
  181. SharedLabelNames string `json:"sharedLabelNames"`
  182. SharedLabelValues string `json:"sharedLabelValues"`
  183. 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)
  184. ReadOnly string `json:"readOnly"`
  185. EditorAccess string `json:"editorAccess"`
  186. KubecostToken string `json:"kubecostToken"`
  187. GoogleAnalyticsTag string `json:"googleAnalyticsTag"`
  188. ExcludeProviderID string `json:"excludeProviderID"`
  189. DefaultLBPrice string `json:"defaultLBPrice"`
  190. }
  191. // GetSharedOverheadCostPerMonth parses and returns a float64 representation
  192. // of the configured monthly shared overhead cost. If the string version cannot
  193. // be parsed into a float, an error is logged and 0.0 is returned.
  194. func (cp *CustomPricing) GetSharedOverheadCostPerMonth() float64 {
  195. // Empty string should be interpreted as "no cost", i.e. 0.0
  196. if cp.SharedOverhead == "" {
  197. return 0.0
  198. }
  199. // Attempt to parse, but log and return 0.0 if that fails.
  200. sharedCostPerMonth, err := strconv.ParseFloat(cp.SharedOverhead, 64)
  201. if err != nil {
  202. log.Errorf("SharedOverhead: failed to parse shared overhead \"%s\": %s", cp.SharedOverhead, err)
  203. return 0.0
  204. }
  205. return sharedCostPerMonth
  206. }
  207. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  208. structValue := reflect.ValueOf(obj).Elem()
  209. structFieldValue := structValue.FieldByName(name)
  210. if !structFieldValue.IsValid() {
  211. return fmt.Errorf("No such field: %s in obj", name)
  212. }
  213. if !structFieldValue.CanSet() {
  214. return fmt.Errorf("Cannot set %s field value", name)
  215. }
  216. structFieldType := structFieldValue.Type()
  217. value = sanitizePolicy.Sanitize(value)
  218. val := reflect.ValueOf(value)
  219. if structFieldType != val.Type() {
  220. return fmt.Errorf("Provided value type didn't match custom pricing field type")
  221. }
  222. structFieldValue.Set(val)
  223. return nil
  224. }
  225. type ServiceAccountStatus struct {
  226. Checks []*ServiceAccountCheck `json:"checks"`
  227. }
  228. // ServiceAccountChecks is a thread safe map for holding ServiceAccountCheck objects
  229. type ServiceAccountChecks struct {
  230. sync.RWMutex
  231. serviceAccountChecks map[string]*ServiceAccountCheck
  232. }
  233. // NewServiceAccountChecks initialize ServiceAccountChecks
  234. func NewServiceAccountChecks() *ServiceAccountChecks {
  235. return &ServiceAccountChecks{
  236. serviceAccountChecks: make(map[string]*ServiceAccountCheck),
  237. }
  238. }
  239. func (sac *ServiceAccountChecks) Set(key string, check *ServiceAccountCheck) {
  240. sac.Lock()
  241. defer sac.Unlock()
  242. sac.serviceAccountChecks[key] = check
  243. }
  244. // getStatus extracts ServiceAccountCheck objects into a slice and returns them in a ServiceAccountStatus
  245. func (sac *ServiceAccountChecks) GetStatus() *ServiceAccountStatus {
  246. sac.Lock()
  247. defer sac.Unlock()
  248. checks := []*ServiceAccountCheck{}
  249. for _, v := range sac.serviceAccountChecks {
  250. checks = append(checks, v)
  251. }
  252. return &ServiceAccountStatus{
  253. Checks: checks,
  254. }
  255. }
  256. type ServiceAccountCheck struct {
  257. Message string `json:"message"`
  258. Status bool `json:"status"`
  259. AdditionalInfo string `json:"additionalInfo"`
  260. }
  261. type PricingSources struct {
  262. PricingSources map[string]*PricingSource
  263. }
  264. type PricingSource struct {
  265. Name string `json:"name"`
  266. Enabled bool `json:"enabled"`
  267. Available bool `json:"available"`
  268. Error string `json:"error"`
  269. }
  270. type PricingType string
  271. const (
  272. Api PricingType = "api"
  273. Spot PricingType = "spot"
  274. Reserved PricingType = "reserved"
  275. SavingsPlan PricingType = "savingsPlan"
  276. CsvExact PricingType = "csvExact"
  277. CsvClass PricingType = "csvClass"
  278. DefaultPrices PricingType = "defaultPrices"
  279. )
  280. type PricingMatchMetadata struct {
  281. TotalNodes int `json:"TotalNodes"`
  282. PricingTypeCounts map[PricingType]int `json:"PricingType"`
  283. }
  284. // Provider represents a k8s provider.
  285. type Provider interface {
  286. ClusterInfo() (map[string]string, error)
  287. GetAddresses() ([]byte, error)
  288. GetDisks() ([]byte, error)
  289. GetOrphanedResources() ([]OrphanedResource, error)
  290. NodePricing(Key) (*Node, error)
  291. PVPricing(PVKey) (*PV, error)
  292. NetworkPricing() (*Network, error) // TODO: add key interface arg for dynamic price fetching
  293. LoadBalancerPricing() (*LoadBalancer, error) // TODO: add key interface arg for dynamic price fetching
  294. AllNodePricing() (interface{}, error)
  295. DownloadPricingData() error
  296. GetKey(map[string]string, *v1.Node) Key
  297. GetPVKey(*v1.PersistentVolume, map[string]string, string) PVKey
  298. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  299. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  300. GetConfig() (*CustomPricing, error)
  301. GetManagementPlatform() (string, error)
  302. GetLocalStorageQuery(time.Duration, time.Duration, bool, bool) string
  303. ApplyReservedInstancePricing(map[string]*Node)
  304. ServiceAccountStatus() *ServiceAccountStatus
  305. PricingSourceStatus() map[string]*PricingSource
  306. ClusterManagementPricing() (string, float64, error)
  307. CombinedDiscountForNode(string, bool, float64, float64) float64
  308. Regions() []string
  309. PricingSourceSummary() interface{}
  310. }