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(offset string) (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="/"} %s) by (instance, cluster_id)) by (cluster_id) / 1024 / 1024 / 1024 * %f`, offset, 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(clusterIDKey), 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 = "%s"
  183. GROUP BY aggregator, environment, service;`, c.BillingDataDataset, start, end, aggregator) // 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. remote := os.Getenv(remoteEnabled)
  220. remoteEnabled := false
  221. if os.Getenv(remote) == "true" {
  222. remoteEnabled = true
  223. }
  224. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  225. userAgent: "kubecost",
  226. base: http.DefaultTransport,
  227. }})
  228. attribute, err := metadataClient.InstanceAttributeValue("cluster-name")
  229. if err != nil {
  230. return nil, err
  231. }
  232. c, err := gcp.GetConfig()
  233. if err != nil {
  234. klog.V(1).Infof("Error opening config: %s", err.Error())
  235. }
  236. if c.ClusterName != "" {
  237. attribute = c.ClusterName
  238. }
  239. m := make(map[string]string)
  240. m["name"] = attribute
  241. m["provider"] = "GCP"
  242. m["id"] = os.Getenv(clusterIDKey)
  243. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  244. return m, nil
  245. }
  246. // AddServiceKey adds the service key as required for GetDisks
  247. func (*GCP) AddServiceKey(formValues url.Values) error {
  248. key := formValues.Get("key")
  249. k := []byte(key)
  250. return ioutil.WriteFile("/var/configs/key.json", k, 0644)
  251. }
  252. // 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.
  253. func (*GCP) GetDisks() ([]byte, error) {
  254. // metadata API setup
  255. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  256. userAgent: "kubecost",
  257. base: http.DefaultTransport,
  258. }})
  259. projID, err := metadataClient.ProjectID()
  260. if err != nil {
  261. return nil, err
  262. }
  263. client, err := google.DefaultClient(oauth2.NoContext,
  264. "https://www.googleapis.com/auth/compute.readonly")
  265. if err != nil {
  266. return nil, err
  267. }
  268. svc, err := compute.New(client)
  269. if err != nil {
  270. return nil, err
  271. }
  272. res, err := svc.Disks.AggregatedList(projID).Do()
  273. if err != nil {
  274. return nil, err
  275. }
  276. return json.Marshal(res)
  277. }
  278. // GCPPricing represents GCP pricing data for a SKU
  279. type GCPPricing struct {
  280. Name string `json:"name"`
  281. SKUID string `json:"skuId"`
  282. Description string `json:"description"`
  283. Category *GCPResourceInfo `json:"category"`
  284. ServiceRegions []string `json:"serviceRegions"`
  285. PricingInfo []*PricingInfo `json:"pricingInfo"`
  286. ServiceProviderName string `json:"serviceProviderName"`
  287. Node *Node `json:"node"`
  288. PV *PV `json:"pv"`
  289. }
  290. // PricingInfo contains metadata about a cost.
  291. type PricingInfo struct {
  292. Summary string `json:"summary"`
  293. PricingExpression *PricingExpression `json:"pricingExpression"`
  294. CurrencyConversionRate int `json:"currencyConversionRate"`
  295. EffectiveTime string `json:""`
  296. }
  297. // PricingExpression contains metadata about a cost.
  298. type PricingExpression struct {
  299. UsageUnit string `json:"usageUnit"`
  300. UsageUnitDescription string `json:"usageUnitDescription"`
  301. BaseUnit string `json:"baseUnit"`
  302. BaseUnitConversionFactor int64 `json:"-"`
  303. DisplayQuantity int `json:"displayQuantity"`
  304. TieredRates []*TieredRates `json:"tieredRates"`
  305. }
  306. // TieredRates contain data about variable pricing.
  307. type TieredRates struct {
  308. StartUsageAmount int `json:"startUsageAmount"`
  309. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  310. }
  311. // UnitPriceInfo contains data about the actual price being charged.
  312. type UnitPriceInfo struct {
  313. CurrencyCode string `json:"currencyCode"`
  314. Units string `json:"units"`
  315. Nanos float64 `json:"nanos"`
  316. }
  317. // GCPResourceInfo contains metadata about the node.
  318. type GCPResourceInfo struct {
  319. ServiceDisplayName string `json:"serviceDisplayName"`
  320. ResourceFamily string `json:"resourceFamily"`
  321. ResourceGroup string `json:"resourceGroup"`
  322. UsageType string `json:"usageType"`
  323. }
  324. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, string, error) {
  325. gcpPricingList := make(map[string]*GCPPricing)
  326. var nextPageToken string
  327. dec := json.NewDecoder(r)
  328. for {
  329. t, err := dec.Token()
  330. if err == io.EOF {
  331. break
  332. }
  333. if t == "skus" {
  334. _, err := dec.Token() // consumes [
  335. if err != nil {
  336. return nil, "", err
  337. }
  338. for dec.More() {
  339. product := &GCPPricing{}
  340. err := dec.Decode(&product)
  341. if err != nil {
  342. return nil, "", err
  343. }
  344. usageType := strings.ToLower(product.Category.UsageType)
  345. instanceType := strings.ToLower(product.Category.ResourceGroup)
  346. if instanceType == "ssd" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  347. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  348. var nanos float64
  349. if len(product.PricingInfo) > 0 {
  350. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  351. } else {
  352. continue
  353. }
  354. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  355. for _, sr := range product.ServiceRegions {
  356. region := sr
  357. candidateKey := region + "," + "ssd"
  358. if _, ok := pvKeys[candidateKey]; ok {
  359. product.PV = &PV{
  360. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  361. }
  362. gcpPricingList[candidateKey] = product
  363. continue
  364. }
  365. }
  366. continue
  367. } else if instanceType == "pdstandard" && !strings.Contains(product.Description, "Regional") { // TODO: support regional
  368. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  369. var nanos float64
  370. if len(product.PricingInfo) > 0 {
  371. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  372. } else {
  373. continue
  374. }
  375. hourlyPrice := (nanos * math.Pow10(-9)) / 730
  376. for _, sr := range product.ServiceRegions {
  377. region := sr
  378. candidateKey := region + "," + "pdstandard"
  379. if _, ok := pvKeys[candidateKey]; ok {
  380. product.PV = &PV{
  381. Cost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  382. }
  383. gcpPricingList[candidateKey] = product
  384. continue
  385. }
  386. }
  387. continue
  388. }
  389. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  390. instanceType = "custom"
  391. }
  392. /*
  393. var partialCPU float64
  394. if strings.ToLower(instanceType) == "f1micro" {
  395. partialCPU = 0.2
  396. } else if strings.ToLower(instanceType) == "g1small" {
  397. partialCPU = 0.5
  398. }
  399. */
  400. var gpuType string
  401. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  402. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  403. if matchnum == 1 {
  404. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  405. klog.V(4).Info("GPU type found: " + gpuType)
  406. }
  407. }
  408. for _, sr := range product.ServiceRegions {
  409. region := sr
  410. candidateKey := region + "," + instanceType + "," + usageType
  411. candidateKeyGPU := candidateKey + ",gpu"
  412. if gpuType != "" {
  413. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  414. var nanos float64
  415. if len(product.PricingInfo) > 0 {
  416. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  417. } else {
  418. continue
  419. }
  420. hourlyPrice := nanos * math.Pow10(-9)
  421. for k, key := range inputKeys {
  422. if key.GPUType() == gpuType+","+usageType {
  423. if region == strings.Split(k, ",")[0] {
  424. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  425. matchedKey := key.Features()
  426. if pl, ok := gcpPricingList[matchedKey]; ok {
  427. pl.Node.GPUName = gpuType
  428. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  429. pl.Node.GPU = "1"
  430. } else {
  431. product.Node = &Node{
  432. GPUName: gpuType,
  433. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  434. GPU: "1",
  435. }
  436. gcpPricingList[matchedKey] = product
  437. }
  438. klog.V(3).Infof("Added data for " + matchedKey)
  439. }
  440. }
  441. }
  442. } else {
  443. _, ok := inputKeys[candidateKey]
  444. _, ok2 := inputKeys[candidateKeyGPU]
  445. if ok || ok2 {
  446. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  447. var nanos float64
  448. if len(product.PricingInfo) > 0 {
  449. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  450. } else {
  451. continue
  452. }
  453. hourlyPrice := nanos * math.Pow10(-9)
  454. if hourlyPrice == 0 {
  455. continue
  456. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  457. if instanceType == "custom" {
  458. klog.V(4).Infof("RAM custom sku is: " + product.Name)
  459. }
  460. if _, ok := gcpPricingList[candidateKey]; ok {
  461. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  462. } else {
  463. product = &GCPPricing{}
  464. product.Node = &Node{
  465. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  466. }
  467. /*
  468. if partialCPU != 0 {
  469. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  470. }
  471. */
  472. product.Node.UsageType = usageType
  473. gcpPricingList[candidateKey] = product
  474. }
  475. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  476. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  477. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  478. } else {
  479. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  480. product = &GCPPricing{}
  481. product.Node = &Node{
  482. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  483. }
  484. /*
  485. if partialCPU != 0 {
  486. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  487. }
  488. */
  489. product.Node.UsageType = usageType
  490. gcpPricingList[candidateKeyGPU] = product
  491. }
  492. break
  493. } else {
  494. if _, ok := gcpPricingList[candidateKey]; ok {
  495. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  496. } else {
  497. product = &GCPPricing{}
  498. product.Node = &Node{
  499. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  500. }
  501. /*
  502. if partialCPU != 0 {
  503. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  504. }
  505. */
  506. product.Node.UsageType = usageType
  507. gcpPricingList[candidateKey] = product
  508. }
  509. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  510. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  511. } else {
  512. product = &GCPPricing{}
  513. product.Node = &Node{
  514. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  515. }
  516. /*
  517. if partialCPU != 0 {
  518. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  519. }
  520. */
  521. product.Node.UsageType = usageType
  522. gcpPricingList[candidateKeyGPU] = product
  523. }
  524. break
  525. }
  526. }
  527. }
  528. }
  529. }
  530. }
  531. if t == "nextPageToken" {
  532. pageToken, err := dec.Token()
  533. if err != nil {
  534. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  535. return nil, "", err
  536. }
  537. if pageToken.(string) != "" {
  538. nextPageToken = pageToken.(string)
  539. } else {
  540. nextPageToken = "done"
  541. }
  542. }
  543. }
  544. return gcpPricingList, nextPageToken, nil
  545. }
  546. func (gcp *GCP) parsePages(inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, error) {
  547. var pages []map[string]*GCPPricing
  548. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey
  549. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  550. var parsePagesHelper func(string) error
  551. parsePagesHelper = func(pageToken string) error {
  552. if pageToken == "done" {
  553. return nil
  554. } else if pageToken != "" {
  555. url = url + "&pageToken=" + pageToken
  556. }
  557. resp, err := http.Get(url)
  558. if err != nil {
  559. return err
  560. }
  561. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  562. if err != nil {
  563. return err
  564. }
  565. pages = append(pages, page)
  566. return parsePagesHelper(token)
  567. }
  568. err := parsePagesHelper("")
  569. if err != nil {
  570. return nil, err
  571. }
  572. returnPages := make(map[string]*GCPPricing)
  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. }