gcpprovider.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  1. package cloud
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "math"
  9. "net/http"
  10. "os"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "k8s.io/klog"
  17. "cloud.google.com/go/bigquery"
  18. "cloud.google.com/go/compute/metadata"
  19. "github.com/kubecost/cost-model/pkg/clustercache"
  20. "github.com/kubecost/cost-model/pkg/util"
  21. "golang.org/x/oauth2"
  22. "golang.org/x/oauth2/google"
  23. compute "google.golang.org/api/compute/v1"
  24. "google.golang.org/api/iterator"
  25. v1 "k8s.io/api/core/v1"
  26. )
  27. const GKE_GPU_TAG = "cloud.google.com/gke-accelerator"
  28. const BigqueryUpdateType = "bigqueryupdate"
  29. type userAgentTransport struct {
  30. userAgent string
  31. base http.RoundTripper
  32. }
  33. func (t userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  34. req.Header.Set("User-Agent", t.userAgent)
  35. return t.base.RoundTrip(req)
  36. }
  37. // GCP implements a provider interface for GCP
  38. type GCP struct {
  39. Pricing map[string]*GCPPricing
  40. Clientset clustercache.ClusterCache
  41. APIKey string
  42. BaseCPUPrice string
  43. ProjectID string
  44. BillingDataDataset string
  45. DownloadPricingDataLock sync.RWMutex
  46. ReservedInstances []*GCPReservedInstance
  47. Config *ProviderConfig
  48. serviceKeyProvided bool
  49. ValidPricingKeys map[string]bool
  50. *CustomProvider
  51. }
  52. type gcpAllocation struct {
  53. Aggregator bigquery.NullString
  54. Environment bigquery.NullString
  55. Service string
  56. Cost float64
  57. }
  58. type multiKeyGCPAllocation struct {
  59. Keys bigquery.NullString
  60. Service string
  61. Cost float64
  62. }
  63. func multiKeyGCPAllocationToOutOfClusterAllocation(gcpAlloc multiKeyGCPAllocation, aggregatorNames []string) *OutOfClusterAllocation {
  64. var keys []map[string]string
  65. var environment string
  66. var usedAggregatorName string
  67. if gcpAlloc.Keys.Valid {
  68. err := json.Unmarshal([]byte(gcpAlloc.Keys.StringVal), &keys)
  69. if err != nil {
  70. klog.Infof("Invalid unmarshaling response from BigQuery filtered query: %s", err.Error())
  71. }
  72. keyloop:
  73. for _, label := range keys {
  74. for _, aggregatorName := range aggregatorNames {
  75. if label["key"] == aggregatorName {
  76. environment = label["value"]
  77. usedAggregatorName = label["key"]
  78. break keyloop
  79. }
  80. }
  81. }
  82. }
  83. return &OutOfClusterAllocation{
  84. Aggregator: usedAggregatorName,
  85. Environment: environment,
  86. Service: gcpAlloc.Service,
  87. Cost: gcpAlloc.Cost,
  88. }
  89. }
  90. func gcpAllocationToOutOfClusterAllocation(gcpAlloc gcpAllocation) *OutOfClusterAllocation {
  91. var aggregator string
  92. if gcpAlloc.Aggregator.Valid {
  93. aggregator = gcpAlloc.Aggregator.StringVal
  94. }
  95. var environment string
  96. if gcpAlloc.Environment.Valid {
  97. environment = gcpAlloc.Environment.StringVal
  98. }
  99. return &OutOfClusterAllocation{
  100. Aggregator: aggregator,
  101. Environment: environment,
  102. Service: gcpAlloc.Service,
  103. Cost: gcpAlloc.Cost,
  104. }
  105. }
  106. // GetLocalStorageQuery returns the cost of local storage for the given window. Setting rate=true
  107. // returns hourly spend. Setting used=true only tracks used storage, not total.
  108. func (gcp *GCP) GetLocalStorageQuery(window, offset string, rate bool, used bool) string {
  109. // TODO Set to the price for the appropriate storage class. It's not trivial to determine the local storage disk type
  110. // See https://cloud.google.com/compute/disks-image-pricing#persistentdisk
  111. localStorageCost := 0.04
  112. baseMetric := "container_fs_limit_bytes"
  113. if used {
  114. baseMetric = "container_fs_usage_bytes"
  115. }
  116. fmtOffset := ""
  117. if offset != "" {
  118. fmtOffset = fmt.Sprintf("offset %s", offset)
  119. }
  120. fmtCumulativeQuery := `sum(
  121. sum_over_time(%s{device!="tmpfs", id="/"}[%s:1m]%s)
  122. ) by (cluster_id) / 60 / 730 / 1024 / 1024 / 1024 * %f`
  123. fmtMonthlyQuery := `sum(
  124. avg_over_time(%s{device!="tmpfs", id="/"}[%s:1m]%s)
  125. ) by (cluster_id) / 1024 / 1024 / 1024 * %f`
  126. fmtQuery := fmtCumulativeQuery
  127. if rate {
  128. fmtQuery = fmtMonthlyQuery
  129. }
  130. return fmt.Sprintf(fmtQuery, baseMetric, window, fmtOffset, localStorageCost)
  131. }
  132. func (gcp *GCP) GetConfig() (*CustomPricing, error) {
  133. c, err := gcp.Config.GetCustomPricingData()
  134. if err != nil {
  135. return nil, err
  136. }
  137. if c.Discount == "" {
  138. c.Discount = "30%"
  139. }
  140. if c.NegotiatedDiscount == "" {
  141. c.NegotiatedDiscount = "0%"
  142. }
  143. return c, nil
  144. }
  145. type BigQueryConfig struct {
  146. ProjectID string `json:"projectID"`
  147. BillingDataDataset string `json:"billingDataDataset"`
  148. Key map[string]string `json:"key"`
  149. }
  150. func (gcp *GCP) GetManagementPlatform() (string, error) {
  151. nodes := gcp.Clientset.GetAllNodes()
  152. if len(nodes) > 0 {
  153. n := nodes[0]
  154. version := n.Status.NodeInfo.KubeletVersion
  155. if strings.Contains(version, "gke") {
  156. return "gke", nil
  157. }
  158. }
  159. return "", nil
  160. }
  161. // Attempts to load a GCP auth secret and copy the contents to the key file.
  162. func (*GCP) loadGCPAuthSecret() {
  163. path := os.Getenv("CONFIG_PATH")
  164. if path == "" {
  165. path = "/models/"
  166. }
  167. keyPath := path + "key.json"
  168. keyExists, _ := util.FileExists(keyPath)
  169. if keyExists {
  170. klog.V(1).Infof("GCP Auth Key already exists, no need to load from secret")
  171. return
  172. }
  173. exists, err := util.FileExists(authSecretPath)
  174. if !exists || err != nil {
  175. errMessage := "Secret does not exist"
  176. if err != nil {
  177. errMessage = err.Error()
  178. }
  179. klog.V(4).Infof("[Warning] Failed to load auth secret, or was not mounted: %s", errMessage)
  180. return
  181. }
  182. result, err := ioutil.ReadFile(authSecretPath)
  183. if err != nil {
  184. klog.V(4).Infof("[Warning] Failed to load auth secret, or was not mounted: %s", err.Error())
  185. return
  186. }
  187. err = ioutil.WriteFile(keyPath, result, 0644)
  188. if err != nil {
  189. klog.V(4).Infof("[Warning] Failed to copy auth secret to %s: %s", keyPath, err.Error())
  190. }
  191. }
  192. func (gcp *GCP) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  193. return gcp.Config.UpdateFromMap(a)
  194. }
  195. func (gcp *GCP) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  196. return gcp.Config.Update(func(c *CustomPricing) error {
  197. if updateType == BigqueryUpdateType {
  198. a := BigQueryConfig{}
  199. err := json.NewDecoder(r).Decode(&a)
  200. if err != nil {
  201. return err
  202. }
  203. c.ProjectID = a.ProjectID
  204. c.BillingDataDataset = a.BillingDataDataset
  205. if len(a.Key) > 0 {
  206. j, err := json.Marshal(a.Key)
  207. if err != nil {
  208. return err
  209. }
  210. path := os.Getenv("CONFIG_PATH")
  211. if path == "" {
  212. path = "/models/"
  213. }
  214. keyPath := path + "key.json"
  215. err = ioutil.WriteFile(keyPath, j, 0644)
  216. if err != nil {
  217. return err
  218. }
  219. gcp.serviceKeyProvided = true
  220. }
  221. } else if updateType == AthenaInfoUpdateType {
  222. a := AwsAthenaInfo{}
  223. err := json.NewDecoder(r).Decode(&a)
  224. if err != nil {
  225. return err
  226. }
  227. c.AthenaBucketName = a.AthenaBucketName
  228. c.AthenaRegion = a.AthenaRegion
  229. c.AthenaDatabase = a.AthenaDatabase
  230. c.AthenaTable = a.AthenaTable
  231. c.ServiceKeyName = a.ServiceKeyName
  232. c.ServiceKeySecret = a.ServiceKeySecret
  233. c.AthenaProjectID = a.AccountID
  234. } else {
  235. a := make(map[string]interface{})
  236. err := json.NewDecoder(r).Decode(&a)
  237. if err != nil {
  238. return err
  239. }
  240. for k, v := range a {
  241. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  242. vstr, ok := v.(string)
  243. if ok {
  244. err := SetCustomPricingField(c, kUpper, vstr)
  245. if err != nil {
  246. return err
  247. }
  248. } else {
  249. sci := v.(map[string]interface{})
  250. sc := make(map[string]string)
  251. for k, val := range sci {
  252. sc[k] = val.(string)
  253. }
  254. c.SharedCosts = sc //todo: support reflection/multiple map fields
  255. }
  256. }
  257. }
  258. remoteEnabled := os.Getenv(remoteEnabled)
  259. if remoteEnabled == "true" {
  260. err := UpdateClusterMeta(os.Getenv(clusterIDKey), c.ClusterName)
  261. if err != nil {
  262. return err
  263. }
  264. }
  265. return nil
  266. })
  267. }
  268. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  269. // "start" and "end" are dates of the format YYYY-MM-DD
  270. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  271. func (gcp *GCP) ExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool) ([]*OutOfClusterAllocation, error) {
  272. c, err := gcp.Config.GetCustomPricingData()
  273. if err != nil {
  274. return nil, err
  275. }
  276. var s []*OutOfClusterAllocation
  277. if c.ServiceKeyName != "" && c.ServiceKeySecret != "" && !crossCluster {
  278. aws, err := NewCrossClusterProvider("aws", "gcp.json", gcp.Clientset)
  279. if err != nil {
  280. klog.Infof("Could not instantiate cross-cluster provider %s", err.Error())
  281. }
  282. awsOOC, err := aws.ExternalAllocations(start, end, aggregators, filterType, filterValue, true)
  283. if err != nil {
  284. klog.Infof("Could not fetch cross-cluster costs %s", err.Error())
  285. }
  286. s = append(s, awsOOC...)
  287. }
  288. formattedAggregators := []string{}
  289. for _, a := range aggregators {
  290. formattedAggregators = append(formattedAggregators, strconv.Quote(a))
  291. }
  292. aggregator := strings.Join(formattedAggregators, ",")
  293. var qerr error
  294. if filterType == "kubernetes_" {
  295. // start, end formatted like: "2019-04-20 00:00:00"
  296. /* OLD METHOD: supported getting all data, including unaggregated.
  297. queryString := fmt.Sprintf(`SELECT
  298. service,
  299. labels.key as aggregator,
  300. labels.value as environment,
  301. SUM(cost) as cost
  302. FROM (SELECT
  303. service.description as service,
  304. labels,
  305. cost
  306. FROM %s
  307. WHERE usage_start_time >= "%s" AND usage_start_time < "%s")
  308. LEFT JOIN UNNEST(labels) as labels
  309. ON labels.key = "%s"
  310. GROUP BY aggregator, environment, service;`, c.BillingDataDataset, start, end, aggregator) // For example, "billing_data.gcp_billing_export_v1_01AC9F_74CF1D_5565A2"
  311. klog.V(3).Infof("Querying \"%s\" with : %s", c.ProjectID, queryString)
  312. gcpOOC, err := gcp.QuerySQL(queryString)
  313. s = append(s, gcpOOC...)
  314. qerr = err
  315. */
  316. queryString := fmt.Sprintf(`(
  317. SELECT
  318. service.description as service,
  319. TO_JSON_STRING(labels) as keys,
  320. SUM(cost) as cost
  321. FROM %s
  322. WHERE EXISTS (SELECT * FROM UNNEST(labels) AS l2 WHERE l2.key IN (%s))
  323. AND usage_start_time >= "%s" AND usage_start_time < "%s"
  324. GROUP BY service, keys
  325. )`, c.BillingDataDataset, aggregator, start, end)
  326. klog.V(3).Infof("Querying \"%s\" with : %s", c.ProjectID, queryString)
  327. gcpOOC, err := gcp.multiLabelQuery(queryString, aggregators)
  328. s = append(s, gcpOOC...)
  329. qerr = err
  330. } else {
  331. if filterType == "kubernetes_labels" {
  332. fvs := strings.Split(filterValue, "=")
  333. if len(fvs) == 2 {
  334. // if we are given "app=myapp" then look for label "kubernetes_label_app=myapp"
  335. filterType = fmt.Sprintf("kubernetes_label_%s", fvs[0])
  336. filterValue = fvs[1]
  337. } else {
  338. klog.V(2).Infof("[Warning] illegal kubernetes_labels filterValue: %s", filterValue)
  339. }
  340. }
  341. queryString := fmt.Sprintf(`(
  342. SELECT
  343. service.description as service,
  344. TO_JSON_STRING(labels) as keys,
  345. SUM(cost) as cost
  346. FROM %s
  347. WHERE EXISTS (SELECT * FROM UNNEST(labels) AS l2 WHERE l2.key IN (%s))
  348. AND EXISTS (SELECT * FROM UNNEST(labels) AS l WHERE l.key = "%s" AND l.value = "%s")
  349. AND usage_start_time >= "%s" AND usage_start_time < "%s"
  350. GROUP BY service, keys
  351. )`, c.BillingDataDataset, aggregator, filterType, filterValue, start, end)
  352. klog.V(4).Infof("Querying \"%s\" with : %s", c.ProjectID, queryString)
  353. gcpOOC, err := gcp.multiLabelQuery(queryString, aggregators)
  354. s = append(s, gcpOOC...)
  355. qerr = err
  356. }
  357. if qerr != nil && gcp.serviceKeyProvided {
  358. klog.Infof("Error querying gcp: %s", qerr)
  359. }
  360. return s, qerr
  361. }
  362. func (gcp *GCP) multiLabelQuery(query string, aggregators []string) ([]*OutOfClusterAllocation, error) {
  363. c, err := gcp.Config.GetCustomPricingData()
  364. if err != nil {
  365. return nil, err
  366. }
  367. ctx := context.Background()
  368. client, err := bigquery.NewClient(ctx, c.ProjectID) // For example, "guestbook-227502"
  369. if err != nil {
  370. return nil, err
  371. }
  372. q := client.Query(query)
  373. it, err := q.Read(ctx)
  374. if err != nil {
  375. return nil, err
  376. }
  377. var allocations []*OutOfClusterAllocation
  378. for {
  379. var a multiKeyGCPAllocation
  380. err := it.Next(&a)
  381. if err == iterator.Done {
  382. break
  383. }
  384. if err != nil {
  385. return nil, err
  386. }
  387. allocations = append(allocations, multiKeyGCPAllocationToOutOfClusterAllocation(a, aggregators))
  388. }
  389. return allocations, nil
  390. }
  391. // QuerySQL should query BigQuery for billing data for out of cluster costs.
  392. func (gcp *GCP) QuerySQL(query string) ([]*OutOfClusterAllocation, error) {
  393. c, err := gcp.Config.GetCustomPricingData()
  394. if err != nil {
  395. return nil, err
  396. }
  397. ctx := context.Background()
  398. client, err := bigquery.NewClient(ctx, c.ProjectID) // For example, "guestbook-227502"
  399. if err != nil {
  400. return nil, err
  401. }
  402. q := client.Query(query)
  403. it, err := q.Read(ctx)
  404. if err != nil {
  405. return nil, err
  406. }
  407. var allocations []*OutOfClusterAllocation
  408. for {
  409. var a gcpAllocation
  410. err := it.Next(&a)
  411. if err == iterator.Done {
  412. break
  413. }
  414. if err != nil {
  415. return nil, err
  416. }
  417. allocations = append(allocations, gcpAllocationToOutOfClusterAllocation(a))
  418. }
  419. return allocations, nil
  420. }
  421. // ClusterName returns the name of a GKE cluster, as provided by metadata.
  422. func (gcp *GCP) ClusterInfo() (map[string]string, error) {
  423. remote := os.Getenv(remoteEnabled)
  424. remoteEnabled := false
  425. if os.Getenv(remote) == "true" {
  426. remoteEnabled = true
  427. }
  428. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  429. userAgent: "kubecost",
  430. base: http.DefaultTransport,
  431. }})
  432. attribute, err := metadataClient.InstanceAttributeValue("cluster-name")
  433. if err != nil {
  434. klog.Infof("Error loading metadata cluster-name: %s", err.Error())
  435. }
  436. c, err := gcp.GetConfig()
  437. if err != nil {
  438. klog.V(1).Infof("Error opening config: %s", err.Error())
  439. }
  440. if c.ClusterName != "" {
  441. attribute = c.ClusterName
  442. }
  443. m := make(map[string]string)
  444. m["name"] = attribute
  445. m["provider"] = "GCP"
  446. m["id"] = os.Getenv(clusterIDKey)
  447. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  448. return m, nil
  449. }
  450. func (*GCP) GetAddresses() ([]byte, error) {
  451. // metadata API setup
  452. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  453. userAgent: "kubecost",
  454. base: http.DefaultTransport,
  455. }})
  456. projID, err := metadataClient.ProjectID()
  457. if err != nil {
  458. return nil, err
  459. }
  460. client, err := google.DefaultClient(oauth2.NoContext,
  461. "https://www.googleapis.com/auth/compute.readonly")
  462. if err != nil {
  463. return nil, err
  464. }
  465. svc, err := compute.New(client)
  466. if err != nil {
  467. return nil, err
  468. }
  469. res, err := svc.Addresses.AggregatedList(projID).Do()
  470. if err != nil {
  471. return nil, err
  472. }
  473. return json.Marshal(res)
  474. }
  475. // GetDisks returns the GCP disks backing PVs. Useful because sometimes k8s will not clean up PVs correctly. Requires a json config in /var/configs with key region.
  476. func (*GCP) GetDisks() ([]byte, error) {
  477. // metadata API setup
  478. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  479. userAgent: "kubecost",
  480. base: http.DefaultTransport,
  481. }})
  482. projID, err := metadataClient.ProjectID()
  483. if err != nil {
  484. return nil, err
  485. }
  486. client, err := google.DefaultClient(oauth2.NoContext,
  487. "https://www.googleapis.com/auth/compute.readonly")
  488. if err != nil {
  489. return nil, err
  490. }
  491. svc, err := compute.New(client)
  492. if err != nil {
  493. return nil, err
  494. }
  495. res, err := svc.Disks.AggregatedList(projID).Do()
  496. if err != nil {
  497. return nil, err
  498. }
  499. return json.Marshal(res)
  500. }
  501. // GCPPricing represents GCP pricing data for a SKU
  502. type GCPPricing struct {
  503. Name string `json:"name"`
  504. SKUID string `json:"skuId"`
  505. Description string `json:"description"`
  506. Category *GCPResourceInfo `json:"category"`
  507. ServiceRegions []string `json:"serviceRegions"`
  508. PricingInfo []*PricingInfo `json:"pricingInfo"`
  509. ServiceProviderName string `json:"serviceProviderName"`
  510. Node *Node `json:"node"`
  511. PV *PV `json:"pv"`
  512. }
  513. // PricingInfo contains metadata about a cost.
  514. type PricingInfo struct {
  515. Summary string `json:"summary"`
  516. PricingExpression *PricingExpression `json:"pricingExpression"`
  517. CurrencyConversionRate int `json:"currencyConversionRate"`
  518. EffectiveTime string `json:""`
  519. }
  520. // PricingExpression contains metadata about a cost.
  521. type PricingExpression struct {
  522. UsageUnit string `json:"usageUnit"`
  523. UsageUnitDescription string `json:"usageUnitDescription"`
  524. BaseUnit string `json:"baseUnit"`
  525. BaseUnitConversionFactor int64 `json:"-"`
  526. DisplayQuantity int `json:"displayQuantity"`
  527. TieredRates []*TieredRates `json:"tieredRates"`
  528. }
  529. // TieredRates contain data about variable pricing.
  530. type TieredRates struct {
  531. StartUsageAmount int `json:"startUsageAmount"`
  532. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  533. }
  534. // UnitPriceInfo contains data about the actual price being charged.
  535. type UnitPriceInfo struct {
  536. CurrencyCode string `json:"currencyCode"`
  537. Units string `json:"units"`
  538. Nanos float64 `json:"nanos"`
  539. }
  540. // GCPResourceInfo contains metadata about the node.
  541. type GCPResourceInfo struct {
  542. ServiceDisplayName string `json:"serviceDisplayName"`
  543. ResourceFamily string `json:"resourceFamily"`
  544. ResourceGroup string `json:"resourceGroup"`
  545. UsageType string `json:"usageType"`
  546. }
  547. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, string, error) {
  548. gcpPricingList := make(map[string]*GCPPricing)
  549. var nextPageToken string
  550. dec := json.NewDecoder(r)
  551. for {
  552. t, err := dec.Token()
  553. if err == io.EOF {
  554. break
  555. }
  556. if t == "skus" {
  557. _, err := dec.Token() // consumes [
  558. if err != nil {
  559. return nil, "", err
  560. }
  561. for dec.More() {
  562. product := &GCPPricing{}
  563. err := dec.Decode(&product)
  564. if err != nil {
  565. return nil, "", err
  566. }
  567. usageType := strings.ToLower(product.Category.UsageType)
  568. instanceType := strings.ToLower(product.Category.ResourceGroup)
  569. if instanceType == "ssd" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  570. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  571. var nanos float64
  572. if len(product.PricingInfo) > 0 {
  573. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  574. } else {
  575. continue
  576. }
  577. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  578. for _, sr := range product.ServiceRegions {
  579. region := sr
  580. candidateKey := region + "," + "ssd"
  581. if _, ok := pvKeys[candidateKey]; ok {
  582. product.PV = &PV{
  583. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  584. }
  585. gcpPricingList[candidateKey] = product
  586. continue
  587. }
  588. }
  589. continue
  590. } else if instanceType == "pdstandard" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  591. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  592. var nanos float64
  593. if len(product.PricingInfo) > 0 {
  594. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  595. } else {
  596. continue
  597. }
  598. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  599. for _, sr := range product.ServiceRegions {
  600. region := sr
  601. candidateKey := region + "," + "pdstandard"
  602. if _, ok := pvKeys[candidateKey]; ok {
  603. product.PV = &PV{
  604. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  605. }
  606. gcpPricingList[candidateKey] = product
  607. continue
  608. }
  609. }
  610. continue
  611. }
  612. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  613. instanceType = "custom"
  614. }
  615. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "N2") {
  616. instanceType = "n2standard"
  617. }
  618. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "COMPUTE OPTIMIZED") {
  619. instanceType = "c2standard"
  620. }
  621. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "E2 INSTANCE") {
  622. instanceType = "e2"
  623. }
  624. partialCPUMap := make(map[string]float64)
  625. partialCPUMap["e2micro"] = 0.25
  626. partialCPUMap["e2small"] = 0.5
  627. partialCPUMap["e2medium"] = 1
  628. /*
  629. var partialCPU float64
  630. if strings.ToLower(instanceType) == "f1micro" {
  631. partialCPU = 0.2
  632. } else if strings.ToLower(instanceType) == "g1small" {
  633. partialCPU = 0.5
  634. }
  635. */
  636. var gpuType string
  637. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  638. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  639. if matchnum == 1 {
  640. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  641. klog.V(4).Info("GPU type found: " + gpuType)
  642. }
  643. }
  644. candidateKeys := []string{}
  645. if gcp.ValidPricingKeys == nil {
  646. gcp.ValidPricingKeys = make(map[string]bool)
  647. }
  648. for _, region := range product.ServiceRegions {
  649. if instanceType == "e2" { // this needs to be done to handle a partial cpu mapping
  650. candidateKeys = append(candidateKeys, region+","+"e2micro"+","+usageType)
  651. candidateKeys = append(candidateKeys, region+","+"e2small"+","+usageType)
  652. candidateKeys = append(candidateKeys, region+","+"e2medium"+","+usageType)
  653. candidateKeys = append(candidateKeys, region+","+"e2standard"+","+usageType)
  654. } else {
  655. candidateKey := region + "," + instanceType + "," + usageType
  656. candidateKeys = append(candidateKeys, candidateKey)
  657. }
  658. }
  659. for _, candidateKey := range candidateKeys {
  660. instanceType = strings.Split(candidateKey, ",")[1] // we may have overriden this while generating candidate keys
  661. region := strings.Split(candidateKey, ",")[0]
  662. candidateKeyGPU := candidateKey + ",gpu"
  663. gcp.ValidPricingKeys[candidateKey] = true
  664. gcp.ValidPricingKeys[candidateKeyGPU] = true
  665. if gpuType != "" {
  666. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  667. var nanos float64
  668. if len(product.PricingInfo) > 0 {
  669. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  670. } else {
  671. continue
  672. }
  673. hourlyPrice := nanos * math.Pow10(-9)
  674. for k, key := range inputKeys {
  675. if key.GPUType() == gpuType+","+usageType {
  676. if region == strings.Split(k, ",")[0] {
  677. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  678. klog.V(4).Infof("PRODUCT DESCRIPTION: %s", product.Description)
  679. matchedKey := key.Features()
  680. if pl, ok := gcpPricingList[matchedKey]; ok {
  681. pl.Node.GPUName = gpuType
  682. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  683. pl.Node.GPU = "1"
  684. } else {
  685. product.Node = &Node{
  686. GPUName: gpuType,
  687. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  688. GPU: "1",
  689. }
  690. gcpPricingList[matchedKey] = product
  691. }
  692. klog.V(3).Infof("Added data for " + matchedKey)
  693. }
  694. }
  695. }
  696. } else {
  697. _, ok := inputKeys[candidateKey]
  698. _, ok2 := inputKeys[candidateKeyGPU]
  699. if ok || ok2 {
  700. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  701. var nanos float64
  702. if len(product.PricingInfo) > 0 {
  703. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  704. } else {
  705. continue
  706. }
  707. hourlyPrice := nanos * math.Pow10(-9)
  708. if hourlyPrice == 0 {
  709. continue
  710. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  711. if instanceType == "custom" {
  712. klog.V(4).Infof("RAM custom sku is: " + product.Name)
  713. }
  714. if _, ok := gcpPricingList[candidateKey]; ok {
  715. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  716. } else {
  717. product = &GCPPricing{}
  718. product.Node = &Node{
  719. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  720. }
  721. partialCPU, pcok := partialCPUMap[instanceType]
  722. if pcok {
  723. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  724. }
  725. product.Node.UsageType = usageType
  726. gcpPricingList[candidateKey] = product
  727. }
  728. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  729. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  730. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  731. } else {
  732. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  733. product = &GCPPricing{}
  734. product.Node = &Node{
  735. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  736. }
  737. partialCPU, pcok := partialCPUMap[instanceType]
  738. if pcok {
  739. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  740. }
  741. product.Node.UsageType = usageType
  742. gcpPricingList[candidateKeyGPU] = product
  743. }
  744. break
  745. } else {
  746. if _, ok := gcpPricingList[candidateKey]; ok {
  747. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  748. } else {
  749. product = &GCPPricing{}
  750. product.Node = &Node{
  751. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  752. }
  753. partialCPU, pcok := partialCPUMap[instanceType]
  754. if pcok {
  755. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  756. }
  757. product.Node.UsageType = usageType
  758. gcpPricingList[candidateKey] = product
  759. }
  760. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  761. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  762. } else {
  763. product = &GCPPricing{}
  764. product.Node = &Node{
  765. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  766. }
  767. partialCPU, pcok := partialCPUMap[instanceType]
  768. if pcok {
  769. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  770. }
  771. product.Node.UsageType = usageType
  772. gcpPricingList[candidateKeyGPU] = product
  773. }
  774. break
  775. }
  776. }
  777. }
  778. }
  779. }
  780. }
  781. if t == "nextPageToken" {
  782. pageToken, err := dec.Token()
  783. if err != nil {
  784. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  785. return nil, "", err
  786. }
  787. if pageToken.(string) != "" {
  788. nextPageToken = pageToken.(string)
  789. } else {
  790. nextPageToken = "done"
  791. }
  792. }
  793. }
  794. return gcpPricingList, nextPageToken, nil
  795. }
  796. func (gcp *GCP) parsePages(inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, error) {
  797. var pages []map[string]*GCPPricing
  798. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey
  799. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  800. var parsePagesHelper func(string) error
  801. parsePagesHelper = func(pageToken string) error {
  802. if pageToken == "done" {
  803. return nil
  804. } else if pageToken != "" {
  805. url = url + "&pageToken=" + pageToken
  806. }
  807. resp, err := http.Get(url)
  808. if err != nil {
  809. return err
  810. }
  811. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  812. if err != nil {
  813. return err
  814. }
  815. pages = append(pages, page)
  816. return parsePagesHelper(token)
  817. }
  818. err := parsePagesHelper("")
  819. if err != nil {
  820. return nil, err
  821. }
  822. returnPages := make(map[string]*GCPPricing)
  823. for _, page := range pages {
  824. for k, v := range page {
  825. if val, ok := returnPages[k]; ok { //keys may need to be merged
  826. if val.Node != nil {
  827. if val.Node.VCPUCost == "" {
  828. val.Node.VCPUCost = v.Node.VCPUCost
  829. }
  830. if val.Node.RAMCost == "" {
  831. val.Node.RAMCost = v.Node.RAMCost
  832. }
  833. if val.Node.GPUCost == "" {
  834. val.Node.GPUCost = v.Node.GPUCost
  835. val.Node.GPU = v.Node.GPU
  836. val.Node.GPUName = v.Node.GPUName
  837. }
  838. }
  839. if val.PV != nil {
  840. if val.PV.Cost == "" {
  841. val.PV.Cost = v.PV.Cost
  842. }
  843. }
  844. } else {
  845. returnPages[k] = v
  846. }
  847. }
  848. }
  849. klog.V(1).Infof("ALL PAGES: %+v", returnPages)
  850. for k, v := range returnPages {
  851. klog.V(1).Infof("Returned Page: %s : %+v", k, v.Node)
  852. }
  853. return returnPages, err
  854. }
  855. // DownloadPricingData fetches data from the GCP Pricing API. Requires a key-- a kubecost key is provided for quickstart, but should be replaced by a users.
  856. func (gcp *GCP) DownloadPricingData() error {
  857. gcp.DownloadPricingDataLock.Lock()
  858. defer gcp.DownloadPricingDataLock.Unlock()
  859. c, err := gcp.Config.GetCustomPricingData()
  860. if err != nil {
  861. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  862. return err
  863. }
  864. gcp.loadGCPAuthSecret()
  865. gcp.BaseCPUPrice = c.CPU
  866. gcp.ProjectID = c.ProjectID
  867. gcp.BillingDataDataset = c.BillingDataDataset
  868. nodeList := gcp.Clientset.GetAllNodes()
  869. inputkeys := make(map[string]Key)
  870. for _, n := range nodeList {
  871. labels := n.GetObjectMeta().GetLabels()
  872. key := gcp.GetKey(labels, n)
  873. inputkeys[key.Features()] = key
  874. }
  875. pvList := gcp.Clientset.GetAllPersistentVolumes()
  876. storageClasses := gcp.Clientset.GetAllStorageClasses()
  877. storageClassMap := make(map[string]map[string]string)
  878. for _, storageClass := range storageClasses {
  879. params := storageClass.Parameters
  880. storageClassMap[storageClass.ObjectMeta.Name] = params
  881. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  882. storageClassMap["default"] = params
  883. storageClassMap[""] = params
  884. }
  885. }
  886. pvkeys := make(map[string]PVKey)
  887. for _, pv := range pvList {
  888. params, ok := storageClassMap[pv.Spec.StorageClassName]
  889. if !ok {
  890. klog.Infof("Unable to find params for storageClassName %s", pv.Name)
  891. continue
  892. }
  893. key := gcp.GetPVKey(pv, params, "")
  894. pvkeys[key.Features()] = key
  895. }
  896. reserved, err := gcp.getReservedInstances()
  897. if err != nil {
  898. klog.V(1).Infof("Failed to lookup reserved instance data: %s", err.Error())
  899. } else {
  900. klog.V(1).Infof("Found %d reserved instances", len(reserved))
  901. gcp.ReservedInstances = reserved
  902. for _, r := range reserved {
  903. klog.V(1).Infof("%s", r)
  904. }
  905. }
  906. pages, err := gcp.parsePages(inputkeys, pvkeys)
  907. if err != nil {
  908. return err
  909. }
  910. gcp.Pricing = pages
  911. return nil
  912. }
  913. func (gcp *GCP) PVPricing(pvk PVKey) (*PV, error) {
  914. gcp.DownloadPricingDataLock.RLock()
  915. defer gcp.DownloadPricingDataLock.RUnlock()
  916. pricing, ok := gcp.Pricing[pvk.Features()]
  917. if !ok {
  918. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  919. return &PV{}, nil
  920. }
  921. return pricing.PV, nil
  922. }
  923. // Stubbed NetworkPricing for GCP. Pull directly from gcp.json for now
  924. func (gcp *GCP) NetworkPricing() (*Network, error) {
  925. cpricing, err := gcp.Config.GetCustomPricingData()
  926. if err != nil {
  927. return nil, err
  928. }
  929. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  930. if err != nil {
  931. return nil, err
  932. }
  933. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  934. if err != nil {
  935. return nil, err
  936. }
  937. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  938. if err != nil {
  939. return nil, err
  940. }
  941. return &Network{
  942. ZoneNetworkEgressCost: znec,
  943. RegionNetworkEgressCost: rnec,
  944. InternetNetworkEgressCost: inec,
  945. }, nil
  946. }
  947. const (
  948. GCPReservedInstanceResourceTypeRAM string = "MEMORY"
  949. GCPReservedInstanceResourceTypeCPU string = "VCPU"
  950. GCPReservedInstanceStatusActive string = "ACTIVE"
  951. GCPReservedInstancePlanOneYear string = "TWELVE_MONTH"
  952. GCPReservedInstancePlanThreeYear string = "THIRTY_SIX_MONTH"
  953. )
  954. type GCPReservedInstancePlan struct {
  955. Name string
  956. CPUCost float64
  957. RAMCost float64
  958. }
  959. type GCPReservedInstance struct {
  960. ReservedRAM int64
  961. ReservedCPU int64
  962. Plan *GCPReservedInstancePlan
  963. StartDate time.Time
  964. EndDate time.Time
  965. Region string
  966. }
  967. func (r *GCPReservedInstance) String() string {
  968. return fmt.Sprintf("[CPU: %d, RAM: %d, Region: %s, Start: %s, End: %s]", r.ReservedCPU, r.ReservedRAM, r.Region, r.StartDate.String(), r.EndDate.String())
  969. }
  970. type GCPReservedCounter struct {
  971. RemainingCPU int64
  972. RemainingRAM int64
  973. Instance *GCPReservedInstance
  974. }
  975. func newReservedCounter(instance *GCPReservedInstance) *GCPReservedCounter {
  976. return &GCPReservedCounter{
  977. RemainingCPU: instance.ReservedCPU,
  978. RemainingRAM: instance.ReservedRAM,
  979. Instance: instance,
  980. }
  981. }
  982. // Two available Reservation plans for GCP, 1-year and 3-year
  983. var gcpReservedInstancePlans map[string]*GCPReservedInstancePlan = map[string]*GCPReservedInstancePlan{
  984. GCPReservedInstancePlanOneYear: &GCPReservedInstancePlan{
  985. Name: GCPReservedInstancePlanOneYear,
  986. CPUCost: 0.019915,
  987. RAMCost: 0.002669,
  988. },
  989. GCPReservedInstancePlanThreeYear: &GCPReservedInstancePlan{
  990. Name: GCPReservedInstancePlanThreeYear,
  991. CPUCost: 0.014225,
  992. RAMCost: 0.001907,
  993. },
  994. }
  995. func (gcp *GCP) ApplyReservedInstancePricing(nodes map[string]*Node) {
  996. numReserved := len(gcp.ReservedInstances)
  997. // Early return if no reserved instance data loaded
  998. if numReserved == 0 {
  999. klog.V(4).Infof("[Reserved] No Reserved Instances")
  1000. return
  1001. }
  1002. now := time.Now()
  1003. counters := make(map[string][]*GCPReservedCounter)
  1004. for _, r := range gcp.ReservedInstances {
  1005. if now.Before(r.StartDate) || now.After(r.EndDate) {
  1006. klog.V(1).Infof("[Reserved] Skipped Reserved Instance due to dates")
  1007. continue
  1008. }
  1009. _, ok := counters[r.Region]
  1010. counter := newReservedCounter(r)
  1011. if !ok {
  1012. counters[r.Region] = []*GCPReservedCounter{counter}
  1013. } else {
  1014. counters[r.Region] = append(counters[r.Region], counter)
  1015. }
  1016. }
  1017. gcpNodes := make(map[string]*v1.Node)
  1018. currentNodes := gcp.Clientset.GetAllNodes()
  1019. // Create a node name -> node map
  1020. for _, gcpNode := range currentNodes {
  1021. gcpNodes[gcpNode.GetName()] = gcpNode
  1022. }
  1023. // go through all provider nodes using k8s nodes for region
  1024. for nodeName, node := range nodes {
  1025. // Reset reserved allocation to prevent double allocation
  1026. node.Reserved = nil
  1027. kNode, ok := gcpNodes[nodeName]
  1028. if !ok {
  1029. klog.V(4).Infof("[Reserved] Could not find K8s Node with name: %s", nodeName)
  1030. continue
  1031. }
  1032. nodeRegion, ok := kNode.Labels[v1.LabelZoneRegion]
  1033. if !ok {
  1034. klog.V(4).Infof("[Reserved] Could not find node region")
  1035. continue
  1036. }
  1037. reservedCounters, ok := counters[nodeRegion]
  1038. if !ok {
  1039. klog.V(4).Infof("[Reserved] Could not find counters for region: %s", nodeRegion)
  1040. continue
  1041. }
  1042. node.Reserved = &ReservedInstanceData{
  1043. ReservedCPU: 0,
  1044. ReservedRAM: 0,
  1045. }
  1046. for _, reservedCounter := range reservedCounters {
  1047. if reservedCounter.RemainingCPU != 0 {
  1048. nodeCPU, _ := strconv.ParseInt(node.VCPU, 10, 64)
  1049. nodeCPU -= node.Reserved.ReservedCPU
  1050. node.Reserved.CPUCost = reservedCounter.Instance.Plan.CPUCost
  1051. if reservedCounter.RemainingCPU >= nodeCPU {
  1052. reservedCounter.RemainingCPU -= nodeCPU
  1053. node.Reserved.ReservedCPU += nodeCPU
  1054. } else {
  1055. node.Reserved.ReservedCPU += reservedCounter.RemainingCPU
  1056. reservedCounter.RemainingCPU = 0
  1057. }
  1058. }
  1059. if reservedCounter.RemainingRAM != 0 {
  1060. nodeRAMF, _ := strconv.ParseFloat(node.RAMBytes, 64)
  1061. nodeRAM := int64(nodeRAMF)
  1062. nodeRAM -= node.Reserved.ReservedRAM
  1063. node.Reserved.RAMCost = reservedCounter.Instance.Plan.RAMCost
  1064. if reservedCounter.RemainingRAM >= nodeRAM {
  1065. reservedCounter.RemainingRAM -= nodeRAM
  1066. node.Reserved.ReservedRAM += nodeRAM
  1067. } else {
  1068. node.Reserved.ReservedRAM += reservedCounter.RemainingRAM
  1069. reservedCounter.RemainingRAM = 0
  1070. }
  1071. }
  1072. }
  1073. }
  1074. }
  1075. func (gcp *GCP) getReservedInstances() ([]*GCPReservedInstance, error) {
  1076. var results []*GCPReservedInstance
  1077. ctx := context.Background()
  1078. computeService, err := compute.NewService(ctx)
  1079. if err != nil {
  1080. return nil, err
  1081. }
  1082. commitments, err := computeService.RegionCommitments.AggregatedList(gcp.ProjectID).Do()
  1083. if err != nil {
  1084. return nil, err
  1085. }
  1086. for regionKey, commitList := range commitments.Items {
  1087. for _, commit := range commitList.Commitments {
  1088. if commit.Status != GCPReservedInstanceStatusActive {
  1089. continue
  1090. }
  1091. var vcpu int64 = 0
  1092. var ram int64 = 0
  1093. for _, resource := range commit.Resources {
  1094. switch resource.Type {
  1095. case GCPReservedInstanceResourceTypeRAM:
  1096. ram = resource.Amount * 1024 * 1024
  1097. case GCPReservedInstanceResourceTypeCPU:
  1098. vcpu = resource.Amount
  1099. default:
  1100. klog.V(4).Infof("Failed to handle resource type: %s", resource.Type)
  1101. }
  1102. }
  1103. var region string
  1104. regionStr := strings.Split(regionKey, "/")
  1105. if len(regionStr) == 2 {
  1106. region = regionStr[1]
  1107. }
  1108. timeLayout := "2006-01-02T15:04:05Z07:00"
  1109. startTime, err := time.Parse(timeLayout, commit.StartTimestamp)
  1110. if err != nil {
  1111. klog.V(1).Infof("Failed to parse start date: %s", commit.StartTimestamp)
  1112. continue
  1113. }
  1114. endTime, err := time.Parse(timeLayout, commit.EndTimestamp)
  1115. if err != nil {
  1116. klog.V(1).Infof("Failed to parse end date: %s", commit.EndTimestamp)
  1117. continue
  1118. }
  1119. // Look for a plan based on the name. Default to One Year if it fails
  1120. plan, ok := gcpReservedInstancePlans[commit.Plan]
  1121. if !ok {
  1122. plan = gcpReservedInstancePlans[GCPReservedInstancePlanOneYear]
  1123. }
  1124. results = append(results, &GCPReservedInstance{
  1125. Region: region,
  1126. ReservedRAM: ram,
  1127. ReservedCPU: vcpu,
  1128. Plan: plan,
  1129. StartDate: startTime,
  1130. EndDate: endTime,
  1131. })
  1132. }
  1133. }
  1134. return results, nil
  1135. }
  1136. type pvKey struct {
  1137. Labels map[string]string
  1138. StorageClass string
  1139. StorageClassParameters map[string]string
  1140. DefaultRegion string
  1141. }
  1142. func (key *pvKey) GetStorageClass() string {
  1143. return key.StorageClass
  1144. }
  1145. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  1146. return &pvKey{
  1147. Labels: pv.Labels,
  1148. StorageClass: pv.Spec.StorageClassName,
  1149. StorageClassParameters: parameters,
  1150. DefaultRegion: defaultRegion,
  1151. }
  1152. }
  1153. func (key *pvKey) Features() string {
  1154. // TODO: regional cluster pricing.
  1155. storageClass := key.StorageClassParameters["type"]
  1156. if storageClass == "pd-ssd" {
  1157. storageClass = "ssd"
  1158. } else if storageClass == "pd-standard" {
  1159. storageClass = "pdstandard"
  1160. }
  1161. return key.Labels[v1.LabelZoneRegion] + "," + storageClass
  1162. }
  1163. type gcpKey struct {
  1164. Labels map[string]string
  1165. }
  1166. func (gcp *GCP) GetKey(labels map[string]string, n *v1.Node) Key {
  1167. return &gcpKey{
  1168. Labels: labels,
  1169. }
  1170. }
  1171. func (gcp *gcpKey) ID() string {
  1172. return ""
  1173. }
  1174. func (gcp *gcpKey) GPUType() string {
  1175. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1176. var usageType string
  1177. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  1178. usageType = "preemptible"
  1179. } else {
  1180. usageType = "ondemand"
  1181. }
  1182. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  1183. return t + "," + usageType
  1184. }
  1185. return ""
  1186. }
  1187. // GetKey maps node labels to information needed to retrieve pricing data
  1188. func (gcp *gcpKey) Features() string {
  1189. instanceType := strings.ToLower(strings.Join(strings.Split(gcp.Labels[v1.LabelInstanceType], "-")[:2], ""))
  1190. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  1191. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  1192. } else if instanceType == "n2highmem" || instanceType == "n2highcpu" {
  1193. instanceType = "n2standard"
  1194. } else if instanceType == "e2highmem" || instanceType == "e2highcpu" {
  1195. instanceType = "e2standard"
  1196. } else if strings.HasPrefix(instanceType, "custom") {
  1197. instanceType = "custom" // The suffix of custom does not matter
  1198. }
  1199. region := strings.ToLower(gcp.Labels[v1.LabelZoneRegion])
  1200. var usageType string
  1201. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  1202. usageType = "preemptible"
  1203. } else {
  1204. usageType = "ondemand"
  1205. }
  1206. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1207. return region + "," + instanceType + "," + usageType + "," + "gpu"
  1208. }
  1209. return region + "," + instanceType + "," + usageType
  1210. }
  1211. // AllNodePricing returns the GCP pricing objects stored
  1212. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  1213. gcp.DownloadPricingDataLock.RLock()
  1214. defer gcp.DownloadPricingDataLock.RUnlock()
  1215. return gcp.Pricing, nil
  1216. }
  1217. func (gcp *GCP) getPricing(key Key) (*GCPPricing, bool) {
  1218. gcp.DownloadPricingDataLock.RLock()
  1219. defer gcp.DownloadPricingDataLock.RUnlock()
  1220. n, ok := gcp.Pricing[key.Features()]
  1221. return n, ok
  1222. }
  1223. func (gcp *GCP) isValidPricingKey(key Key) bool {
  1224. gcp.DownloadPricingDataLock.RLock()
  1225. defer gcp.DownloadPricingDataLock.RUnlock()
  1226. _, ok := gcp.ValidPricingKeys[key.Features()]
  1227. return ok
  1228. }
  1229. // NodePricing returns GCP pricing data for a single node
  1230. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  1231. if n, ok := gcp.getPricing(key); ok {
  1232. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  1233. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  1234. return n.Node, nil
  1235. } else if ok := gcp.isValidPricingKey(key); ok {
  1236. err := gcp.DownloadPricingData()
  1237. if err != nil {
  1238. return nil, fmt.Errorf("Download pricing data failed: %s", err.Error())
  1239. }
  1240. if n, ok := gcp.getPricing(key); ok {
  1241. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  1242. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  1243. return n.Node, nil
  1244. }
  1245. klog.V(1).Infof("[Warning] no pricing data found for %s: %s", key.Features(), key)
  1246. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  1247. }
  1248. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  1249. }