provider.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. package cloud
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "strings"
  8. "k8s.io/klog"
  9. "cloud.google.com/go/compute/metadata"
  10. "github.com/kubecost/cost-model/pkg/clustercache"
  11. "github.com/kubecost/cost-model/pkg/env"
  12. v1 "k8s.io/api/core/v1"
  13. )
  14. const authSecretPath = "/var/secrets/service-key.json"
  15. var createTableStatements = []string{
  16. `CREATE TABLE IF NOT EXISTS names (
  17. cluster_id VARCHAR(255) NOT NULL,
  18. cluster_name VARCHAR(255) NULL,
  19. PRIMARY KEY (cluster_id)
  20. );`,
  21. }
  22. // ReservedInstanceData keeps record of resources on a node should be
  23. // priced at reserved rates
  24. type ReservedInstanceData struct {
  25. ReservedCPU int64 `json:"reservedCPU"`
  26. ReservedRAM int64 `json:"reservedRAM"`
  27. CPUCost float64 `json:"CPUHourlyCost"`
  28. RAMCost float64 `json:"RAMHourlyCost"`
  29. }
  30. // Node is the interface by which the provider and cost model communicate Node prices.
  31. // The provider will best-effort try to fill out this struct.
  32. type Node struct {
  33. Cost string `json:"hourlyCost"`
  34. VCPU string `json:"CPU"`
  35. VCPUCost string `json:"CPUHourlyCost"`
  36. RAM string `json:"RAM"`
  37. RAMBytes string `json:"RAMBytes"`
  38. RAMCost string `json:"RAMGBHourlyCost"`
  39. Storage string `json:"storage"`
  40. StorageCost string `json:"storageHourlyCost"`
  41. UsesBaseCPUPrice bool `json:"usesDefaultPrice"`
  42. BaseCPUPrice string `json:"baseCPUPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  43. BaseRAMPrice string `json:"baseRAMPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  44. BaseGPUPrice string `json:"baseGPUPrice"`
  45. UsageType string `json:"usageType"`
  46. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  47. GPUName string `json:"gpuName"`
  48. GPUCost string `json:"gpuCost"`
  49. InstanceType string `json:"instanceType,omitempty"`
  50. Region string `json:"region,omitempty"`
  51. Reserved *ReservedInstanceData `json:"reserved,omitempty"`
  52. ProviderID string `json:"providerID,omitempty"`
  53. PricingType PricingType `json:"pricingType,omitempty"`
  54. }
  55. // IsSpot determines whether or not a Node uses spot by usage type
  56. func (n *Node) IsSpot() bool {
  57. if n != nil {
  58. return strings.Contains(n.UsageType, "spot") || strings.Contains(n.UsageType, "emptible")
  59. } else {
  60. return false
  61. }
  62. }
  63. // LoadBalancer is the interface by which the provider and cost model communicate LoadBalancer prices.
  64. // The provider will best-effort try to fill out this struct.
  65. type LoadBalancer struct {
  66. IngressIPAddresses []string `json:"IngressIPAddresses"`
  67. Cost float64 `json:"hourlyCost"`
  68. }
  69. // TODO: used for dynamic cloud provider price fetching.
  70. // determine what identifies a load balancer in the json returned from the cloud provider pricing API call
  71. // type LBKey interface {
  72. // }
  73. // Network is the interface by which the provider and cost model communicate network egress prices.
  74. // The provider will best-effort try to fill out this struct.
  75. type Network struct {
  76. ZoneNetworkEgressCost float64
  77. RegionNetworkEgressCost float64
  78. InternetNetworkEgressCost float64
  79. }
  80. // PV is the interface by which the provider and cost model communicate PV prices.
  81. // The provider will best-effort try to fill out this struct.
  82. type PV struct {
  83. Cost string `json:"hourlyCost"`
  84. CostPerIO string `json:"costPerIOOperation"`
  85. Class string `json:"storageClass"`
  86. Size string `json:"size"`
  87. Region string `json:"region"`
  88. ProviderID string `json:"providerID,omitempty"`
  89. Parameters map[string]string `json:"parameters"`
  90. }
  91. // Key represents a way for nodes to match between the k8s API and a pricing API
  92. type Key interface {
  93. ID() string // ID represents an exact match
  94. Features() string // Features are a comma separated string of node metadata that could match pricing
  95. GPUType() string // GPUType returns "" if no GPU exists, but the name of the GPU otherwise
  96. }
  97. type PVKey interface {
  98. Features() string
  99. GetStorageClass() string
  100. ID() string
  101. }
  102. // OutOfClusterAllocation represents a cloud provider cost not associated with kubernetes
  103. type OutOfClusterAllocation struct {
  104. Aggregator string `json:"aggregator"`
  105. Environment string `json:"environment"`
  106. Service string `json:"service"`
  107. Cost float64 `json:"cost"`
  108. Cluster string `json:"cluster"`
  109. }
  110. type CustomPricing struct {
  111. Provider string `json:"provider"`
  112. Description string `json:"description"`
  113. CPU string `json:"CPU"`
  114. SpotCPU string `json:"spotCPU"`
  115. RAM string `json:"RAM"`
  116. SpotRAM string `json:"spotRAM"`
  117. GPU string `json:"GPU"`
  118. SpotGPU string `json:"spotGPU"`
  119. Storage string `json:"storage"`
  120. ZoneNetworkEgress string `json:"zoneNetworkEgress"`
  121. RegionNetworkEgress string `json:"regionNetworkEgress"`
  122. InternetNetworkEgress string `json:"internetNetworkEgress"`
  123. FirstFiveForwardingRulesCost string `json:"firstFiveForwardingRulesCost"`
  124. AdditionalForwardingRuleCost string `json:"additionalForwardingRuleCost"`
  125. LBIngressDataCost string `json:"LBIngressDataCost"`
  126. SpotLabel string `json:"spotLabel,omitempty"`
  127. SpotLabelValue string `json:"spotLabelValue,omitempty"`
  128. GpuLabel string `json:"gpuLabel,omitempty"`
  129. GpuLabelValue string `json:"gpuLabelValue,omitempty"`
  130. ServiceKeyName string `json:"awsServiceKeyName,omitempty"`
  131. ServiceKeySecret string `json:"awsServiceKeySecret,omitempty"`
  132. SpotDataRegion string `json:"awsSpotDataRegion,omitempty"`
  133. SpotDataBucket string `json:"awsSpotDataBucket,omitempty"`
  134. SpotDataPrefix string `json:"awsSpotDataPrefix,omitempty"`
  135. ProjectID string `json:"projectID,omitempty"`
  136. AthenaProjectID string `json:"athenaProjectID,omitempty"`
  137. AthenaBucketName string `json:"athenaBucketName"`
  138. AthenaRegion string `json:"athenaRegion"`
  139. AthenaDatabase string `json:"athenaDatabase"`
  140. AthenaTable string `json:"athenaTable"`
  141. MasterPayerARN string `json:"masterPayerARN"`
  142. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  143. CustomPricesEnabled string `json:"customPricesEnabled"`
  144. DefaultIdle string `json:"defaultIdle"`
  145. AzureSubscriptionID string `json:"azureSubscriptionID"`
  146. AzureClientID string `json:"azureClientID"`
  147. AzureClientSecret string `json:"azureClientSecret"`
  148. AzureTenantID string `json:"azureTenantID"`
  149. AzureBillingRegion string `json:"azureBillingRegion"`
  150. CurrencyCode string `json:"currencyCode"`
  151. Discount string `json:"discount"`
  152. NegotiatedDiscount string `json:"negotiatedDiscount"`
  153. SharedCosts map[string]string `json:"sharedCost"`
  154. ClusterName string `json:"clusterName"`
  155. SharedNamespaces string `json:"sharedNamespaces"`
  156. SharedLabelNames string `json:"sharedLabelNames"`
  157. SharedLabelValues string `json:"sharedLabelValues"`
  158. ReadOnly string `json:"readOnly"`
  159. }
  160. type ServiceAccountStatus struct {
  161. Checks []*ServiceAccountCheck `json:"checks"`
  162. }
  163. type ServiceAccountCheck struct {
  164. Message string `json:"message"`
  165. Status bool `json:"status"`
  166. AdditionalInfo string `json:additionalInfo`
  167. }
  168. type PricingSources struct {
  169. PricingSources map[string]*PricingSource
  170. }
  171. type PricingSource struct {
  172. Name string `json:"name"`
  173. Available bool `json:"available"`
  174. Error string `json:"error"`
  175. }
  176. type PricingType string
  177. const (
  178. Api PricingType = "api"
  179. Spot PricingType = "spot"
  180. Reserved PricingType = "reserved"
  181. SavingsPlan PricingType = "savingsPlan"
  182. CsvExact PricingType = "csvExact"
  183. CsvClass PricingType = "csvClass"
  184. DefaultPrices PricingType = "defaultPrices"
  185. )
  186. type PricingMatchMetadata struct {
  187. TotalNodes int `json:"TotalNodes"`
  188. PricingTypeCounts map[PricingType]int `json:"PricingType"`
  189. }
  190. // Provider represents a k8s provider.
  191. type Provider interface {
  192. ClusterInfo() (map[string]string, error)
  193. GetAddresses() ([]byte, error)
  194. GetDisks() ([]byte, error)
  195. NodePricing(Key) (*Node, error)
  196. PVPricing(PVKey) (*PV, error)
  197. NetworkPricing() (*Network, error) // TODO: add key interface arg for dynamic price fetching
  198. LoadBalancerPricing() (*LoadBalancer, error) // TODO: add key interface arg for dynamic price fetching
  199. AllNodePricing() (interface{}, error)
  200. DownloadPricingData() error
  201. GetKey(map[string]string, *v1.Node) Key
  202. GetPVKey(*v1.PersistentVolume, map[string]string, string) PVKey
  203. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  204. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  205. GetConfig() (*CustomPricing, error)
  206. GetManagementPlatform() (string, error)
  207. GetLocalStorageQuery(string, string, bool, bool) string
  208. ExternalAllocations(string, string, []string, string, string, bool) ([]*OutOfClusterAllocation, error)
  209. ApplyReservedInstancePricing(map[string]*Node)
  210. ServiceAccountStatus() *ServiceAccountStatus
  211. PricingSourceStatus() map[string]*PricingSource
  212. ClusterManagementPricing() (string, float64, error)
  213. CombinedDiscountForNode(string, bool, float64, float64) float64
  214. ParseID(string) string
  215. ParsePVID(string) string
  216. }
  217. // ClusterName returns the name defined in cluster info, defaulting to the
  218. // CLUSTER_ID environment variable
  219. func ClusterName(p Provider) string {
  220. info, err := p.ClusterInfo()
  221. if err != nil {
  222. return env.GetClusterID()
  223. }
  224. name, ok := info["name"]
  225. if !ok {
  226. return env.GetClusterID()
  227. }
  228. return name
  229. }
  230. // CustomPricesEnabled returns the boolean equivalent of the cloup provider's custom prices flag,
  231. // indicating whether or not the cluster is using custom pricing.
  232. func CustomPricesEnabled(p Provider) bool {
  233. config, err := p.GetConfig()
  234. if err != nil {
  235. return false
  236. }
  237. if config.NegotiatedDiscount == "" {
  238. config.NegotiatedDiscount = "0%"
  239. }
  240. return config.CustomPricesEnabled == "true"
  241. }
  242. // AllocateIdleByDefault returns true if the application settings specify to allocate idle by default
  243. func AllocateIdleByDefault(p Provider) bool {
  244. config, err := p.GetConfig()
  245. if err != nil {
  246. return false
  247. }
  248. return config.DefaultIdle == "true"
  249. }
  250. // SharedNamespace returns a list of names of shared namespaces, as defined in the application settings
  251. func SharedNamespaces(p Provider) []string {
  252. namespaces := []string{}
  253. config, err := p.GetConfig()
  254. if err != nil {
  255. return namespaces
  256. }
  257. if config.SharedNamespaces == "" {
  258. return namespaces
  259. }
  260. // trim spaces so that "kube-system, kubecost" is equivalent to "kube-system,kubecost"
  261. for _, ns := range strings.Split(config.SharedNamespaces, ",") {
  262. namespaces = append(namespaces, strings.Trim(ns, " "))
  263. }
  264. return namespaces
  265. }
  266. // SharedLabel returns the configured set of shared labels as a parallel tuple of keys to values; e.g.
  267. // for app:kubecost,type:staging this returns (["app", "type"], ["kubecost", "staging"]) in order to
  268. // match the signature of the NewSharedResourceInfo
  269. func SharedLabels(p Provider) ([]string, []string) {
  270. names := []string{}
  271. values := []string{}
  272. config, err := p.GetConfig()
  273. if err != nil {
  274. return names, values
  275. }
  276. if config.SharedLabelNames == "" || config.SharedLabelValues == "" {
  277. return names, values
  278. }
  279. ks := strings.Split(config.SharedLabelNames, ",")
  280. vs := strings.Split(config.SharedLabelValues, ",")
  281. if len(ks) != len(vs) {
  282. klog.V(2).Infof("[Warning] shared labels have mis-matched lengths: %d names, %d values", len(ks), len(vs))
  283. return names, values
  284. }
  285. for i := range ks {
  286. names = append(names, strings.Trim(ks[i], " "))
  287. values = append(values, strings.Trim(vs[i], " "))
  288. }
  289. return names, values
  290. }
  291. func NewCrossClusterProvider(ctype string, overrideConfigPath string, cache clustercache.ClusterCache) (Provider, error) {
  292. if ctype == "aws" {
  293. return &AWS{
  294. Clientset: cache,
  295. Config: NewProviderConfig(overrideConfigPath),
  296. }, nil
  297. } else if ctype == "gcp" {
  298. return &GCP{
  299. Clientset: cache,
  300. Config: NewProviderConfig(overrideConfigPath),
  301. }, nil
  302. }
  303. return &CustomProvider{
  304. Clientset: cache,
  305. Config: NewProviderConfig(overrideConfigPath),
  306. }, nil
  307. }
  308. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  309. func NewProvider(cache clustercache.ClusterCache, apiKey string) (Provider, error) {
  310. nodes := cache.GetAllNodes()
  311. if len(nodes) == 0 {
  312. return nil, fmt.Errorf("Could not locate any nodes for cluster.")
  313. }
  314. provider := strings.ToLower(nodes[0].Spec.ProviderID)
  315. if env.IsUseCSVProvider() {
  316. klog.Infof("Using CSV Provider with CSV at %s", env.GetCSVPath())
  317. configFileName := ""
  318. if metadata.OnGCE() {
  319. configFileName = "gcp.json"
  320. } else if strings.HasPrefix(provider, "aws") {
  321. configFileName = "aws.json"
  322. } else if strings.HasPrefix(provider, "azure") {
  323. configFileName = "azure.json"
  324. } else {
  325. configFileName = "default.json"
  326. }
  327. return &CSVProvider{
  328. CSVLocation: env.GetCSVPath(),
  329. CustomProvider: &CustomProvider{
  330. Clientset: cache,
  331. Config: NewProviderConfig(configFileName),
  332. },
  333. }, nil
  334. }
  335. if metadata.OnGCE() {
  336. klog.V(3).Info("metadata reports we are in GCE")
  337. if apiKey == "" {
  338. return nil, errors.New("Supply a GCP Key to start getting data")
  339. }
  340. return &GCP{
  341. Clientset: cache,
  342. APIKey: apiKey,
  343. Config: NewProviderConfig("gcp.json"),
  344. }, nil
  345. }
  346. if strings.HasPrefix(provider, "aws") {
  347. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  348. return &AWS{
  349. Clientset: cache,
  350. Config: NewProviderConfig("aws.json"),
  351. }, nil
  352. } else if strings.HasPrefix(provider, "azure") {
  353. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  354. return &Azure{
  355. Clientset: cache,
  356. Config: NewProviderConfig("azure.json"),
  357. }, nil
  358. } else {
  359. klog.V(2).Info("Unsupported provider, falling back to default")
  360. return &CustomProvider{
  361. Clientset: cache,
  362. Config: NewProviderConfig("default.json"),
  363. }, nil
  364. }
  365. }
  366. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  367. pw := env.GetRemotePW()
  368. address := env.GetSQLAddress()
  369. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  370. db, err := sql.Open("postgres", connStr)
  371. if err != nil {
  372. return err
  373. }
  374. defer db.Close()
  375. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  376. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  377. if err != nil {
  378. return err
  379. }
  380. return nil
  381. }
  382. func CreateClusterMeta(cluster_id, cluster_name string) error {
  383. pw := env.GetRemotePW()
  384. address := env.GetSQLAddress()
  385. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  386. db, err := sql.Open("postgres", connStr)
  387. if err != nil {
  388. return err
  389. }
  390. defer db.Close()
  391. for _, stmt := range createTableStatements {
  392. _, err := db.Exec(stmt)
  393. if err != nil {
  394. return err
  395. }
  396. }
  397. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  398. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  399. if err != nil {
  400. return err
  401. }
  402. return nil
  403. }
  404. func GetClusterMeta(cluster_id string) (string, string, error) {
  405. pw := env.GetRemotePW()
  406. address := env.GetSQLAddress()
  407. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  408. db, err := sql.Open("postgres", connStr)
  409. defer db.Close()
  410. query := `SELECT cluster_id, cluster_name
  411. FROM names
  412. WHERE cluster_id = ?`
  413. rows, err := db.Query(query, cluster_id)
  414. if err != nil {
  415. return "", "", err
  416. }
  417. defer rows.Close()
  418. var (
  419. sql_cluster_id string
  420. cluster_name string
  421. )
  422. for rows.Next() {
  423. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  424. return "", "", err
  425. }
  426. }
  427. return sql_cluster_id, cluster_name, nil
  428. }
  429. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  430. id, name, err := GetClusterMeta(cluster_id)
  431. if err != nil {
  432. err := CreateClusterMeta(cluster_id, cluster_name)
  433. if err != nil {
  434. return "", "", err
  435. }
  436. }
  437. if id == "" {
  438. err := CreateClusterMeta(cluster_id, cluster_name)
  439. if err != nil {
  440. return "", "", err
  441. }
  442. }
  443. return id, name, nil
  444. }