provider.go 12 KB

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