provider.go 13 KB

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