-
Notifications
You must be signed in to change notification settings - Fork 0
/
abstract.go
278 lines (243 loc) · 8.17 KB
/
abstract.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package exporter
import (
"context"
"math"
"sync"
"github.com/aws/aws-sdk-go/service/sts"
)
func scrapeAwsData(
ctx context.Context,
config ScrapeConf,
metricsPerQuery int,
cloudwatchSemaphore,
tagSemaphore chan struct{},
cache SessionCache,
logger Logger,
) ([]*taggedResource, []*cloudwatchData) {
mux := &sync.Mutex{}
cwData := make([]*cloudwatchData, 0)
awsInfoData := make([]*taggedResource, 0)
var wg sync.WaitGroup
// since we have called refresh, we have loaded all the credentials
// into the clients and it is now safe to call concurrently. Defer the
// clearing, so we always clear credentials before the next scrape
cache.Refresh()
defer cache.Clear()
for _, discoveryJob := range config.Discovery.Jobs {
for _, role := range discoveryJob.Roles {
for _, region := range discoveryJob.Regions {
wg.Add(1)
go func(discoveryJob *Job, region string, role Role) {
defer wg.Done()
jobLogger := logger.With("job_type", discoveryJob.Type, "region", region, "arn", role.RoleArn)
result, err := cache.GetSTS(role).GetCallerIdentityWithContext(ctx, &sts.GetCallerIdentityInput{})
if err != nil || result.Account == nil {
jobLogger.Error(err, "Couldn't get account Id")
return
}
jobLogger = jobLogger.With("account", *result.Account)
clientCloudwatch := cloudwatchInterface{
client: cache.GetCloudwatch(®ion, role),
logger: jobLogger,
}
clientTag := tagsInterface{
client: cache.GetTagging(®ion, role),
apiGatewayClient: cache.GetAPIGateway(®ion, role),
asgClient: cache.GetASG(®ion, role),
dmsClient: cache.GetDMS(®ion, role),
ec2Client: cache.GetEC2(®ion, role),
storagegatewayClient: cache.GetStorageGateway(®ion, role),
logger: jobLogger,
}
resources, metrics := scrapeDiscoveryJobUsingMetricData(ctx, discoveryJob, region, result.Account, config.Discovery.ExportedTagsOnMetrics, clientTag, clientCloudwatch, metricsPerQuery, discoveryJob.RoundingPeriod, tagSemaphore, jobLogger)
if len(resources) != 0 && len(metrics) != 0 {
mux.Lock()
awsInfoData = append(awsInfoData, resources...)
cwData = append(cwData, metrics...)
mux.Unlock()
}
}(discoveryJob, region, role)
}
}
}
for _, staticJob := range config.Static {
for _, role := range staticJob.Roles {
for _, region := range staticJob.Regions {
wg.Add(1)
go func(staticJob *Static, region string, role Role) {
defer wg.Done()
jobLogger := logger.With("static_job_name", staticJob.Name, "region", region, "arn", role.RoleArn)
result, err := cache.GetSTS(role).GetCallerIdentityWithContext(ctx, &sts.GetCallerIdentityInput{})
if err != nil || result.Account == nil {
jobLogger.Error(err, "Couldn't get account Id")
return
}
jobLogger = jobLogger.With("account", *result.Account)
clientCloudwatch := cloudwatchInterface{
client: cache.GetCloudwatch(®ion, role),
logger: jobLogger,
}
metrics := scrapeStaticJob(ctx, staticJob, region, result.Account, clientCloudwatch, cloudwatchSemaphore, jobLogger)
mux.Lock()
cwData = append(cwData, metrics...)
mux.Unlock()
}(staticJob, region, role)
}
}
}
wg.Wait()
return awsInfoData, cwData
}
func scrapeStaticJob(ctx context.Context, resource *Static, region string, accountId *string, clientCloudwatch cloudwatchInterface, cloudwatchSemaphore chan struct{}, logger Logger) (cw []*cloudwatchData) {
mux := &sync.Mutex{}
var wg sync.WaitGroup
for j := range resource.Metrics {
metric := resource.Metrics[j]
wg.Add(1)
go func() {
defer wg.Done()
cloudwatchSemaphore <- struct{}{}
defer func() {
<-cloudwatchSemaphore
}()
id := resource.Name
data := cloudwatchData{
ID: &id,
Metric: &metric.Name,
Namespace: &resource.Namespace,
Statistics: metric.Statistics,
NilToZero: metric.NilToZero,
AddCloudwatchTimestamp: metric.AddCloudwatchTimestamp,
CustomTags: resource.CustomTags,
Dimensions: createStaticDimensions(resource.Dimensions),
Region: ®ion,
AccountId: accountId,
}
filter := createGetMetricStatisticsInput(
data.Dimensions,
&resource.Namespace,
metric,
logger,
)
data.Points = clientCloudwatch.get(ctx, filter)
if data.Points != nil {
mux.Lock()
cw = append(cw, &data)
mux.Unlock()
}
}()
}
wg.Wait()
return cw
}
func GetMetricDataInputLength(job *Job) int64 {
length := defaultLengthSeconds
if job.Length > 0 {
length = job.Length
}
for _, metric := range job.Metrics {
if metric.Length > length {
length = metric.Length
}
}
return length
}
func getMetricDataForQueries(
ctx context.Context,
discoveryJob *Job,
svc *serviceFilter,
region string,
accountId *string,
tagsOnMetrics exportedTagsOnMetrics,
clientCloudwatch cloudwatchInterface,
resources []*taggedResource,
tagSemaphore chan struct{},
logger Logger) []cloudwatchData {
var getMetricDatas []cloudwatchData
// For every metric of the job
for _, metric := range discoveryJob.Metrics {
// Get the full list of metrics
// This includes, for this metric the possible combinations
// of dimensions and value of dimensions with data
tagSemaphore <- struct{}{}
metricsList, err := getFullMetricsList(ctx, svc.Namespace, metric, clientCloudwatch)
<-tagSemaphore
if err != nil {
logger.Error(err, "Failed to get full metric list", "metric_name", metric.Name, "namespace", svc.Namespace)
continue
}
if len(resources) == 0 {
logger.Debug("No resources for metric", "metric_name", metric.Name, "namespace", svc.Namespace)
}
getMetricDatas = append(getMetricDatas, getFilteredMetricDatas(region, accountId, discoveryJob.Type, discoveryJob.CustomTags, tagsOnMetrics, svc.DimensionRegexps, resources, metricsList.Metrics, discoveryJob.DimensionNameRequirements, metric)...)
}
return getMetricDatas
}
func scrapeDiscoveryJobUsingMetricData(
ctx context.Context,
job *Job,
region string,
accountId *string,
tagsOnMetrics exportedTagsOnMetrics,
clientTag tagsInterface,
clientCloudwatch cloudwatchInterface,
metricsPerQuery int,
roundingPeriod *int64,
tagSemaphore chan struct{},
logger Logger) (resources []*taggedResource, cw []*cloudwatchData) {
// Add the info tags of all the resources
tagSemaphore <- struct{}{}
resources, err := clientTag.get(ctx, job, region)
<-tagSemaphore
if err != nil {
logger.Error(err, "Couldn't describe resources")
return
}
if len(resources) == 0 {
logger.Info("No tagged resources made it through filtering")
return
}
svc := SupportedServices.GetService(job.Type)
getMetricDatas := getMetricDataForQueries(ctx, job, svc, region, accountId, tagsOnMetrics, clientCloudwatch, resources, tagSemaphore, logger)
metricDataLength := len(getMetricDatas)
if metricDataLength == 0 {
logger.Debug("No metrics data found")
return
}
maxMetricCount := metricsPerQuery
length := GetMetricDataInputLength(job)
partition := int(math.Ceil(float64(metricDataLength) / float64(maxMetricCount)))
mux := &sync.Mutex{}
var wg sync.WaitGroup
wg.Add(partition)
for i := 0; i < metricDataLength; i += maxMetricCount {
go func(i int) {
defer wg.Done()
end := i + maxMetricCount
if end > metricDataLength {
end = metricDataLength
}
input := getMetricDatas[i:end]
filter := createGetMetricDataInput(input, &svc.Namespace, length, job.Delay, roundingPeriod, logger)
data := clientCloudwatch.getMetricData(ctx, filter)
if data != nil {
output := make([]*cloudwatchData, 0)
for _, MetricDataResult := range data.MetricDataResults {
getMetricData, err := findGetMetricDataById(input, *MetricDataResult.Id)
if err == nil {
if len(MetricDataResult.Values) != 0 {
getMetricData.GetMetricDataPoint = MetricDataResult.Values[0]
getMetricData.GetMetricDataTimestamps = MetricDataResult.Timestamps[0]
}
output = append(output, &getMetricData)
}
}
mux.Lock()
cw = append(cw, output...)
mux.Unlock()
}
}(i)
}
wg.Wait()
return resources, cw
}