types.go 15 KB

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