-
Notifications
You must be signed in to change notification settings - Fork 10
/
usage.go
175 lines (147 loc) · 4.49 KB
/
usage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package cloudwatch
import (
"context"
"fmt"
"log/slog"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
aws_cloudwatch "github.com/aws/aws-sdk-go-v2/service/cloudwatch"
aws_cloudwatch_types "github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
converter "github.com/qonto/prometheus-rds-exporter/internal/app/unit"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
)
var tracer = otel.Tracer("github/qonto/prometheus-rds-exporter/internal/app/cloudwatch")
type UsageMetrics struct {
AllocatedStorage float64
DBInstances float64
ManualSnapshots float64
ReservedDBInstances float64
}
func (u *UsageMetrics) Update(field string, value float64) error {
switch field {
case "AllocatedStorage":
u.AllocatedStorage = converter.GigaBytesToBytes(value)
case "DBInstances":
u.DBInstances = value
case "ManualSnapshots":
u.ManualSnapshots = value
case "ReservedDBInstances":
u.ReservedDBInstances = value
default:
return fmt.Errorf("can't process %s metrics: %w", field, errUnknownMetric)
}
return nil
}
func generateCloudWatchDataQueriesForUsage(service string, metricsName []string) map[string]CloudWatchMetricRequest {
requests := make(map[string]CloudWatchMetricRequest)
for i, metricName := range metricsName {
id := aws.String(fmt.Sprintf("%s_%d", strings.ToLower(metricName), i))
query := &aws_cloudwatch_types.MetricDataQuery{
Id: id,
MetricStat: &aws_cloudwatch_types.MetricStat{
Metric: &aws_cloudwatch_types.Metric{
Namespace: aws.String("AWS/Usage"),
MetricName: aws.String("ResourceCount"),
Dimensions: []aws_cloudwatch_types.Dimension{
{
Name: aws.String("Service"),
Value: aws.String(service),
},
{
Name: aws.String("Type"),
Value: aws.String("Resource"),
},
{
Name: aws.String("Resource"),
Value: aws.String(metricName),
},
{
Name: aws.String("Class"),
Value: aws.String("None"),
},
},
},
Stat: aws.String("Average"), // Specify the statistic to retrieve
Period: aws.Int32(Minute), // Specify the period of the metric. Granularity - 1 minute
},
}
requests[*id] = CloudWatchMetricRequest{
Dbidentifier: "",
MetricName: metricName,
Query: *query,
}
}
return requests
}
func generateCloudWatchQueriesForUsage() *aws_cloudwatch.GetMetricDataInput {
metricsName := []string{
"AllocatedStorage",
"DBInstances",
"ManualSnapshots",
}
cloudwatchDataQueries := []aws_cloudwatch_types.MetricDataQuery{}
queries := generateCloudWatchDataQueriesForUsage("RDS", metricsName)
for _, usageQuery := range queries {
query := aws_cloudwatch_types.MetricDataQuery{
Id: usageQuery.Query.Id,
MetricStat: &aws_cloudwatch_types.MetricStat{
Metric: usageQuery.Query.MetricStat.Metric,
Stat: aws.String("Average"),
Period: aws.Int32(CloudwatchUsagePeriod * Minute),
},
}
cloudwatchDataQueries = append(cloudwatchDataQueries, query)
}
return &aws_cloudwatch.GetMetricDataInput{
StartTime: aws.Time(time.Now().Add(-5 * time.Hour)),
EndTime: aws.Time(time.Now()),
ScanBy: "TimestampDescending",
MetricDataQueries: cloudwatchDataQueries,
}
}
func NewUsageFetcher(ctx context.Context, client CloudWatchClient, logger slog.Logger) *usageFetcher {
return &usageFetcher{
ctx: ctx,
client: client,
logger: &logger,
}
}
type usageFetcher struct {
ctx context.Context
client CloudWatchClient
statistics Statistics
logger *slog.Logger
}
func (u *usageFetcher) GetStatistics() Statistics {
return u.statistics
}
// GetUsageMetrics returns RDS service usages metrics
func (u *usageFetcher) GetUsageMetrics() (UsageMetrics, error) {
_, span := tracer.Start(u.ctx, "collect-usage")
defer span.End()
metrics := UsageMetrics{}
query := generateCloudWatchQueriesForUsage()
resp, err := u.client.GetMetricData(context.TODO(), query)
u.statistics.CloudWatchAPICall++
if err != nil {
return metrics, fmt.Errorf("error calling GetMetricData: %w", err)
}
for _, m := range resp.MetricDataResults {
if m.Values == nil {
u.logger.Warn("cloudwatch value is empty", "metric", *m.Label)
continue
}
if len(m.Values) > 0 {
err = metrics.Update(*m.Label, m.Values[0])
if err != nil {
span.SetStatus(codes.Error, "can't update internal values")
span.RecordError(err)
return metrics, fmt.Errorf("can't update internal values: %w", err)
}
}
}
span.SetStatus(codes.Ok, "metrics fetched")
return metrics, nil
}