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

initialize aws cost explorer getCostAndUsageWithResource anycall handler function #1309

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
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
15 changes: 14 additions & 1 deletion cloud-control-manager/cloud-driver/drivers/aws/AwsDriver.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/costexplorer"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/eks"
"github.com/aws/aws-sdk-go/service/elbv2"
Expand Down Expand Up @@ -228,6 +229,7 @@ func (driver *AwsDriver) ConnectCloud(connectionInfo idrv.ConnectionInfo) (icon.
if err != nil {
return nil, err
}
costExplorerClient, err := getCostExplorerClient(connectionInfo)

//iConn = acon.AwsCloudConnection{}
iConn := acon.AwsCloudConnection{
Expand Down Expand Up @@ -256,7 +258,8 @@ func (driver *AwsDriver) ConnectCloud(connectionInfo idrv.ConnectionInfo) (icon.
// Connection for AnyCall
AnyCallClient: vmClient,

TagClient: vmClient,
TagClient: vmClient,
CostExplorerClient: costExplorerClient,
}

return &iConn, nil // return type: (icon.CloudConnection, error)
Expand Down Expand Up @@ -298,6 +301,16 @@ func getPricingClient(connectionInfo idrv.ConnectionInfo) (*pricing.Pricing, err
return svc, nil
}

func getCostExplorerClient(connectionInfo idrv.ConnectionInfo) (*costexplorer.CostExplorer, error) {
sess := session.Must(session.NewSession())
svc := costexplorer.New(sess, &aws.Config{
Region: aws.String(connectionInfo.RegionInfo.Region),
Credentials: credentials.NewStaticCredentials(connectionInfo.CredentialInfo.ClientId, connectionInfo.CredentialInfo.ClientSecret, "")},
)

return svc, nil
}

/*
func (AwsDriver) ConnectCloud(connectionInfo idrv.ConnectionInfo) (icon.CloudConnection, error) {
// 1. get info of credential and region for Test A Cloud from connectionInfo.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
ars "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/drivers/aws/resources"

//ec2drv "github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/costexplorer"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/elbv2"
"github.com/aws/aws-sdk-go/service/pricing"
Expand Down Expand Up @@ -62,6 +63,8 @@ type AwsCloudConnection struct {

AnyCallClient *ec2.EC2
TagClient *ec2.EC2

CostExplorerClient *costexplorer.CostExplorer
}

var cblogger *logrus.Logger
Expand Down Expand Up @@ -186,7 +189,7 @@ func (cloudConn *AwsCloudConnection) CreateClusterHandler() (irs.ClusterHandler,
}

func (cloudConn *AwsCloudConnection) CreateAnyCallHandler() (irs.AnyCallHandler, error) {
handler := ars.AwsAnyCallHandler{Region: cloudConn.Region, CredentialInfo: cloudConn.CredentialInfo, Client: cloudConn.AnyCallClient}
handler := ars.AwsAnyCallHandler{Region: cloudConn.Region, CredentialInfo: cloudConn.CredentialInfo, Client: cloudConn.AnyCallClient, CeClient: cloudConn.CostExplorerClient}
return &handler, nil
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
package resources

import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
Expand All @@ -19,8 +20,10 @@ import (
"errors"
"fmt"
"io"
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/costexplorer"
"github.com/aws/aws-sdk-go/service/ec2"
idrv "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/interfaces"
irs "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/interfaces/resources"
Expand All @@ -30,19 +33,24 @@ type AwsAnyCallHandler struct {
Region idrv.RegionInfo
CredentialInfo idrv.CredentialInfo
Client *ec2.EC2
CeClient *costexplorer.CostExplorer
}

/********************************************************
// call example
curl -sX POST http://localhost:1024/spider/anycall -H 'Content-Type: application/json' -d \
'{
"ConnectionName" : "aws-ohio-config",
"ReqInfo" : {
"FID" : "createTags",
"IKeyValueList" : [{"Key":"key1", "Value":"value1"}, {"Key":"key2", "Value":"value2"}]
}
}' | json_pp
********************************************************/
/*
*******************************************************

// call example
curl -sX POST http://localhost:1024/spider/anycall -H 'Content-Type: application/json' -d \
'{
"ConnectionName" : "aws-ohio-config",
"ReqInfo" : {
"FID" : "createTags",
"IKeyValueList" : [{"Key":"key1", "Value":"value1"}, {"Key":"key2", "Value":"value2"}]
}
}' | json_pp

*******************************************************
*/
func (anyCallHandler *AwsAnyCallHandler) AnyCall(callInfo irs.AnyCallInfo) (irs.AnyCallInfo, error) {
cblogger.Info("AWS Driver: called AnyCall()!")

Expand All @@ -53,16 +61,17 @@ func (anyCallHandler *AwsAnyCallHandler) AnyCall(callInfo irs.AnyCallInfo) (irs.
return associateIamInstanceProfile(anyCallHandler, callInfo)
case "getRegionInfo":
return getRegionInfo(anyCallHandler, callInfo)
// add more ...
case "getCostWithResource":
return getCostWithResource(anyCallHandler, callInfo)

default:
return irs.AnyCallInfo{}, errors.New("AWS Driver: " + callInfo.FID + " Function is not implemented!")
}
}

///////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////
// implemented by developer user, like 'createTags(kv []KeyVale) bool'
///////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////
const (
CreateTagsResourceId = "ResourceId"
CreateTagsTag = "Tag"
Expand Down Expand Up @@ -131,9 +140,9 @@ const (
AssociateIamInstanceProfileRole = "Role"
)

///////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
// implemented by developer user, like 'associateIamInstanceProfile(kv []KeyValue) bool'
///////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
func associateIamInstanceProfile(anyCallHandler *AwsAnyCallHandler, callInfo irs.AnyCallInfo) (irs.AnyCallInfo, error) {
cblogger.Info("AWS Driver: called AnyCall()/associateIamInstanceProfile()!")

Expand Down Expand Up @@ -232,3 +241,176 @@ func encrypt(contents []byte) ([]byte, error) {

return encryptData, nil
}

type CostWithResourceReq struct {
StartDate string `json:"startDate"`
EndDate string `json:"endDate"`
Granularity string `json:"granularity"`
Metrics []string `json:"metrics"`
Filter FilterExpression `json:"filter"`
Groups []GroupBy `json:"groups"`
}

type FilterExpression struct {
And []*FilterExpression `json:"and,omitempty"`
Or []*FilterExpression `json:"or,omitempty"`
Not *FilterExpression `json:"not,omitempty"`
CostCategories *KeyValues `json:"costCategories,omitempty"`
Dimensions *KeyValues `json:"dimensions,omitempty"`
Tags *KeyValues `json:"tags,omitempty"`
}

type KeyValues struct {
Key string `json:"key"`
Values []string `json:"values"`
}

type GroupBy struct {
Key string `json:"key"`
Type string `json:"type"` // DIMENSION | TAG | COST_CATEGORY
}

func getCostWithResource(anyCallHandler *AwsAnyCallHandler, callInfo irs.AnyCallInfo) (irs.AnyCallInfo, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

reqMap, err := ConvertTagListToTagsMap(callInfo.IKeyValueList)
if err != nil {
return callInfo, errors.New("invalid key value list")
}

body, ok := reqMap["requestBody"]

if !ok || body == nil {
return callInfo, errors.New("requestBody is required")
}

var costWithResourceReq CostWithResourceReq
err = json.Unmarshal([]byte(*body), &costWithResourceReq)
if err != nil {
return callInfo, err
}

startDate := costWithResourceReq.StartDate
endDate := costWithResourceReq.EndDate
granularity := costWithResourceReq.Granularity
metric := costWithResourceReq.Metrics
filter := convertToCostExplorerExpression(&costWithResourceReq.Filter)
group := costExplorerGroupGenerate(costWithResourceReq.Groups)

input := &costexplorer.GetCostAndUsageWithResourcesInput{
TimePeriod: &costexplorer.DateInterval{
Start: aws.String(startDate),
End: aws.String(endDate),
},
Granularity: aws.String(granularity),
Metrics: aws.StringSlice(metric),
Filter: filter,
GroupBy: group,
}

res, err := anyCallHandler.CeClient.GetCostAndUsageWithResourcesWithContext(ctx, input)
if err != nil {
cblogger.Error("error occur", err)
return callInfo, err
}

m, err := json.Marshal(res)
if err != nil {

return callInfo, err
}

callInfo.OKeyValueList = []irs.KeyValue{
{
Key: "result",
Value: string(m),
},
}
return callInfo, nil
}

// convertToCostExplorerExpression converts a FilterExpression into a Cost Explorer Expression object.
// It recursively converts nested filter expressions and handles `And`, `Or`, and `Not` conditions.
func convertToCostExplorerExpression(filter *FilterExpression) *costexplorer.Expression {
if filter == nil {
return nil
}

expression := &costexplorer.Expression{
CostCategories: convertKeyValuesToCostCategoryValues(filter.CostCategories),
Dimensions: convertKeyValuesToDimensionValues(filter.Dimensions),
Tags: convertKeyValuesToTagValues(filter.Tags),
}

if len(filter.And) > 0 {
expression.And = make([]*costexplorer.Expression, len(filter.And))
for i, f := range filter.And {
expression.And[i] = convertToCostExplorerExpression(f)
}
}

if len(filter.Or) > 0 {
expression.Or = make([]*costexplorer.Expression, len(filter.Or))
for i, f := range filter.Or {
expression.Or[i] = convertToCostExplorerExpression(f)
}
}

if filter.Not != nil {
expression.Not = convertToCostExplorerExpression(filter.Not)
}

return expression
}

// convertKeyValuesToCostCategoryValues converts a KeyValues object into a Cost Explorer CostCategoryValues object.
// It maps the Key and Values fields from the input to the corresponding fields in the CostCategoryValues.
func convertKeyValuesToCostCategoryValues(kv *KeyValues) *costexplorer.CostCategoryValues {
if kv == nil {
return nil
}
return &costexplorer.CostCategoryValues{
Key: aws.String(kv.Key),
Values: aws.StringSlice(kv.Values),
}
}

// convertKeyValuesToDimensionValues converts a KeyValues object into a Cost Explorer DimensionValues object.
// It maps the Key and Values fields from the input to the corresponding fields in the DimensionValues.
func convertKeyValuesToDimensionValues(kv *KeyValues) *costexplorer.DimensionValues {
if kv == nil {
return nil
}
return &costexplorer.DimensionValues{
Key: aws.String(kv.Key),
Values: aws.StringSlice(kv.Values),
}
}

// convertKeyValuesToTagValues converts a KeyValues object into a Cost Explorer TagValues object.
// It maps the Key and Values fields from the input to the corresponding fields in the TagValues.
// TagValues ​​refers to AWS's cost allocation tag, not the tags commonly used for resources.
func convertKeyValuesToTagValues(kv *KeyValues) *costexplorer.TagValues {
if kv == nil {
return nil
}
return &costexplorer.TagValues{
Key: aws.String(kv.Key),
Values: aws.StringSlice(kv.Values),
}
}

// costExplorerGroupGenerate generates a slice of GroupDefinition objects from a slice of Cost Explorer GroupBy objects.
// Each GroupBy object is converted into a GroupDefinition with the corresponding Key and Type fields.
func costExplorerGroupGenerate(g []GroupBy) []*costexplorer.GroupDefinition {
var groupBy []*costexplorer.GroupDefinition
for _, v := range g {
groupBy = append(groupBy, &costexplorer.GroupDefinition{
Key: aws.String(v.Key),
Type: aws.String(v.Type),
})
}

return groupBy
}
Loading