|
| 1 | +package clients |
| 2 | + |
| 3 | +//go:generate mockgen -destination=mocks/cloudwatch.go . CloudwatchClient |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "fmt" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/aws/aws-sdk-go-v2/aws" |
| 11 | + "github.com/aws/aws-sdk-go-v2/service/cloudwatch" |
| 12 | + cloudwatchTypes "github.com/aws/aws-sdk-go-v2/service/cloudwatch/types" |
| 13 | +) |
| 14 | + |
| 15 | +type CloudwatchClient interface { |
| 16 | + // GetAverage returns the average value of a metric over a period of time |
| 17 | + GetAverage(ctx context.Context, input *GetAverageInput) (*float64, error) |
| 18 | +} |
| 19 | + |
| 20 | +// GetAverageInput is the input for the GetAverage function |
| 21 | +type GetAverageInput struct { |
| 22 | + // MetricName is the name of the metric to get the average value of |
| 23 | + MetricName string |
| 24 | + // ClusterName is the name of the cluster to get the average value of |
| 25 | + ClusterName string |
| 26 | + // ServiceName is the name of the service to get the average value of |
| 27 | + ServiceName string |
| 28 | + // TimeFrame is the period of time to get the average value over |
| 29 | + TimeFrame time.Duration |
| 30 | +} |
| 31 | + |
| 32 | +type cloudWatchClient struct { |
| 33 | + client *cloudwatch.Client |
| 34 | +} |
| 35 | + |
| 36 | +// NewCloudWatchClient returns a new CloudWatchClient |
| 37 | +func NewCloudWatchClient(client *cloudwatch.Client) CloudwatchClient { |
| 38 | + return &cloudWatchClient{client: client} |
| 39 | +} |
| 40 | + |
| 41 | +func (c *cloudWatchClient) GetAverage(ctx context.Context, input *GetAverageInput) (*float64, error) { |
| 42 | + now := time.Now() |
| 43 | + period := int32(input.TimeFrame.Seconds()) |
| 44 | + startTime := now.Add(-input.TimeFrame) |
| 45 | + getMetricsInput := &cloudwatch.GetMetricStatisticsInput{ |
| 46 | + MetricName: &input.MetricName, |
| 47 | + Dimensions: []cloudwatchTypes.Dimension{ |
| 48 | + { |
| 49 | + Name: aws.String("ClusterName"), |
| 50 | + Value: &input.ClusterName, |
| 51 | + }, |
| 52 | + { |
| 53 | + Name: aws.String("ServiceName"), |
| 54 | + Value: &input.ServiceName, |
| 55 | + }, |
| 56 | + }, |
| 57 | + StartTime: &startTime, |
| 58 | + EndTime: &now, |
| 59 | + Namespace: aws.String("AWS/ECS"), |
| 60 | + Period: &period, |
| 61 | + Statistics: []cloudwatchTypes.Statistic{ |
| 62 | + cloudwatchTypes.StatisticAverage, |
| 63 | + }, |
| 64 | + } |
| 65 | + metricsResponse, err := c.client.GetMetricStatistics(ctx, getMetricsInput) |
| 66 | + if err != nil { |
| 67 | + return nil, fmt.Errorf("failed to get metrics: %w", err) |
| 68 | + } |
| 69 | + if len(metricsResponse.Datapoints) != 1 { |
| 70 | + return nil, fmt.Errorf("failed to get %s data points from CloudWatch", input.MetricName) |
| 71 | + } |
| 72 | + return metricsResponse.Datapoints[0].Average, nil |
| 73 | +} |
0 commit comments