provider.go 13 KB

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