gcpprovider.go 32 KB

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