provider.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. package cloud
  2. import (
  3. "database/sql"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/url"
  10. "os"
  11. "reflect"
  12. "strings"
  13. "sync"
  14. "k8s.io/klog"
  15. "cloud.google.com/go/compute/metadata"
  16. "github.com/kubecost/cost-model/clustercache"
  17. v1 "k8s.io/api/core/v1"
  18. )
  19. const clusterIDKey = "CLUSTER_ID"
  20. const remoteEnabled = "REMOTE_WRITE_ENABLED"
  21. const remotePW = "REMOTE_WRITE_PASSWORD"
  22. const sqlAddress = "SQL_ADDRESS"
  23. var createTableStatements = []string{
  24. `CREATE TABLE IF NOT EXISTS names (
  25. cluster_id VARCHAR(255) NOT NULL,
  26. cluster_name VARCHAR(255) NULL,
  27. PRIMARY KEY (cluster_id)
  28. );`,
  29. }
  30. // This Mutex is used to control read/writes to our default config file
  31. var configLock sync.Mutex
  32. // ReservedInstanceData keeps record of resources on a node should be
  33. // priced at reserved rates
  34. type ReservedInstanceData struct {
  35. ReservedCPU int64 `json:"reservedCPU"`
  36. ReservedRAM int64 `json:"reservedRAM"`
  37. CPUCost float64 `json:"CPUHourlyCost"`
  38. RAMCost float64 `json:"RAMHourlyCost"`
  39. }
  40. // Node is the interface by which the provider and cost model communicate Node prices.
  41. // The provider will best-effort try to fill out this struct.
  42. type Node struct {
  43. Cost string `json:"hourlyCost"`
  44. VCPU string `json:"CPU"`
  45. VCPUCost string `json:"CPUHourlyCost"`
  46. RAM string `json:"RAM"`
  47. RAMBytes string `json:"RAMBytes"`
  48. RAMCost string `json:"RAMGBHourlyCost"`
  49. Storage string `json:"storage"`
  50. StorageCost string `json:"storageHourlyCost"`
  51. UsesBaseCPUPrice bool `json:"usesDefaultPrice"`
  52. BaseCPUPrice string `json:"baseCPUPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  53. BaseRAMPrice string `json:"baseRAMPrice"` // Used to compute an implicit RAM GB/Hr price when RAM pricing is not provided.
  54. BaseGPUPrice string `json:"baseGPUPrice"`
  55. UsageType string `json:"usageType"`
  56. GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
  57. GPUName string `json:"gpuName"`
  58. GPUCost string `json:"gpuCost"`
  59. Reserved *ReservedInstanceData `json:"reserved,omitempty"`
  60. }
  61. // IsSpot determines whether or not a Node uses spot by usage type
  62. func (n *Node) IsSpot() bool {
  63. return strings.Contains(n.UsageType, "spot") || strings.Contains(n.UsageType, "emptible")
  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. 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) 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(offset string) (string, error)
  162. ExternalAllocations(string, string, string, string, string) ([]*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. // DefaultPricing should be returned so we can do computation even if no file is supplied.
  191. func DefaultPricing() *CustomPricing {
  192. return &CustomPricing{
  193. Provider: "base",
  194. Description: "Default prices based on GCP us-central1",
  195. CPU: "0.031611",
  196. SpotCPU: "0.006655",
  197. RAM: "0.004237",
  198. SpotRAM: "0.000892",
  199. GPU: "0.95",
  200. Storage: "0.00005479452",
  201. ZoneNetworkEgress: "0.01",
  202. RegionNetworkEgress: "0.01",
  203. InternetNetworkEgress: "0.12",
  204. CustomPricesEnabled: "false",
  205. }
  206. }
  207. // GetDefaultPricingData will search for a json file representing pricing data in /models/ and use it for base pricing info.
  208. func GetCustomPricingData(fname string) (*CustomPricing, error) {
  209. configLock.Lock()
  210. defer configLock.Unlock()
  211. path := configPathFor(fname)
  212. exists, err := fileExists(path)
  213. // File Error other than NotExists
  214. if err != nil {
  215. klog.Infof("Custom Pricing file at path '%s' read error: '%s'", path, err.Error())
  216. return DefaultPricing(), err
  217. }
  218. // File Doesn't Exist
  219. if !exists {
  220. klog.Infof("Could not find Custom Pricing file at path '%s'", path)
  221. c := DefaultPricing()
  222. cj, err := json.Marshal(c)
  223. if err != nil {
  224. return c, err
  225. }
  226. err = ioutil.WriteFile(path, cj, 0644)
  227. if err != nil {
  228. klog.Infof("Could not write Custom Pricing file to path '%s'", path)
  229. return c, err
  230. }
  231. return c, nil
  232. }
  233. // File Exists - Read all contents of file, unmarshal json
  234. byteValue, err := ioutil.ReadFile(path)
  235. if err != nil {
  236. klog.Infof("Could not read Custom Pricing file at path %s", path)
  237. return DefaultPricing(), err
  238. }
  239. var customPricing CustomPricing
  240. err = json.Unmarshal(byteValue, &customPricing)
  241. if err != nil {
  242. klog.Infof("Could not decode Custom Pricing file at path %s", path)
  243. return DefaultPricing(), err
  244. }
  245. return &customPricing, nil
  246. }
  247. func configmapUpdate(c *CustomPricing, path string, a map[string]string) (*CustomPricing, error) {
  248. for k, v := range a {
  249. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  250. err := SetCustomPricingField(c, kUpper, v)
  251. if err != nil {
  252. return nil, err
  253. }
  254. }
  255. cj, err := json.Marshal(c)
  256. if err != nil {
  257. return c, err
  258. }
  259. configLock.Lock()
  260. err = ioutil.WriteFile(path, cj, 0644)
  261. configLock.Unlock()
  262. if err != nil {
  263. return c, err
  264. }
  265. return c, nil
  266. }
  267. func SetCustomPricingField(obj *CustomPricing, name string, value string) error {
  268. structValue := reflect.ValueOf(obj).Elem()
  269. structFieldValue := structValue.FieldByName(name)
  270. if !structFieldValue.IsValid() {
  271. return fmt.Errorf("No such field: %s in obj", name)
  272. }
  273. if !structFieldValue.CanSet() {
  274. return fmt.Errorf("Cannot set %s field value", name)
  275. }
  276. structFieldType := structFieldValue.Type()
  277. val := reflect.ValueOf(value)
  278. if structFieldType != val.Type() {
  279. return fmt.Errorf("Provided value type didn't match custom pricing field type")
  280. }
  281. structFieldValue.Set(val)
  282. return nil
  283. }
  284. // NewProvider looks at the nodespec or provider metadata server to decide which provider to instantiate.
  285. func NewProvider(cache clustercache.ClusterCache, apiKey string) (Provider, error) {
  286. if metadata.OnGCE() {
  287. klog.V(3).Info("metadata reports we are in GCE")
  288. if apiKey == "" {
  289. return nil, errors.New("Supply a GCP Key to start getting data")
  290. }
  291. return &GCP{
  292. Clientset: cache,
  293. APIKey: apiKey,
  294. }, nil
  295. }
  296. nodes := cache.GetAllNodes()
  297. if len(nodes) == 0 {
  298. return nil, fmt.Errorf("Could not locate any nodes for cluster.")
  299. }
  300. provider := strings.ToLower(nodes[0].Spec.ProviderID)
  301. if strings.HasPrefix(provider, "aws") {
  302. klog.V(2).Info("Found ProviderID starting with \"aws\", using AWS Provider")
  303. return &AWS{
  304. Clientset: cache,
  305. }, nil
  306. } else if strings.HasPrefix(provider, "azure") {
  307. klog.V(2).Info("Found ProviderID starting with \"azure\", using Azure Provider")
  308. return &Azure{
  309. Clientset: cache,
  310. }, nil
  311. } else {
  312. klog.V(2).Info("Unsupported provider, falling back to default")
  313. return &CustomProvider{
  314. Clientset: cache,
  315. }, nil
  316. }
  317. }
  318. func UpdateClusterMeta(cluster_id, cluster_name string) error {
  319. pw := os.Getenv(remotePW)
  320. address := os.Getenv(sqlAddress)
  321. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  322. db, err := sql.Open("postgres", connStr)
  323. if err != nil {
  324. return err
  325. }
  326. defer db.Close()
  327. updateStmt := `UPDATE names SET cluster_name = $1 WHERE cluster_id = $2;`
  328. _, err = db.Exec(updateStmt, cluster_name, cluster_id)
  329. if err != nil {
  330. return err
  331. }
  332. return nil
  333. }
  334. func CreateClusterMeta(cluster_id, cluster_name string) error {
  335. pw := os.Getenv(remotePW)
  336. address := os.Getenv(sqlAddress)
  337. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  338. db, err := sql.Open("postgres", connStr)
  339. if err != nil {
  340. return err
  341. }
  342. defer db.Close()
  343. for _, stmt := range createTableStatements {
  344. _, err := db.Exec(stmt)
  345. if err != nil {
  346. return err
  347. }
  348. }
  349. insertStmt := `INSERT INTO names (cluster_id, cluster_name) VALUES ($1, $2);`
  350. _, err = db.Exec(insertStmt, cluster_id, cluster_name)
  351. if err != nil {
  352. return err
  353. }
  354. return nil
  355. }
  356. func GetClusterMeta(cluster_id string) (string, string, error) {
  357. pw := os.Getenv(remotePW)
  358. address := os.Getenv(sqlAddress)
  359. connStr := fmt.Sprintf("postgres://postgres:%s@%s:5432?sslmode=disable", pw, address)
  360. db, err := sql.Open("postgres", connStr)
  361. defer db.Close()
  362. query := `SELECT cluster_id, cluster_name
  363. FROM names
  364. WHERE cluster_id = ?`
  365. rows, err := db.Query(query, cluster_id)
  366. if err != nil {
  367. return "", "", err
  368. }
  369. defer rows.Close()
  370. var (
  371. sql_cluster_id string
  372. cluster_name string
  373. )
  374. for rows.Next() {
  375. if err := rows.Scan(&sql_cluster_id, &cluster_name); err != nil {
  376. return "", "", err
  377. }
  378. }
  379. return sql_cluster_id, cluster_name, nil
  380. }
  381. func GetOrCreateClusterMeta(cluster_id, cluster_name string) (string, string, error) {
  382. id, name, err := GetClusterMeta(cluster_id)
  383. if err != nil {
  384. err := CreateClusterMeta(cluster_id, cluster_name)
  385. if err != nil {
  386. return "", "", err
  387. }
  388. }
  389. if id == "" {
  390. err := CreateClusterMeta(cluster_id, cluster_name)
  391. if err != nil {
  392. return "", "", err
  393. }
  394. }
  395. return id, name, nil
  396. }
  397. // File exists has three different return cases that should be handled:
  398. // 1. File exists and is not a directory (true, nil)
  399. // 2. File does not exist (false, nil)
  400. // 3. File may or may not exist. Error occurred during stat (false, error)
  401. // The third case represents the scenario where the stat returns an error,
  402. // but the error isn't relevant to the path. This can happen when the current
  403. // user doesn't have permission to access the file.
  404. func fileExists(filename string) (bool, error) {
  405. info, err := os.Stat(filename)
  406. if err != nil {
  407. if os.IsNotExist(err) {
  408. return false, nil
  409. }
  410. return false, err
  411. }
  412. return !info.IsDir(), nil
  413. }
  414. // Returns the configuration directory concatenated with a specific config file name
  415. func configPathFor(filename string) string {
  416. path := os.Getenv("CONFIG_PATH")
  417. if path == "" {
  418. path = "/models/"
  419. }
  420. return path + filename
  421. }