gcpprovider.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. "regexp"
  12. "strconv"
  13. "strings"
  14. "k8s.io/klog"
  15. "cloud.google.com/go/bigquery"
  16. "cloud.google.com/go/compute/metadata"
  17. "golang.org/x/oauth2"
  18. "golang.org/x/oauth2/google"
  19. compute "google.golang.org/api/compute/v1"
  20. "google.golang.org/api/iterator"
  21. v1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/client-go/kubernetes"
  24. )
  25. const GKE_GPU_TAG = "cloud.google.com/gke-accelerator"
  26. type userAgentTransport struct {
  27. userAgent string
  28. base http.RoundTripper
  29. }
  30. func (t userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  31. req.Header.Set("User-Agent", t.userAgent)
  32. return t.base.RoundTrip(req)
  33. }
  34. // GCP implements a provider interface for GCP
  35. type GCP struct {
  36. Pricing map[string]*GCPPricing
  37. Clientset *kubernetes.Clientset
  38. APIKey string
  39. BaseCPUPrice string
  40. ProjectID string
  41. BillingDataDataset string
  42. }
  43. type gcpAllocation struct {
  44. Aggregator bigquery.NullString
  45. Environment bigquery.NullString
  46. Service string
  47. Cost float64
  48. }
  49. func gcpAllocationToOutOfClusterAllocation(gcpAlloc gcpAllocation) *OutOfClusterAllocation {
  50. var aggregator string
  51. if gcpAlloc.Aggregator.Valid {
  52. aggregator = gcpAlloc.Aggregator.StringVal
  53. }
  54. var environment string
  55. if gcpAlloc.Environment.Valid {
  56. environment = gcpAlloc.Environment.StringVal
  57. }
  58. return &OutOfClusterAllocation{
  59. Aggregator: aggregator,
  60. Environment: environment,
  61. Service: gcpAlloc.Service,
  62. Cost: gcpAlloc.Cost,
  63. }
  64. }
  65. func (gcp *GCP) GetConfig() (*CustomPricing, error) {
  66. return nil, nil
  67. }
  68. func (gcp *GCP) UpdateConfig(r io.Reader) (*CustomPricing, error) {
  69. return nil, nil
  70. }
  71. func (gcp *GCP) ExternalAllocations(start string, end string) ([]*OutOfClusterAllocation, error) {
  72. // start, end formatted like: "2019-04-20 00:00:00"
  73. queryString := fmt.Sprintf(`SELECT
  74. service,
  75. labels.key as aggregator,
  76. labels.value as environment,
  77. SUM(cost) as cost
  78. FROM (SELECT
  79. service.description as service,
  80. labels,
  81. cost
  82. FROM %s
  83. WHERE usage_start_time >= "%s" AND usage_start_time < "%s")
  84. LEFT JOIN UNNEST(labels) as labels
  85. ON labels.key = "kubernetes_namespace" OR labels.key = "kubernetes_container" OR labels.key = "kubernetes_deployment" OR labels.key = "kubernetes_pod" OR labels.key = "kubernetes_daemonset"
  86. GROUP BY aggregator, environment, service;`, gcp.BillingDataDataset, start, end) // For example, "billing_data.gcp_billing_export_v1_01AC9F_74CF1D_5565A2"
  87. klog.V(3).Infof("Querying \"%s\" with : %s", gcp.ProjectID, queryString)
  88. return gcp.QuerySQL(queryString)
  89. }
  90. // QuerySQL should query BigQuery for billing data for out of cluster costs.
  91. func (gcp *GCP) QuerySQL(query string) ([]*OutOfClusterAllocation, error) {
  92. ctx := context.Background()
  93. client, err := bigquery.NewClient(ctx, gcp.ProjectID) // For example, "guestbook-227502"
  94. if err != nil {
  95. return nil, err
  96. }
  97. q := client.Query(query)
  98. it, err := q.Read(ctx)
  99. if err != nil {
  100. return nil, err
  101. }
  102. var allocations []*OutOfClusterAllocation
  103. for {
  104. var a gcpAllocation
  105. err := it.Next(&a)
  106. if err == iterator.Done {
  107. break
  108. }
  109. if err != nil {
  110. return nil, err
  111. }
  112. allocations = append(allocations, gcpAllocationToOutOfClusterAllocation(a))
  113. }
  114. return allocations, nil
  115. }
  116. // ClusterName returns the name of a GKE cluster, as provided by metadata.
  117. func (*GCP) ClusterName() ([]byte, error) {
  118. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  119. userAgent: "kubecost",
  120. base: http.DefaultTransport,
  121. }})
  122. attribute, err := metadataClient.InstanceAttributeValue("cluster-name")
  123. if err != nil {
  124. return nil, err
  125. }
  126. m := make(map[string]string)
  127. m["name"] = attribute
  128. m["provider"] = "GCP"
  129. return json.Marshal(m)
  130. }
  131. // AddServiceKey adds the service key as required for GetDisks
  132. func (*GCP) AddServiceKey(formValues url.Values) error {
  133. key := formValues.Get("key")
  134. k := []byte(key)
  135. return ioutil.WriteFile("/var/configs/key.json", k, 0644)
  136. }
  137. // 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.
  138. func (*GCP) GetDisks() ([]byte, error) {
  139. // metadata API setup
  140. metadataClient := metadata.NewClient(&http.Client{Transport: userAgentTransport{
  141. userAgent: "kubecost",
  142. base: http.DefaultTransport,
  143. }})
  144. projID, err := metadataClient.ProjectID()
  145. if err != nil {
  146. return nil, err
  147. }
  148. client, err := google.DefaultClient(oauth2.NoContext,
  149. "https://www.googleapis.com/auth/compute.readonly")
  150. if err != nil {
  151. return nil, err
  152. }
  153. svc, err := compute.New(client)
  154. if err != nil {
  155. return nil, err
  156. }
  157. res, err := svc.Disks.AggregatedList(projID).Do()
  158. if err != nil {
  159. return nil, err
  160. }
  161. return json.Marshal(res)
  162. }
  163. // GCPPricing represents GCP pricing data for a SKU
  164. type GCPPricing struct {
  165. Name string `json:"name"`
  166. SKUID string `json:"skuId"`
  167. Description string `json:"description"`
  168. Category *GCPResourceInfo `json:"category"`
  169. ServiceRegions []string `json:"serviceRegions"`
  170. PricingInfo []*PricingInfo `json:"pricingInfo"`
  171. ServiceProviderName string `json:"serviceProviderName"`
  172. Node *Node `json:"node"`
  173. }
  174. // PricingInfo contains metadata about a cost.
  175. type PricingInfo struct {
  176. Summary string `json:"summary"`
  177. PricingExpression *PricingExpression `json:"pricingExpression"`
  178. CurrencyConversionRate int `json:"currencyConversionRate"`
  179. EffectiveTime string `json:""`
  180. }
  181. // PricingExpression contains metadata about a cost.
  182. type PricingExpression struct {
  183. UsageUnit string `json:"usageUnit"`
  184. UsageUnitDescription string `json:"usageUnitDescription"`
  185. BaseUnit string `json:"baseUnit"`
  186. BaseUnitConversionFactor int64 `json:"-"`
  187. DisplayQuantity int `json:"displayQuantity"`
  188. TieredRates []*TieredRates `json:"tieredRates"`
  189. }
  190. // TieredRates contain data about variable pricing.
  191. type TieredRates struct {
  192. StartUsageAmount int `json:"startUsageAmount"`
  193. UnitPrice *UnitPriceInfo `json:"unitPrice"`
  194. }
  195. // UnitPriceInfo contains data about the actual price being charged.
  196. type UnitPriceInfo struct {
  197. CurrencyCode string `json:"currencyCode"`
  198. Units string `json:"units"`
  199. Nanos float64 `json:"nanos"`
  200. }
  201. // GCPResourceInfo contains metadata about the node.
  202. type GCPResourceInfo struct {
  203. ServiceDisplayName string `json:"serviceDisplayName"`
  204. ResourceFamily string `json:"resourceFamily"`
  205. ResourceGroup string `json:"resourceGroup"`
  206. UsageType string `json:"usageType"`
  207. }
  208. func (gcp *GCP) parsePage(r io.Reader, inputKeys map[string]Key) (map[string]*GCPPricing, string, error) {
  209. gcpPricingList := make(map[string]*GCPPricing)
  210. var nextPageToken string
  211. dec := json.NewDecoder(r)
  212. for {
  213. t, err := dec.Token()
  214. if err == io.EOF {
  215. break
  216. }
  217. if t == "skus" {
  218. _, err := dec.Token() // consumes [
  219. if err != nil {
  220. return nil, "", err
  221. }
  222. for dec.More() {
  223. product := &GCPPricing{}
  224. err := dec.Decode(&product)
  225. if err != nil {
  226. return nil, "", err
  227. }
  228. usageType := strings.ToLower(product.Category.UsageType)
  229. instanceType := strings.ToLower(product.Category.ResourceGroup)
  230. if (instanceType == "ram" || instanceType == "cpu") && strings.Contains(strings.ToUpper(product.Description), "CUSTOM") {
  231. instanceType = "custom"
  232. }
  233. var partialCPU float64
  234. if strings.ToLower(instanceType) == "f1micro" {
  235. partialCPU = 0.2
  236. } else if strings.ToLower(instanceType) == "g1small" {
  237. partialCPU = 0.5
  238. }
  239. var gpuType string
  240. provIdRx := regexp.MustCompile("(Nvidia Tesla [^ ]+) ")
  241. for matchnum, group := range provIdRx.FindStringSubmatch(product.Description) {
  242. if matchnum == 1 {
  243. gpuType = strings.ToLower(strings.Join(strings.Split(group, " "), "-"))
  244. klog.V(4).Info("GPU TYPE FOUND: " + gpuType)
  245. }
  246. }
  247. for _, sr := range product.ServiceRegions {
  248. region := sr
  249. candidateKey := region + "," + instanceType + "," + usageType
  250. candidateKeyGPU := candidateKey + ",gpu"
  251. if gpuType != "" {
  252. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  253. var nanos float64
  254. if len(product.PricingInfo) > 0 {
  255. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  256. } else {
  257. continue
  258. }
  259. hourlyPrice := nanos * math.Pow10(-9)
  260. for k, key := range inputKeys {
  261. if key.GPUType() == gpuType {
  262. if region == strings.Split(k, ",")[0] {
  263. klog.V(3).Infof("Matched GPU to node in region \"%s\"", region)
  264. candidateKeyGPU = key.Features()
  265. if pl, ok := gcpPricingList[candidateKeyGPU]; ok {
  266. pl.Node.GPUName = gpuType
  267. pl.Node.GPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  268. pl.Node.GPU = "1"
  269. } else {
  270. product.Node = &Node{
  271. GPUName: gpuType,
  272. GPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  273. GPU: "1",
  274. }
  275. klog.V(3).Infof("Added data for " + candidateKeyGPU)
  276. gcpPricingList[candidateKeyGPU] = product
  277. }
  278. }
  279. }
  280. }
  281. } else {
  282. if _, ok := inputKeys[candidateKey]; ok {
  283. lastRateIndex := len(product.PricingInfo[0].PricingExpression.TieredRates) - 1
  284. var nanos float64
  285. if len(product.PricingInfo) > 0 {
  286. nanos = product.PricingInfo[0].PricingExpression.TieredRates[lastRateIndex].UnitPrice.Nanos
  287. } else {
  288. continue
  289. }
  290. hourlyPrice := nanos * math.Pow10(-9)
  291. if hourlyPrice == 0 {
  292. continue
  293. } else if strings.Contains(strings.ToUpper(product.Description), "RAM") {
  294. if instanceType == "custom" {
  295. klog.V(4).Infof("RAM custom sku is: " + product.Name)
  296. }
  297. if _, ok := gcpPricingList[candidateKey]; ok {
  298. gcpPricingList[candidateKey].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  299. } else {
  300. product.Node = &Node{
  301. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  302. }
  303. if partialCPU != 0 {
  304. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  305. }
  306. product.Node.UsageType = usageType
  307. gcpPricingList[candidateKey] = product
  308. }
  309. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  310. gcpPricingList[candidateKeyGPU].Node.RAMCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  311. } else {
  312. product.Node = &Node{
  313. RAMCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  314. }
  315. if partialCPU != 0 {
  316. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  317. }
  318. product.Node.UsageType = usageType
  319. gcpPricingList[candidateKeyGPU] = product
  320. }
  321. break
  322. } else {
  323. if _, ok := gcpPricingList[candidateKey]; ok {
  324. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  325. } else {
  326. product.Node = &Node{
  327. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  328. }
  329. if partialCPU != 0 {
  330. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  331. }
  332. product.Node.UsageType = usageType
  333. gcpPricingList[candidateKey] = product
  334. }
  335. if _, ok := gcpPricingList[candidateKeyGPU]; ok {
  336. gcpPricingList[candidateKey].Node.VCPUCost = strconv.FormatFloat(hourlyPrice, 'f', -1, 64)
  337. } else {
  338. product.Node = &Node{
  339. VCPUCost: strconv.FormatFloat(hourlyPrice, 'f', -1, 64),
  340. }
  341. if partialCPU != 0 {
  342. product.Node.VCPU = fmt.Sprintf("%f", partialCPU)
  343. }
  344. product.Node.UsageType = usageType
  345. gcpPricingList[candidateKeyGPU] = product
  346. }
  347. break
  348. }
  349. }
  350. }
  351. }
  352. }
  353. }
  354. if t == "nextPageToken" {
  355. pageToken, err := dec.Token()
  356. if err != nil {
  357. klog.V(2).Infof("Error parsing nextpage token: " + err.Error())
  358. return nil, "", err
  359. }
  360. if pageToken.(string) != "" {
  361. nextPageToken = pageToken.(string)
  362. } else {
  363. nextPageToken = "done"
  364. }
  365. }
  366. }
  367. return gcpPricingList, nextPageToken, nil
  368. }
  369. func (gcp *GCP) parsePages(inputKeys map[string]Key) (map[string]*GCPPricing, error) {
  370. var pages []map[string]*GCPPricing
  371. url := "https://cloudbilling.googleapis.com/v1/services/6F81-5844-456A/skus?key=" + gcp.APIKey
  372. klog.V(2).Infof("Fetch GCP Billing Data from URL: %s", url)
  373. var parsePagesHelper func(string) error
  374. parsePagesHelper = func(pageToken string) error {
  375. if pageToken == "done" {
  376. return nil
  377. } else if pageToken != "" {
  378. url = url + "&pageToken=" + pageToken
  379. }
  380. resp, err := http.Get(url)
  381. if err != nil {
  382. return err
  383. }
  384. page, token, err := gcp.parsePage(resp.Body, inputKeys)
  385. if err != nil {
  386. return err
  387. }
  388. pages = append(pages, page)
  389. return parsePagesHelper(token)
  390. }
  391. err := parsePagesHelper("")
  392. if err != nil {
  393. return nil, err
  394. }
  395. returnPages := make(map[string]*GCPPricing)
  396. for _, page := range pages {
  397. for k, v := range page {
  398. if val, ok := returnPages[k]; ok { //keys may need to be merged
  399. if val.Node.RAMCost != "" && val.Node.VCPUCost == "" {
  400. val.Node.VCPUCost = v.Node.VCPUCost
  401. } else if val.Node.VCPUCost != "" && val.Node.RAMCost == "" {
  402. val.Node.RAMCost = v.Node.RAMCost
  403. } else {
  404. returnPages[k] = v
  405. }
  406. } else {
  407. returnPages[k] = v
  408. }
  409. }
  410. }
  411. return returnPages, err
  412. }
  413. // 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.
  414. func (gcp *GCP) DownloadPricingData() error {
  415. c, err := GetDefaultPricingData("gcp.json")
  416. if err != nil {
  417. klog.V(2).Infof("Error downloading default pricing data: %s", err.Error())
  418. }
  419. gcp.BaseCPUPrice = c.CPU
  420. gcp.ProjectID = c.ProjectID
  421. gcp.BillingDataDataset = c.BillingDataDataset
  422. nodeList, err := gcp.Clientset.CoreV1().Nodes().List(metav1.ListOptions{})
  423. if err != nil {
  424. return err
  425. }
  426. inputkeys := make(map[string]Key)
  427. for _, n := range nodeList.Items {
  428. labels := n.GetObjectMeta().GetLabels()
  429. key := gcp.GetKey(labels)
  430. inputkeys[key.Features()] = key
  431. }
  432. pages, err := gcp.parsePages(inputkeys)
  433. if err != nil {
  434. return err
  435. }
  436. gcp.Pricing = pages
  437. return nil
  438. }
  439. type gcpKey struct {
  440. Labels map[string]string
  441. }
  442. func (gcp *GCP) GetKey(labels map[string]string) Key {
  443. return &gcpKey{
  444. Labels: labels,
  445. }
  446. }
  447. func (gcp *gcpKey) ID() string {
  448. return ""
  449. }
  450. func (gcp *gcpKey) GPUType() string {
  451. if t, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  452. klog.V(4).Infof("GPU of type: \"%s\" found", t)
  453. return t
  454. }
  455. return ""
  456. }
  457. // GetKey maps node labels to information needed to retrieve pricing data
  458. func (gcp *gcpKey) Features() string {
  459. instanceType := strings.ToLower(strings.Join(strings.Split(gcp.Labels[v1.LabelInstanceType], "-")[:2], ""))
  460. if instanceType == "n1highmem" || instanceType == "n1highcpu" {
  461. instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
  462. } else if strings.HasPrefix(instanceType, "custom") {
  463. instanceType = "custom" // The suffix of custom does not matter
  464. }
  465. region := strings.ToLower(gcp.Labels[v1.LabelZoneRegion])
  466. var usageType string
  467. if t, ok := gcp.Labels["cloud.google.com/gke-preemptible"]; ok && t == "true" {
  468. usageType = "preemptible"
  469. } else {
  470. usageType = "ondemand"
  471. }
  472. if _, ok := gcp.Labels[GKE_GPU_TAG]; ok {
  473. return region + "," + instanceType + "," + usageType + "," + "gpu"
  474. }
  475. return region + "," + instanceType + "," + usageType
  476. }
  477. // AllNodePricing returns the GCP pricing objects stored
  478. func (gcp *GCP) AllNodePricing() (interface{}, error) {
  479. return gcp.Pricing, nil
  480. }
  481. // NodePricing returns GCP pricing data for a single node
  482. func (gcp *GCP) NodePricing(key Key) (*Node, error) {
  483. if n, ok := gcp.Pricing[key.Features()]; ok {
  484. klog.V(4).Infof("Returning pricing for node %s: %+v from SKU %s", key, n.Node, n.Name)
  485. n.Node.BaseCPUPrice = gcp.BaseCPUPrice
  486. return n.Node, nil
  487. }
  488. klog.V(1).Infof("Warning: no pricing data found for %s: %s", key.Features(), key)
  489. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  490. }