provider.go 14 KB

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