gcpprovider.go 28 KB

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