provider.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. Parameters map[string]string `json:"parameters"`
  88. }
  89. // Key represents a way for nodes to match between the k8s API and a pricing API
  90. type Key interface {
  91. ID() string // ID represents an exact match
  92. Features() string // Features are a comma separated string of node metadata that could match pricing
  93. GPUType() string // GPUType returns "" if no GPU exists, but the name of the GPU otherwise
  94. }
  95. type PVKey interface {
  96. Features() string
  97. GetStorageClass() string
  98. }
  99. // OutOfClusterAllocation represents a cloud provider cost not associated with kubernetes
  100. type OutOfClusterAllocation struct {
  101. Aggregator string `json:"aggregator"`
  102. Environment string `json:"environment"`
  103. Service string `json:"service"`
  104. Cost float64 `json:"cost"`
  105. Cluster string `json:"cluster"`
  106. }
  107. type CustomPricing struct {
  108. Provider string `json:"provider"`
  109. Description string `json:"description"`
  110. CPU string `json:"CPU"`
  111. SpotCPU string `json:"spotCPU"`
  112. RAM string `json:"RAM"`
  113. SpotRAM string `json:"spotRAM"`
  114. GPU string `json:"GPU"`
  115. SpotGPU string `json:"spotGPU"`
  116. Storage string `json:"storage"`
  117. ZoneNetworkEgress string `json:"zoneNetworkEgress"`
  118. RegionNetworkEgress string `json:"regionNetworkEgress"`
  119. InternetNetworkEgress string `json:"internetNetworkEgress"`
  120. FirstFiveForwardingRulesCost string `json:"firstFiveForwardingRulesCost"`
  121. AdditionalForwardingRuleCost string `json:"additionalForwardingRuleCost"`
  122. LBIngressDataCost string `json:"LBIngressDataCost"`
  123. SpotLabel string `json:"spotLabel,omitempty"`
  124. SpotLabelValue string `json:"spotLabelValue,omitempty"`
  125. GpuLabel string `json:"gpuLabel,omitempty"`
  126. GpuLabelValue string `json:"gpuLabelValue,omitempty"`
  127. ServiceKeyName string `json:"awsServiceKeyName,omitempty"`
  128. ServiceKeySecret string `json:"awsServiceKeySecret,omitempty"`
  129. SpotDataRegion string `json:"awsSpotDataRegion,omitempty"`
  130. SpotDataBucket string `json:"awsSpotDataBucket,omitempty"`
  131. SpotDataPrefix string `json:"awsSpotDataPrefix,omitempty"`
  132. ProjectID string `json:"projectID,omitempty"`
  133. AthenaProjectID string `json:"athenaProjectID,omitempty"`
  134. AthenaBucketName string `json:"athenaBucketName"`
  135. AthenaRegion string `json:"athenaRegion"`
  136. AthenaDatabase string `json:"athenaDatabase"`
  137. AthenaTable string `json:"athenaTable"`
  138. MasterPayerARN string `json:"masterPayerARN"`
  139. BillingDataDataset string `json:"billingDataDataset,omitempty"`
  140. CustomPricesEnabled string `json:"customPricesEnabled"`
  141. DefaultIdle string `json:"defaultIdle"`
  142. AzureSubscriptionID string `json:"azureSubscriptionID"`
  143. AzureClientID string `json:"azureClientID"`
  144. AzureClientSecret string `json:"azureClientSecret"`
  145. AzureTenantID string `json:"azureTenantID"`
  146. AzureBillingRegion string `json:"azureBillingRegion"`
  147. CurrencyCode string `json:"currencyCode"`
  148. Discount string `json:"discount"`
  149. NegotiatedDiscount string `json:"negotiatedDiscount"`
  150. SharedCosts map[string]string `json:"sharedCost"`
  151. ClusterName string `json:"clusterName"`
  152. SharedNamespaces string `json:"sharedNamespaces"`
  153. SharedLabelNames string `json:"sharedLabelNames"`
  154. SharedLabelValues string `json:"sharedLabelValues"`
  155. ReadOnly string `json:"readOnly"`
  156. }
  157. type ServiceAccountStatus struct {
  158. Checks []*ServiceAccountCheck `json:"checks"`
  159. }
  160. type ServiceAccountCheck struct {
  161. Message string `json:"message"`
  162. Status bool `json:"status"`
  163. AdditionalInfo string `json:additionalInfo`
  164. }
  165. // Provider represents a k8s provider.
  166. type Provider interface {
  167. ClusterInfo() (map[string]string, error)
  168. GetAddresses() ([]byte, error)
  169. GetDisks() ([]byte, error)
  170. NodePricing(Key) (*Node, error)
  171. PVPricing(PVKey) (*PV, error)
  172. NetworkPricing() (*Network, error) // TODO: add key interface arg for dynamic price fetching
  173. LoadBalancerPricing() (*LoadBalancer, error) // TODO: add key interface arg for dynamic price fetching
  174. AllNodePricing() (interface{}, error)
  175. DownloadPricingData() error
  176. GetKey(map[string]string, *v1.Node) Key
  177. GetPVKey(*v1.PersistentVolume, map[string]string, string) PVKey
  178. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  179. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  180. GetConfig() (*CustomPricing, error)
  181. GetManagementPlatform() (string, error)
  182. GetLocalStorageQuery(string, string, bool, bool) string
  183. ExternalAllocations(string, string, []string, string, string, bool) ([]*OutOfClusterAllocation, error)
  184. ApplyReservedInstancePricing(map[string]*Node)
  185. ServiceAccountStatus() *ServiceAccountStatus
  186. ClusterManagementPricing() (string, float64, error)
  187. CombinedDiscountForNode(string, bool, float64, float64) float64
  188. ParseID(string) string
  189. }
  190. // ClusterName returns the name defined in cluster info, defaulting to the
  191. // CLUSTER_ID environment variable
  192. func ClusterName(p Provider) string {
  193. info, err := p.ClusterInfo()
  194. if err != nil {
  195. return env.GetClusterID()
  196. }
  197. name, ok := info["name"]
  198. if !ok {
  199. return env.GetClusterID()
  200. }
  201. return name
  202. }
  203. // CustomPricesEnabled returns the boolean equivalent of the cloup provider's custom prices flag,
  204. // indicating whether or not the cluster is using custom pricing.
  205. func CustomPricesEnabled(p Provider) bool {
  206. config, err := p.GetConfig()
  207. if err != nil {
  208. return false
  209. }
  210. if config.NegotiatedDiscount == "" {
  211. config.NegotiatedDiscount = "0%"
  212. }
  213. return config.CustomPricesEnabled == "true"
  214. }
  215. func NewCrossClusterProvider(ctype string, overrideConfigPath string, cache clustercache.ClusterCache) (Provider, error) {
  216. if ctype == "aws" {
  217. return &AWS{
  218. Clientset: cache,
  219. Config: NewProviderConfig(overrideConfigPath),
  220. }, nil
  221. } else if ctype == "gcp" {
  222. return &GCP{
  223. Clientset: cache,
  224. Config: NewProviderConfig(overrideConfigPath),
  225. }, nil
  226. }
  227. return &CustomProvider{
  228. Clientset: cache,
  229. Config: NewProviderConfig(overrideConfigPath),
  230. }, nil
  231. }
  232. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  233. func NewProvider(cache clustercache.ClusterCache, apiKey string) (Provider, error) {
  234. nodes := cache.GetAllNodes()
  235. if len(nodes) == 0 {
  236. return nil, fmt.Errorf("Could not locate any nodes for cluster.")
  237. }
  238. provider := strings.ToLower(nodes[0].Spec.ProviderID)
  239. if env.IsUseCSVProvider() {
  240. klog.Infof("Using CSV Provider with CSV at %s", env.GetCSVPath())
  241. configFileName := ""
  242. if metadata.OnGCE() {
  243. configFileName = "gcp.json"
  244. } else if strings.HasPrefix(provider, "aws") {
  245. configFileName = "aws.json"
  246. } else if strings.HasPrefix(provider, "azure") {
  247. configFileName = "azure.json"
  248. } else {
  249. configFileName = "default.json"
  250. }
  251. return &CSVProvider{
  252. CSVLocation: env.GetCSVPath(),
  253. CustomProvider: &CustomProvider{
  254. Clientset: cache,
  255. Config: NewProviderConfig(configFileName),
  256. },
  257. }, nil
  258. }
  259. if metadata.OnGCE() {
  260. klog.V(3).Info("metadata reports we are in GCE")
  261. if apiKey == "" {
  262. return nil, errors.New("Supply a GCP Key to start getting data")
  263. }
  264. return &GCP{
  265. Clientset: cache,
  266. APIKey: apiKey,
  267. Config: NewProviderConfig("gcp.json"),
  268. }, nil
  269. }
  270. if strings.HasPrefix(provider, "aws") {
  271. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  272. return &AWS{
  273. Clientset: cache,
  274. Config: NewProviderConfig("aws.json"),
  275. }, nil
  276. } else if strings.HasPrefix(provider, "azure") {
  277. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  278. return &Azure{
  279. Clientset: cache,
  280. Config: NewProviderConfig("azure.json"),
  281. }, nil
  282. } else {
  283. klog.V(2).Info("Unsupported provider, falling back to default")
  284. return &CustomProvider{
  285. Clientset: cache,
  286. Config: NewProviderConfig("default.json"),
  287. }, nil
  288. }
  289. }
  290. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  291. pw := env.GetRemotePW()
  292. address := env.GetSQLAddress()
  293. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  294. db, err := sql.Open("postgres", connStr)
  295. if err != nil {
  296. return err
  297. }
  298. defer db.Close()
  299. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  300. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  301. if err != nil {
  302. return err
  303. }
  304. return nil
  305. }
  306. func CreateClusterMeta(cluster_id, cluster_name string) error {
  307. pw := env.GetRemotePW()
  308. address := env.GetSQLAddress()
  309. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  310. db, err := sql.Open("postgres", connStr)
  311. if err != nil {
  312. return err
  313. }
  314. defer db.Close()
  315. for _, stmt := range createTableStatements {
  316. _, err := db.Exec(stmt)
  317. if err != nil {
  318. return err
  319. }
  320. }
  321. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  322. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  323. if err != nil {
  324. return err
  325. }
  326. return nil
  327. }
  328. func GetClusterMeta(cluster_id string) (string, string, error) {
  329. pw := env.GetRemotePW()
  330. address := env.GetSQLAddress()
  331. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  332. db, err := sql.Open("postgres", connStr)
  333. defer db.Close()
  334. query := `SELECT cluster_id, cluster_name
  335. FROM names
  336. WHERE cluster_id = ?`
  337. rows, err := db.Query(query, cluster_id)
  338. if err != nil {
  339. return "", "", err
  340. }
  341. defer rows.Close()
  342. var (
  343. sql_cluster_id string
  344. cluster_name string
  345. )
  346. for rows.Next() {
  347. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  348. return "", "", err
  349. }
  350. }
  351. return sql_cluster_id, cluster_name, nil
  352. }
  353. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  354. id, name, err := GetClusterMeta(cluster_id)
  355. if err != nil {
  356. err := CreateClusterMeta(cluster_id, cluster_name)
  357. if err != nil {
  358. return "", "", err
  359. }
  360. }
  361. if id == "" {
  362. err := CreateClusterMeta(cluster_id, cluster_name)
  363. if err != nil {
  364. return "", "", err
  365. }
  366. }
  367. return id, name, nil
  368. }