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. "europe-west9",
  67. "northamerica-northeast1",
  68. "northamerica-northeast2",
  69. "southamerica-east1",
  70. "us-central1",
  71. "us-east1",
  72. "us-east4",
  73. "us-west1",
  74. "us-west2",
  75. "us-west3",
  76. "us-west4",
  77. }
  78. var (
  79. nvidiaGPURegex = regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  80. // gce://guestbook-12345/...
  81. // => guestbook-12345
  82. gceRegex = regexp.MustCompile("gce://([^/]*)/*")
  83. )
  84. // GCP implements a provider interface for GCP
  85. type GCP struct {
  86. Pricing map[string]*GCPPricing
  87. Clientset clustercache.ClusterCache
  88. APIKey string
  89. BaseCPUPrice string
  90. ProjectID string
  91. BillingDataDataset string
  92. DownloadPricingDataLock sync.RWMutex
  93. ReservedInstances []*GCPReservedInstance
  94. Config models.ProviderConfig
  95. ServiceKeyProvided bool
  96. ValidPricingKeys map[string]bool
  97. MetadataClient *metadata.Client
  98. clusterManagementPrice float64
  99. ClusterRegion string
  100. ClusterAccountID string
  101. ClusterProjectID string
  102. clusterProvisioner string
  103. }
  104. type gcpAllocation struct {
  105. Aggregator bigquery.NullString
  106. Environment bigquery.NullString
  107. Service string
  108. Cost float64
  109. }
  110. type multiKeyGCPAllocation struct {
  111. Keys bigquery.NullString
  112. Service string
  113. Cost float64
  114. }
  115. // GetLocalStorageQuery returns the cost of local storage for the given window. Setting rate=true
  116. // returns hourly spend. Setting used=true only tracks used storage, not total.
  117. func (gcp *GCP) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  118. // TODO Set to the price for the appropriate storage class. It's not trivial to determine the local storage disk type
  119. // See https://cloud.google.com/compute/disks-image-pricing#persistentdisk
  120. localStorageCost := 0.04
  121. baseMetric := "container_fs_limit_bytes"
  122. if used {
  123. baseMetric = "container_fs_usage_bytes"
  124. }
  125. fmtOffset := timeutil.DurationToPromOffsetString(offset)
  126. fmtCumulativeQuery := `sum(
  127. sum_over_time(%s{device!="tmpfs", id="/", %s}[%s:1m]%s)
  128. ) by (%s) / 60 / 730 / 1024 / 1024 / 1024 * %f`
  129. fmtMonthlyQuery := `sum(
  130. avg_over_time(%s{device!="tmpfs", id="/", %s}[%s:1m]%s)
  131. ) by (%s) / 1024 / 1024 / 1024 * %f`
  132. fmtQuery := fmtCumulativeQuery
  133. if rate {
  134. fmtQuery = fmtMonthlyQuery
  135. }
  136. fmtWindow := timeutil.DurationString(window)
  137. return fmt.Sprintf(fmtQuery, baseMetric, env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), localStorageCost)
  138. }
  139. func (gcp *GCP) GetConfig() (*models.CustomPricing, error) {
  140. c, err := gcp.Config.GetCustomPricingData()
  141. if err != nil {
  142. return nil, err
  143. }
  144. if c.Discount == "" {
  145. c.Discount = "30%"
  146. }
  147. if c.NegotiatedDiscount == "" {
  148. c.NegotiatedDiscount = "0%"
  149. }
  150. if c.CurrencyCode == "" {
  151. c.CurrencyCode = "USD"
  152. }
  153. if c.ShareTenancyCosts == "" {
  154. c.ShareTenancyCosts = models.DefaultShareTenancyCost
  155. }
  156. return c, nil
  157. }
  158. // BigQueryConfig contain the required config and credentials to access OOC resources for GCP
  159. // Deprecated: v1.104 Use BigQueryConfiguration instead
  160. type BigQueryConfig struct {
  161. ProjectID string `json:"projectID"`
  162. BillingDataDataset string `json:"billingDataDataset"`
  163. Key map[string]string `json:"key"`
  164. }
  165. // IsEmpty returns true if all fields in config are empty, false if not.
  166. func (bqc *BigQueryConfig) IsEmpty() bool {
  167. return bqc.ProjectID == "" &&
  168. bqc.BillingDataDataset == "" &&
  169. (bqc.Key == nil || len(bqc.Key) == 0)
  170. }
  171. func (gcp *GCP) GetManagementPlatform() (string, error) {
  172. nodes := gcp.Clientset.GetAllNodes()
  173. if len(nodes) > 0 {
  174. n := nodes[0]
  175. version := n.Status.NodeInfo.KubeletVersion
  176. if strings.Contains(version, "gke") {
  177. return "gke", nil
  178. }
  179. }
  180. return "", nil
  181. }
  182. // Attempts to load a GCP auth secret and copy the contents to the key file.
  183. func (*GCP) loadGCPAuthSecret() {
  184. path := env.GetConfigPathWithDefault("/models/")
  185. keyPath := path + "key.json"
  186. keyExists, _ := fileutil.FileExists(keyPath)
  187. if keyExists {
  188. log.Info("GCP Auth Key already exists, no need to load from secret")
  189. return
  190. }
  191. exists, err := fileutil.FileExists(models.AuthSecretPath)
  192. if !exists || err != nil {
  193. errMessage := "Secret does not exist"
  194. if err != nil {
  195. errMessage = err.Error()
  196. }
  197. log.Warnf("Failed to load auth secret, or was not mounted: %s", errMessage)
  198. return
  199. }
  200. result, err := os.ReadFile(models.AuthSecretPath)
  201. if err != nil {
  202. log.Warnf("Failed to load auth secret, or was not mounted: %s", err.Error())
  203. return
  204. }
  205. err = os.WriteFile(keyPath, result, 0644)
  206. if err != nil {
  207. log.Warnf("Failed to copy auth secret to %s: %s", keyPath, err.Error())
  208. }
  209. }
  210. func (gcp *GCP) UpdateConfigFromConfigMap(a map[string]string) (*models.CustomPricing, error) {
  211. return gcp.Config.UpdateFromMap(a)
  212. }
  213. func (gcp *GCP) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  214. return gcp.Config.Update(func(c *models.CustomPricing) error {
  215. if updateType == BigqueryUpdateType {
  216. a := BigQueryConfig{}
  217. err := json.NewDecoder(r).Decode(&a)
  218. if err != nil {
  219. return err
  220. }
  221. c.ProjectID = a.ProjectID
  222. c.BillingDataDataset = a.BillingDataDataset
  223. if len(a.Key) > 0 {
  224. j, err := json.Marshal(a.Key)
  225. if err != nil {
  226. return err
  227. }
  228. path := env.GetConfigPathWithDefault("/models/")
  229. keyPath := path + "key.json"
  230. err = os.WriteFile(keyPath, j, 0644)
  231. if err != nil {
  232. return err
  233. }
  234. gcp.ServiceKeyProvided = true
  235. }
  236. } else if updateType == aws.AthenaInfoUpdateType {
  237. a := aws.AwsAthenaInfo{}
  238. err := json.NewDecoder(r).Decode(&a)
  239. if err != nil {
  240. return err
  241. }
  242. c.AthenaBucketName = a.AthenaBucketName
  243. c.AthenaRegion = a.AthenaRegion
  244. c.AthenaDatabase = a.AthenaDatabase
  245. c.AthenaCatalog = a.AthenaCatalog
  246. c.AthenaTable = a.AthenaTable
  247. c.AthenaWorkgroup = a.AthenaWorkgroup
  248. c.ServiceKeyName = a.ServiceKeyName
  249. c.ServiceKeySecret = a.ServiceKeySecret
  250. c.AthenaProjectID = a.AccountID
  251. } else {
  252. a := make(map[string]interface{})
  253. err := json.NewDecoder(r).Decode(&a)
  254. if err != nil {
  255. return err
  256. }
  257. for k, v := range a {
  258. kUpper := utils.ToTitle.String(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  259. vstr, ok := v.(string)
  260. if ok {
  261. err := models.SetCustomPricingField(c, kUpper, vstr)
  262. if err != nil {
  263. return err
  264. }
  265. } else {
  266. return fmt.Errorf("type error while updating config for %s", kUpper)
  267. }
  268. }
  269. }
  270. if env.IsRemoteEnabled() {
  271. err := utils.UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  272. if err != nil {
  273. return err
  274. }
  275. }
  276. return nil
  277. })
  278. }
  279. // ClusterInfo returns information on the GKE cluster, as provided by metadata.
  280. func (gcp *GCP) ClusterInfo() (map[string]string, error) {
  281. remoteEnabled := env.IsRemoteEnabled()
  282. attribute, err := gcp.MetadataClient.InstanceAttributeValue("cluster-name")
  283. if err != nil {
  284. log.Infof("Error loading metadata cluster-name: %s", err.Error())
  285. }
  286. c, err := gcp.GetConfig()
  287. if err != nil {
  288. log.Errorf("Error opening config: %s", err.Error())
  289. }
  290. if c.ClusterName != "" {
  291. attribute = c.ClusterName
  292. }
  293. // Use a default name if none has been set until this point
  294. if attribute == "" {
  295. attribute = "GKE Cluster #1"
  296. }
  297. m := make(map[string]string)
  298. m["name"] = attribute
  299. m["provider"] = kubecost.GCPProvider
  300. m["region"] = gcp.ClusterRegion
  301. m["account"] = gcp.ClusterAccountID
  302. m["project"] = gcp.ClusterProjectID
  303. m["provisioner"] = gcp.clusterProvisioner
  304. m["id"] = env.GetClusterID()
  305. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  306. return m, nil
  307. }
  308. func (gcp *GCP) ClusterManagementPricing() (string, float64, error) {
  309. return gcp.clusterProvisioner, gcp.clusterManagementPrice, nil
  310. }
  311. func (gcp *GCP) getAllAddresses() (*compute.AddressAggregatedList, error) {
  312. projID, err := gcp.MetadataClient.ProjectID()
  313. if err != nil {
  314. return nil, err
  315. }
  316. client, err := google.DefaultClient(context.TODO(),
  317. "https://www.googleapis.com/auth/compute.readonly")
  318. if err != nil {
  319. return nil, err
  320. }
  321. svc, err := compute.New(client)
  322. if err != nil {
  323. return nil, err
  324. }
  325. res, err := svc.Addresses.AggregatedList(projID).Do()
  326. if err != nil {
  327. return nil, err
  328. }
  329. return res, nil
  330. }
  331. func (gcp *GCP) GetAddresses() ([]byte, error) {
  332. res, err := gcp.getAllAddresses()
  333. if err != nil {
  334. return nil, err
  335. }
  336. return json.Marshal(res)
  337. }
  338. func (gcp *GCP) isAddressOrphaned(address *compute.Address) bool {
  339. // Consider address orphaned if it has 0 users
  340. return len(address.Users) == 0
  341. }
  342. func (gcp *GCP) getAllDisks() (*compute.DiskAggregatedList, error) {
  343. projID, err := gcp.MetadataClient.ProjectID()
  344. if err != nil {
  345. return nil, err
  346. }
  347. client, err := google.DefaultClient(context.TODO(),
  348. "https://www.googleapis.com/auth/compute.readonly")
  349. if err != nil {
  350. return nil, err
  351. }
  352. svc, err := compute.New(client)
  353. if err != nil {
  354. return nil, err
  355. }
  356. res, err := svc.Disks.AggregatedList(projID).Do()
  357. if err != nil {
  358. return nil, err
  359. }
  360. return res, nil
  361. }
  362. // 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.
  363. func (gcp *GCP) GetDisks() ([]byte, error) {
  364. res, err := gcp.getAllDisks()
  365. if err != nil {
  366. return nil, err
  367. }
  368. return json.Marshal(res)
  369. }
  370. func (gcp *GCP) isDiskOrphaned(disk *compute.Disk) (bool, error) {
  371. // Do not consider disk orphaned if it has more than 0 users
  372. if len(disk.Users) > 0 {
  373. return false, nil
  374. }
  375. // Do not consider disk orphaned if it was used within the last hour
  376. threshold := time.Now().Add(time.Duration(-1) * time.Hour)
  377. if disk.LastDetachTimestamp != "" {
  378. lastUsed, err := time.Parse(time.RFC3339, disk.LastDetachTimestamp)
  379. if err != nil {
  380. // This can return false since errors are checked before the bool
  381. return false, fmt.Errorf("error parsing time: %s", err)
  382. }
  383. if threshold.Before(lastUsed) {
  384. return false, nil
  385. }
  386. }
  387. return true, nil
  388. }
  389. func (gcp *GCP) GetOrphanedResources() ([]models.OrphanedResource, error) {
  390. disks, err := gcp.getAllDisks()
  391. if err != nil {
  392. return nil, err
  393. }
  394. addresses, err := gcp.getAllAddresses()
  395. if err != nil {
  396. return nil, err
  397. }
  398. var orphanedResources []models.OrphanedResource
  399. for _, diskList := range disks.Items {
  400. if len(diskList.Disks) == 0 {
  401. continue
  402. }
  403. for _, disk := range diskList.Disks {
  404. isOrphaned, err := gcp.isDiskOrphaned(disk)
  405. if err != nil {
  406. return nil, err
  407. }
  408. if isOrphaned {
  409. cost, err := gcp.findCostForDisk(disk)
  410. if err != nil {
  411. return nil, err
  412. }
  413. // GCP gives us description as a string formatted as a map[string]string, so we need to
  414. // deconstruct it back into a map[string]string to match the OR struct
  415. desc := map[string]string{}
  416. if disk.Description != "" {
  417. if err := json.Unmarshal([]byte(disk.Description), &desc); err != nil {
  418. return nil, fmt.Errorf("error converting string to map: %s", err)
  419. }
  420. }
  421. // Converts https://www.googleapis.com/compute/v1/projects/xxxxx/zones/us-central1-c to us-central1-c
  422. zone := path.Base(disk.Zone)
  423. if zone == "." {
  424. zone = ""
  425. }
  426. or := models.OrphanedResource{
  427. Kind: "disk",
  428. Region: zone,
  429. Description: desc,
  430. Size: &disk.SizeGb,
  431. DiskName: disk.Name,
  432. Url: disk.SelfLink,
  433. MonthlyCost: cost,
  434. }
  435. orphanedResources = append(orphanedResources, or)
  436. }
  437. }
  438. }
  439. for _, addressList := range addresses.Items {
  440. if len(addressList.Addresses) == 0 {
  441. continue
  442. }
  443. for _, address := range addressList.Addresses {
  444. if gcp.isAddressOrphaned(address) {
  445. //todo: use GCP pricing
  446. cost := GCPHourlyPublicIPCost * timeutil.HoursPerMonth
  447. // Converts https://www.googleapis.com/compute/v1/projects/xxxxx/regions/us-central1 to us-central1
  448. region := path.Base(address.Region)
  449. if region == "." {
  450. region = ""
  451. }
  452. or := models.OrphanedResource{
  453. Kind: "address",
  454. Region: region,
  455. Description: map[string]string{
  456. "type": address.AddressType,
  457. },
  458. Address: address.Address,
  459. Url: address.SelfLink,
  460. MonthlyCost: &cost,
  461. }
  462. orphanedResources = append(orphanedResources, or)
  463. }
  464. }
  465. }
  466. return orphanedResources, nil
  467. }
  468. func (gcp *GCP) findCostForDisk(disk *compute.Disk) (*float64, error) {
  469. //todo: use GCP pricing struct
  470. price := GCPMonthlyBasicDiskCost
  471. if strings.Contains(disk.Type, "ssd") {
  472. price = GCPMonthlySSDDiskCost
  473. }
  474. if strings.Contains(disk.Type, "gp2") {
  475. price = GCPMonthlyGP2DiskCost
  476. }
  477. cost := price * float64(disk.SizeGb)
  478. // This isn't much use but I (Nick) think its could be going down the
  479. // right path. Disk region isnt returning anything (and if it did its
  480. // a url, same with type). Currently the only region stored in the
  481. // Pricing struct is uscentral-1, so that would need to be fixed
  482. // key := disk.Region + "," + disk.Type
  483. // priceStr := gcp.Pricing[key].PV.Cost
  484. // price, err := strconv.ParseFloat(priceStr, 64)
  485. // if err != nil {
  486. // return nil, err
  487. // }
  488. // cost := price * timeutil.HoursPerMonth * float64(disk.SizeGb)
  489. return &cost, nil
  490. }
  491. // GCPPricing represents GCP pricing data for a SKU
  492. type GCPPricing struct {
  493. Name string `json:"name"`
  494. SKUID string `json:"skuId"`
  495. Description string `json:"description"`
  496. Category *GCPResourceInfo `json:"category"`
  497. ServiceRegions []string `json:"serviceRegions"`
  498. PricingInfo []*PricingInfo `json:"pricingInfo"`
  499. ServiceProviderName string `json:"serviceProviderName"`
  500. Node *models.Node `json:"node"`
  501. PV *models.PV `json:"pv"`
  502. }
  503. // PricingInfo contains metadata about a cost.
  504. type PricingInfo struct {
  505. Summary string `json:"summary"`
  506. PricingExpression *PricingExpression `json:"pricingExpression"`
  507. CurrencyConversionRate float64 `json:"currencyConversionRate"`
  508. EffectiveTime string `json:""`
  509. }
  510. // PricingExpression contains metadata about a cost.
  511. type PricingExpression struct {
  512. UsageUnit string `json:"usageUnit"`
  513. UsageUnitDescription string `json:"usageUnitDescription"`
  514. BaseUnit string `json:"baseUnit"`
  515. BaseUnitConversionFactor int64 `json:"-"`
  516. DisplayQuantity int `json:"displayQuantity"`
  517. TieredRates []*TieredRates `json:"tieredRates"`
  518. }
  519. // TieredRates contain data about variable pricing.
  520. type TieredRates struct {
  521. StartUsageAmount int `json:"startUsageAmount"`
  522. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  523. }
  524. // UnitPriceInfo contains data about the actual price being charged.
  525. type UnitPriceInfo struct {
  526. CurrencyCode string `json:"currencyCode"`
  527. Units string `json:"units"`
  528. Nanos float64 `json:"nanos"`
  529. }
  530. // GCPResourceInfo contains metadata about the node.
  531. type GCPResourceInfo struct {
  532. ServiceDisplayName string `json:"serviceDisplayName"`
  533. ResourceFamily string `json:"resourceFamily"`
  534. ResourceGroup string `json:"resourceGroup"`
  535. UsageType string `json:"usageType"`
  536. }
  537. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]models.Key, pvKeys map[string]models.PVKey) (map[string]*GCPPricing, string, error) {
  538. gcpPricingList := make(map[string]*GCPPricing)
  539. var nextPageToken string
  540. dec := json.NewDecoder(r)
  541. for {
  542. t, err := dec.Token()
  543. if err == io.EOF {
  544. break
  545. } else if err != nil {
  546. return nil, "", fmt.Errorf("error parsing GCP pricing page: %s", err)
  547. }
  548. if t == "skus" {
  549. _, err := dec.Token() // consumes [
  550. if err != nil {
  551. return nil, "", err
  552. }
  553. for dec.More() {
  554. product := &GCPPricing{}
  555. err := dec.Decode(&product)
  556. if err != nil {
  557. return nil, "", err
  558. }
  559. usageType := strings.ToLower(product.Category.UsageType)
  560. instanceType := strings.ToLower(product.Category.ResourceGroup)
  561. if instanceType == "ssd" && strings.Contains(product.Description, "SSD backed") && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  562. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  563. var nanos float64
  564. if lastRateIndex > -1 && len(product.PricingInfo) > 0 {
  565. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  566. } else {
  567. continue
  568. }
  569. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  570. for _, sr := range product.ServiceRegions {
  571. region := sr
  572. candidateKey := region + "," + "ssd"
  573. if _, ok := pvKeys[candidateKey]; ok {
  574. product.PV = &models.PV{
  575. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  576. }
  577. gcpPricingList[candidateKey] = product
  578. continue
  579. }
  580. }
  581. continue
  582. } else if instanceType == "ssd" && strings.Contains(product.Description, "SSD backed") && strings.Contains(product.Description, "Regional") { // TODO: support regional
  583. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  584. var nanos float64
  585. if lastRateIndex > -1 && len(product.PricingInfo) > 0 {
  586. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  587. } else {
  588. continue
  589. }
  590. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  591. for _, sr := range product.ServiceRegions {
  592. region := sr
  593. candidateKey := region + "," + "ssd" + "," + "regional"
  594. if _, ok := pvKeys[candidateKey]; ok {
  595. product.PV = &models.PV{
  596. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  597. }
  598. gcpPricingList[candidateKey] = product
  599. continue
  600. }
  601. }
  602. continue
  603. } else if instanceType == "pdstandard" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  604. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  605. var nanos float64
  606. if lastRateIndex > -1 && len(product.PricingInfo) > 0 {
  607. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  608. } else {
  609. continue
  610. }
  611. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  612. for _, sr := range product.ServiceRegions {
  613. region := sr
  614. candidateKey := region + "," + "pdstandard"
  615. if _, ok := pvKeys[candidateKey]; ok {
  616. product.PV = &models.PV{
  617. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  618. }
  619. gcpPricingList[candidateKey] = product
  620. continue
  621. }
  622. }
  623. continue
  624. } else if instanceType == "pdstandard" && strings.Contains(product.Description, "Regional") { // TODO: support regional
  625. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  626. var nanos float64
  627. if lastRateIndex > -1 && len(product.PricingInfo) > 0 {
  628. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  629. } else {
  630. continue
  631. }
  632. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  633. for _, sr := range product.ServiceRegions {
  634. region := sr
  635. candidateKey := region + "," + "pdstandard" + "," + "regional"
  636. if _, ok := pvKeys[candidateKey]; ok {
  637. product.PV = &models.PV{
  638. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  639. }
  640. gcpPricingList[candidateKey] = product
  641. continue
  642. }
  643. }
  644. continue
  645. }
  646. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  647. instanceType = "custom"
  648. }
  649. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "N2") && !strings.Contains(strings.ToUpper(product.Description), "PREMIUM") {
  650. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "N2D AMD") {
  651. instanceType = "n2dstandard"
  652. } else {
  653. instanceType = "n2standard"
  654. }
  655. }
  656. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "A2 INSTANCE") {
  657. instanceType = "a2"
  658. }
  659. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "COMPUTE OPTIMIZED") {
  660. instanceType = "c2standard"
  661. }
  662. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "E2 INSTANCE") {
  663. instanceType = "e2"
  664. }
  665. partialCPUMap := make(map[string]float64)
  666. partialCPUMap["e2micro"] = 0.25
  667. partialCPUMap["e2small"] = 0.5
  668. partialCPUMap["e2medium"] = 1
  669. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "T2D AMD") {
  670. instanceType = "t2dstandard"
  671. }
  672. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "T2A ARM") {
  673. instanceType = "t2astandard"
  674. }
  675. var gpuType string
  676. for matchnum, group := range nvidiaGPURegex.FindStringSubmatch(product.Description) {
  677. if matchnum == 1 {
  678. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  679. log.Debugf("GCP Billing API: GPU type found: '%s'", gpuType)
  680. }
  681. }
  682. candidateKeys := []string{}
  683. if gcp.ValidPricingKeys == nil {
  684. gcp.ValidPricingKeys = make(map[string]bool)
  685. }
  686. for _, region := range product.ServiceRegions {
  687. switch instanceType {
  688. case "e2":
  689. candidateKeys = append(candidateKeys, region+","+"e2micro"+","+usageType)
  690. candidateKeys = append(candidateKeys, region+","+"e2small"+","+usageType)
  691. candidateKeys = append(candidateKeys, region+","+"e2medium"+","+usageType)
  692. candidateKeys = append(candidateKeys, region+","+"e2standard"+","+usageType)
  693. candidateKeys = append(candidateKeys, region+","+"e2custom"+","+usageType)
  694. case "a2":
  695. candidateKeys = append(candidateKeys, region+","+"a2highgpu"+","+usageType)
  696. candidateKeys = append(candidateKeys, region+","+"a2megagpu"+","+usageType)
  697. candidateKeys = append(candidateKeys, region+","+"a2ultragpu"+","+usageType)
  698. default:
  699. candidateKey := region + "," + instanceType + "," + usageType
  700. candidateKeys = append(candidateKeys, candidateKey)
  701. }
  702. }
  703. for _, candidateKey := range candidateKeys {
  704. instanceType = strings.Split(candidateKey, ",")[1] // we may have overridden this while generating candidate keys
  705. region := strings.Split(candidateKey, ",")[0]
  706. candidateKeyGPU := candidateKey + ",gpu"
  707. gcp.ValidPricingKeys[candidateKey] = true
  708. gcp.ValidPricingKeys[candidateKeyGPU] = true
  709. if gpuType != "" {
  710. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  711. var nanos float64
  712. var unitsBaseCurrency int
  713. if lastRateIndex > -1 && len(product.PricingInfo) > 0 {
  714. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  715. unitsBaseCurrency, err = strconv.Atoi(product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Units)
  716. if err != nil {
  717. return nil, "", fmt.Errorf("error parsing base unit price for gpu: %w", err)
  718. }
  719. } else {
  720. continue
  721. }
  722. // as per https://cloud.google.com/billing/v1/how-tos/catalog-api
  723. // the hourly price is the whole currency price + the fractional currency price
  724. hourlyPrice := (nanos * math.Pow10(-9)) + float64(unitsBaseCurrency)
  725. // GPUs with an hourly price of 0 are reserved versions of GPUs
  726. // (E.g., SKU "2013-37B4-22EA")
  727. // and are excluded from cost computations
  728. if hourlyPrice == 0 {
  729. log.Debugf("GCP Billing API: excluding reserved GPU SKU #%s", product.SKUID)
  730. continue
  731. }
  732. for k, key := range inputKeys {
  733. if key.GPUType() == gpuType+","+usageType {
  734. if region == strings.Split(k, ",")[0] {
  735. matchedKey := key.Features()
  736. log.Debugf("GCP Billing API: matched GPU to node: %s: %s", matchedKey, product.Description)
  737. if pl, ok := gcpPricingList[matchedKey]; ok {
  738. pl.Node.GPUName = gpuType
  739. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  740. pl.Node.GPU = "1"
  741. } else {
  742. product.Node = &models.Node{
  743. GPUName: gpuType,
  744. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  745. GPU: "1",
  746. }
  747. gcpPricingList[matchedKey] = product
  748. }
  749. }
  750. }
  751. }
  752. } else {
  753. _, ok := inputKeys[candidateKey]
  754. _, ok2 := inputKeys[candidateKeyGPU]
  755. if ok || ok2 {
  756. var nanos float64
  757. var unitsBaseCurrency int
  758. if len(product.PricingInfo) > 0 {
  759. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  760. if lastRateIndex >= 0 {
  761. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  762. unitsBaseCurrency, err = strconv.Atoi(product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Units)
  763. if err != nil {
  764. return nil, "", fmt.Errorf("error parsing base unit price for instance: %w", err)
  765. }
  766. } else {
  767. continue
  768. }
  769. } else {
  770. continue
  771. }
  772. // as per https://cloud.google.com/billing/v1/how-tos/catalog-api
  773. // the hourly price is the whole currency price + the fractional currency price
  774. hourlyPrice := (nanos * math.Pow10(-9)) + float64(unitsBaseCurrency)
  775. if hourlyPrice == 0 {
  776. continue
  777. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  778. if instanceType == "custom" {
  779. log.Debugf("GCP Billing API: RAM custom sku '%s'", product.Name)
  780. }
  781. if _, ok := gcpPricingList[candidateKey]; ok {
  782. log.Debugf("GCP Billing API: key '%s': RAM price: %f", candidateKey, hourlyPrice)
  783. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  784. } else {
  785. log.Debugf("GCP Billing API: key '%s': RAM price: %f", candidateKey, hourlyPrice)
  786. pricing := &GCPPricing{}
  787. pricing.Node = &models.Node{
  788. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  789. }
  790. partialCPU, pcok := partialCPUMap[instanceType]
  791. if pcok {
  792. pricing.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  793. }
  794. pricing.Node.UsageType = usageType
  795. gcpPricingList[candidateKey] = pricing
  796. }
  797. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  798. log.Debugf("GCP Billing API: key '%s': RAM price: %f", candidateKeyGPU, hourlyPrice)
  799. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  800. } else {
  801. log.Debugf("GCP Billing API: key '%s': RAM price: %f", candidateKeyGPU, hourlyPrice)
  802. pricing := &GCPPricing{}
  803. pricing.Node = &models.Node{
  804. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  805. }
  806. partialCPU, pcok := partialCPUMap[instanceType]
  807. if pcok {
  808. pricing.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  809. }
  810. pricing.Node.UsageType = usageType
  811. gcpPricingList[candidateKeyGPU] = pricing
  812. }
  813. } else {
  814. if _, ok := gcpPricingList[candidateKey]; ok {
  815. log.Debugf("GCP Billing API: key '%s': CPU price: %f", candidateKey, hourlyPrice)
  816. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  817. } else {
  818. log.Debugf("GCP Billing API: key '%s': CPU price: %f", candidateKey, hourlyPrice)
  819. pricing := &GCPPricing{}
  820. pricing.Node = &models.Node{
  821. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  822. }
  823. partialCPU, pcok := partialCPUMap[instanceType]
  824. if pcok {
  825. pricing.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  826. }
  827. pricing.Node.UsageType = usageType
  828. gcpPricingList[candidateKey] = pricing
  829. }
  830. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  831. log.Debugf("GCP Billing API: key '%s': CPU price: %f", candidateKeyGPU, hourlyPrice)
  832. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  833. } else {
  834. log.Debugf("GCP Billing API: key '%s': CPU price: %f", candidateKeyGPU, hourlyPrice)
  835. pricing := &GCPPricing{}
  836. pricing.Node = &models.Node{
  837. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  838. }
  839. partialCPU, pcok := partialCPUMap[instanceType]
  840. if pcok {
  841. pricing.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  842. }
  843. pricing.Node.UsageType = usageType
  844. gcpPricingList[candidateKeyGPU] = pricing
  845. }
  846. }
  847. }
  848. }
  849. }
  850. }
  851. }
  852. if t == "nextPageToken" {
  853. pageToken, err := dec.Token()
  854. if err != nil {
  855. log.Errorf("Error parsing nextpage token: " + err.Error())
  856. return nil, "", err
  857. }
  858. if pageToken.(string) != "" {
  859. nextPageToken = pageToken.(string)
  860. } else {
  861. nextPageToken = "done"
  862. }
  863. }
  864. }
  865. return gcpPricingList, nextPageToken, nil
  866. }
  867. func (gcp *GCP) getBillingAPIURL(apiKey, currencyCode string) string {
  868. return fmt.Sprintf(BillingAPIURLFmt, apiKey, currencyCode)
  869. }
  870. func (gcp *GCP) parsePages(inputKeys map[string]models.Key, pvKeys map[string]models.PVKey) (map[string]*GCPPricing, error) {
  871. var pages []map[string]*GCPPricing
  872. c, err := gcp.GetConfig()
  873. if err != nil {
  874. return nil, err
  875. }
  876. url := gcp.getBillingAPIURL(gcp.APIKey, c.CurrencyCode)
  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. }