gcpprovider.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "N2") {
  391. instanceType = "n2standard"
  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 := gcp.Clientset.GetAllNodes()
  617. inputkeys := make(map[string]Key)
  618. for _, n := range nodeList {
  619. labels := n.GetObjectMeta().GetLabels()
  620. key := gcp.GetKey(labels)
  621. inputkeys[key.Features()] = key
  622. }
  623. pvList := gcp.Clientset.GetAllPersistentVolumes()
  624. storageClasses := gcp.Clientset.GetAllStorageClasses()
  625. storageClassMap := make(map[string]map[string]string)
  626. for _, storageClass := range storageClasses {
  627. params := storageClass.Parameters
  628. storageClassMap[storageClass.ObjectMeta.Name] = params
  629. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  630. storageClassMap["default"] = params
  631. storageClassMap[""] = params
  632. }
  633. }
  634. pvkeys := make(map[string]PVKey)
  635. for _, pv := range pvList {
  636. params, ok := storageClassMap[pv.Spec.StorageClassName]
  637. if !ok {
  638. klog.Infof("Unable to find params for storageClassName %s", pv.Name)
  639. continue
  640. }
  641. key := gcp.GetPVKey(pv, params)
  642. pvkeys[key.Features()] = key
  643. }
  644. reserved, err := gcp.getReservedInstances()
  645. if err != nil {
  646. klog.V(1).Infof("Failed to lookup reserved instance data: %s", err.Error())
  647. } else {
  648. klog.V(1).Infof("Found %d reserved instances", len(reserved))
  649. gcp.ReservedInstances = reserved
  650. for _, r := range reserved {
  651. 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())
  652. }
  653. }
  654. pages, err := gcp.parsePages(inputkeys, pvkeys)
  655. if err != nil {
  656. return err
  657. }
  658. gcp.Pricing = pages
  659. return nil
  660. }
  661. func (gcp *GCP) PVPricing(pvk PVKey) (*PV, error) {
  662. gcp.DownloadPricingDataLock.RLock()
  663. defer gcp.DownloadPricingDataLock.RUnlock()
  664. pricing, ok := gcp.Pricing[pvk.Features()]
  665. if !ok {
  666. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  667. return &PV{}, nil
  668. }
  669. return pricing.PV, nil
  670. }
  671. // Stubbed NetworkPricing for GCP. Pull directly from gcp.json for now
  672. func (c *GCP) NetworkPricing() (*Network, error) {
  673. cpricing, err := GetDefaultPricingData("gcp.json")
  674. if err != nil {
  675. return nil, err
  676. }
  677. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  678. if err != nil {
  679. return nil, err
  680. }
  681. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  682. if err != nil {
  683. return nil, err
  684. }
  685. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  686. if err != nil {
  687. return nil, err
  688. }
  689. return &Network{
  690. ZoneNetworkEgressCost: znec,
  691. RegionNetworkEgressCost: rnec,
  692. InternetNetworkEgressCost: inec,
  693. }, nil
  694. }
  695. const (
  696. GCPReservedInstanceResourceTypeRAM string = "MEMORY"
  697. GCPReservedInstanceResourceTypeCPU string = "VCPU"
  698. GCPReservedInstanceStatusActive string = "ACTIVE"
  699. GCPReservedInstancePlanOneYear string = "TWELVE_MONTH"
  700. GCPReservedInstancePlanThreeYear string = "THIRTY_SIX_MONTH"
  701. )
  702. type GCPReservedInstancePlan struct {
  703. Name string
  704. CPUCost float64
  705. RAMCost float64
  706. }
  707. type GCPReservedInstance struct {
  708. ReservedRAM int64
  709. ReservedCPU int64
  710. Plan *GCPReservedInstancePlan
  711. StartDate time.Time
  712. EndDate time.Time
  713. Region string
  714. }
  715. type ReservedCounter struct {
  716. RemainingCPU int64
  717. RemainingRAM int64
  718. Instance *GCPReservedInstance
  719. }
  720. func newReservedCounter(instance *GCPReservedInstance) *ReservedCounter {
  721. return &ReservedCounter{
  722. RemainingCPU: instance.ReservedCPU,
  723. RemainingRAM: instance.ReservedRAM,
  724. Instance: instance,
  725. }
  726. }
  727. // Two available Reservation plans for GCP, 1-year and 3-year
  728. var gcpReservedInstancePlans map[string]*GCPReservedInstancePlan = map[string]*GCPReservedInstancePlan{
  729. GCPReservedInstancePlanOneYear: &GCPReservedInstancePlan{
  730. Name: GCPReservedInstancePlanOneYear,
  731. CPUCost: 0.019915,
  732. RAMCost: 0.002669,
  733. },
  734. GCPReservedInstancePlanThreeYear: &GCPReservedInstancePlan{
  735. Name: GCPReservedInstancePlanThreeYear,
  736. CPUCost: 0.014225,
  737. RAMCost: 0.001907,
  738. },
  739. }
  740. func (gcp *GCP) ApplyReservedInstancePricing(nodes map[string]*Node) {
  741. numReserved := len(gcp.ReservedInstances)
  742. // Early return if no reserved instance data loaded
  743. if numReserved == 0 {
  744. klog.V(1).Infof("[Reserved] No Reserved Instances")
  745. return
  746. }
  747. now := time.Now()
  748. counters := make(map[string][]*ReservedCounter)
  749. for _, r := range gcp.ReservedInstances {
  750. if now.Before(r.StartDate) || now.After(r.EndDate) {
  751. klog.V(1).Infof("[Reserved] Skipped Reserved Instance due to dates")
  752. continue
  753. }
  754. _, ok := counters[r.Region]
  755. counter := newReservedCounter(r)
  756. if !ok {
  757. counters[r.Region] = []*ReservedCounter{counter}
  758. } else {
  759. counters[r.Region] = append(counters[r.Region], counter)
  760. }
  761. }
  762. gcpNodes := make(map[string]*v1.Node)
  763. currentNodes := gcp.Clientset.GetAllNodes()
  764. // Create a node name -> node map
  765. for _, gcpNode := range currentNodes {
  766. gcpNodes[gcpNode.GetName()] = gcpNode
  767. }
  768. // go through all provider nodes using k8s nodes for region
  769. for nodeName, node := range nodes {
  770. // Reset reserved allocation to prevent double allocation
  771. node.Reserved = nil
  772. kNode, ok := gcpNodes[nodeName]
  773. if !ok {
  774. klog.V(1).Infof("[Reserved] Could not find K8s Node with name: %s", nodeName)
  775. continue
  776. }
  777. nodeRegion, ok := kNode.Labels[v1.LabelZoneRegion]
  778. if !ok {
  779. klog.V(1).Infof("[Reserved] Could not find node region")
  780. continue
  781. }
  782. reservedCounters, ok := counters[nodeRegion]
  783. if !ok {
  784. klog.V(1).Infof("[Reserved] Could not find counters for region: %s", nodeRegion)
  785. continue
  786. }
  787. node.Reserved = &ReservedInstanceData{
  788. ReservedCPU: 0,
  789. ReservedRAM: 0,
  790. }
  791. for _, reservedCounter := range reservedCounters {
  792. if reservedCounter.RemainingCPU != 0 {
  793. nodeCPU, _ := strconv.ParseInt(node.VCPU, 10, 64)
  794. nodeCPU -= node.Reserved.ReservedCPU
  795. node.Reserved.CPUCost = reservedCounter.Instance.Plan.CPUCost
  796. if reservedCounter.RemainingCPU >= nodeCPU {
  797. reservedCounter.RemainingCPU -= nodeCPU
  798. node.Reserved.ReservedCPU += nodeCPU
  799. } else {
  800. node.Reserved.ReservedCPU += reservedCounter.RemainingCPU
  801. reservedCounter.RemainingCPU = 0
  802. }
  803. }
  804. if reservedCounter.RemainingRAM != 0 {
  805. nodeRAMF, _ := strconv.ParseFloat(node.RAMBytes, 64)
  806. nodeRAM := int64(nodeRAMF)
  807. nodeRAM -= node.Reserved.ReservedRAM
  808. node.Reserved.RAMCost = reservedCounter.Instance.Plan.RAMCost
  809. if reservedCounter.RemainingRAM >= nodeRAM {
  810. reservedCounter.RemainingRAM -= nodeRAM
  811. node.Reserved.ReservedRAM += nodeRAM
  812. } else {
  813. node.Reserved.ReservedRAM += reservedCounter.RemainingRAM
  814. reservedCounter.RemainingRAM = 0
  815. }
  816. }
  817. }
  818. }
  819. }
  820. func (gcp *GCP) getReservedInstances() ([]*GCPReservedInstance, error) {
  821. var results []*GCPReservedInstance
  822. ctx := context.Background()
  823. computeService, err := compute.NewService(ctx)
  824. if err != nil {
  825. return nil, err
  826. }
  827. commitments, err := computeService.RegionCommitments.AggregatedList(gcp.ProjectID).Do()
  828. if err != nil {
  829. return nil, err
  830. }
  831. for regionKey, commitList := range commitments.Items {
  832. for _, commit := range commitList.Commitments {
  833. if commit.Status != GCPReservedInstanceStatusActive {
  834. continue
  835. }
  836. var vcpu int64 = 0
  837. var ram int64 = 0
  838. for _, resource := range commit.Resources {
  839. switch resource.Type {
  840. case GCPReservedInstanceResourceTypeRAM:
  841. ram = resource.Amount * 1024 * 1024
  842. case GCPReservedInstanceResourceTypeCPU:
  843. vcpu = resource.Amount
  844. default:
  845. klog.V(4).Infof("Failed to handle resource type: %s", resource.Type)
  846. }
  847. }
  848. var region string
  849. regionStr := strings.Split(regionKey, "/")
  850. if len(regionStr) == 2 {
  851. region = regionStr[1]
  852. }
  853. timeLayout := "2006-01-02T15:04:05Z07:00"
  854. startTime, err := time.Parse(timeLayout, commit.StartTimestamp)
  855. if err != nil {
  856. klog.V(1).Infof("Failed to parse start date: %s", commit.StartTimestamp)
  857. continue
  858. }
  859. endTime, err := time.Parse(timeLayout, commit.EndTimestamp)
  860. if err != nil {
  861. klog.V(1).Infof("Failed to parse end date: %s", commit.EndTimestamp)
  862. continue
  863. }
  864. // Look for a plan based on the name. Default to One Year if it fails
  865. plan, ok := gcpReservedInstancePlans[commit.Plan]
  866. if !ok {
  867. plan = gcpReservedInstancePlans[GCPReservedInstancePlanOneYear]
  868. }
  869. results = append(results, &GCPReservedInstance{
  870. Region: region,
  871. ReservedRAM: ram,
  872. ReservedCPU: vcpu,
  873. Plan: plan,
  874. StartDate: startTime,
  875. EndDate: endTime,
  876. })
  877. }
  878. }
  879. return results, nil
  880. }
  881. type pvKey struct {
  882. Labels map[string]string
  883. StorageClass string
  884. StorageClassParameters map[string]string
  885. }
  886. func (key *pvKey) GetStorageClass() string {
  887. return key.StorageClass
  888. }
  889. func (gcp *GCP) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  890. return &pvKey{
  891. Labels: pv.Labels,
  892. StorageClass: pv.Spec.StorageClassName,
  893. StorageClassParameters: parameters,
  894. }
  895. }
  896. func (key *pvKey) Features() string {
  897. // TODO: regional cluster pricing.
  898. storageClass := key.StorageClassParameters["type"]
  899. if storageClass == "pd-ssd" {
  900. storageClass = "ssd"
  901. } else if storageClass == "pd-standard" {
  902. storageClass = "pdstandard"
  903. }
  904. return key.Labels[v1.LabelZoneRegion] + "," + storageClass
  905. }
  906. type gcpKey struct {
  907. Labels map[string]string
  908. }
  909. func (gcp *GCP) GetKey(labels map[string]string) Key {
  910. return &gcpKey{
  911. Labels: labels,
  912. }
  913. }
  914. func (gcp *gcpKey) ID() string {
  915. return ""
  916. }
  917. func (gcp *gcpKey) GPUType() string {
  918. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  919. var usageType string
  920. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  921. usageType = "preemptible"
  922. } else {
  923. usageType = "ondemand"
  924. }
  925. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  926. return t + "," + usageType
  927. }
  928. return ""
  929. }
  930. // GetKey maps node labels to information needed to retrieve pricing data
  931. func (gcp *gcpKey) Features() string {
  932. instanceType := strings.ToLower(strings.Join(strings.Split(gcp.Labels[v1.LabelInstanceType], "-")[:2], ""))
  933. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  934. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  935. } else if strings.HasPrefix(instanceType, "custom") {
  936. instanceType = "custom" // The suffix of custom does not matter
  937. }
  938. region := strings.ToLower(gcp.Labels[v1.LabelZoneRegion])
  939. var usageType string
  940. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  941. usageType = "preemptible"
  942. } else {
  943. usageType = "ondemand"
  944. }
  945. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  946. return region + "," + instanceType + "," + usageType + "," + "gpu"
  947. }
  948. return region + "," + instanceType + "," + usageType
  949. }
  950. // AllNodePricing returns the GCP pricing objects stored
  951. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  952. gcp.DownloadPricingDataLock.RLock()
  953. defer gcp.DownloadPricingDataLock.RUnlock()
  954. return gcp.Pricing, nil
  955. }
  956. // NodePricing returns GCP pricing data for a single node
  957. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  958. gcp.DownloadPricingDataLock.RLock()
  959. defer gcp.DownloadPricingDataLock.RUnlock()
  960. if n, ok := gcp.Pricing[key.Features()]; ok {
  961. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  962. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  963. return n.Node, nil
  964. }
  965. klog.V(1).Infof("Warning: no pricing data found for %s: %s", key.Features(), key)
  966. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  967. }