provider.go 17 KB

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