provider.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. func NewCrossClusterProvider(ctype string, overrideConfigPath string, cache clustercache.ClusterCache) (Provider, error) {
  228. if ctype == "aws" {
  229. return &AWS{
  230. Clientset: cache,
  231. Config: NewProviderConfig(overrideConfigPath),
  232. }, nil
  233. } else if ctype == "gcp" {
  234. return &GCP{
  235. Clientset: cache,
  236. Config: NewProviderConfig(overrideConfigPath),
  237. }, nil
  238. }
  239. return &CustomProvider{
  240. Clientset: cache,
  241. Config: NewProviderConfig(overrideConfigPath),
  242. }, nil
  243. }
  244. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  245. func NewProvider(cache clustercache.ClusterCache, apiKey string) (Provider, error) {
  246. nodes := cache.GetAllNodes()
  247. if len(nodes) == 0 {
  248. return nil, fmt.Errorf("Could not locate any nodes for cluster.")
  249. }
  250. provider := strings.ToLower(nodes[0].Spec.ProviderID)
  251. if env.IsUseCSVProvider() {
  252. klog.Infof("Using CSV Provider with CSV at %s", env.GetCSVPath())
  253. configFileName := ""
  254. if metadata.OnGCE() {
  255. configFileName = "gcp.json"
  256. } else if strings.HasPrefix(provider, "aws") {
  257. configFileName = "aws.json"
  258. } else if strings.HasPrefix(provider, "azure") {
  259. configFileName = "azure.json"
  260. } else {
  261. configFileName = "default.json"
  262. }
  263. return &CSVProvider{
  264. CSVLocation: env.GetCSVPath(),
  265. CustomProvider: &CustomProvider{
  266. Clientset: cache,
  267. Config: NewProviderConfig(configFileName),
  268. },
  269. }, nil
  270. }
  271. if metadata.OnGCE() {
  272. klog.V(3).Info("metadata reports we are in GCE")
  273. if apiKey == "" {
  274. return nil, errors.New("Supply a GCP Key to start getting data")
  275. }
  276. return &GCP{
  277. Clientset: cache,
  278. APIKey: apiKey,
  279. Config: NewProviderConfig("gcp.json"),
  280. }, nil
  281. }
  282. if strings.HasPrefix(provider, "aws") {
  283. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  284. return &AWS{
  285. Clientset: cache,
  286. Config: NewProviderConfig("aws.json"),
  287. }, nil
  288. } else if strings.HasPrefix(provider, "azure") {
  289. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  290. return &Azure{
  291. Clientset: cache,
  292. Config: NewProviderConfig("azure.json"),
  293. }, nil
  294. } else {
  295. klog.V(2).Info("Unsupported provider, falling back to default")
  296. return &CustomProvider{
  297. Clientset: cache,
  298. Config: NewProviderConfig("default.json"),
  299. }, nil
  300. }
  301. }
  302. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  303. pw := env.GetRemotePW()
  304. address := env.GetSQLAddress()
  305. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  306. db, err := sql.Open("postgres", connStr)
  307. if err != nil {
  308. return err
  309. }
  310. defer db.Close()
  311. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  312. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  313. if err != nil {
  314. return err
  315. }
  316. return nil
  317. }
  318. func CreateClusterMeta(cluster_id, cluster_name string) error {
  319. pw := env.GetRemotePW()
  320. address := env.GetSQLAddress()
  321. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  322. db, err := sql.Open("postgres", connStr)
  323. if err != nil {
  324. return err
  325. }
  326. defer db.Close()
  327. for _, stmt := range createTableStatements {
  328. _, err := db.Exec(stmt)
  329. if err != nil {
  330. return err
  331. }
  332. }
  333. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  334. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  335. if err != nil {
  336. return err
  337. }
  338. return nil
  339. }
  340. func GetClusterMeta(cluster_id string) (string, string, error) {
  341. pw := env.GetRemotePW()
  342. address := env.GetSQLAddress()
  343. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  344. db, err := sql.Open("postgres", connStr)
  345. defer db.Close()
  346. query := `SELECT cluster_id, cluster_name
  347. FROM names
  348. WHERE cluster_id = ?`
  349. rows, err := db.Query(query, cluster_id)
  350. if err != nil {
  351. return "", "", err
  352. }
  353. defer rows.Close()
  354. var (
  355. sql_cluster_id string
  356. cluster_name string
  357. )
  358. for rows.Next() {
  359. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  360. return "", "", err
  361. }
  362. }
  363. return sql_cluster_id, cluster_name, nil
  364. }
  365. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  366. id, name, err := GetClusterMeta(cluster_id)
  367. if err != nil {
  368. err := CreateClusterMeta(cluster_id, cluster_name)
  369. if err != nil {
  370. return "", "", err
  371. }
  372. }
  373. if id == "" {
  374. err := CreateClusterMeta(cluster_id, cluster_name)
  375. if err != nil {
  376. return "", "", err
  377. }
  378. }
  379. return id, name, nil
  380. }