-
Notifications
You must be signed in to change notification settings - Fork 2
/
sessions.go
465 lines (396 loc) · 14.7 KB
/
sessions.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
package exporter
import (
"fmt"
"os"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/apigateway"
"github.com/aws/aws-sdk-go/service/apigateway/apigatewayiface"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/autoscaling/autoscalingiface"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/aws/aws-sdk-go/service/cloudwatch/cloudwatchiface"
"github.com/aws/aws-sdk-go/service/databasemigrationservice"
"github.com/aws/aws-sdk-go/service/databasemigrationservice/databasemigrationserviceiface"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
r "github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi"
"github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/resourcegroupstaggingapiiface"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/aws/aws-sdk-go/service/sts/stsiface"
log "github.com/sirupsen/logrus"
)
// SessionCache is an interface to a cache of sessions and clients for all the
// roles specified by the exporter. For jobs with many duplicate roles, this provides
// relief to the AWS API and prevents timeouts by excessive credential requesting.
type SessionCache interface {
GetSTS(Role) stsiface.STSAPI
GetCloudwatch(*string, Role) cloudwatchiface.CloudWatchAPI
GetTagging(*string, Role) resourcegroupstaggingapiiface.ResourceGroupsTaggingAPIAPI
GetASG(*string, Role) autoscalingiface.AutoScalingAPI
GetEC2(*string, Role) ec2iface.EC2API
GetDMS(*string, Role) databasemigrationserviceiface.DatabaseMigrationServiceAPI
GetAPIGateway(*string, Role) apigatewayiface.APIGatewayAPI
Refresh()
Clear()
}
type sessionCache struct {
stsRegion string
session *session.Session
endpointResolver endpoints.ResolverFunc
stscache map[Role]stsiface.STSAPI
clients map[Role]map[string]*clientCache
cleared bool
refreshed bool
mu sync.Mutex
fips bool
}
type clientCache struct {
// if we know that this job is only used for static
// then we don't have to construct as many cached connections
// later on
onlyStatic bool
cloudwatch cloudwatchiface.CloudWatchAPI
tagging resourcegroupstaggingapiiface.ResourceGroupsTaggingAPIAPI
asg autoscalingiface.AutoScalingAPI
ec2 ec2iface.EC2API
dms databasemigrationserviceiface.DatabaseMigrationServiceAPI
apiGateway apigatewayiface.APIGatewayAPI
}
// NewSessionCache creates a new session cache to use when fetching data from
// AWS.
func NewSessionCache(config ScrapeConf, fips bool) SessionCache {
stscache := map[Role]stsiface.STSAPI{}
roleCache := map[Role]map[string]*clientCache{}
for _, discoveryJob := range config.Discovery.Jobs {
for _, role := range discoveryJob.Roles {
if _, ok := stscache[role]; !ok {
stscache[role] = nil
}
if _, ok := roleCache[role]; !ok {
roleCache[role] = map[string]*clientCache{}
}
for _, region := range discoveryJob.Regions {
roleCache[role][region] = &clientCache{}
}
}
}
for _, staticJob := range config.Static {
for _, role := range staticJob.Roles {
if _, ok := stscache[role]; !ok {
stscache[role] = nil
}
if _, ok := roleCache[role]; !ok {
roleCache[role] = map[string]*clientCache{}
}
for _, region := range staticJob.Regions {
// Only write a new region in if the region does not exist
if _, ok := roleCache[role][region]; !ok {
roleCache[role][region] = &clientCache{
onlyStatic: true,
}
}
}
}
}
endpointResolver := endpoints.DefaultResolver().EndpointFor
endpointUrlOverride := os.Getenv("AWS_ENDPOINT_URL")
if endpointUrlOverride != "" {
// allow override of all endpoints for local testing
endpointResolver = func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) {
return endpoints.ResolvedEndpoint{
URL: endpointUrlOverride,
}, nil
}
}
return &sessionCache{
stsRegion: config.StsRegion,
session: nil,
endpointResolver: endpointResolver,
stscache: stscache,
clients: roleCache,
fips: fips,
cleared: false,
refreshed: false,
}
}
// Refresh and Clear help to avoid using lock primitives by asserting that
// there are no ongoing writes to the map.
func (s *sessionCache) Clear() {
if s.cleared {
return
}
for role := range s.stscache {
s.stscache[role] = nil
}
for role, regions := range s.clients {
for region := range regions {
s.clients[role][region].cloudwatch = nil
s.clients[role][region].tagging = nil
s.clients[role][region].asg = nil
s.clients[role][region].ec2 = nil
s.clients[role][region].dms = nil
s.clients[role][region].apiGateway = nil
}
}
s.cleared = true
s.refreshed = false
}
func (s *sessionCache) Refresh() {
// TODO: make all the getter functions atomic pointer loads and sets
if s.refreshed {
return
}
// sessions really only need to be constructed once at runtime
if s.session == nil {
s.session = createAWSSession(s.endpointResolver)
}
for role := range s.stscache {
s.stscache[role] = createStsSession(s.session, role, s.stsRegion, s.fips)
}
for role, regions := range s.clients {
for region := range regions {
// if the role is just used in static jobs, then we
// can skip creating other sessions and potentially running
// into permissions errors or taking up needless cycles
s.clients[role][region].cloudwatch = createCloudwatchSession(s.session, ®ion, role, s.fips)
if s.clients[role][region].onlyStatic {
continue
}
s.clients[role][region].tagging = createTagSession(s.session, ®ion, role, s.fips)
s.clients[role][region].asg = createASGSession(s.session, ®ion, role, s.fips)
s.clients[role][region].ec2 = createEC2Session(s.session, ®ion, role, s.fips)
s.clients[role][region].dms = createDMSSession(s.session, ®ion, role, s.fips)
s.clients[role][region].apiGateway = createAPIGatewaySession(s.session, ®ion, role, s.fips)
}
}
s.cleared = false
s.refreshed = true
}
func (s *sessionCache) GetSTS(role Role) stsiface.STSAPI {
// if we have not refreshed then we need to lock in case we are accessing concurrently
if !s.refreshed {
s.mu.Lock()
defer s.mu.Unlock()
}
if sess, ok := s.stscache[role]; ok && sess != nil {
return sess
}
s.stscache[role] = createStsSession(s.session, role, s.stsRegion, s.fips)
return s.stscache[role]
}
func (s *sessionCache) GetCloudwatch(region *string, role Role) cloudwatchiface.CloudWatchAPI {
// if we have not refreshed then we need to lock in case we are accessing concurrently
if !s.refreshed {
s.mu.Lock()
defer s.mu.Unlock()
}
if sess, ok := s.clients[role][*region]; ok && sess.cloudwatch != nil {
return sess.cloudwatch
}
s.clients[role][*region].cloudwatch = createCloudwatchSession(s.session, region, role, s.fips)
return s.clients[role][*region].cloudwatch
}
func (s *sessionCache) GetTagging(region *string, role Role) resourcegroupstaggingapiiface.ResourceGroupsTaggingAPIAPI {
// if we have not refreshed then we need to lock in case we are accessing concurrently
if !s.refreshed {
s.mu.Lock()
defer s.mu.Unlock()
}
if sess, ok := s.clients[role][*region]; ok && sess.tagging != nil {
return sess.tagging
}
s.clients[role][*region].tagging = createTagSession(s.session, region, role, s.fips)
return s.clients[role][*region].tagging
}
func (s *sessionCache) GetASG(region *string, role Role) autoscalingiface.AutoScalingAPI {
// if we have not refreshed then we need to lock in case we are accessing concurrently
if !s.refreshed {
s.mu.Lock()
defer s.mu.Unlock()
}
if sess, ok := s.clients[role][*region]; ok && sess.asg != nil {
return sess.asg
}
s.clients[role][*region].asg = createASGSession(s.session, region, role, s.fips)
return s.clients[role][*region].asg
}
func (s *sessionCache) GetEC2(region *string, role Role) ec2iface.EC2API {
// if we have not refreshed then we need to lock in case we are accessing concurrently
if !s.refreshed {
s.mu.Lock()
defer s.mu.Unlock()
}
if sess, ok := s.clients[role][*region]; ok && sess.ec2 != nil {
return sess.ec2
}
s.clients[role][*region].ec2 = createEC2Session(s.session, region, role, s.fips)
return s.clients[role][*region].ec2
}
func (s *sessionCache) GetDMS(region *string, role Role) databasemigrationserviceiface.DatabaseMigrationServiceAPI {
// if we have not refreshed then we need to lock in case we are accessing concurrently
if !s.refreshed {
s.mu.Lock()
defer s.mu.Unlock()
}
if sess, ok := s.clients[role][*region]; ok && sess.dms != nil {
return sess.dms
}
s.clients[role][*region].dms = createDMSSession(s.session, region, role, s.fips)
return s.clients[role][*region].dms
}
func (s *sessionCache) GetAPIGateway(region *string, role Role) apigatewayiface.APIGatewayAPI {
// if we have not refreshed then we need to lock in case we are accessing concurrently
if !s.refreshed {
s.mu.Lock()
defer s.mu.Unlock()
}
if sess, ok := s.clients[role][*region]; ok && sess.apiGateway != nil {
return sess.apiGateway
}
s.clients[role][*region].apiGateway = createAPIGatewaySession(s.session, region, role, s.fips)
return s.clients[role][*region].apiGateway
}
func setExternalID(ID string) func(p *stscreds.AssumeRoleProvider) {
return func(p *stscreds.AssumeRoleProvider) {
if ID != "" {
p.ExternalID = aws.String(ID)
}
}
}
func setSTSCreds(sess *session.Session, config *aws.Config, role Role) *aws.Config {
if role.RoleArn != "" {
config.Credentials = stscreds.NewCredentials(
sess, role.RoleArn, setExternalID(role.ExternalID))
}
return config
}
func getAwsRetryer() aws.RequestRetryer {
return client.DefaultRetryer{
NumMaxRetries: 5,
// MaxThrottleDelay and MinThrottleDelay used for throttle errors
MaxThrottleDelay: 10 * time.Second,
MinThrottleDelay: 1 * time.Second,
// For other errors
MaxRetryDelay: 3 * time.Second,
MinRetryDelay: 1 * time.Second,
}
}
func createAWSSession(resolver endpoints.ResolverFunc) *session.Session {
config := aws.Config{
CredentialsChainVerboseErrors: aws.Bool(true),
EndpointResolver: resolver,
}
if log.IsLevelEnabled(log.DebugLevel) {
config.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
}
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
Config: config,
}))
return sess
}
func createStsSession(sess *session.Session, role Role, region string, fips bool) *sts.STS {
maxStsRetries := 5
config := &aws.Config{MaxRetries: &maxStsRetries}
if region != "" {
config = config.WithRegion(region).WithSTSRegionalEndpoint(endpoints.RegionalSTSEndpoint)
}
if fips {
// https://aws.amazon.com/compliance/fips/
endpoint := fmt.Sprintf("https://sts-fips.%s.amazonaws.com", region)
config.Endpoint = aws.String(endpoint)
}
if log.IsLevelEnabled(log.DebugLevel) {
config.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
}
return sts.New(sess, setSTSCreds(sess, config, role))
}
func createCloudwatchSession(sess *session.Session, region *string, role Role, fips bool) *cloudwatch.CloudWatch {
config := &aws.Config{Region: region, Retryer: getAwsRetryer()}
if fips {
// https://docs.aws.amazon.com/general/latest/gr/cw_region.html
endpoint := fmt.Sprintf("https://monitoring-fips.%s.amazonaws.com", *region)
config.Endpoint = aws.String(endpoint)
}
if log.IsLevelEnabled(log.DebugLevel) {
config.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
}
return cloudwatch.New(sess, setSTSCreds(sess, config, role))
}
func createTagSession(sess *session.Session, region *string, role Role, fips bool) *r.ResourceGroupsTaggingAPI {
maxResourceGroupTaggingRetries := 5
config := &aws.Config{
Region: region,
MaxRetries: &maxResourceGroupTaggingRetries,
CredentialsChainVerboseErrors: aws.Bool(true),
}
if log.IsLevelEnabled(log.DebugLevel) {
config.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
}
// ToDo: Resource Groups Tagging API does not have FIPS compliant endpoints
// if fips {
// https://docs.aws.amazon.com/general/latest/gr/arg.html
// endpoint := fmt.Sprintf("https://tagging-fips.%s.amazonaws.com", *region)
// config.Endpoint = aws.String(endpoint)
// }
return r.New(sess, setSTSCreds(sess, config, role))
}
func createASGSession(sess *session.Session, region *string, role Role, fips bool) autoscalingiface.AutoScalingAPI {
maxAutoScalingAPIRetries := 5
config := &aws.Config{Region: region, MaxRetries: &maxAutoScalingAPIRetries}
if log.IsLevelEnabled(log.DebugLevel) {
config.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
}
// ToDo: Autoscaling does not have a FIPS endpoint
// if fips {
// https://docs.aws.amazon.com/general/latest/gr/autoscaling_region.html
// endpoint := fmt.Sprintf("https://autoscaling-plans-fips.%s.amazonaws.com", *region)
// config.Endpoint = aws.String(endpoint)
// }
return autoscaling.New(sess, setSTSCreds(sess, config, role))
}
func createEC2Session(sess *session.Session, region *string, role Role, fips bool) ec2iface.EC2API {
maxEC2APIRetries := 10
config := &aws.Config{Region: region, MaxRetries: &maxEC2APIRetries}
if fips {
// https://docs.aws.amazon.com/general/latest/gr/ec2-service.html
endpoint := fmt.Sprintf("https://ec2-fips.%s.amazonaws.com", *region)
config.Endpoint = aws.String(endpoint)
}
if log.IsLevelEnabled(log.DebugLevel) {
config.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
}
return ec2.New(sess, setSTSCreds(sess, config, role))
}
func createDMSSession(sess *session.Session, region *string, role Role, fips bool) databasemigrationserviceiface.DatabaseMigrationServiceAPI {
maxDMSAPIRetries := 5
config := &aws.Config{Region: region, MaxRetries: &maxDMSAPIRetries}
if fips {
// https://docs.aws.amazon.com/general/latest/gr/dms.html
endpoint := fmt.Sprintf("https://dms-fips.%s.amazonaws.com", *region)
config.Endpoint = aws.String(endpoint)
}
if log.IsLevelEnabled(log.DebugLevel) {
config.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
}
return databasemigrationservice.New(sess, setSTSCreds(sess, config, role))
}
func createAPIGatewaySession(sess *session.Session, region *string, role Role, fips bool) apigatewayiface.APIGatewayAPI {
maxAPIGatewayAPIRetries := 5
config := &aws.Config{Region: region, MaxRetries: &maxAPIGatewayAPIRetries}
if fips {
// https://docs.aws.amazon.com/general/latest/gr/apigateway.html
endpoint := fmt.Sprintf("https://apigateway-fips.%s.amazonaws.com", *region)
config.Endpoint = aws.String(endpoint)
}
if log.IsLevelEnabled(log.DebugLevel) {
config.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
}
return apigateway.New(sess, setSTSCreds(sess, config, role))
}