gcpprovider.go 31 KB

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