provider.go 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  1. package gcp
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "math"
  7. "net/http"
  8. "os"
  9. "path"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/opencost/opencost/pkg/cloud/aws"
  16. "github.com/opencost/opencost/pkg/cloud/models"
  17. "github.com/opencost/opencost/pkg/cloud/utils"
  18. "github.com/opencost/opencost/pkg/kubecost"
  19. "github.com/opencost/opencost/pkg/clustercache"
  20. "github.com/opencost/opencost/pkg/env"
  21. "github.com/opencost/opencost/pkg/log"
  22. "github.com/opencost/opencost/pkg/util"
  23. "github.com/opencost/opencost/pkg/util/fileutil"
  24. "github.com/opencost/opencost/pkg/util/json"
  25. "github.com/opencost/opencost/pkg/util/timeutil"
  26. "github.com/rs/zerolog"
  27. "cloud.google.com/go/bigquery"
  28. "cloud.google.com/go/compute/metadata"
  29. "golang.org/x/oauth2/google"
  30. "google.golang.org/api/compute/v1"
  31. v1 "k8s.io/api/core/v1"
  32. )
  33. const GKE_GPU_TAG = "cloud.google.com/gke-accelerator"
  34. const BigqueryUpdateType = "bigqueryupdate"
  35. const BillingAPIURLFmt = "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=%s&currencyCode=%s"
  36. const (
  37. GCPHourlyPublicIPCost = 0.01
  38. GCPMonthlyBasicDiskCost = 0.04
  39. GCPMonthlySSDDiskCost = 0.17
  40. GCPMonthlyGP2DiskCost = 0.1
  41. GKEPreemptibleLabel = "cloud.google.com/gke-preemptible"
  42. GKESpotLabel = "cloud.google.com/gke-spot"
  43. )
  44. // List obtained by installing the `gcloud` CLI tool,
  45. // logging into gcp account, and running command
  46. // `gcloud compute regions list`
  47. var gcpRegions = []string{
  48. "asia-east1",
  49. "asia-east2",
  50. "asia-northeast1",
  51. "asia-northeast2",
  52. "asia-northeast3",
  53. "asia-south1",
  54. "asia-south2",
  55. "asia-southeast1",
  56. "asia-southeast2",
  57. "australia-southeast1",
  58. "australia-southeast2",
  59. "europe-central2",
  60. "europe-north1",
  61. "europe-west1",
  62. "europe-west2",
  63. "europe-west3",
  64. "europe-west4",
  65. "europe-west6",
  66. "northamerica-northeast1",
  67. "northamerica-northeast2",
  68. "southamerica-east1",
  69. "us-central1",
  70. "us-east1",
  71. "us-east4",
  72. "us-west1",
  73. "us-west2",
  74. "us-west3",
  75. "us-west4",
  76. }
  77. var (
  78. nvidiaGPURegex = regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  79. // gce://guestbook-12345/...
  80. // => guestbook-12345
  81. gceRegex = regexp.MustCompile("gce://([^/]*)/*")
  82. )
  83. // GCP implements a provider interface for GCP
  84. type GCP struct {
  85. Pricing map[string]*GCPPricing
  86. Clientset clustercache.ClusterCache
  87. APIKey string
  88. BaseCPUPrice string
  89. ProjectID string
  90. BillingDataDataset string
  91. DownloadPricingDataLock sync.RWMutex
  92. ReservedInstances []*GCPReservedInstance
  93. Config models.ProviderConfig
  94. ServiceKeyProvided bool
  95. ValidPricingKeys map[string]bool
  96. MetadataClient *metadata.Client
  97. clusterManagementPrice float64
  98. ClusterRegion string
  99. ClusterAccountID string
  100. ClusterProjectID string
  101. clusterProvisioner string
  102. }
  103. type gcpAllocation struct {
  104. Aggregator bigquery.NullString
  105. Environment bigquery.NullString
  106. Service string
  107. Cost float64
  108. }
  109. type multiKeyGCPAllocation struct {
  110. Keys bigquery.NullString
  111. Service string
  112. Cost float64
  113. }
  114. // GetLocalStorageQuery returns the cost of local storage for the given window. Setting rate=true
  115. // returns hourly spend. Setting used=true only tracks used storage, not total.
  116. func (gcp *GCP) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  117. // TODO Set to the price for the appropriate storage class. It's not trivial to determine the local storage disk type
  118. // See https://cloud.google.com/compute/disks-image-pricing#persistentdisk
  119. localStorageCost := 0.04
  120. baseMetric := "container_fs_limit_bytes"
  121. if used {
  122. baseMetric = "container_fs_usage_bytes"
  123. }
  124. fmtOffset := timeutil.DurationToPromOffsetString(offset)
  125. fmtCumulativeQuery := `sum(
  126. sum_over_time(%s{device!="tmpfs", id="/", %s}[%s:1m]%s)
  127. ) by (%s) / 60 / 730 / 1024 / 1024 / 1024 * %f`
  128. fmtMonthlyQuery := `sum(
  129. avg_over_time(%s{device!="tmpfs", id="/", %s}[%s:1m]%s)
  130. ) by (%s) / 1024 / 1024 / 1024 * %f`
  131. fmtQuery := fmtCumulativeQuery
  132. if rate {
  133. fmtQuery = fmtMonthlyQuery
  134. }
  135. fmtWindow := timeutil.DurationString(window)
  136. return fmt.Sprintf(fmtQuery, baseMetric, env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), localStorageCost)
  137. }
  138. func (gcp *GCP) GetConfig() (*models.CustomPricing, error) {
  139. c, err := gcp.Config.GetCustomPricingData()
  140. if err != nil {
  141. return nil, err
  142. }
  143. if c.Discount == "" {
  144. c.Discount = "30%"
  145. }
  146. if c.NegotiatedDiscount == "" {
  147. c.NegotiatedDiscount = "0%"
  148. }
  149. if c.CurrencyCode == "" {
  150. c.CurrencyCode = "USD"
  151. }
  152. if c.ShareTenancyCosts == "" {
  153. c.ShareTenancyCosts = models.DefaultShareTenancyCost
  154. }
  155. return c, nil
  156. }
  157. // BigQueryConfig contain the required config and credentials to access OOC resources for GCP
  158. // Deprecated: v1.104 Use BigQueryConfiguration instead
  159. type BigQueryConfig struct {
  160. ProjectID string `json:"projectID"`
  161. BillingDataDataset string `json:"billingDataDataset"`
  162. Key map[string]string `json:"key"`
  163. }
  164. // IsEmpty returns true if all fields in config are empty, false if not.
  165. func (bqc *BigQueryConfig) IsEmpty() bool {
  166. return bqc.ProjectID == "" &&
  167. bqc.BillingDataDataset == "" &&
  168. (bqc.Key == nil || len(bqc.Key) == 0)
  169. }
  170. func (gcp *GCP) GetManagementPlatform() (string, error) {
  171. nodes := gcp.Clientset.GetAllNodes()
  172. if len(nodes) > 0 {
  173. n := nodes[0]
  174. version := n.Status.NodeInfo.KubeletVersion
  175. if strings.Contains(version, "gke") {
  176. return "gke", nil
  177. }
  178. }
  179. return "", nil
  180. }
  181. // Attempts to load a GCP auth secret and copy the contents to the key file.
  182. func (*GCP) loadGCPAuthSecret() {
  183. path := env.GetConfigPathWithDefault("/models/")
  184. keyPath := path + "key.json"
  185. keyExists, _ := fileutil.FileExists(keyPath)
  186. if keyExists {
  187. log.Info("GCP Auth Key already exists, no need to load from secret")
  188. return
  189. }
  190. exists, err := fileutil.FileExists(models.AuthSecretPath)
  191. if !exists || err != nil {
  192. errMessage := "Secret does not exist"
  193. if err != nil {
  194. errMessage = err.Error()
  195. }
  196. log.Warnf("Failed to load auth secret, or was not mounted: %s", errMessage)
  197. return
  198. }
  199. result, err := os.ReadFile(models.AuthSecretPath)
  200. if err != nil {
  201. log.Warnf("Failed to load auth secret, or was not mounted: %s", err.Error())
  202. return
  203. }
  204. err = os.WriteFile(keyPath, result, 0644)
  205. if err != nil {
  206. log.Warnf("Failed to copy auth secret to %s: %s", keyPath, err.Error())
  207. }
  208. }
  209. func (gcp *GCP) UpdateConfigFromConfigMap(a map[string]string) (*models.CustomPricing, error) {
  210. return gcp.Config.UpdateFromMap(a)
  211. }
  212. func (gcp *GCP) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  213. return gcp.Config.Update(func(c *models.CustomPricing) error {
  214. if updateType == BigqueryUpdateType {
  215. a := BigQueryConfig{}
  216. err := json.NewDecoder(r).Decode(&a)
  217. if err != nil {
  218. return err
  219. }
  220. c.ProjectID = a.ProjectID
  221. c.BillingDataDataset = a.BillingDataDataset
  222. if len(a.Key) > 0 {
  223. j, err := json.Marshal(a.Key)
  224. if err != nil {
  225. return err
  226. }
  227. path := env.GetConfigPathWithDefault("/models/")
  228. keyPath := path + "key.json"
  229. err = os.WriteFile(keyPath, j, 0644)
  230. if err != nil {
  231. return err
  232. }
  233. gcp.ServiceKeyProvided = true
  234. }
  235. } else if updateType == aws.AthenaInfoUpdateType {
  236. a := aws.AwsAthenaInfo{}
  237. err := json.NewDecoder(r).Decode(&a)
  238. if err != nil {
  239. return err
  240. }
  241. c.AthenaBucketName = a.AthenaBucketName
  242. c.AthenaRegion = a.AthenaRegion
  243. c.AthenaDatabase = a.AthenaDatabase
  244. c.AthenaCatalog = a.AthenaCatalog
  245. c.AthenaTable = a.AthenaTable
  246. c.AthenaWorkgroup = a.AthenaWorkgroup
  247. c.ServiceKeyName = a.ServiceKeyName
  248. c.ServiceKeySecret = a.ServiceKeySecret
  249. c.AthenaProjectID = a.AccountID
  250. } else {
  251. a := make(map[string]interface{})
  252. err := json.NewDecoder(r).Decode(&a)
  253. if err != nil {
  254. return err
  255. }
  256. for k, v := range a {
  257. kUpper := utils.ToTitle.String(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  258. vstr, ok := v.(string)
  259. if ok {
  260. err := models.SetCustomPricingField(c, kUpper, vstr)
  261. if err != nil {
  262. return err
  263. }
  264. } else {
  265. return fmt.Errorf("type error while updating config for %s", kUpper)
  266. }
  267. }
  268. }
  269. if env.IsRemoteEnabled() {
  270. err := utils.UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  271. if err != nil {
  272. return err
  273. }
  274. }
  275. return nil
  276. })
  277. }
  278. // ClusterInfo returns information on the GKE cluster, as provided by metadata.
  279. func (gcp *GCP) ClusterInfo() (map[string]string, error) {
  280. remoteEnabled := env.IsRemoteEnabled()
  281. attribute, err := gcp.MetadataClient.InstanceAttributeValue("cluster-name")
  282. if err != nil {
  283. log.Infof("Error loading metadata cluster-name: %s", err.Error())
  284. }
  285. c, err := gcp.GetConfig()
  286. if err != nil {
  287. log.Errorf("Error opening config: %s", err.Error())
  288. }
  289. if c.ClusterName != "" {
  290. attribute = c.ClusterName
  291. }
  292. // Use a default name if none has been set until this point
  293. if attribute == "" {
  294. attribute = "GKE Cluster #1"
  295. }
  296. m := make(map[string]string)
  297. m["name"] = attribute
  298. m["provider"] = kubecost.GCPProvider
  299. m["region"] = gcp.ClusterRegion
  300. m["account"] = gcp.ClusterAccountID
  301. m["project"] = gcp.ClusterProjectID
  302. m["provisioner"] = gcp.clusterProvisioner
  303. m["id"] = env.GetClusterID()
  304. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  305. return m, nil
  306. }
  307. func (gcp *GCP) ClusterManagementPricing() (string, float64, error) {
  308. return gcp.clusterProvisioner, gcp.clusterManagementPrice, nil
  309. }
  310. func (gcp *GCP) getAllAddresses() (*compute.AddressAggregatedList, error) {
  311. projID, err := gcp.MetadataClient.ProjectID()
  312. if err != nil {
  313. return nil, err
  314. }
  315. client, err := google.DefaultClient(context.TODO(),
  316. "https://www.googleapis.com/auth/compute.readonly")
  317. if err != nil {
  318. return nil, err
  319. }
  320. svc, err := compute.New(client)
  321. if err != nil {
  322. return nil, err
  323. }
  324. res, err := svc.Addresses.AggregatedList(projID).Do()
  325. if err != nil {
  326. return nil, err
  327. }
  328. return res, nil
  329. }
  330. func (gcp *GCP) GetAddresses() ([]byte, error) {
  331. res, err := gcp.getAllAddresses()
  332. if err != nil {
  333. return nil, err
  334. }
  335. return json.Marshal(res)
  336. }
  337. func (gcp *GCP) isAddressOrphaned(address *compute.Address) bool {
  338. // Consider address orphaned if it has 0 users
  339. return len(address.Users) == 0
  340. }
  341. func (gcp *GCP) getAllDisks() (*compute.DiskAggregatedList, error) {
  342. projID, err := gcp.MetadataClient.ProjectID()
  343. if err != nil {
  344. return nil, err
  345. }
  346. client, err := google.DefaultClient(context.TODO(),
  347. "https://www.googleapis.com/auth/compute.readonly")
  348. if err != nil {
  349. return nil, err
  350. }
  351. svc, err := compute.New(client)
  352. if err != nil {
  353. return nil, err
  354. }
  355. res, err := svc.Disks.AggregatedList(projID).Do()
  356. if err != nil {
  357. return nil, err
  358. }
  359. return res, nil
  360. }
  361. // 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.
  362. func (gcp *GCP) GetDisks() ([]byte, error) {
  363. res, err := gcp.getAllDisks()
  364. if err != nil {
  365. return nil, err
  366. }
  367. return json.Marshal(res)
  368. }
  369. func (gcp *GCP) isDiskOrphaned(disk *compute.Disk) (bool, error) {
  370. // Do not consider disk orphaned if it has more than 0 users
  371. if len(disk.Users) > 0 {
  372. return false, nil
  373. }
  374. // Do not consider disk orphaned if it was used within the last hour
  375. threshold := time.Now().Add(time.Duration(-1) * time.Hour)
  376. if disk.LastDetachTimestamp != "" {
  377. lastUsed, err := time.Parse(time.RFC3339, disk.LastDetachTimestamp)
  378. if err != nil {
  379. // This can return false since errors are checked before the bool
  380. return false, fmt.Errorf("error parsing time: %s", err)
  381. }
  382. if threshold.Before(lastUsed) {
  383. return false, nil
  384. }
  385. }
  386. return true, nil
  387. }
  388. func (gcp *GCP) GetOrphanedResources() ([]models.OrphanedResource, error) {
  389. disks, err := gcp.getAllDisks()
  390. if err != nil {
  391. return nil, err
  392. }
  393. addresses, err := gcp.getAllAddresses()
  394. if err != nil {
  395. return nil, err
  396. }
  397. var orphanedResources []models.OrphanedResource
  398. for _, diskList := range disks.Items {
  399. if len(diskList.Disks) == 0 {
  400. continue
  401. }
  402. for _, disk := range diskList.Disks {
  403. isOrphaned, err := gcp.isDiskOrphaned(disk)
  404. if err != nil {
  405. return nil, err
  406. }
  407. if isOrphaned {
  408. cost, err := gcp.findCostForDisk(disk)
  409. if err != nil {
  410. return nil, err
  411. }
  412. // GCP gives us description as a string formatted as a map[string]string, so we need to
  413. // deconstruct it back into a map[string]string to match the OR struct
  414. desc := map[string]string{}
  415. if disk.Description != "" {
  416. if err := json.Unmarshal([]byte(disk.Description), &desc); err != nil {
  417. return nil, fmt.Errorf("error converting string to map: %s", err)
  418. }
  419. }
  420. // Converts https://www.googleapis.com/compute/v1/projects/xxxxx/zones/us-central1-c to us-central1-c
  421. zone := path.Base(disk.Zone)
  422. if zone == "." {
  423. zone = ""
  424. }
  425. or := models.OrphanedResource{
  426. Kind: "disk",
  427. Region: zone,
  428. Description: desc,
  429. Size: &disk.SizeGb,
  430. DiskName: disk.Name,
  431. Url: disk.SelfLink,
  432. MonthlyCost: cost,
  433. }
  434. orphanedResources = append(orphanedResources, or)
  435. }
  436. }
  437. }
  438. for _, addressList := range addresses.Items {
  439. if len(addressList.Addresses) == 0 {
  440. continue
  441. }
  442. for _, address := range addressList.Addresses {
  443. if gcp.isAddressOrphaned(address) {
  444. //todo: use GCP pricing
  445. cost := GCPHourlyPublicIPCost * timeutil.HoursPerMonth
  446. // Converts https://www.googleapis.com/compute/v1/projects/xxxxx/regions/us-central1 to us-central1
  447. region := path.Base(address.Region)
  448. if region == "." {
  449. region = ""
  450. }
  451. or := models.OrphanedResource{
  452. Kind: "address",
  453. Region: region,
  454. Description: map[string]string{
  455. "type": address.AddressType,
  456. },
  457. Address: address.Address,
  458. Url: address.SelfLink,
  459. MonthlyCost: &cost,
  460. }
  461. orphanedResources = append(orphanedResources, or)
  462. }
  463. }
  464. }
  465. return orphanedResources, nil
  466. }
  467. func (gcp *GCP) findCostForDisk(disk *compute.Disk) (*float64, error) {
  468. //todo: use GCP pricing struct
  469. price := GCPMonthlyBasicDiskCost
  470. if strings.Contains(disk.Type, "ssd") {
  471. price = GCPMonthlySSDDiskCost
  472. }
  473. if strings.Contains(disk.Type, "gp2") {
  474. price = GCPMonthlyGP2DiskCost
  475. }
  476. cost := price * float64(disk.SizeGb)
  477. // This isn't much use but I (Nick) think its could be going down the
  478. // right path. Disk region isnt returning anything (and if it did its
  479. // a url, same with type). Currently the only region stored in the
  480. // Pricing struct is uscentral-1, so that would need to be fixed
  481. // key := disk.Region + "," + disk.Type
  482. // priceStr := gcp.Pricing[key].PV.Cost
  483. // price, err := strconv.ParseFloat(priceStr, 64)
  484. // if err != nil {
  485. // return nil, err
  486. // }
  487. // cost := price * timeutil.HoursPerMonth * float64(disk.SizeGb)
  488. return &cost, nil
  489. }
  490. // GCPPricing represents GCP pricing data for a SKU
  491. type GCPPricing struct {
  492. Name string `json:"name"`
  493. SKUID string `json:"skuId"`
  494. Description string `json:"description"`
  495. Category *GCPResourceInfo `json:"category"`
  496. ServiceRegions []string `json:"serviceRegions"`
  497. PricingInfo []*PricingInfo `json:"pricingInfo"`
  498. ServiceProviderName string `json:"serviceProviderName"`
  499. Node *models.Node `json:"node"`
  500. PV *models.PV `json:"pv"`
  501. }
  502. // PricingInfo contains metadata about a cost.
  503. type PricingInfo struct {
  504. Summary string `json:"summary"`
  505. PricingExpression *PricingExpression `json:"pricingExpression"`
  506. CurrencyConversionRate float64 `json:"currencyConversionRate"`
  507. EffectiveTime string `json:""`
  508. }
  509. // PricingExpression contains metadata about a cost.
  510. type PricingExpression struct {
  511. UsageUnit string `json:"usageUnit"`
  512. UsageUnitDescription string `json:"usageUnitDescription"`
  513. BaseUnit string `json:"baseUnit"`
  514. BaseUnitConversionFactor int64 `json:"-"`
  515. DisplayQuantity int `json:"displayQuantity"`
  516. TieredRates []*TieredRates `json:"tieredRates"`
  517. }
  518. // TieredRates contain data about variable pricing.
  519. type TieredRates struct {
  520. StartUsageAmount int `json:"startUsageAmount"`
  521. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  522. }
  523. // UnitPriceInfo contains data about the actual price being charged.
  524. type UnitPriceInfo struct {
  525. CurrencyCode string `json:"currencyCode"`
  526. Units string `json:"units"`
  527. Nanos float64 `json:"nanos"`
  528. }
  529. // GCPResourceInfo contains metadata about the node.
  530. type GCPResourceInfo struct {
  531. ServiceDisplayName string `json:"serviceDisplayName"`
  532. ResourceFamily string `json:"resourceFamily"`
  533. ResourceGroup string `json:"resourceGroup"`
  534. UsageType string `json:"usageType"`
  535. }
  536. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]models.Key, pvKeys map[string]models.PVKey) (map[string]*GCPPricing, string, error) {
  537. gcpPricingList := make(map[string]*GCPPricing)
  538. var nextPageToken string
  539. dec := json.NewDecoder(r)
  540. for {
  541. t, err := dec.Token()
  542. if err == io.EOF {
  543. break
  544. } else if err != nil {
  545. return nil, "", fmt.Errorf("error parsing GCP pricing page: %s", err)
  546. }
  547. if t == "skus" {
  548. _, err := dec.Token() // consumes [
  549. if err != nil {
  550. return nil, "", err
  551. }
  552. for dec.More() {
  553. product := &GCPPricing{}
  554. err := dec.Decode(&product)
  555. if err != nil {
  556. return nil, "", err
  557. }
  558. usageType := strings.ToLower(product.Category.UsageType)
  559. instanceType := strings.ToLower(product.Category.ResourceGroup)
  560. if instanceType == "ssd" && strings.Contains(product.Description, "SSD backed") && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  561. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  562. var nanos float64
  563. if lastRateIndex > -1 && len(product.PricingInfo) > 0 {
  564. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  565. } else {
  566. continue
  567. }
  568. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  569. for _, sr := range product.ServiceRegions {
  570. region := sr
  571. candidateKey := region + "," + "ssd"
  572. if _, ok := pvKeys[candidateKey]; ok {
  573. product.PV = &models.PV{
  574. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  575. }
  576. gcpPricingList[candidateKey] = product
  577. continue
  578. }
  579. }
  580. continue
  581. } else if instanceType == "ssd" && strings.Contains(product.Description, "SSD backed") && strings.Contains(product.Description, "Regional") { // TODO: support regional
  582. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  583. var nanos float64
  584. if lastRateIndex > -1 && len(product.PricingInfo) > 0 {
  585. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  586. } else {
  587. continue
  588. }
  589. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  590. for _, sr := range product.ServiceRegions {
  591. region := sr
  592. candidateKey := region + "," + "ssd" + "," + "regional"
  593. if _, ok := pvKeys[candidateKey]; ok {
  594. product.PV = &models.PV{
  595. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  596. }
  597. gcpPricingList[candidateKey] = product
  598. continue
  599. }
  600. }
  601. continue
  602. } else if instanceType == "pdstandard" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  603. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  604. var nanos float64
  605. if lastRateIndex > -1 && len(product.PricingInfo) > 0 {
  606. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  607. } else {
  608. continue
  609. }
  610. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  611. for _, sr := range product.ServiceRegions {
  612. region := sr
  613. candidateKey := region + "," + "pdstandard"
  614. if _, ok := pvKeys[candidateKey]; ok {
  615. product.PV = &models.PV{
  616. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  617. }
  618. gcpPricingList[candidateKey] = product
  619. continue
  620. }
  621. }
  622. continue
  623. } else if instanceType == "pdstandard" && strings.Contains(product.Description, "Regional") { // TODO: support regional
  624. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  625. var nanos float64
  626. if lastRateIndex > -1 && len(product.PricingInfo) > 0 {
  627. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  628. } else {
  629. continue
  630. }
  631. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  632. for _, sr := range product.ServiceRegions {
  633. region := sr
  634. candidateKey := region + "," + "pdstandard" + "," + "regional"
  635. if _, ok := pvKeys[candidateKey]; ok {
  636. product.PV = &models.PV{
  637. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  638. }
  639. gcpPricingList[candidateKey] = product
  640. continue
  641. }
  642. }
  643. continue
  644. }
  645. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  646. instanceType = "custom"
  647. }
  648. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "N2") && !strings.Contains(strings.ToUpper(product.Description), "PREMIUM") {
  649. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "N2D AMD") {
  650. instanceType = "n2dstandard"
  651. } else {
  652. instanceType = "n2standard"
  653. }
  654. }
  655. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "A2 INSTANCE") {
  656. instanceType = "a2"
  657. }
  658. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "COMPUTE OPTIMIZED") {
  659. instanceType = "c2standard"
  660. }
  661. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "E2 INSTANCE") {
  662. instanceType = "e2"
  663. }
  664. partialCPUMap := make(map[string]float64)
  665. partialCPUMap["e2micro"] = 0.25
  666. partialCPUMap["e2small"] = 0.5
  667. partialCPUMap["e2medium"] = 1
  668. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "T2D AMD") {
  669. instanceType = "t2dstandard"
  670. }
  671. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "T2A ARM") {
  672. instanceType = "t2astandard"
  673. }
  674. var gpuType string
  675. for matchnum, group := range nvidiaGPURegex.FindStringSubmatch(product.Description) {
  676. if matchnum == 1 {
  677. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  678. log.Debugf("GCP Billing API: GPU type found: '%s'", gpuType)
  679. }
  680. }
  681. candidateKeys := []string{}
  682. if gcp.ValidPricingKeys == nil {
  683. gcp.ValidPricingKeys = make(map[string]bool)
  684. }
  685. for _, region := range product.ServiceRegions {
  686. switch instanceType {
  687. case "e2":
  688. candidateKeys = append(candidateKeys, region+","+"e2micro"+","+usageType)
  689. candidateKeys = append(candidateKeys, region+","+"e2small"+","+usageType)
  690. candidateKeys = append(candidateKeys, region+","+"e2medium"+","+usageType)
  691. candidateKeys = append(candidateKeys, region+","+"e2standard"+","+usageType)
  692. candidateKeys = append(candidateKeys, region+","+"e2custom"+","+usageType)
  693. case "a2":
  694. candidateKeys = append(candidateKeys, region+","+"a2highgpu"+","+usageType)
  695. candidateKeys = append(candidateKeys, region+","+"a2megagpu"+","+usageType)
  696. candidateKeys = append(candidateKeys, region+","+"a2ultragpu"+","+usageType)
  697. default:
  698. candidateKey := region + "," + instanceType + "," + usageType
  699. candidateKeys = append(candidateKeys, candidateKey)
  700. }
  701. }
  702. for _, candidateKey := range candidateKeys {
  703. instanceType = strings.Split(candidateKey, ",")[1] // we may have overridden this while generating candidate keys
  704. region := strings.Split(candidateKey, ",")[0]
  705. candidateKeyGPU := candidateKey + ",gpu"
  706. gcp.ValidPricingKeys[candidateKey] = true
  707. gcp.ValidPricingKeys[candidateKeyGPU] = true
  708. if gpuType != "" {
  709. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  710. var nanos float64
  711. var unitsBaseCurrency int
  712. if lastRateIndex > -1 && len(product.PricingInfo) > 0 {
  713. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  714. unitsBaseCurrency, err = strconv.Atoi(product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Units)
  715. if err != nil {
  716. return nil, "", fmt.Errorf("error parsing base unit price for gpu: %w", err)
  717. }
  718. } else {
  719. continue
  720. }
  721. // as per https://cloud.google.com/billing/v1/how-tos/catalog-api
  722. // the hourly price is the whole currency price + the fractional currency price
  723. hourlyPrice := (nanos * math.Pow10(-9)) + float64(unitsBaseCurrency)
  724. // GPUs with an hourly price of 0 are reserved versions of GPUs
  725. // (E.g., SKU "2013-37B4-22EA")
  726. // and are excluded from cost computations
  727. if hourlyPrice == 0 {
  728. log.Debugf("GCP Billing API: excluding reserved GPU SKU #%s", product.SKUID)
  729. continue
  730. }
  731. for k, key := range inputKeys {
  732. if key.GPUType() == gpuType+","+usageType {
  733. if region == strings.Split(k, ",")[0] {
  734. matchedKey := key.Features()
  735. log.Debugf("GCP Billing API: matched GPU to node: %s: %s", matchedKey, product.Description)
  736. if pl, ok := gcpPricingList[matchedKey]; ok {
  737. pl.Node.GPUName = gpuType
  738. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  739. pl.Node.GPU = "1"
  740. } else {
  741. product.Node = &models.Node{
  742. GPUName: gpuType,
  743. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  744. GPU: "1",
  745. }
  746. gcpPricingList[matchedKey] = product
  747. }
  748. }
  749. }
  750. }
  751. } else {
  752. _, ok := inputKeys[candidateKey]
  753. _, ok2 := inputKeys[candidateKeyGPU]
  754. if ok || ok2 {
  755. var nanos float64
  756. var unitsBaseCurrency int
  757. if len(product.PricingInfo) > 0 {
  758. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  759. if lastRateIndex >= 0 {
  760. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  761. unitsBaseCurrency, err = strconv.Atoi(product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Units)
  762. if err != nil {
  763. return nil, "", fmt.Errorf("error parsing base unit price for instance: %w", err)
  764. }
  765. } else {
  766. continue
  767. }
  768. } else {
  769. continue
  770. }
  771. // as per https://cloud.google.com/billing/v1/how-tos/catalog-api
  772. // the hourly price is the whole currency price + the fractional currency price
  773. hourlyPrice := (nanos * math.Pow10(-9)) + float64(unitsBaseCurrency)
  774. if hourlyPrice == 0 {
  775. continue
  776. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  777. if instanceType == "custom" {
  778. log.Debugf("GCP Billing API: RAM custom sku '%s'", product.Name)
  779. }
  780. if _, ok := gcpPricingList[candidateKey]; ok {
  781. log.Debugf("GCP Billing API: key '%s': RAM price: %f", candidateKey, hourlyPrice)
  782. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  783. } else {
  784. log.Debugf("GCP Billing API: key '%s': RAM price: %f", candidateKey, hourlyPrice)
  785. pricing := &GCPPricing{}
  786. pricing.Node = &models.Node{
  787. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  788. }
  789. partialCPU, pcok := partialCPUMap[instanceType]
  790. if pcok {
  791. pricing.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  792. }
  793. pricing.Node.UsageType = usageType
  794. gcpPricingList[candidateKey] = pricing
  795. }
  796. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  797. log.Debugf("GCP Billing API: key '%s': RAM price: %f", candidateKeyGPU, hourlyPrice)
  798. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  799. } else {
  800. log.Debugf("GCP Billing API: key '%s': RAM price: %f", candidateKeyGPU, hourlyPrice)
  801. pricing := &GCPPricing{}
  802. pricing.Node = &models.Node{
  803. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  804. }
  805. partialCPU, pcok := partialCPUMap[instanceType]
  806. if pcok {
  807. pricing.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  808. }
  809. pricing.Node.UsageType = usageType
  810. gcpPricingList[candidateKeyGPU] = pricing
  811. }
  812. } else {
  813. if _, ok := gcpPricingList[candidateKey]; ok {
  814. log.Debugf("GCP Billing API: key '%s': CPU price: %f", candidateKey, hourlyPrice)
  815. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  816. } else {
  817. log.Debugf("GCP Billing API: key '%s': CPU price: %f", candidateKey, hourlyPrice)
  818. pricing := &GCPPricing{}
  819. pricing.Node = &models.Node{
  820. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  821. }
  822. partialCPU, pcok := partialCPUMap[instanceType]
  823. if pcok {
  824. pricing.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  825. }
  826. pricing.Node.UsageType = usageType
  827. gcpPricingList[candidateKey] = pricing
  828. }
  829. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  830. log.Debugf("GCP Billing API: key '%s': CPU price: %f", candidateKeyGPU, hourlyPrice)
  831. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  832. } else {
  833. log.Debugf("GCP Billing API: key '%s': CPU price: %f", candidateKeyGPU, hourlyPrice)
  834. pricing := &GCPPricing{}
  835. pricing.Node = &models.Node{
  836. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  837. }
  838. partialCPU, pcok := partialCPUMap[instanceType]
  839. if pcok {
  840. pricing.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  841. }
  842. pricing.Node.UsageType = usageType
  843. gcpPricingList[candidateKeyGPU] = pricing
  844. }
  845. }
  846. }
  847. }
  848. }
  849. }
  850. }
  851. if t == "nextPageToken" {
  852. pageToken, err := dec.Token()
  853. if err != nil {
  854. log.Errorf("Error parsing nextpage token: " + err.Error())
  855. return nil, "", err
  856. }
  857. if pageToken.(string) != "" {
  858. nextPageToken = pageToken.(string)
  859. } else {
  860. nextPageToken = "done"
  861. }
  862. }
  863. }
  864. return gcpPricingList, nextPageToken, nil
  865. }
  866. func (gcp *GCP) getBillingAPIURL(apiKey, currencyCode string) string {
  867. return fmt.Sprintf(BillingAPIURLFmt, apiKey, currencyCode)
  868. }
  869. func (gcp *GCP) parsePages(inputKeys map[string]models.Key, pvKeys map[string]models.PVKey) (map[string]*GCPPricing, error) {
  870. var pages []map[string]*GCPPricing
  871. c, err := gcp.GetConfig()
  872. if err != nil {
  873. return nil, err
  874. }
  875. url := gcp.getBillingAPIURL(gcp.APIKey, c.CurrencyCode)
  876. log.Infof("Fetch GCP Billing Data from URL: %s", url)
  877. var parsePagesHelper func(string) error
  878. parsePagesHelper = func(pageToken string) error {
  879. if pageToken == "done" {
  880. return nil
  881. } else if pageToken != "" {
  882. url = url + "&pageToken=" + pageToken
  883. }
  884. resp, err := http.Get(url)
  885. if err != nil {
  886. return err
  887. }
  888. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  889. if err != nil {
  890. return err
  891. }
  892. pages = append(pages, page)
  893. return parsePagesHelper(token)
  894. }
  895. err = parsePagesHelper("")
  896. if err != nil {
  897. return nil, err
  898. }
  899. returnPages := make(map[string]*GCPPricing)
  900. for _, page := range pages {
  901. for k, v := range page {
  902. if val, ok := returnPages[k]; ok { //keys may need to be merged
  903. if val.Node != nil {
  904. if val.Node.VCPUCost == "" {
  905. val.Node.VCPUCost = v.Node.VCPUCost
  906. }
  907. if val.Node.RAMCost == "" {
  908. val.Node.RAMCost = v.Node.RAMCost
  909. }
  910. if val.Node.GPUCost == "" {
  911. val.Node.GPUCost = v.Node.GPUCost
  912. val.Node.GPU = v.Node.GPU
  913. val.Node.GPUName = v.Node.GPUName
  914. }
  915. }
  916. if val.PV != nil {
  917. if val.PV.Cost == "" {
  918. val.PV.Cost = v.PV.Cost
  919. }
  920. }
  921. } else {
  922. returnPages[k] = v
  923. }
  924. }
  925. }
  926. log.Debugf("ALL PAGES: %+v", returnPages)
  927. for k, v := range returnPages {
  928. if v.Node != nil {
  929. log.Debugf("Returned Page: %s : %+v", k, v.Node)
  930. }
  931. if v.PV != nil {
  932. log.Debugf("Returned Page: %s : %+v", k, v.PV)
  933. }
  934. }
  935. return returnPages, err
  936. }
  937. // 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.
  938. func (gcp *GCP) DownloadPricingData() error {
  939. gcp.DownloadPricingDataLock.Lock()
  940. defer gcp.DownloadPricingDataLock.Unlock()
  941. c, err := gcp.Config.GetCustomPricingData()
  942. if err != nil {
  943. log.Errorf("Error downloading default pricing data: %s", err.Error())
  944. return err
  945. }
  946. gcp.loadGCPAuthSecret()
  947. gcp.BaseCPUPrice = c.CPU
  948. gcp.ProjectID = c.ProjectID
  949. gcp.BillingDataDataset = c.BillingDataDataset
  950. nodeList := gcp.Clientset.GetAllNodes()
  951. inputkeys := make(map[string]models.Key)
  952. defaultRegion := "" // Sometimes, PVs may be missing the region label. In that case assume that they are in the same region as the nodes
  953. for _, n := range nodeList {
  954. labels := n.GetObjectMeta().GetLabels()
  955. 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
  956. gcp.clusterManagementPrice = 0.10
  957. gcp.clusterProvisioner = "GKE"
  958. }
  959. r, _ := util.GetRegion(labels)
  960. if r != "" {
  961. defaultRegion = r
  962. }
  963. key := gcp.GetKey(labels, n)
  964. inputkeys[key.Features()] = key
  965. }
  966. pvList := gcp.Clientset.GetAllPersistentVolumes()
  967. storageClasses := gcp.Clientset.GetAllStorageClasses()
  968. storageClassMap := make(map[string]map[string]string)
  969. for _, storageClass := range storageClasses {
  970. params := storageClass.Parameters
  971. storageClassMap[storageClass.ObjectMeta.Name] = params
  972. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  973. storageClassMap["default"] = params
  974. storageClassMap[""] = params
  975. }
  976. }
  977. pvkeys := make(map[string]models.PVKey)
  978. for _, pv := range pvList {
  979. params, ok := storageClassMap[pv.Spec.StorageClassName]
  980. if !ok {
  981. log.DedupedWarningf(5, "Unable to find params for storageClassName %s", pv.Name)
  982. continue
  983. }
  984. key := gcp.GetPVKey(pv, params, defaultRegion)
  985. pvkeys[key.Features()] = key
  986. }
  987. reserved, err := gcp.getReservedInstances()
  988. if err != nil {
  989. log.Errorf("Failed to lookup reserved instance data: %s", err.Error())
  990. } else {
  991. gcp.ReservedInstances = reserved
  992. if zerolog.GlobalLevel() <= zerolog.DebugLevel {
  993. log.Debugf("Found %d reserved instances", len(reserved))
  994. for _, r := range reserved {
  995. log.Debugf("%s", r)
  996. }
  997. }
  998. }
  999. pages, err := gcp.parsePages(inputkeys, pvkeys)
  1000. if err != nil {
  1001. return err
  1002. }
  1003. gcp.Pricing = pages
  1004. return nil
  1005. }
  1006. func (gcp *GCP) PVPricing(pvk models.PVKey) (*models.PV, error) {
  1007. gcp.DownloadPricingDataLock.RLock()
  1008. defer gcp.DownloadPricingDataLock.RUnlock()
  1009. pricing, ok := gcp.Pricing[pvk.Features()]
  1010. if !ok {
  1011. log.Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  1012. return &models.PV{}, nil
  1013. }
  1014. return pricing.PV, nil
  1015. }
  1016. // Stubbed NetworkPricing for GCP. Pull directly from gcp.json for now
  1017. func (gcp *GCP) NetworkPricing() (*models.Network, error) {
  1018. cpricing, err := gcp.Config.GetCustomPricingData()
  1019. if err != nil {
  1020. return nil, err
  1021. }
  1022. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  1023. if err != nil {
  1024. return nil, err
  1025. }
  1026. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  1027. if err != nil {
  1028. return nil, err
  1029. }
  1030. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  1031. if err != nil {
  1032. return nil, err
  1033. }
  1034. return &models.Network{
  1035. ZoneNetworkEgressCost: znec,
  1036. RegionNetworkEgressCost: rnec,
  1037. InternetNetworkEgressCost: inec,
  1038. }, nil
  1039. }
  1040. func (gcp *GCP) LoadBalancerPricing() (*models.LoadBalancer, error) {
  1041. fffrc := 0.025
  1042. afrc := 0.010
  1043. lbidc := 0.008
  1044. numForwardingRules := 1.0
  1045. dataIngressGB := 0.0
  1046. var totalCost float64
  1047. if numForwardingRules < 5 {
  1048. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  1049. } else {
  1050. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  1051. }
  1052. return &models.LoadBalancer{
  1053. Cost: totalCost,
  1054. }, nil
  1055. }
  1056. const (
  1057. GCPReservedInstanceResourceTypeRAM string = "MEMORY"
  1058. GCPReservedInstanceResourceTypeCPU string = "VCPU"
  1059. GCPReservedInstanceStatusActive string = "ACTIVE"
  1060. GCPReservedInstancePlanOneYear string = "TWELVE_MONTH"
  1061. GCPReservedInstancePlanThreeYear string = "THIRTY_SIX_MONTH"
  1062. )
  1063. type GCPReservedInstancePlan struct {
  1064. Name string
  1065. CPUCost float64
  1066. RAMCost float64
  1067. }
  1068. type GCPReservedInstance struct {
  1069. ReservedRAM int64
  1070. ReservedCPU int64
  1071. Plan *GCPReservedInstancePlan
  1072. StartDate time.Time
  1073. EndDate time.Time
  1074. Region string
  1075. }
  1076. func (r *GCPReservedInstance) String() string {
  1077. 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())
  1078. }
  1079. type GCPReservedCounter struct {
  1080. RemainingCPU int64
  1081. RemainingRAM int64
  1082. Instance *GCPReservedInstance
  1083. }
  1084. func newReservedCounter(instance *GCPReservedInstance) *GCPReservedCounter {
  1085. return &GCPReservedCounter{
  1086. RemainingCPU: instance.ReservedCPU,
  1087. RemainingRAM: instance.ReservedRAM,
  1088. Instance: instance,
  1089. }
  1090. }
  1091. // Two available Reservation plans for GCP, 1-year and 3-year
  1092. var gcpReservedInstancePlans map[string]*GCPReservedInstancePlan = map[string]*GCPReservedInstancePlan{
  1093. GCPReservedInstancePlanOneYear: {
  1094. Name: GCPReservedInstancePlanOneYear,
  1095. CPUCost: 0.019915,
  1096. RAMCost: 0.002669,
  1097. },
  1098. GCPReservedInstancePlanThreeYear: {
  1099. Name: GCPReservedInstancePlanThreeYear,
  1100. CPUCost: 0.014225,
  1101. RAMCost: 0.001907,
  1102. },
  1103. }
  1104. func (gcp *GCP) ApplyReservedInstancePricing(nodes map[string]*models.Node) {
  1105. numReserved := len(gcp.ReservedInstances)
  1106. // Early return if no reserved instance data loaded
  1107. if numReserved == 0 {
  1108. log.Debug("[Reserved] No Reserved Instances")
  1109. return
  1110. }
  1111. now := time.Now()
  1112. counters := make(map[string][]*GCPReservedCounter)
  1113. for _, r := range gcp.ReservedInstances {
  1114. if now.Before(r.StartDate) || now.After(r.EndDate) {
  1115. log.Infof("[Reserved] Skipped Reserved Instance due to dates")
  1116. continue
  1117. }
  1118. _, ok := counters[r.Region]
  1119. counter := newReservedCounter(r)
  1120. if !ok {
  1121. counters[r.Region] = []*GCPReservedCounter{counter}
  1122. } else {
  1123. counters[r.Region] = append(counters[r.Region], counter)
  1124. }
  1125. }
  1126. gcpNodes := make(map[string]*v1.Node)
  1127. currentNodes := gcp.Clientset.GetAllNodes()
  1128. // Create a node name -> node map
  1129. for _, gcpNode := range currentNodes {
  1130. gcpNodes[gcpNode.GetName()] = gcpNode
  1131. }
  1132. // go through all provider nodes using k8s nodes for region
  1133. for nodeName, node := range nodes {
  1134. // Reset reserved allocation to prevent double allocation
  1135. node.Reserved = nil
  1136. kNode, ok := gcpNodes[nodeName]
  1137. if !ok {
  1138. log.Debugf("[Reserved] Could not find K8s Node with name: %s", nodeName)
  1139. continue
  1140. }
  1141. nodeRegion, ok := util.GetRegion(kNode.Labels)
  1142. if !ok {
  1143. log.Debug("[Reserved] Could not find node region")
  1144. continue
  1145. }
  1146. reservedCounters, ok := counters[nodeRegion]
  1147. if !ok {
  1148. log.Debugf("[Reserved] Could not find counters for region: %s", nodeRegion)
  1149. continue
  1150. }
  1151. node.Reserved = &models.ReservedInstanceData{
  1152. ReservedCPU: 0,
  1153. ReservedRAM: 0,
  1154. }
  1155. for _, reservedCounter := range reservedCounters {
  1156. if reservedCounter.RemainingCPU != 0 {
  1157. nodeCPU, _ := strconv.ParseInt(node.VCPU, 10, 64)
  1158. nodeCPU -= node.Reserved.ReservedCPU
  1159. node.Reserved.CPUCost = reservedCounter.Instance.Plan.CPUCost
  1160. if reservedCounter.RemainingCPU >= nodeCPU {
  1161. reservedCounter.RemainingCPU -= nodeCPU
  1162. node.Reserved.ReservedCPU += nodeCPU
  1163. } else {
  1164. node.Reserved.ReservedCPU += reservedCounter.RemainingCPU
  1165. reservedCounter.RemainingCPU = 0
  1166. }
  1167. }
  1168. if reservedCounter.RemainingRAM != 0 {
  1169. nodeRAMF, _ := strconv.ParseFloat(node.RAMBytes, 64)
  1170. nodeRAM := int64(nodeRAMF)
  1171. nodeRAM -= node.Reserved.ReservedRAM
  1172. node.Reserved.RAMCost = reservedCounter.Instance.Plan.RAMCost
  1173. if reservedCounter.RemainingRAM >= nodeRAM {
  1174. reservedCounter.RemainingRAM -= nodeRAM
  1175. node.Reserved.ReservedRAM += nodeRAM
  1176. } else {
  1177. node.Reserved.ReservedRAM += reservedCounter.RemainingRAM
  1178. reservedCounter.RemainingRAM = 0
  1179. }
  1180. }
  1181. }
  1182. }
  1183. }
  1184. func (gcp *GCP) getReservedInstances() ([]*GCPReservedInstance, error) {
  1185. var results []*GCPReservedInstance
  1186. ctx := context.Background()
  1187. computeService, err := compute.NewService(ctx)
  1188. if err != nil {
  1189. return nil, err
  1190. }
  1191. commitments, err := computeService.RegionCommitments.AggregatedList(gcp.ProjectID).Do()
  1192. if err != nil {
  1193. return nil, err
  1194. }
  1195. for regionKey, commitList := range commitments.Items {
  1196. for _, commit := range commitList.Commitments {
  1197. if commit.Status != GCPReservedInstanceStatusActive {
  1198. continue
  1199. }
  1200. var vcpu int64 = 0
  1201. var ram int64 = 0
  1202. for _, resource := range commit.Resources {
  1203. switch resource.Type {
  1204. case GCPReservedInstanceResourceTypeRAM:
  1205. ram = resource.Amount * 1024 * 1024
  1206. case GCPReservedInstanceResourceTypeCPU:
  1207. vcpu = resource.Amount
  1208. default:
  1209. log.Debugf("Failed to handle resource type: %s", resource.Type)
  1210. }
  1211. }
  1212. var region string
  1213. regionStr := strings.Split(regionKey, "/")
  1214. if len(regionStr) == 2 {
  1215. region = regionStr[1]
  1216. }
  1217. timeLayout := "2006-01-02T15:04:05Z07:00"
  1218. startTime, err := time.Parse(timeLayout, commit.StartTimestamp)
  1219. if err != nil {
  1220. log.Warnf("Failed to parse start date: %s", commit.StartTimestamp)
  1221. continue
  1222. }
  1223. endTime, err := time.Parse(timeLayout, commit.EndTimestamp)
  1224. if err != nil {
  1225. log.Warnf("Failed to parse end date: %s", commit.EndTimestamp)
  1226. continue
  1227. }
  1228. // Look for a plan based on the name. Default to One Year if it fails
  1229. plan, ok := gcpReservedInstancePlans[commit.Plan]
  1230. if !ok {
  1231. plan = gcpReservedInstancePlans[GCPReservedInstancePlanOneYear]
  1232. }
  1233. results = append(results, &GCPReservedInstance{
  1234. Region: region,
  1235. ReservedRAM: ram,
  1236. ReservedCPU: vcpu,
  1237. Plan: plan,
  1238. StartDate: startTime,
  1239. EndDate: endTime,
  1240. })
  1241. }
  1242. }
  1243. return results, nil
  1244. }
  1245. type pvKey struct {
  1246. ProviderID string
  1247. Labels map[string]string
  1248. StorageClass string
  1249. StorageClassParameters map[string]string
  1250. DefaultRegion string
  1251. }
  1252. func (key *pvKey) ID() string {
  1253. return key.ProviderID
  1254. }
  1255. func (key *pvKey) GetStorageClass() string {
  1256. return key.StorageClass
  1257. }
  1258. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  1259. providerID := ""
  1260. if pv.Spec.GCEPersistentDisk != nil {
  1261. providerID = pv.Spec.GCEPersistentDisk.PDName
  1262. }
  1263. return &pvKey{
  1264. ProviderID: providerID,
  1265. Labels: pv.Labels,
  1266. StorageClass: pv.Spec.StorageClassName,
  1267. StorageClassParameters: parameters,
  1268. DefaultRegion: defaultRegion,
  1269. }
  1270. }
  1271. func (key *pvKey) Features() string {
  1272. // TODO: regional cluster pricing.
  1273. storageClass := key.StorageClassParameters["type"]
  1274. if storageClass == "pd-ssd" {
  1275. storageClass = "ssd"
  1276. } else if storageClass == "pd-standard" {
  1277. storageClass = "pdstandard"
  1278. }
  1279. replicationType := ""
  1280. if rt, ok := key.StorageClassParameters["replication-type"]; ok {
  1281. if rt == "regional-pd" {
  1282. replicationType = ",regional"
  1283. }
  1284. }
  1285. region, _ := util.GetRegion(key.Labels)
  1286. if region == "" {
  1287. region = key.DefaultRegion
  1288. }
  1289. return region + "," + storageClass + replicationType
  1290. }
  1291. type gcpKey struct {
  1292. Labels map[string]string
  1293. }
  1294. func (gcp *GCP) GetKey(labels map[string]string, n *v1.Node) models.Key {
  1295. return &gcpKey{
  1296. Labels: labels,
  1297. }
  1298. }
  1299. func (gcp *gcpKey) ID() string {
  1300. return ""
  1301. }
  1302. func (k *gcpKey) GPUCount() int {
  1303. return 0
  1304. }
  1305. func (gcp *gcpKey) GPUType() string {
  1306. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1307. usageType := getUsageType(gcp.Labels)
  1308. log.Debugf("GPU of type: \"%s\" found", t)
  1309. return t + "," + usageType
  1310. }
  1311. return ""
  1312. }
  1313. func parseGCPInstanceTypeLabel(it string) string {
  1314. var instanceType string
  1315. splitByDash := strings.Split(it, "-")
  1316. // GKE nodes are labeled with the GCP instance type, but users can deploy on GCP
  1317. // with tools like K3s, whose instance type labels will be "k3s". This logic
  1318. // avoids a panic in the slice operation then there are no dashes (-) in the
  1319. // instance type label value.
  1320. if len(splitByDash) < 2 {
  1321. instanceType = "unknown"
  1322. } else {
  1323. instanceType = strings.ToLower(strings.Join(splitByDash[:2], ""))
  1324. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  1325. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  1326. } else if instanceType == "n2highmem" || instanceType == "n2highcpu" {
  1327. instanceType = "n2standard"
  1328. } else if instanceType == "e2highmem" || instanceType == "e2highcpu" {
  1329. instanceType = "e2standard"
  1330. } else if instanceType == "n2dhighmem" || instanceType == "n2dhighcpu" {
  1331. instanceType = "n2dstandard"
  1332. } else if strings.HasPrefix(instanceType, "custom") {
  1333. instanceType = "custom" // The suffix of custom does not matter
  1334. }
  1335. }
  1336. return instanceType
  1337. }
  1338. // GetKey maps node labels to information needed to retrieve pricing data
  1339. func (gcp *gcpKey) Features() string {
  1340. var instanceType string
  1341. it, _ := util.GetInstanceType(gcp.Labels)
  1342. if it == "" {
  1343. log.DedupedErrorf(1, "Missing or Unknown 'node.kubernetes.io/instance-type' node label")
  1344. instanceType = "unknown"
  1345. } else {
  1346. instanceType = parseGCPInstanceTypeLabel(it)
  1347. }
  1348. r, _ := util.GetRegion(gcp.Labels)
  1349. region := strings.ToLower(r)
  1350. usageType := getUsageType(gcp.Labels)
  1351. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  1352. return region + "," + instanceType + "," + usageType + "," + "gpu"
  1353. }
  1354. return region + "," + instanceType + "," + usageType
  1355. }
  1356. // AllNodePricing returns the GCP pricing objects stored
  1357. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  1358. gcp.DownloadPricingDataLock.RLock()
  1359. defer gcp.DownloadPricingDataLock.RUnlock()
  1360. return gcp.Pricing, nil
  1361. }
  1362. func (gcp *GCP) getPricing(key models.Key) (*GCPPricing, bool) {
  1363. gcp.DownloadPricingDataLock.RLock()
  1364. defer gcp.DownloadPricingDataLock.RUnlock()
  1365. n, ok := gcp.Pricing[key.Features()]
  1366. return n, ok
  1367. }
  1368. func (gcp *GCP) isValidPricingKey(key models.Key) bool {
  1369. gcp.DownloadPricingDataLock.RLock()
  1370. defer gcp.DownloadPricingDataLock.RUnlock()
  1371. _, ok := gcp.ValidPricingKeys[key.Features()]
  1372. return ok
  1373. }
  1374. // NodePricing returns GCP pricing data for a single node
  1375. func (gcp *GCP) NodePricing(key models.Key) (*models.Node, models.PricingMetadata, error) {
  1376. meta := models.PricingMetadata{}
  1377. c, err := gcp.Config.GetCustomPricingData()
  1378. if err != nil {
  1379. meta.Warnings = append(meta.Warnings, fmt.Sprintf("failed to detect currency: %s", err))
  1380. } else {
  1381. meta.Currency = c.CurrencyCode
  1382. }
  1383. if n, ok := gcp.getPricing(key); ok {
  1384. log.Debugf("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  1385. // Add pricing URL, but redact the key (hence, "***"")
  1386. meta.Source = fmt.Sprintf("Downloaded pricing from %s", gcp.getBillingAPIURL("***", c.CurrencyCode))
  1387. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  1388. return n.Node, meta, nil
  1389. } else if ok := gcp.isValidPricingKey(key); ok {
  1390. meta.Warnings = append(meta.Warnings, fmt.Sprintf("No pricing found, but key is valid: %s", key.Features()))
  1391. err := gcp.DownloadPricingData()
  1392. if err != nil {
  1393. log.Warnf("no pricing data found for %s", key.Features())
  1394. meta.Warnings = append(meta.Warnings, "Failed to download pricing data")
  1395. return nil, meta, fmt.Errorf("failed to download pricing data: %w", err)
  1396. }
  1397. if n, ok := gcp.getPricing(key); ok {
  1398. log.Debugf("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  1399. // Add pricing URL, but redact the key (hence, "***"")
  1400. meta.Source = fmt.Sprintf("Downloaded pricing from %s", gcp.getBillingAPIURL("***", c.CurrencyCode))
  1401. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  1402. return n.Node, meta, nil
  1403. }
  1404. log.Warnf("no pricing data found for %s", key.Features())
  1405. meta.Warnings = append(meta.Warnings, "Failed to find pricing after downloading data, but key is valid")
  1406. return nil, meta, fmt.Errorf("failed to find pricing data: %s", key.Features())
  1407. }
  1408. meta.Warnings = append(meta.Warnings, fmt.Sprintf("No pricing found, and key is not valid: %s", key.Features()))
  1409. return nil, meta, fmt.Errorf("no pricing data found for %s", key.Features())
  1410. }
  1411. func (gcp *GCP) ServiceAccountStatus() *models.ServiceAccountStatus {
  1412. return &models.ServiceAccountStatus{
  1413. Checks: []*models.ServiceAccountCheck{},
  1414. }
  1415. }
  1416. func (gcp *GCP) PricingSourceStatus() map[string]*models.PricingSource {
  1417. return make(map[string]*models.PricingSource)
  1418. }
  1419. func (gcp *GCP) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1420. class := strings.Split(instanceType, "-")[0]
  1421. return 1.0 - ((1.0 - sustainedUseDiscount(class, defaultDiscount, isPreemptible)) * (1.0 - negotiatedDiscount))
  1422. }
  1423. func (gcp *GCP) Regions() []string {
  1424. regionOverrides := env.GetRegionOverrideList()
  1425. if len(regionOverrides) > 0 {
  1426. log.Debugf("Overriding GCP regions with configured region list: %+v", regionOverrides)
  1427. return regionOverrides
  1428. }
  1429. return gcpRegions
  1430. }
  1431. func sustainedUseDiscount(class string, defaultDiscount float64, isPreemptible bool) float64 {
  1432. if isPreemptible {
  1433. return 0.0
  1434. }
  1435. discount := defaultDiscount
  1436. switch class {
  1437. case "e2", "f1", "g1":
  1438. discount = 0.0
  1439. case "n2", "n2d":
  1440. discount = 0.2
  1441. }
  1442. return discount
  1443. }
  1444. func ParseGCPProjectID(id string) string {
  1445. // gce://guestbook-12345/...
  1446. // => guestbook-12345
  1447. match := gceRegex.FindStringSubmatch(id)
  1448. if len(match) >= 2 {
  1449. return match[1]
  1450. }
  1451. // Return empty string if an account could not be parsed from provided string
  1452. return ""
  1453. }
  1454. func getUsageType(labels map[string]string) string {
  1455. if t, ok := labels[GKEPreemptibleLabel]; ok && t == "true" {
  1456. return "preemptible"
  1457. } else if t, ok := labels[GKESpotLabel]; ok && t == "true" {
  1458. // https://cloud.google.com/kubernetes-engine/docs/concepts/spot-vms
  1459. return "preemptible"
  1460. } else if t, ok := labels[models.KarpenterCapacityTypeLabel]; ok && t == models.KarpenterCapacitySpotTypeValue {
  1461. return "preemptible"
  1462. }
  1463. return "ondemand"
  1464. }
  1465. // PricingSourceSummary returns the pricing source summary for the provider.
  1466. // The summary represents what was _parsed_ from the pricing source, not
  1467. // everything that was _available_ in the pricing source.
  1468. func (gcp *GCP) PricingSourceSummary() interface{} {
  1469. return gcp.Pricing
  1470. }