provider.go 13 KB

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