gcpprovider.go 39 KB

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