gcpprovider.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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. if c.NegotiatedDiscount == "" {
  84. c.NegotiatedDiscount = "0%"
  85. }
  86. return c, nil
  87. }
  88. type BigQueryConfig struct {
  89. ProjectID string `json:"projectID"`
  90. BillingDataDataset string `json:"billingDataDataset"`
  91. Key map[string]string `json:"key"`
  92. }
  93. func (gcp *GCP) GetManagementPlatform() (string, error) {
  94. nodes := gcp.Clientset.GetAllNodes()
  95. if len(nodes) > 0 {
  96. n := nodes[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. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "N2") {
  394. instanceType = "n2standard"
  395. }
  396. /*
  397. var partialCPU float64
  398. if strings.ToLower(instanceType) == "f1micro" {
  399. partialCPU = 0.2
  400. } else if strings.ToLower(instanceType) == "g1small" {
  401. partialCPU = 0.5
  402. }
  403. */
  404. var gpuType string
  405. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  406. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  407. if matchnum == 1 {
  408. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  409. klog.V(4).Info("GPU type found: " + gpuType)
  410. }
  411. }
  412. for _, sr := range product.ServiceRegions {
  413. region := sr
  414. candidateKey := region + "," + instanceType + "," + usageType
  415. candidateKeyGPU := candidateKey + ",gpu"
  416. if gpuType != "" {
  417. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  418. var nanos float64
  419. if len(product.PricingInfo) > 0 {
  420. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  421. } else {
  422. continue
  423. }
  424. hourlyPrice := nanos * math.Pow10(-9)
  425. for k, key := range inputKeys {
  426. if key.GPUType() == gpuType+","+usageType {
  427. if region == strings.Split(k, ",")[0] {
  428. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  429. matchedKey := key.Features()
  430. if pl, ok := gcpPricingList[matchedKey]; ok {
  431. pl.Node.GPUName = gpuType
  432. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  433. pl.Node.GPU = "1"
  434. } else {
  435. product.Node = &Node{
  436. GPUName: gpuType,
  437. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  438. GPU: "1",
  439. }
  440. gcpPricingList[matchedKey] = product
  441. }
  442. klog.V(3).Infof("Added data for " + matchedKey)
  443. }
  444. }
  445. }
  446. } else {
  447. _, ok := inputKeys[candidateKey]
  448. _, ok2 := inputKeys[candidateKeyGPU]
  449. if ok || ok2 {
  450. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  451. var nanos float64
  452. if len(product.PricingInfo) > 0 {
  453. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  454. } else {
  455. continue
  456. }
  457. hourlyPrice := nanos * math.Pow10(-9)
  458. if hourlyPrice == 0 {
  459. continue
  460. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  461. if instanceType == "custom" {
  462. klog.V(4).Infof("RAM custom sku is: " + product.Name)
  463. }
  464. if _, ok := gcpPricingList[candidateKey]; ok {
  465. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  466. } else {
  467. product = &GCPPricing{}
  468. product.Node = &Node{
  469. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  470. }
  471. /*
  472. if partialCPU != 0 {
  473. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  474. }
  475. */
  476. product.Node.UsageType = usageType
  477. gcpPricingList[candidateKey] = product
  478. }
  479. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  480. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  481. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  482. } else {
  483. klog.V(1).Infof("Adding RAM %f for %s", hourlyPrice, candidateKeyGPU)
  484. product = &GCPPricing{}
  485. product.Node = &Node{
  486. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  487. }
  488. /*
  489. if partialCPU != 0 {
  490. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  491. }
  492. */
  493. product.Node.UsageType = usageType
  494. gcpPricingList[candidateKeyGPU] = product
  495. }
  496. break
  497. } else {
  498. if _, ok := gcpPricingList[candidateKey]; ok {
  499. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  500. } else {
  501. product = &GCPPricing{}
  502. product.Node = &Node{
  503. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  504. }
  505. /*
  506. if partialCPU != 0 {
  507. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  508. }
  509. */
  510. product.Node.UsageType = usageType
  511. gcpPricingList[candidateKey] = product
  512. }
  513. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  514. gcpPricingList[candidateKeyGPU].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  515. } else {
  516. product = &GCPPricing{}
  517. product.Node = &Node{
  518. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  519. }
  520. /*
  521. if partialCPU != 0 {
  522. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  523. }
  524. */
  525. product.Node.UsageType = usageType
  526. gcpPricingList[candidateKeyGPU] = product
  527. }
  528. break
  529. }
  530. }
  531. }
  532. }
  533. }
  534. }
  535. if t == "nextPageToken" {
  536. pageToken, err := dec.Token()
  537. if err != nil {
  538. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  539. return nil, "", err
  540. }
  541. if pageToken.(string) != "" {
  542. nextPageToken = pageToken.(string)
  543. } else {
  544. nextPageToken = "done"
  545. }
  546. }
  547. }
  548. return gcpPricingList, nextPageToken, nil
  549. }
  550. func (gcp *GCP) parsePages(inputKeys map[string]Key, pvKeys map[string]PVKey) (map[string]*GCPPricing, error) {
  551. var pages []map[string]*GCPPricing
  552. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey
  553. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  554. var parsePagesHelper func(string) error
  555. parsePagesHelper = func(pageToken string) error {
  556. if pageToken == "done" {
  557. return nil
  558. } else if pageToken != "" {
  559. url = url + "&pageToken=" + pageToken
  560. }
  561. resp, err := http.Get(url)
  562. if err != nil {
  563. return err
  564. }
  565. page, token, err := gcp.parsePage(resp.Body, inputKeys, pvKeys)
  566. if err != nil {
  567. return err
  568. }
  569. pages = append(pages, page)
  570. return parsePagesHelper(token)
  571. }
  572. err := parsePagesHelper("")
  573. if err != nil {
  574. return nil, err
  575. }
  576. returnPages := make(map[string]*GCPPricing)
  577. for _, page := range pages {
  578. for k, v := range page {
  579. if val, ok := returnPages[k]; ok { //keys may need to be merged
  580. if val.Node != nil {
  581. if val.Node.VCPUCost == "" {
  582. val.Node.VCPUCost = v.Node.VCPUCost
  583. }
  584. if val.Node.RAMCost == "" {
  585. val.Node.RAMCost = v.Node.RAMCost
  586. }
  587. if val.Node.GPUCost == "" {
  588. val.Node.GPUCost = v.Node.GPUCost
  589. }
  590. }
  591. if val.PV != nil {
  592. if val.PV.Cost == "" {
  593. val.PV.Cost = v.PV.Cost
  594. }
  595. }
  596. } else {
  597. returnPages[k] = v
  598. }
  599. }
  600. }
  601. klog.V(1).Infof("ALL PAGES: %+v", returnPages)
  602. for k, v := range returnPages {
  603. klog.V(1).Infof("Returned Page: %s : %+v", k, v.Node)
  604. }
  605. return returnPages, err
  606. }
  607. // 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.
  608. func (gcp *GCP) DownloadPricingData() error {
  609. gcp.DownloadPricingDataLock.Lock()
  610. defer gcp.DownloadPricingDataLock.Unlock()
  611. c, err := GetDefaultPricingData("gcp.json")
  612. if err != nil {
  613. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  614. return err
  615. }
  616. gcp.BaseCPUPrice = c.CPU
  617. gcp.ProjectID = c.ProjectID
  618. gcp.BillingDataDataset = c.BillingDataDataset
  619. nodeList := gcp.Clientset.GetAllNodes()
  620. inputkeys := make(map[string]Key)
  621. for _, n := range nodeList {
  622. labels := n.GetObjectMeta().GetLabels()
  623. key := gcp.GetKey(labels)
  624. inputkeys[key.Features()] = key
  625. }
  626. pvList := gcp.Clientset.GetAllPersistentVolumes()
  627. storageClasses := gcp.Clientset.GetAllStorageClasses()
  628. storageClassMap := make(map[string]map[string]string)
  629. for _, storageClass := range storageClasses {
  630. params := storageClass.Parameters
  631. storageClassMap[storageClass.ObjectMeta.Name] = params
  632. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  633. storageClassMap["default"] = params
  634. storageClassMap[""] = params
  635. }
  636. }
  637. pvkeys := make(map[string]PVKey)
  638. for _, pv := range pvList {
  639. params, ok := storageClassMap[pv.Spec.StorageClassName]
  640. if !ok {
  641. klog.Infof("Unable to find params for storageClassName %s", pv.Name)
  642. continue
  643. }
  644. key := gcp.GetPVKey(pv, params)
  645. pvkeys[key.Features()] = key
  646. }
  647. reserved, err := gcp.getReservedInstances()
  648. if err != nil {
  649. klog.V(1).Infof("Failed to lookup reserved instance data: %s", err.Error())
  650. } else {
  651. klog.V(1).Infof("Found %d reserved instances", len(reserved))
  652. gcp.ReservedInstances = reserved
  653. for _, r := range reserved {
  654. klog.V(1).Infof("%s", r)
  655. }
  656. }
  657. pages, err := gcp.parsePages(inputkeys, pvkeys)
  658. if err != nil {
  659. return err
  660. }
  661. gcp.Pricing = pages
  662. return nil
  663. }
  664. func (gcp *GCP) PVPricing(pvk PVKey) (*PV, error) {
  665. gcp.DownloadPricingDataLock.RLock()
  666. defer gcp.DownloadPricingDataLock.RUnlock()
  667. pricing, ok := gcp.Pricing[pvk.Features()]
  668. if !ok {
  669. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  670. return &PV{}, nil
  671. }
  672. return pricing.PV, nil
  673. }
  674. // Stubbed NetworkPricing for GCP. Pull directly from gcp.json for now
  675. func (c *GCP) NetworkPricing() (*Network, error) {
  676. cpricing, err := GetDefaultPricingData("gcp.json")
  677. if err != nil {
  678. return nil, err
  679. }
  680. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  681. if err != nil {
  682. return nil, err
  683. }
  684. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  685. if err != nil {
  686. return nil, err
  687. }
  688. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  689. if err != nil {
  690. return nil, err
  691. }
  692. return &Network{
  693. ZoneNetworkEgressCost: znec,
  694. RegionNetworkEgressCost: rnec,
  695. InternetNetworkEgressCost: inec,
  696. }, nil
  697. }
  698. const (
  699. GCPReservedInstanceResourceTypeRAM string = "MEMORY"
  700. GCPReservedInstanceResourceTypeCPU string = "VCPU"
  701. GCPReservedInstanceStatusActive string = "ACTIVE"
  702. GCPReservedInstancePlanOneYear string = "TWELVE_MONTH"
  703. GCPReservedInstancePlanThreeYear string = "THIRTY_SIX_MONTH"
  704. )
  705. type GCPReservedInstancePlan struct {
  706. Name string
  707. CPUCost float64
  708. RAMCost float64
  709. }
  710. type GCPReservedInstance struct {
  711. ReservedRAM int64
  712. ReservedCPU int64
  713. Plan *GCPReservedInstancePlan
  714. StartDate time.Time
  715. EndDate time.Time
  716. Region string
  717. }
  718. func (r *GCPReservedInstance) String() string {
  719. return fmt.Sprintf("[CPU: %d, RAM: %d, Region: %s, Start: %s, End: %s]", r.ReservedCPU, r.ReservedRAM, r.Region, r.StartDate.String(), r.EndDate.String())
  720. }
  721. type GCPReservedCounter struct {
  722. RemainingCPU int64
  723. RemainingRAM int64
  724. Instance *GCPReservedInstance
  725. }
  726. func newReservedCounter(instance *GCPReservedInstance) *GCPReservedCounter {
  727. return &GCPReservedCounter{
  728. RemainingCPU: instance.ReservedCPU,
  729. RemainingRAM: instance.ReservedRAM,
  730. Instance: instance,
  731. }
  732. }
  733. // Two available Reservation plans for GCP, 1-year and 3-year
  734. var gcpReservedInstancePlans map[string]*GCPReservedInstancePlan = map[string]*GCPReservedInstancePlan{
  735. GCPReservedInstancePlanOneYear: &GCPReservedInstancePlan{
  736. Name: GCPReservedInstancePlanOneYear,
  737. CPUCost: 0.019915,
  738. RAMCost: 0.002669,
  739. },
  740. GCPReservedInstancePlanThreeYear: &GCPReservedInstancePlan{
  741. Name: GCPReservedInstancePlanThreeYear,
  742. CPUCost: 0.014225,
  743. RAMCost: 0.001907,
  744. },
  745. }
  746. func (gcp *GCP) ApplyReservedInstancePricing(nodes map[string]*Node) {
  747. numReserved := len(gcp.ReservedInstances)
  748. // Early return if no reserved instance data loaded
  749. if numReserved == 0 {
  750. klog.V(1).Infof("[Reserved] No Reserved Instances")
  751. return
  752. }
  753. now := time.Now()
  754. counters := make(map[string][]*GCPReservedCounter)
  755. for _, r := range gcp.ReservedInstances {
  756. if now.Before(r.StartDate) || now.After(r.EndDate) {
  757. klog.V(1).Infof("[Reserved] Skipped Reserved Instance due to dates")
  758. continue
  759. }
  760. _, ok := counters[r.Region]
  761. counter := newReservedCounter(r)
  762. if !ok {
  763. counters[r.Region] = []*GCPReservedCounter{counter}
  764. } else {
  765. counters[r.Region] = append(counters[r.Region], counter)
  766. }
  767. }
  768. gcpNodes := make(map[string]*v1.Node)
  769. currentNodes := gcp.Clientset.GetAllNodes()
  770. // Create a node name -> node map
  771. for _, gcpNode := range currentNodes {
  772. gcpNodes[gcpNode.GetName()] = gcpNode
  773. }
  774. // go through all provider nodes using k8s nodes for region
  775. for nodeName, node := range nodes {
  776. // Reset reserved allocation to prevent double allocation
  777. node.Reserved = nil
  778. kNode, ok := gcpNodes[nodeName]
  779. if !ok {
  780. klog.V(1).Infof("[Reserved] Could not find K8s Node with name: %s", nodeName)
  781. continue
  782. }
  783. nodeRegion, ok := kNode.Labels[v1.LabelZoneRegion]
  784. if !ok {
  785. klog.V(1).Infof("[Reserved] Could not find node region")
  786. continue
  787. }
  788. reservedCounters, ok := counters[nodeRegion]
  789. if !ok {
  790. klog.V(1).Infof("[Reserved] Could not find counters for region: %s", nodeRegion)
  791. continue
  792. }
  793. node.Reserved = &ReservedInstanceData{
  794. ReservedCPU: 0,
  795. ReservedRAM: 0,
  796. }
  797. for _, reservedCounter := range reservedCounters {
  798. if reservedCounter.RemainingCPU != 0 {
  799. nodeCPU, _ := strconv.ParseInt(node.VCPU, 10, 64)
  800. nodeCPU -= node.Reserved.ReservedCPU
  801. node.Reserved.CPUCost = reservedCounter.Instance.Plan.CPUCost
  802. if reservedCounter.RemainingCPU >= nodeCPU {
  803. reservedCounter.RemainingCPU -= nodeCPU
  804. node.Reserved.ReservedCPU += nodeCPU
  805. } else {
  806. node.Reserved.ReservedCPU += reservedCounter.RemainingCPU
  807. reservedCounter.RemainingCPU = 0
  808. }
  809. }
  810. if reservedCounter.RemainingRAM != 0 {
  811. nodeRAMF, _ := strconv.ParseFloat(node.RAMBytes, 64)
  812. nodeRAM := int64(nodeRAMF)
  813. nodeRAM -= node.Reserved.ReservedRAM
  814. node.Reserved.RAMCost = reservedCounter.Instance.Plan.RAMCost
  815. if reservedCounter.RemainingRAM >= nodeRAM {
  816. reservedCounter.RemainingRAM -= nodeRAM
  817. node.Reserved.ReservedRAM += nodeRAM
  818. } else {
  819. node.Reserved.ReservedRAM += reservedCounter.RemainingRAM
  820. reservedCounter.RemainingRAM = 0
  821. }
  822. }
  823. }
  824. }
  825. }
  826. func (gcp *GCP) getReservedInstances() ([]*GCPReservedInstance, error) {
  827. var results []*GCPReservedInstance
  828. ctx := context.Background()
  829. computeService, err := compute.NewService(ctx)
  830. if err != nil {
  831. return nil, err
  832. }
  833. commitments, err := computeService.RegionCommitments.AggregatedList(gcp.ProjectID).Do()
  834. if err != nil {
  835. return nil, err
  836. }
  837. for regionKey, commitList := range commitments.Items {
  838. for _, commit := range commitList.Commitments {
  839. if commit.Status != GCPReservedInstanceStatusActive {
  840. continue
  841. }
  842. var vcpu int64 = 0
  843. var ram int64 = 0
  844. for _, resource := range commit.Resources {
  845. switch resource.Type {
  846. case GCPReservedInstanceResourceTypeRAM:
  847. ram = resource.Amount * 1024 * 1024
  848. case GCPReservedInstanceResourceTypeCPU:
  849. vcpu = resource.Amount
  850. default:
  851. klog.V(4).Infof("Failed to handle resource type: %s", resource.Type)
  852. }
  853. }
  854. var region string
  855. regionStr := strings.Split(regionKey, "/")
  856. if len(regionStr) == 2 {
  857. region = regionStr[1]
  858. }
  859. timeLayout := "2006-01-02T15:04:05Z07:00"
  860. startTime, err := time.Parse(timeLayout, commit.StartTimestamp)
  861. if err != nil {
  862. klog.V(1).Infof("Failed to parse start date: %s", commit.StartTimestamp)
  863. continue
  864. }
  865. endTime, err := time.Parse(timeLayout, commit.EndTimestamp)
  866. if err != nil {
  867. klog.V(1).Infof("Failed to parse end date: %s", commit.EndTimestamp)
  868. continue
  869. }
  870. // Look for a plan based on the name. Default to One Year if it fails
  871. plan, ok := gcpReservedInstancePlans[commit.Plan]
  872. if !ok {
  873. plan = gcpReservedInstancePlans[GCPReservedInstancePlanOneYear]
  874. }
  875. results = append(results, &GCPReservedInstance{
  876. Region: region,
  877. ReservedRAM: ram,
  878. ReservedCPU: vcpu,
  879. Plan: plan,
  880. StartDate: startTime,
  881. EndDate: endTime,
  882. })
  883. }
  884. }
  885. return results, nil
  886. }
  887. type pvKey struct {
  888. Labels map[string]string
  889. StorageClass string
  890. StorageClassParameters map[string]string
  891. }
  892. func (key *pvKey) GetStorageClass() string {
  893. return key.StorageClass
  894. }
  895. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  896. return &pvKey{
  897. Labels: pv.Labels,
  898. StorageClass: pv.Spec.StorageClassName,
  899. StorageClassParameters: parameters,
  900. }
  901. }
  902. func (key *pvKey) Features() string {
  903. // TODO: regional cluster pricing.
  904. storageClass := key.StorageClassParameters["type"]
  905. if storageClass == "pd-ssd" {
  906. storageClass = "ssd"
  907. } else if storageClass == "pd-standard" {
  908. storageClass = "pdstandard"
  909. }
  910. return key.Labels[v1.LabelZoneRegion] + "," + storageClass
  911. }
  912. type gcpKey struct {
  913. Labels map[string]string
  914. }
  915. func (gcp *GCP) GetKey(labels map[string]string) Key {
  916. return &gcpKey{
  917. Labels: labels,
  918. }
  919. }
  920. func (gcp *gcpKey) ID() string {
  921. return ""
  922. }
  923. func (gcp *gcpKey) GPUType() string {
  924. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  925. var usageType string
  926. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  927. usageType = "preemptible"
  928. } else {
  929. usageType = "ondemand"
  930. }
  931. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  932. return t + "," + usageType
  933. }
  934. return ""
  935. }
  936. // GetKey maps node labels to information needed to retrieve pricing data
  937. func (gcp *gcpKey) Features() string {
  938. instanceType := strings.ToLower(strings.Join(strings.Split(gcp.Labels[v1.LabelInstanceType], "-")[:2], ""))
  939. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  940. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  941. } else if strings.HasPrefix(instanceType, "custom") {
  942. instanceType = "custom" // The suffix of custom does not matter
  943. }
  944. region := strings.ToLower(gcp.Labels[v1.LabelZoneRegion])
  945. var usageType string
  946. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  947. usageType = "preemptible"
  948. } else {
  949. usageType = "ondemand"
  950. }
  951. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  952. return region + "," + instanceType + "," + usageType + "," + "gpu"
  953. }
  954. return region + "," + instanceType + "," + usageType
  955. }
  956. // AllNodePricing returns the GCP pricing objects stored
  957. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  958. gcp.DownloadPricingDataLock.RLock()
  959. defer gcp.DownloadPricingDataLock.RUnlock()
  960. return gcp.Pricing, nil
  961. }
  962. // NodePricing returns GCP pricing data for a single node
  963. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  964. gcp.DownloadPricingDataLock.RLock()
  965. defer gcp.DownloadPricingDataLock.RUnlock()
  966. if n, ok := gcp.Pricing[key.Features()]; ok {
  967. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  968. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  969. return n.Node, nil
  970. }
  971. klog.V(1).Infof("Warning: no pricing data found for %s: %s", key.Features(), key)
  972. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  973. }