provider.go 13 KB

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