provider.go 12 KB

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