provider.go 13 KB

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