gcpprovider.go 44 KB

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