gcpprovider.go 42 KB

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