gcpprovider.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  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. "k8s.io/klog"
  17. "cloud.google.com/go/bigquery"
  18. "cloud.google.com/go/compute/metadata"
  19. "golang.org/x/oauth2"
  20. "golang.org/x/oauth2/google"
  21. compute "google.golang.org/api/compute/v1"
  22. "google.golang.org/api/iterator"
  23. v1 "k8s.io/api/core/v1"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/client-go/kubernetes"
  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 *kubernetes.Clientset
  41. APIKey string
  42. BaseCPUPrice string
  43. ProjectID string
  44. BillingDataDataset string
  45. DownloadPricingDataLock sync.RWMutex
  46. *CustomProvider
  47. }
  48. type gcpAllocation struct {
  49. Aggregator bigquery.NullString
  50. Environment bigquery.NullString
  51. Service string
  52. Cost float64
  53. }
  54. func gcpAllocationToOutOfClusterAllocation(gcpAlloc gcpAllocation) *OutOfClusterAllocation {
  55. var aggregator string
  56. if gcpAlloc.Aggregator.Valid {
  57. aggregator = gcpAlloc.Aggregator.StringVal
  58. }
  59. var environment string
  60. if gcpAlloc.Environment.Valid {
  61. environment = gcpAlloc.Environment.StringVal
  62. }
  63. return &OutOfClusterAllocation{
  64. Aggregator: aggregator,
  65. Environment: environment,
  66. Service: gcpAlloc.Service,
  67. Cost: gcpAlloc.Cost,
  68. }
  69. }
  70. func (gcp *GCP) GetLocalStorageQuery() (string, error) {
  71. localStorageCost := 0.04 // TODO: Set to the price for the appropriate storage class. It's not trivial to determine the local storage disk type
  72. return fmt.Sprintf(`sum(sum(container_fs_limit_bytes{device!="tmpfs", id="/"}) by (instance) / 1024 / 1024 / 1024) * %f`, localStorageCost), nil
  73. }
  74. func (gcp *GCP) GetConfig() (*CustomPricing, error) {
  75. c, err := GetDefaultPricingData("gcp.json")
  76. if err != nil {
  77. return nil, err
  78. }
  79. if c.Discount == "" {
  80. c.Discount = "30%"
  81. }
  82. return c, nil
  83. }
  84. type BigQueryConfig struct {
  85. ProjectID string `json:"projectID"`
  86. BillingDataDataset string `json:"billingDataDataset"`
  87. Key map[string]string `json:"key"`
  88. }
  89. func (gcp *GCP) GetManagementPlatform() (string, error) {
  90. nodes, err := gcp.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  91. if err != nil {
  92. return "", err
  93. }
  94. if len(nodes.Items) > 0 {
  95. n := nodes.Items[0]
  96. version := n.Status.NodeInfo.KubeletVersion
  97. if strings.Contains(version, "gke") {
  98. return "gke", nil
  99. }
  100. }
  101. return "", nil
  102. }
  103. func (gcp *GCP) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  104. c, err := GetDefaultPricingData("gcp.json")
  105. if err != nil {
  106. return nil, err
  107. }
  108. path := os.Getenv("CONFIG_PATH")
  109. if path == "" {
  110. path = "/models/"
  111. }
  112. if updateType == BigqueryUpdateType {
  113. a := BigQueryConfig{}
  114. err = json.NewDecoder(r).Decode(&a)
  115. if err != nil {
  116. return nil, err
  117. }
  118. c.ProjectID = a.ProjectID
  119. c.BillingDataDataset = a.BillingDataDataset
  120. j, err := json.Marshal(a.Key)
  121. if err != nil {
  122. return nil, err
  123. }
  124. keyPath := path + "key.json"
  125. err = ioutil.WriteFile(keyPath, j, 0644)
  126. if err != nil {
  127. return nil, err
  128. }
  129. } else {
  130. a := make(map[string]string)
  131. err = json.NewDecoder(r).Decode(&a)
  132. if err != nil {
  133. return nil, err
  134. }
  135. for k, v := range a {
  136. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  137. err := SetCustomPricingField(c, kUpper, v)
  138. if err != nil {
  139. return nil, err
  140. }
  141. }
  142. }
  143. cj, err := json.Marshal(c)
  144. if err != nil {
  145. return nil, err
  146. }
  147. remoteEnabled := os.Getenv(remoteEnabled)
  148. if remoteEnabled == "true" {
  149. err = UpdateClusterMeta(os.Getenv(KC_CLUSTER_ID), c.ClusterName)
  150. if err != nil {
  151. return nil, err
  152. }
  153. }
  154. configPath := path + "gcp.json"
  155. err = ioutil.WriteFile(configPath, cj, 0644)
  156. if err != nil {
  157. return nil, err
  158. }
  159. return c, nil
  160. }
  161. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  162. // "start" and "end" are dates of the format YYYY-MM-DD
  163. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  164. func (gcp *GCP) ExternalAllocations(start string, end string, aggregator string) ([]*OutOfClusterAllocation, error) {
  165. c, err := GetDefaultPricingData("gcp.json")
  166. if err != nil {
  167. return nil, err
  168. }
  169. // start, end formatted like: "2019-04-20 00:00:00"
  170. queryString := fmt.Sprintf(`SELECT
  171. service,
  172. labels.key as aggregator,
  173. labels.value as environment,
  174. SUM(cost) as cost
  175. FROM (SELECT
  176. service.description as service,
  177. labels,
  178. cost
  179. FROM %s
  180. WHERE usage_start_time >= "%s" AND usage_start_time < "%s")
  181. LEFT JOIN UNNEST(labels) as labels
  182. ON labels.key = "kubernetes_namespace" OR labels.key = "kubernetes_container" OR labels.key = "kubernetes_deployment" OR labels.key = "kubernetes_pod" OR labels.key = "kubernetes_daemonset"
  183. GROUP BY aggregator, environment, service;`, c.BillingDataDataset, start, end) // For example, "billing_data.gcp_billing_export_v1_01AC9F_74CF1D_5565A2"
  184. klog.V(4).Infof("Querying \"%s\" with : %s", c.ProjectID, queryString)
  185. return gcp.QuerySQL(queryString)
  186. }
  187. // QuerySQL should query BigQuery for billing data for out of cluster costs.
  188. func (gcp *GCP) QuerySQL(query string) ([]*OutOfClusterAllocation, error) {
  189. c, err := GetDefaultPricingData("gcp.json")
  190. if err != nil {
  191. return nil, err
  192. }
  193. ctx := context.Background()
  194. client, err := bigquery.NewClient(ctx, c.ProjectID) // For example, "guestbook-227502"
  195. if err != nil {
  196. return nil, err
  197. }
  198. q := client.Query(query)
  199. it, err := q.Read(ctx)
  200. if err != nil {
  201. return nil, err
  202. }
  203. var allocations []*OutOfClusterAllocation
  204. for {
  205. var a gcpAllocation
  206. err := it.Next(&a)
  207. if err == iterator.Done {
  208. break
  209. }
  210. if err != nil {
  211. return nil, err
  212. }
  213. allocations = append(allocations, gcpAllocationToOutOfClusterAllocation(a))
  214. }
  215. return allocations, nil
  216. }
  217. // ClusterName returns the name of a GKE cluster, as provided by metadata.
  218. func (gcp *GCP) ClusterInfo() (map[string]string, error) {
  219. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  220. userAgent: "kubecost",
  221. base: http.DefaultTransport,
  222. }})
  223. attribute, err := metadataClient.InstanceAttributeValue("cluster-name")
  224. if err != nil {
  225. return nil, err
  226. }
  227. c, err := gcp.GetConfig()
  228. if err != nil {
  229. klog.V(1).Infof("Error opening config: %s", err.Error())
  230. }
  231. if c.ClusterName != "" {
  232. attribute = c.ClusterName
  233. }
  234. m := make(map[string]string)
  235. m["name"] = attribute
  236. m["provider"] = "GCP"
  237. m["id"] = os.Getenv(KC_CLUSTER_ID)
  238. return m, nil
  239. }
  240. // AddServiceKey adds the service key as required for GetDisks
  241. func (*GCP) AddServiceKey(formValues url.Values) error {
  242. key := formValues.Get("key")
  243. k := []byte(key)
  244. return ioutil.WriteFile("/var/configs/key.json", k, 0644)
  245. }
  246. // 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.
  247. func (*GCP) GetDisks() ([]byte, error) {
  248. // metadata API setup
  249. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  250. userAgent: "kubecost",
  251. base: http.DefaultTransport,
  252. }})
  253. projID, err := metadataClient.ProjectID()
  254. if err != nil {
  255. return nil, err
  256. }
  257. client, err := google.DefaultClient(oauth2.NoContext,
  258. "https://www.googleapis.com/auth/compute.readonly")
  259. if err != nil {
  260. return nil, err
  261. }
  262. svc, err := compute.New(client)
  263. if err != nil {
  264. return nil, err
  265. }
  266. res, err := svc.Disks.AggregatedList(projID).Do()
  267. if err != nil {
  268. return nil, err
  269. }
  270. return json.Marshal(res)
  271. }
  272. // GCPPricing represents GCP pricing data for a SKU
  273. type GCPPricing struct {
  274. Name string `json:"name"`
  275. SKUID string `json:"skuId"`
  276. Description string `json:"description"`
  277. Category *GCPResourceInfo `json:"category"`
  278. ServiceRegions []string `json:"serviceRegions"`
  279. PricingInfo []*PricingInfo `json:"pricingInfo"`
  280. ServiceProviderName string `json:"serviceProviderName"`
  281. Node *Node `json:"node"`
  282. PV *PV `json:"pv"`
  283. }
  284. // PricingInfo contains metadata about a cost.
  285. type PricingInfo struct {
  286. Summary string `json:"summary"`
  287. PricingExpression *PricingExpression `json:"pricingExpression"`
  288. CurrencyConversionRate int `json:"currencyConversionRate"`
  289. EffectiveTime string `json:""`
  290. }
  291. // PricingExpression contains metadata about a cost.
  292. type PricingExpression struct {
  293. UsageUnit string `json:"usageUnit"`
  294. UsageUnitDescription string `json:"usageUnitDescription"`
  295. BaseUnit string `json:"baseUnit"`
  296. BaseUnitConversionFactor int64 `json:"-"`
  297. DisplayQuantity int `json:"displayQuantity"`
  298. TieredRates []*TieredRates `json:"tieredRates"`
  299. }
  300. // TieredRates contain data about variable pricing.
  301. type TieredRates struct {
  302. StartUsageAmount int `json:"startUsageAmount"`
  303. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  304. }
  305. // UnitPriceInfo contains data about the actual price being charged.
  306. type UnitPriceInfo struct {
  307. CurrencyCode string `json:"currencyCode"`
  308. Units string `json:"units"`
  309. Nanos float64 `json:"nanos"`
  310. }
  311. // GCPResourceInfo contains metadata about the node.
  312. type GCPResourceInfo struct {
  313. ServiceDisplayName string `json:"serviceDisplayName"`
  314. ResourceFamily string `json:"resourceFamily"`
  315. ResourceGroup string `json:"resourceGroup"`
  316. UsageType string `json:"usageType"`
  317. }
  318. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, string, error) {
  319. gcpPricingList := make(map[string]*GCPPricing)
  320. var nextPageToken string
  321. dec := json.NewDecoder(r)
  322. for {
  323. t, err := dec.Token()
  324. if err == io.EOF {
  325. break
  326. }
  327. if t == "skus" {
  328. _, err := dec.Token() // consumes [
  329. if err != nil {
  330. return nil, "", err
  331. }
  332. for dec.More() {
  333. product := &GCPPricing{}
  334. err := dec.Decode(&product)
  335. if err != nil {
  336. return nil, "", err
  337. }
  338. usageType := strings.ToLower(product.Category.UsageType)
  339. instanceType := strings.ToLower(product.Category.ResourceGroup)
  340. if instanceType == "ssd" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  341. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  342. var nanos float64
  343. if len(product.PricingInfo) > 0 {
  344. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  345. } else {
  346. continue
  347. }
  348. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  349. for _, sr := range product.ServiceRegions {
  350. region := sr
  351. candidateKey := region + "," + "ssd"
  352. if _, ok := pvKeys[candidateKey]; ok {
  353. product.PV = &PV{
  354. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  355. }
  356. gcpPricingList[candidateKey] = product
  357. continue
  358. }
  359. }
  360. continue
  361. } else if instanceType == "pdstandard" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  362. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  363. var nanos float64
  364. if len(product.PricingInfo) > 0 {
  365. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  366. } else {
  367. continue
  368. }
  369. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  370. for _, sr := range product.ServiceRegions {
  371. region := sr
  372. candidateKey := region + "," + "pdstandard"
  373. if _, ok := pvKeys[candidateKey]; ok {
  374. product.PV = &PV{
  375. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  376. }
  377. gcpPricingList[candidateKey] = product
  378. continue
  379. }
  380. }
  381. continue
  382. }
  383. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  384. instanceType = "custom"
  385. }
  386. /*
  387. var partialCPU float64
  388. if strings.ToLower(instanceType) == "f1micro" {
  389. partialCPU = 0.2
  390. } else if strings.ToLower(instanceType) == "g1small" {
  391. partialCPU = 0.5
  392. }
  393. */
  394. var gpuType string
  395. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  396. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  397. if matchnum == 1 {
  398. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  399. klog.V(4).Info("GPU type found: " + gpuType)
  400. }
  401. }
  402. for _, sr := range product.ServiceRegions {
  403. region := sr
  404. candidateKey := region + "," + instanceType + "," + usageType
  405. candidateKeyGPU := candidateKey + ",gpu"
  406. if gpuType != "" {
  407. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  408. var nanos float64
  409. if len(product.PricingInfo) > 0 {
  410. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  411. } else {
  412. continue
  413. }
  414. hourlyPrice := nanos * math.Pow10(-9)
  415. for k, key := range inputKeys {
  416. if key.GPUType() == gpuType+","+usageType {
  417. if region == strings.Split(k, ",")[0] {
  418. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  419. matchedKey := key.Features()
  420. if pl, ok := gcpPricingList[matchedKey]; ok {
  421. pl.Node.GPUName = gpuType
  422. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  423. pl.Node.GPU = "1"
  424. } else {
  425. product.Node = &Node{
  426. GPUName: gpuType,
  427. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  428. GPU: "1",
  429. }
  430. gcpPricingList[matchedKey] = product
  431. }
  432. klog.V(3).Infof("Added data for " + matchedKey)
  433. }
  434. }
  435. }
  436. } else {
  437. _, ok := inputKeys[candidateKey]
  438. _, ok2 := inputKeys[candidateKeyGPU]
  439. if ok || ok2 {
  440. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  441. var nanos float64
  442. if len(product.PricingInfo) > 0 {
  443. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  444. } else {
  445. continue
  446. }
  447. hourlyPrice := nanos * math.Pow10(-9)
  448. if hourlyPrice == 0 {
  449. continue
  450. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  451. if instanceType == "custom" {
  452. klog.V(4).Infof("RAM custom sku is: " + product.Name)
  453. }
  454. if _, ok := gcpPricingList[candidateKey]; ok {
  455. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  456. } else {
  457. product = &GCPPricing{}
  458. product.Node = &Node{
  459. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  460. }
  461. /*
  462. if partialCPU != 0 {
  463. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  464. }
  465. */
  466. product.Node.UsageType = usageType
  467. gcpPricingList[candidateKey] = product
  468. }
  469. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  470. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  471. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  472. } else {
  473. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  474. product = &GCPPricing{}
  475. product.Node = &Node{
  476. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  477. }
  478. /*
  479. if partialCPU != 0 {
  480. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  481. }
  482. */
  483. product.Node.UsageType = usageType
  484. gcpPricingList[candidateKeyGPU] = product
  485. }
  486. break
  487. } else {
  488. if _, ok := gcpPricingList[candidateKey]; ok {
  489. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  490. } else {
  491. product = &GCPPricing{}
  492. product.Node = &Node{
  493. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  494. }
  495. /*
  496. if partialCPU != 0 {
  497. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  498. }
  499. */
  500. product.Node.UsageType = usageType
  501. gcpPricingList[candidateKey] = product
  502. }
  503. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  504. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  505. } else {
  506. product = &GCPPricing{}
  507. product.Node = &Node{
  508. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  509. }
  510. /*
  511. if partialCPU != 0 {
  512. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  513. }
  514. */
  515. product.Node.UsageType = usageType
  516. gcpPricingList[candidateKeyGPU] = product
  517. }
  518. break
  519. }
  520. }
  521. }
  522. }
  523. }
  524. }
  525. if t == "nextPageToken" {
  526. pageToken, err := dec.Token()
  527. if err != nil {
  528. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  529. return nil, "", err
  530. }
  531. if pageToken.(string) != "" {
  532. nextPageToken = pageToken.(string)
  533. } else {
  534. nextPageToken = "done"
  535. }
  536. }
  537. }
  538. return gcpPricingList, nextPageToken, nil
  539. }
  540. func (gcp *GCP) parsePages(inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, error) {
  541. var pages []map[string]*GCPPricing
  542. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey
  543. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  544. var parsePagesHelper func(string) error
  545. parsePagesHelper = func(pageToken string) error {
  546. if pageToken == "done" {
  547. return nil
  548. } else if pageToken != "" {
  549. url = url + "&pageToken=" + pageToken
  550. }
  551. resp, err := http.Get(url)
  552. if err != nil {
  553. return err
  554. }
  555. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  556. if err != nil {
  557. return err
  558. }
  559. pages = append(pages, page)
  560. return parsePagesHelper(token)
  561. }
  562. err := parsePagesHelper("")
  563. if err != nil {
  564. return nil, err
  565. }
  566. returnPages := make(map[string]*GCPPricing)
  567. for _, page := range pages {
  568. klog.V(1).Infof("Page: %s : %+v", page)
  569. for k, v := range page {
  570. klog.V(1).Infof("Unmerged Page: %s : %+v", k, v)
  571. }
  572. }
  573. for _, page := range pages {
  574. for k, v := range page {
  575. if val, ok := returnPages[k]; ok { //keys may need to be merged
  576. if val.Node != nil {
  577. if val.Node.VCPUCost == "" {
  578. val.Node.VCPUCost = v.Node.VCPUCost
  579. }
  580. if val.Node.RAMCost == "" {
  581. val.Node.RAMCost = v.Node.RAMCost
  582. }
  583. if val.Node.GPUCost == "" {
  584. val.Node.GPUCost = v.Node.GPUCost
  585. }
  586. }
  587. if val.PV != nil {
  588. if val.PV.Cost == "" {
  589. val.PV.Cost = v.PV.Cost
  590. }
  591. }
  592. } else {
  593. returnPages[k] = v
  594. }
  595. }
  596. }
  597. klog.V(1).Infof("ALL PAGES: %+v", returnPages)
  598. for k, v := range returnPages {
  599. klog.V(1).Infof("Returned Page: %s : %+v", k, v.Node)
  600. }
  601. return returnPages, err
  602. }
  603. // 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.
  604. func (gcp *GCP) DownloadPricingData() error {
  605. gcp.DownloadPricingDataLock.Lock()
  606. defer gcp.DownloadPricingDataLock.Unlock()
  607. c, err := GetDefaultPricingData("gcp.json")
  608. if err != nil {
  609. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  610. return err
  611. }
  612. gcp.BaseCPUPrice = c.CPU
  613. gcp.ProjectID = c.ProjectID
  614. gcp.BillingDataDataset = c.BillingDataDataset
  615. nodeList, err := gcp.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  616. if err != nil {
  617. return err
  618. }
  619. inputkeys := make(map[string]Key)
  620. for _, n := range nodeList.Items {
  621. labels := n.GetObjectMeta().GetLabels()
  622. key := gcp.GetKey(labels)
  623. inputkeys[key.Features()] = key
  624. }
  625. pvList, err := gcp.Clientset.CoreV1().PersistentVolumes().List(metav1.ListOptions{})
  626. if err != nil {
  627. return err
  628. }
  629. storageClasses, err := gcp.Clientset.StorageV1().StorageClasses().List(metav1.ListOptions{})
  630. storageClassMap := make(map[string]map[string]string)
  631. for _, storageClass := range storageClasses.Items {
  632. params := storageClass.Parameters
  633. storageClassMap[storageClass.ObjectMeta.Name] = params
  634. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  635. storageClassMap["default"] = params
  636. storageClassMap[""] = params
  637. }
  638. }
  639. pvkeys := make(map[string]PVKey)
  640. for _, pv := range pvList.Items {
  641. params, ok := storageClassMap[pv.Spec.StorageClassName]
  642. if !ok {
  643. klog.Infof("Unable to find params for storageClassName %s", pv.Name)
  644. continue
  645. }
  646. key := gcp.GetPVKey(&pv, params)
  647. pvkeys[key.Features()] = key
  648. }
  649. pages, err := gcp.parsePages(inputkeys, pvkeys)
  650. if err != nil {
  651. return err
  652. }
  653. gcp.Pricing = pages
  654. return nil
  655. }
  656. func (gcp *GCP) PVPricing(pvk PVKey) (*PV, error) {
  657. gcp.DownloadPricingDataLock.RLock()
  658. defer gcp.DownloadPricingDataLock.RUnlock()
  659. pricing, ok := gcp.Pricing[pvk.Features()]
  660. if !ok {
  661. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  662. return &PV{}, nil
  663. }
  664. return pricing.PV, nil
  665. }
  666. // Stubbed NetworkPricing for GCP. Pull directly from gcp.json for now
  667. func (c *GCP) NetworkPricing() (*Network, error) {
  668. cpricing, err := GetDefaultPricingData("gcp.json")
  669. if err != nil {
  670. return nil, err
  671. }
  672. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  673. if err != nil {
  674. return nil, err
  675. }
  676. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  677. if err != nil {
  678. return nil, err
  679. }
  680. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  681. if err != nil {
  682. return nil, err
  683. }
  684. return &Network{
  685. ZoneNetworkEgressCost: znec,
  686. RegionNetworkEgressCost: rnec,
  687. InternetNetworkEgressCost: inec,
  688. }, nil
  689. }
  690. type pvKey struct {
  691. Labels map[string]string
  692. StorageClass string
  693. StorageClassParameters map[string]string
  694. }
  695. func (key *pvKey) GetStorageClass() string {
  696. return key.StorageClass
  697. }
  698. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  699. return &pvKey{
  700. Labels: pv.Labels,
  701. StorageClass: pv.Spec.StorageClassName,
  702. StorageClassParameters: parameters,
  703. }
  704. }
  705. func (key *pvKey) Features() string {
  706. // TODO: regional cluster pricing.
  707. storageClass := key.StorageClassParameters["type"]
  708. if storageClass == "pd-ssd" {
  709. storageClass = "ssd"
  710. } else if storageClass == "pd-standard" {
  711. storageClass = "pdstandard"
  712. }
  713. return key.Labels[v1.LabelZoneRegion] + "," + storageClass
  714. }
  715. type gcpKey struct {
  716. Labels map[string]string
  717. }
  718. func (gcp *GCP) GetKey(labels map[string]string) Key {
  719. return &gcpKey{
  720. Labels: labels,
  721. }
  722. }
  723. func (gcp *gcpKey) ID() string {
  724. return ""
  725. }
  726. func (gcp *gcpKey) GPUType() string {
  727. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  728. var usageType string
  729. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  730. usageType = "preemptible"
  731. } else {
  732. usageType = "ondemand"
  733. }
  734. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  735. return t + "," + usageType
  736. }
  737. return ""
  738. }
  739. // GetKey maps node labels to information needed to retrieve pricing data
  740. func (gcp *gcpKey) Features() string {
  741. instanceType := strings.ToLower(strings.Join(strings.Split(gcp.Labels[v1.LabelInstanceType], "-")[:2], ""))
  742. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  743. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  744. } else if strings.HasPrefix(instanceType, "custom") {
  745. instanceType = "custom" // The suffix of custom does not matter
  746. }
  747. region := strings.ToLower(gcp.Labels[v1.LabelZoneRegion])
  748. var usageType string
  749. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  750. usageType = "preemptible"
  751. } else {
  752. usageType = "ondemand"
  753. }
  754. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  755. return region + "," + instanceType + "," + usageType + "," + "gpu"
  756. }
  757. return region + "," + instanceType + "," + usageType
  758. }
  759. // AllNodePricing returns the GCP pricing objects stored
  760. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  761. gcp.DownloadPricingDataLock.RLock()
  762. defer gcp.DownloadPricingDataLock.RUnlock()
  763. return gcp.Pricing, nil
  764. }
  765. // NodePricing returns GCP pricing data for a single node
  766. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  767. gcp.DownloadPricingDataLock.RLock()
  768. defer gcp.DownloadPricingDataLock.RUnlock()
  769. if n, ok := gcp.Pricing[key.Features()]; ok {
  770. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  771. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  772. return n.Node, nil
  773. }
  774. klog.V(1).Infof("Warning: no pricing data found for %s: %s", key.Features(), key)
  775. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  776. }