provider.go 13 KB

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