provider.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. // Provider represents a k8s provider.
  168. type Provider interface {
  169. ClusterInfo() (map[string]string, error)
  170. GetAddresses() ([]byte, error)
  171. GetDisks() ([]byte, error)
  172. NodePricing(Key) (*Node, error)
  173. PVPricing(PVKey) (*PV, error)
  174. NetworkPricing() (*Network, error) // TODO: add key interface arg for dynamic price fetching
  175. LoadBalancerPricing() (*LoadBalancer, error) // TODO: add key interface arg for dynamic price fetching
  176. AllNodePricing() (interface{}, error)
  177. DownloadPricingData() error
  178. GetKey(map[string]string, *v1.Node) Key
  179. GetPVKey(*v1.PersistentVolume, map[string]string, string) PVKey
  180. UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error)
  181. UpdateConfigFromConfigMap(map[string]string) (*CustomPricing, error)
  182. GetConfig() (*CustomPricing, error)
  183. GetManagementPlatform() (string, error)
  184. GetLocalStorageQuery(string, string, bool, bool) string
  185. ExternalAllocations(string, string, []string, string, string, bool) ([]*OutOfClusterAllocation, error)
  186. ApplyReservedInstancePricing(map[string]*Node)
  187. ServiceAccountStatus() *ServiceAccountStatus
  188. ClusterManagementPricing() (string, float64, error)
  189. CombinedDiscountForNode(string, bool, float64, float64) float64
  190. ParseID(string) string
  191. ParsePVID(string) string
  192. }
  193. // ClusterName returns the name defined in cluster info, defaulting to the
  194. // CLUSTER_ID environment variable
  195. func ClusterName(p Provider) string {
  196. info, err := p.ClusterInfo()
  197. if err != nil {
  198. return env.GetClusterID()
  199. }
  200. name, ok := info["name"]
  201. if !ok {
  202. return env.GetClusterID()
  203. }
  204. return name
  205. }
  206. // CustomPricesEnabled returns the boolean equivalent of the cloup provider's custom prices flag,
  207. // indicating whether or not the cluster is using custom pricing.
  208. func CustomPricesEnabled(p Provider) bool {
  209. config, err := p.GetConfig()
  210. if err != nil {
  211. return false
  212. }
  213. if config.NegotiatedDiscount == "" {
  214. config.NegotiatedDiscount = "0%"
  215. }
  216. return config.CustomPricesEnabled == "true"
  217. }
  218. func NewCrossClusterProvider(ctype string, overrideConfigPath string, cache clustercache.ClusterCache) (Provider, error) {
  219. if ctype == "aws" {
  220. return &AWS{
  221. Clientset: cache,
  222. Config: NewProviderConfig(overrideConfigPath),
  223. }, nil
  224. } else if ctype == "gcp" {
  225. return &GCP{
  226. Clientset: cache,
  227. Config: NewProviderConfig(overrideConfigPath),
  228. }, nil
  229. }
  230. return &CustomProvider{
  231. Clientset: cache,
  232. Config: NewProviderConfig(overrideConfigPath),
  233. }, nil
  234. }
  235. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  236. func NewProvider(cache clustercache.ClusterCache, apiKey string) (Provider, error) {
  237. nodes := cache.GetAllNodes()
  238. if len(nodes) == 0 {
  239. return nil, fmt.Errorf("Could not locate any nodes for cluster.")
  240. }
  241. provider := strings.ToLower(nodes[0].Spec.ProviderID)
  242. if env.IsUseCSVProvider() {
  243. klog.Infof("Using CSV Provider with CSV at %s", env.GetCSVPath())
  244. configFileName := ""
  245. if metadata.OnGCE() {
  246. configFileName = "gcp.json"
  247. } else if strings.HasPrefix(provider, "aws") {
  248. configFileName = "aws.json"
  249. } else if strings.HasPrefix(provider, "azure") {
  250. configFileName = "azure.json"
  251. } else {
  252. configFileName = "default.json"
  253. }
  254. return &CSVProvider{
  255. CSVLocation: env.GetCSVPath(),
  256. CustomProvider: &CustomProvider{
  257. Clientset: cache,
  258. Config: NewProviderConfig(configFileName),
  259. },
  260. }, nil
  261. }
  262. if metadata.OnGCE() {
  263. klog.V(3).Info("metadata reports we are in GCE")
  264. if apiKey == "" {
  265. return nil, errors.New("Supply a GCP Key to start getting data")
  266. }
  267. return &GCP{
  268. Clientset: cache,
  269. APIKey: apiKey,
  270. Config: NewProviderConfig("gcp.json"),
  271. }, nil
  272. }
  273. if strings.HasPrefix(provider, "aws") {
  274. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  275. return &AWS{
  276. Clientset: cache,
  277. Config: NewProviderConfig("aws.json"),
  278. }, nil
  279. } else if strings.HasPrefix(provider, "azure") {
  280. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  281. return &Azure{
  282. Clientset: cache,
  283. Config: NewProviderConfig("azure.json"),
  284. }, nil
  285. } else {
  286. klog.V(2).Info("Unsupported provider, falling back to default")
  287. return &CustomProvider{
  288. Clientset: cache,
  289. Config: NewProviderConfig("default.json"),
  290. }, nil
  291. }
  292. }
  293. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  294. pw := env.GetRemotePW()
  295. address := env.GetSQLAddress()
  296. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  297. db, err := sql.Open("postgres", connStr)
  298. if err != nil {
  299. return err
  300. }
  301. defer db.Close()
  302. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  303. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  304. if err != nil {
  305. return err
  306. }
  307. return nil
  308. }
  309. func CreateClusterMeta(cluster_id, cluster_name string) error {
  310. pw := env.GetRemotePW()
  311. address := env.GetSQLAddress()
  312. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  313. db, err := sql.Open("postgres", connStr)
  314. if err != nil {
  315. return err
  316. }
  317. defer db.Close()
  318. for _, stmt := range createTableStatements {
  319. _, err := db.Exec(stmt)
  320. if err != nil {
  321. return err
  322. }
  323. }
  324. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  325. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  326. if err != nil {
  327. return err
  328. }
  329. return nil
  330. }
  331. func GetClusterMeta(cluster_id string) (string, string, error) {
  332. pw := env.GetRemotePW()
  333. address := env.GetSQLAddress()
  334. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  335. db, err := sql.Open("postgres", connStr)
  336. defer db.Close()
  337. query := `SELECT cluster_id, cluster_name
  338. FROM names
  339. WHERE cluster_id = ?`
  340. rows, err := db.Query(query, cluster_id)
  341. if err != nil {
  342. return "", "", err
  343. }
  344. defer rows.Close()
  345. var (
  346. sql_cluster_id string
  347. cluster_name string
  348. )
  349. for rows.Next() {
  350. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  351. return "", "", err
  352. }
  353. }
  354. return sql_cluster_id, cluster_name, nil
  355. }
  356. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  357. id, name, err := GetClusterMeta(cluster_id)
  358. if err != nil {
  359. err := CreateClusterMeta(cluster_id, cluster_name)
  360. if err != nil {
  361. return "", "", err
  362. }
  363. }
  364. if id == "" {
  365. err := CreateClusterMeta(cluster_id, cluster_name)
  366. if err != nil {
  367. return "", "", err
  368. }
  369. }
  370. return id, name, nil
  371. }