provider.go 12 KB

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