Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEAT-778] Calculate cost for GCP Redis instances #1227

Merged
merged 4 commits into from
Dec 15, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 97 additions & 1 deletion providers/gcp/redis/instances.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ package redis

import (
"context"
"encoding/json"
"math"
"net/http"

"fmt"
"regexp"
"time"
Expand All @@ -18,7 +22,97 @@ import (
"github.com/tailwarden/komiser/utils"
)

type RedisPrice []struct {
Val int `json:"val"`
Currency string `json:"currnecy"`
Nanos float64 `json:"nanos"`
}

type RegionBasedPricing struct {
Regions map[string]struct {
Price RedisPrice `json:"price"`
} `json:"regions"`
}

type GcpDatabasePricing struct {
Gcp struct {
Databases struct {
CloudMemorystore struct {
Redis struct {
Basic map[string]RegionBasedPricing `json:"basic"`
Standard map[string]RegionBasedPricing `json:"standard"`
} `json:"redis"`
} `json:"cloud_memorystore"`
} `json:"databases"`
} `json:"gcp"`
}

func calculateRedisCost(redis *redispb.Instance, pricing GcpDatabasePricing) float64 {
var priceMap map[string]RegionBasedPricing
var priceKey string

prices := []int32{4, 10, 35, 100}
capacityTier := getCapacityTier(redis.MemorySizeGb, prices)

if redis.Tier == redispb.Instance_BASIC {
priceMap = pricing.Gcp.Databases.CloudMemorystore.Redis.Basic
priceKey = fmt.Sprintf("Rediscapacitybasicm%ddefault", capacityTier)
} else if redis.Tier == redispb.Instance_STANDARD_HA {
priceMap = pricing.Gcp.Databases.CloudMemorystore.Redis.Standard
if redis.ReadReplicasMode == redispb.Instance_READ_REPLICAS_DISABLED {
priceKey = fmt.Sprintf("Rediscapacitystandardm%ddefault", capacityTier)
} else {
priceKey = fmt.Sprintf("Rediscapacitystandardnodem%d", capacityTier)
}
}

pricePerHrPerGbInNanos := priceMap[priceKey].Regions[redis.LocationId].Price[0].Nanos
pricePerHrPerGbInDollars := pricePerHrPerGbInNanos / math.Pow(10, 9)

now := time.Now()
startTime := getStartTime(redis.GetCreateTime().AsTime(), now)

hours := now.Sub(startTime).Hours()

cost := hours * pricePerHrPerGbInDollars

if redis.ReadReplicasMode == redispb.Instance_READ_REPLICAS_ENABLED {
cost *= float64(redis.ReplicaCount)
}

return cost
}

func getCapacityTier(memorySizeGb int32, prices []int32) int {
capacityTier := 5
for idx, price := range prices {
if memorySizeGb <= price {
capacityTier = idx + 1
}
}
return capacityTier
}

func getStartTime(createTime, now time.Time) time.Time {
firstOfCurrentMonth := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you check with other places in the code and see if this is the same? I think we use UTC time.
Also, it'd be great if we had a util function for doing this repetitive task, since we do it across all the providers.

if createTime.After(firstOfCurrentMonth) {
return createTime
}
return firstOfCurrentMonth
}

func Instances(ctx context.Context, client providers.ProviderClient) ([]models.Resource, error) {
res, err := http.Get("https://www.gstatic.com/cloud-site-ux/pricing/data/gcp-databases.json")
if err != nil {
return nil, err
}

var pricing GcpDatabasePricing
err = json.NewDecoder(res.Body).Decode(&pricing)
if err != nil {
return nil, err
}

resources := make([]models.Resource, 0)

regions, err := utils.FetchGCPRegionsInRealtime(client.GCPClient.Credentials.ProjectID, option.WithCredentials(client.GCPClient.Credentials))
Expand Down Expand Up @@ -57,6 +151,8 @@ RegionsLoop:
re := regexp.MustCompile(`instances\/(.+)$`)
redisInstanceName := re.FindStringSubmatch(redis.Name)[1]

cost := calculateRedisCost(redis, pricing)

resources = append(resources, models.Resource{
Provider: "GCP",
Account: client.Name,
Expand All @@ -65,7 +161,7 @@ RegionsLoop:
Name: redis.DisplayName,
Region: regionName,
CreatedAt: redis.CreateTime.AsTime(),
Cost: 0,
Cost: cost,
FetchedAt: time.Now(),
Link: fmt.Sprintf("https://console.cloud.google.com/memorystore/redis/locations/%s/instances/%s/details/overview?project=%s", regionName, redisInstanceName, client.GCPClient.Credentials.ProjectID),
})
Expand Down