/
rds.go
255 lines (217 loc) · 6.86 KB
/
rds.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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// Package cloudwatch implements methods to retrieve AWS Cloudwatch information
package cloudwatch
import (
"context"
"errors"
"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_cloudwath_types "github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
)
const (
MaxQueriesPerCloudwatchRequest int = 500
CloudwatchUsagePeriod int32 = 5
Minute int32 = 60
)
var errUnknownMetric = errors.New("unknown metric")
type CloudWatchMetrics struct {
Instances map[string]*RdsMetrics
}
type RdsMetrics struct {
CPUUtilization *float64
DBLoad *float64
DBLoadCPU *float64
DBLoadNonCPU *float64
DatabaseConnections *float64
FreeStorageSpace *float64
FreeableMemory *float64
MaximumUsedTransactionIDs *float64
ReadIOPS *float64
ReadThroughput *float64
ReplicaLag *float64
ReplicationSlotDiskUsage *float64
SwapUsage *float64
TransactionLogsDiskUsage *float64
WriteIOPS *float64
WriteThroughput *float64
}
func (m *RdsMetrics) Update(field string, value float64) error {
switch field {
case "DBLoad":
m.DBLoad = &value
case "DBLoadCPU":
m.DBLoadCPU = &value
case "DBLoadNonCPU":
m.DBLoadNonCPU = &value
case "CPUUtilization":
m.CPUUtilization = &value
case "DatabaseConnections":
m.DatabaseConnections = &value
case "FreeStorageSpace":
m.FreeStorageSpace = &value
case "FreeableMemory":
m.FreeableMemory = &value
case "SwapUsage":
m.SwapUsage = &value
case "WriteIOPS":
m.WriteIOPS = &value
case "ReadIOPS":
m.ReadIOPS = &value
case "ReplicaLag":
m.ReplicaLag = &value
case "ReplicationSlotDiskUsage":
m.ReplicationSlotDiskUsage = &value
case "MaximumUsedTransactionIDs":
m.MaximumUsedTransactionIDs = &value
case "ReadThroughput":
m.ReadThroughput = &value
case "WriteThroughput":
m.WriteThroughput = &value
case "TransactionLogsDiskUsage":
m.TransactionLogsDiskUsage = &value
default:
return fmt.Errorf("can't process '%s' metrics: %w", field, errUnknownMetric)
}
return nil
}
// getCloudWatchMetricsName returns names of Cloudwatch metrics to collect
func getCloudWatchMetricsName() [16]string {
return [16]string{
"CPUUtilization",
"DBLoad",
"DBLoadCPU",
"DBLoadNonCPU",
"DatabaseConnections",
"FreeStorageSpace",
"FreeableMemory",
"MaximumUsedTransactionIDs",
"ReadIOPS",
"ReadThroughput",
"ReplicaLag",
"ReplicationSlotDiskUsage",
"SwapUsage",
"TransactionLogsDiskUsage",
"WriteIOPS",
"WriteThroughput",
}
}
// generateCloudWatchQueryForInstance return the cloudwatch query for a specific instance's metric
func generateCloudWatchQueryForInstance(queryID *string, metricName string, dbIdentifier string) CloudWatchMetricRequest {
query := &aws_cloudwath_types.MetricDataQuery{
Id: queryID,
MetricStat: &aws_cloudwath_types.MetricStat{
Metric: &aws_cloudwath_types.Metric{
Namespace: aws.String("AWS/RDS"),
MetricName: aws.String(metricName),
Dimensions: []aws_cloudwath_types.Dimension{
{
Name: aws.String("DBInstanceIdentifier"),
Value: aws.String(dbIdentifier),
},
},
},
Stat: aws.String("Average"), // Specify the statistic to retrieve
Period: aws.Int32(Minute), // Specify the period of the metric. Granularity - 1 minute
},
}
return CloudWatchMetricRequest{
Dbidentifier: dbIdentifier,
MetricName: metricName,
Query: *query,
}
}
// generateCloudWatchQueriesForInstances returns all cloudwatch queries for specified instances
func generateCloudWatchQueriesForInstances(dbIdentifiers []string) map[string]CloudWatchMetricRequest {
queries := make(map[string]CloudWatchMetricRequest)
metrics := getCloudWatchMetricsName()
for i, dbIdentifier := range dbIdentifiers {
for _, metricName := range metrics {
queryID := aws.String(fmt.Sprintf("%s_%d", strings.ToLower(metricName), i))
query := generateCloudWatchQueryForInstance(queryID, metricName, dbIdentifier)
queries[*queryID] = query
}
}
return queries
}
func NewRDSFetcher(client CloudWatchClient, logger slog.Logger) *RdsFetcher {
return &RdsFetcher{
client: client,
logger: &logger,
}
}
type RdsFetcher struct {
client CloudWatchClient
statistics Statistics
logger *slog.Logger
}
func (c *RdsFetcher) GetStatistics() *Statistics {
return &c.statistics
}
func (c *RdsFetcher) updateMetricsWithCloudWatchQueriesResult(metrics map[string]*RdsMetrics, requests map[string]CloudWatchMetricRequest, startTime *time.Time, endTime *time.Time, chunk []string) error {
params := &aws_cloudwatch.GetMetricDataInput{
StartTime: startTime,
EndTime: endTime,
ScanBy: "TimestampDescending",
MetricDataQueries: []aws_cloudwath_types.MetricDataQuery{},
}
for _, key := range chunk {
query := requests[key].Query
params.MetricDataQueries = append(params.MetricDataQueries, query)
}
resp, err := c.client.GetMetricData(context.TODO(), params)
if err != nil {
return fmt.Errorf("error calling GetMetricData: %w", err)
}
for _, m := range resp.MetricDataResults {
if m.Values == nil {
c.logger.Warn("cloudwatch value is empty", "metric", *m.Label)
continue
}
val := requests[*m.Id]
_, instanceMetricExists := metrics[val.Dbidentifier]
if !instanceMetricExists {
metrics[val.Dbidentifier] = &RdsMetrics{}
}
if len(m.Values) > 0 {
err := metrics[val.Dbidentifier].Update(val.MetricName, m.Values[0])
if err != nil {
return fmt.Errorf("failed to process metrics %s: %w", val.MetricName, err)
}
}
}
return nil
}
func (c *RdsFetcher) GetRDSInstanceMetrics(dbIdentifiers []string) (CloudWatchMetrics, error) {
metrics := make(map[string]*RdsMetrics)
cloudWatchQueries := generateCloudWatchQueriesForInstances(dbIdentifiers)
startTime := aws.Time(time.Now().Add(-3 * time.Minute)) // Start time - 1 hour ago
endTime := aws.Time(time.Now()) // End time - now
chunkSize := MaxQueriesPerCloudwatchRequest
cloudWatchAPICalls := float64(0)
chunk := make([]string, 0, chunkSize)
for query := range cloudWatchQueries {
chunk = append(chunk, query)
if len(chunk) == chunkSize {
err := c.updateMetricsWithCloudWatchQueriesResult(metrics, cloudWatchQueries, startTime, endTime, chunk)
if err != nil {
return CloudWatchMetrics{}, fmt.Errorf("can't fetch Cloudwatch metrics: %w", err)
}
chunk = nil
cloudWatchAPICalls += 1
}
}
// Process last, potentially incomplete batch
if len(chunk) > 0 {
err := c.updateMetricsWithCloudWatchQueriesResult(metrics, cloudWatchQueries, startTime, endTime, chunk)
if err != nil {
return CloudWatchMetrics{}, fmt.Errorf("can't fetch Cloudwatch metrics: %w", err)
}
c.statistics.CloudWatchAPICall++
}
return CloudWatchMetrics{
Instances: metrics,
}, nil
}