-
Notifications
You must be signed in to change notification settings - Fork 80
/
accountcollector.py
2556 lines (2365 loc) · 121 KB
/
accountcollector.py
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import concurrent.futures
import json
import re
import socket
from collections.abc import Mapping
from functools import lru_cache
from pprint import pformat
from threading import Lock
from typing import Tuple, Callable, Pattern
import botocore.exceptions
import urllib3
from botocore.client import BaseClient
from pkg_resources import resource_filename
from retrying import retry
from resotolib.config import Config
from resotolib.types import Json
from resotolib.utils import chunks, rrdata_as_dict
from .resources import *
from .utils import aws_session, paginate, arn_partition
# boto3 has no way of converting between short and long region names
# The pricing API expects long region names, whereas ever other API works with short region names.
# The mapping can be found in one of the SDK's resource files 'endpoints.json' from where we read it.
endpoint_file = resource_filename("botocore", "data/endpoints.json")
with open(endpoint_file, "r") as f:
endpoints = json.load(f)
first_partition: Json = next(iter(endpoints.get("partitions", [])), {})
EC2_TO_PRICING_REGIONS = {k: v["description"] for k, v in first_partition.get("regions", {}).items()}
# Again the pricing API uses slightly different tenancy names than all the other APIs.
# This static mapping translates between them.
PRICING_TO_EC2_TENANCY = {"Shared": "default", "Host": "host", "Dedicated": "dedicated"}
EBS_TO_PRICING_NAMES = {
"standard": "Magnetic",
"gp2": "General Purpose",
"gp3": "General Purpose",
"io1": "Provisioned IOPS",
"st1": "Throughput Optimized HDD",
"sc1": "Cold HDD",
}
# This dict maps from quota names to service names.
# If the key is a string we try to match it directly.
# If the key is a re.Pattern we'll try to match that. If it's value is of type int we'll map to that group number
# otherwise we'll use the string value as the key in the resulting map.
QUOTA_TO_SERVICE_MAP: Dict[str, Dict[Union[str, Pattern[str]], Union[str, int]]] = {
"ebs": {
"General Purpose (SSD) volume storage": "gp2",
"Magnetic volume storage": "standard",
"Max Cold HDD (SC1) Storage": "sc1",
"Max Throughput Optimized HDD (ST1) Storage": "st1",
"Provisioned IOPS (SSD) volume storage": "io1",
"Number of EBS snapshots": "snapshots",
"Provisioned IOPS": "iops",
},
"vpc": {"Internet gateways per Region": "igw", "VPCs per Region": "vpc"},
"ec2": {
"Total running On-Demand instances": "total",
"Running On-Demand F instances": "f_ondemand",
"Running On-Demand G instances": "g_ondemand",
"Running On-Demand Inf instances": "inf_ondemand",
"Running On-Demand P instances": "p_ondemand",
"Running On-Demand X instances": "x_ondemand",
"Running On-Demand Standard (A, C, D, H, I, M, R, T, Z) instances": "standard_ondemand",
re.compile("Running On-Demand (.*) hosts"): 1,
},
"elasticloadbalancing": {
"Application Load Balancers per Region": "alb",
"Classic Load Balancers per Region": "elb",
},
"s3": {},
"iam": {
"Access keys per user": "access_keys_per_user",
"Groups per account": "groups",
"Customer managed policies per account": "policies",
"Instance profiles per account": "instance_profiles",
"Roles per account": "roles",
"Server certificates per account": "server_certificates",
"Users per account": "users",
},
}
metrics_unhandled_collector_exceptions = Counter(
"resoto_plugin_aws_unhandled_collector_exceptions_total",
"Unhandled AWS Plugin Collector Exceptions",
["account", "region", "collector"],
)
metrics_collect_vpcs = Summary(
"resoto_plugin_aws_collect_vpcs_seconds",
"Time it took the collect_vpcs() method",
)
metrics_collect_subnets = Summary(
"resoto_plugin_aws_collect_subnets_seconds",
"Time it took the collect_subnets() method",
)
metrics_collect_route_tables = Summary(
"resoto_plugin_aws_collect_route_tables_seconds",
"Time it took the collectroute_tables() method",
)
metrics_collect_security_groups = Summary(
"resoto_plugin_aws_collect_security_groups_seconds",
"Time it took the collect_security_groups() method",
)
metrics_collect_internet_gateways = Summary(
"resoto_plugin_aws_collect_internet_gateways_seconds",
"Time it took the collect_internet_gateways() method",
)
metrics_collect_instances = Summary(
"resoto_plugin_aws_collect_instances_seconds",
"Time it took the collect_instances() method",
)
metrics_collect_lambda_functions = Summary(
"resoto_plugin_aws_collect_lambda_functions_seconds",
"Time it took the collect_lambda_functions() method",
)
metrics_collect_keypairs = Summary(
"resoto_plugin_aws_collect_keypairs_seconds",
"Time it took the collect_keypairs() method",
)
metrics_collect_autoscaling_groups = Summary(
"resoto_plugin_aws_collect_autoscaling_groups_seconds",
"Time it took the collect_autoscaling_groups() method",
)
metrics_collect_reserved_instances = Summary(
"resoto_plugin_aws_collect_reserved_instances_seconds",
"Time it took the collect_reserved_instances() method",
)
metrics_collect_volumes = Summary(
"resoto_plugin_aws_collect_volumes_seconds",
"Time it took the collect_volumes() method",
)
metrics_collect_snapshots = Summary(
"resoto_plugin_aws_collect_snapshots_seconds",
"Time it took the collect_snapshots() method",
)
metrics_collect_volume_metrics = Summary(
"resoto_plugin_aws_collect_volume_metrics_seconds",
"Time it took the collect_volume_metrics() method",
)
metrics_collect_network_interfaces = Summary(
"resoto_plugin_aws_collect_network_interfaces_seconds",
"Time it took the collect_network_interfaces() method",
)
metrics_collect_network_acls = Summary(
"resoto_plugin_aws_collect_network_acls_seconds",
"Time it took the collect_network_acls() method",
)
metrics_collect_nat_gateways = Summary(
"resoto_plugin_aws_collect_nat_gateways_seconds",
"Time it took the collect_nat_gateways() method",
)
metrics_collect_vpc_peering_connections = Summary(
"resoto_plugin_aws_collect_vpc_peering_connections_seconds",
"Time it took the collect_vpc_peering_connections() method",
)
metrics_collect_vpc_endpoints = Summary(
"resoto_plugin_aws_collect_vpc_endpoints_seconds",
"Time it took the collect_vpc_endpoints() method",
)
metrics_collect_buckets = Summary(
"resoto_plugin_aws_collect_buckets_seconds",
"Time it took the collect_buckets() method",
)
metrics_collect_s3_buckets = Summary(
"resoto_plugin_aws_collect_s3_buckets_seconds",
"Time it took the collect_s3_buckets() method",
)
metrics_collect_elbs = Summary(
"resoto_plugin_aws_collect_elbs_seconds",
"Time it took the collect_elbs() method",
)
metrics_collect_alb_target_groups = Summary(
"resoto_plugin_aws_collect_alb_target_groups_seconds",
"Time it took the collect_alb_target_groups() method",
)
metrics_collect_albs = Summary(
"resoto_plugin_aws_collect_albs_seconds",
"Time it took the collect_albs() method",
)
metrics_collect_rds_instances = Summary(
"resoto_plugin_aws_collect_rds_instances_seconds",
"Time it took the collect_rds_instances() method",
)
metrics_collect_rds_metrics = Summary(
"resoto_plugin_aws_collect_rds_metrics_seconds",
"Time it took the collect_rds_metrics() method",
)
metrics_collect_iam_account_summary = Summary(
"resoto_plugin_aws_collect_iam_account_summary_seconds",
"Time it took the collect_iam_account_summary() method",
)
metrics_collect_iam_policies = Summary(
"resoto_plugin_aws_collect_iam_policies_seconds",
"Time it took the collect_iam_policies() method",
)
metrics_collect_iam_groups = Summary(
"resoto_plugin_aws_collect_iam_groups_seconds",
"Time it took the collect_iam_groups() method",
)
metrics_collect_iam_instance_profiles = Summary(
"resoto_plugin_aws_collect_iam_instance_profiles_seconds",
"Time it took the collect_iam_instance_profiles() method",
)
metrics_collect_iam_roles = Summary(
"resoto_plugin_aws_collect_iam_roles_seconds",
"Time it took the collect_iam_roles() method",
)
metrics_collect_iam_users = Summary(
"resoto_plugin_aws_collect_iam_users_seconds",
"Time it took the collect_iam_users() method",
)
metrics_collect_iam_server_certificates = Summary(
"resoto_plugin_aws_collect_iam_server_certificates_seconds",
"Time it took the collect_iam_server_certificates() method",
)
metrics_collect_cloudformation_stacks = Summary(
"resoto_plugin_aws_collect_cloudformation_stacks_seconds",
"Time it took the collect_cloudformation_stacks() method",
)
metrics_collect_cloudformation_stack_sets = Summary(
"resoto_plugin_aws_collect_cloudformation_stack_sets_seconds",
"Time it took the collect_cloudformation_stack_sets() method",
)
metrics_collect_eks_clusters = Summary(
"resoto_plugin_aws_collect_eks_clusters_seconds",
"Time it took the collect_eks_clusters() method",
)
metrics_collect_elastic_ips = Summary(
"resoto_plugin_aws_collect_elastic_ips_seconds",
"Time it took the collect_elastic_ips() method",
)
metrics_get_eks_nodegroups = Summary(
"resoto_plugin_aws_get_eks_nodegroups_seconds",
"Time it took the get_eks_nodegroups() method",
)
metrics_collect_cloudwatch_alarms = Summary(
"resoto_plugin_aws_collect_cloudwatch_alarms_seconds",
"Time it took the collect_cloudwatch_alarms() method",
)
metrics_collect_route53_zones = Summary(
"resoto_plugin_aws_collect_route53_zones_seconds",
"Time it took the collect_route53_zones() method",
)
def retry_on_request_limit_exceeded(e: Exception) -> bool:
if isinstance(e, botocore.exceptions.ClientError):
if e.response["Error"]["Code"] in ("RequestLimitExceeded", "Throttling"):
log.debug("AWS API request limit exceeded or throttling, retrying with exponential backoff")
return True
return False
CollectorFn = Callable[[AWSRegion, Graph], None]
class AWSAccountCollector:
def __init__(self, regions: List[str], account: AWSAccount) -> None:
self.regions = [AWSRegion(id=region, tags={}, account=account) for region in regions]
self.account = account
self.root = self.account
self.graph = Graph(root=self.account)
# The pricing info is being used to cache the results of pricing information. This way we don't ask
# the API 10 times what the price of an e.g. m5.xlarge instance is. The lock is being used to ensure
# we're not doing multiple identical calls while fetching instance information in parallel threads.
# service -> region -> instance_type_name -> instance type
self._price_info: Dict[str, Dict[str, Dict[str, AWSEC2InstanceType]]] = {"ec2": {}, "ebs": {}}
self._price_info_lock = Lock()
self.global_collectors: Dict[str, CollectorFn] = {
"iam_account_summary": self.collect_iam_account_summary,
"iam_policies": self.collect_iam_policies,
"iam_groups": self.collect_iam_groups,
"iam_instance_profiles": self.collect_iam_instance_profiles,
"iam_roles": self.collect_iam_roles,
"iam_users": self.collect_iam_users,
"iam_server_certificates": self.collect_iam_server_certificates,
"s3_buckets": self.collect_s3_buckets,
"route53_zones": self.collect_route53_zones,
}
self.region_collectors = {
"reserved_instances": self.collect_reserved_instances,
"vpcs": self.collect_vpcs,
"subnets": self.collect_subnets,
"route_tables": self.collect_route_tables,
"security_groups": self.collect_security_groups,
"internet_gateways": self.collect_internet_gateways,
"keypairs": self.collect_keypairs,
"instances": self.collect_instances,
"lambda_functions": self.collect_lambda_functions,
"volumes": self.collect_volumes,
"snapshots": self.collect_snapshots,
"elbs": self.collect_elbs,
"albs": self.collect_albs,
"alb_target_groups": self.collect_alb_target_groups,
"autoscaling_groups": self.collect_autoscaling_groups,
"network_acls": self.collect_network_acls,
"network_interfaces": self.collect_network_interfaces,
"nat_gateways": self.collect_nat_gateways,
"rds_instances": self.collect_rds_instances,
"cloudformation_stack_sets": self.collect_cloudformation_stack_sets,
"cloudformation_stacks": self.collect_cloudformation_stacks,
"eks_clusters": self.collect_eks_clusters,
"vpc_peering_connections": self.collect_vpc_peering_connections,
"vpc_endpoints": self.collect_vpc_endpoints,
"elastic_ips": self.collect_elastic_ips,
"cloudwatch_alarms": self.collect_cloudwatch_alarms,
}
self.collector_set = set(self.global_collectors.keys()).union(set(self.region_collectors.keys()))
def collect(self) -> None:
account_alias = self.account_alias()
if account_alias:
self.account.name = self.account.account_alias = account_alias
collectors = self.collector_set
if len(Config.aws.collect) > 0:
collectors = set(Config.aws.collect).intersection(self.collector_set)
log.debug(f"Running the following collectors in account {self.account.dname}: {', '.join(collectors)}")
# Collect global resources like IAM and S3 first
global_region = AWSRegion(id="us-east-1", tags={}, name="global", account=self.account)
graph = self.collect_resources(self.global_collectors, global_region)
log.debug(f"Adding graph of region {global_region.name} to account graph")
self.graph.merge(graph)
# Collect regions in parallel after global resources have been collected
with concurrent.futures.ThreadPoolExecutor(
max_workers=Config.aws.region_pool_size,
thread_name_prefix=f"aws_{self.account.id}",
) as executor:
futures = {
executor.submit(self.collect_resources, self.region_collectors, region): region
for region in self.regions
}
for future in concurrent.futures.as_completed(futures):
region = futures[future]
try:
graph = future.result()
except Exception:
log.exception(
(
f"Unhandeled exception while collecting resources in "
f"account {self.account.dname} region {region.name}"
)
)
else:
log.debug(f"Adding graph of region {region.name} to account graph")
self.graph.merge(graph)
@retry( # type: ignore
stop_max_attempt_number=10,
wait_exponential_multiplier=3000,
wait_exponential_max=300000,
retry_on_exception=retry_on_request_limit_exceeded,
)
def collect_resources(self, collectors: Dict[str, CollectorFn], region: AWSRegion) -> Graph:
log.info(f"Collecting resources in AWS account {self.account.dname} region {region.name}")
graph = Graph(root=region)
for collector_name, collector in collectors.items():
if (
len(Config.aws.collect) > 0 and collector_name not in Config.aws.collect
) or collector_name in Config.aws.no_collect:
log.debug(
f"Not running {collector_name} collector in account {self.account.dname} region {region.name}"
)
continue
try:
log.debug(f"Running {collector_name} collector in account {self.account.dname} region {region.name}")
collector(region, graph)
except botocore.exceptions.ClientError as e:
if e.response["Error"]["Code"] == "UnauthorizedOperation":
log.error(f"Not authorized to collect resources in account {self.account.dname} region {region.id}")
return graph
elif e.response["Error"]["Code"] in (
"RequestLimitExceeded",
"Throttling",
):
raise
else:
log.exception(
(
f"An AWS API error occured during {collector_name} resource collection in "
f"account {self.account.dname} region {region.name} - skipping resources"
)
)
metrics_unhandled_collector_exceptions.labels(
account=self.account.dname,
region=region.name,
collector=collector_name,
).inc()
except Exception:
log.exception(
(
f"Unhandeled collector exception while collecting {collector_name} resources in "
f"account {self.account.dname} region {region.name}"
)
)
metrics_unhandled_collector_exceptions.labels(
account=self.account.dname,
region=region.name,
collector=collector_name,
).inc()
return graph
# todo: more targeted caching than four layers of lru_cache()
@lru_cache()
def get_s3_service_quotas(self, region: AWSRegion) -> Dict[str, float]:
log.debug(f"Retrieving AWS S3 Service Quotas in account {self.account.dname} region {region.id}")
return self.get_service_quotas(region, "s3")
@lru_cache()
def get_elb_service_quotas(self, region: AWSRegion) -> Dict[str, float]:
log.debug(f"Retrieving AWS ELB Service Quotas in account {self.account.dname} region {region.id}")
return self.get_service_quotas(region, "elasticloadbalancing")
@lru_cache()
def get_vpc_service_quotas(self, region: AWSRegion) -> Dict[str, float]:
log.debug(f"Retrieving AWS VPC Service Quotas in account {self.account.dname} region {region.id}")
return self.get_service_quotas(region, "vpc")
@lru_cache()
def get_ec2_instance_type_quota(self, region: AWSRegion, instance_type: str) -> float:
# TODO: support dedicated hosts
log.debug(
(
f"Retrieving AWS EC2 Instance Type Quota in account {self.account.dname} region {region.id} "
f"for instance type {instance_type}"
)
)
return self.get_ec2_service_quotas(region).get(instance_type, 0)
@lru_cache()
def get_ec2_service_quotas(self, region: AWSRegion) -> Dict[str, float]:
log.debug(f"Retrieving AWS EC2 Service Quotas in account {self.account.dname} region {region.id}")
return self.get_service_quotas(region, "ec2")
@lru_cache()
def get_ebs_volume_type_quota(self, region: AWSRegion, volume_type: str) -> float:
log.debug(
(
f"Retrieving AWS EBS Volume Type Quota in account {self.account.dname} region {region.id} "
f"for instance type {volume_type}"
)
)
return self.get_ebs_service_quotas(region).get(volume_type, 0)
@lru_cache()
def get_ebs_service_quotas(self, region: AWSRegion) -> Dict[str, float]:
log.debug(f"Retrieving AWS EBS Service Quotas in account {self.account.dname} region {region.id}")
return self.get_service_quotas(region, "ebs")
@lru_cache()
def get_iam_service_quotas(self, region: AWSRegion) -> Dict[str, float]:
log.debug(f"Retrieving AWS IAM Service Quotas in account {self.account.dname} region {region.id}")
return self.get_service_quotas(region, "iam")
@lru_cache()
def get_service_quotas(self, region: AWSRegion, service: str) -> Dict[str, float]:
try:
service_quotas = self.get_raw_service_quotas(region, service)
except botocore.exceptions.ClientError:
log.exception(f"Failed to retrieve raw service quotas in account {self.account.dname} region {region.name}")
metrics_unhandled_collector_exceptions.labels(
account=self.account.name, region=region.name, collector="Service Quota"
).inc()
return {}
log.debug(
(
f"Trying to parse raw AWS Service Quotas in account {self.account.dname} region {region.id} for "
f"service {service}"
)
)
quotas: Dict[str, float] = {}
if service not in QUOTA_TO_SERVICE_MAP:
log.error(f"Service {service} not in quota service map")
return quotas
for service_quota in service_quotas:
quota_name = str(service_quota.get("QuotaName", ""))
quota_value = float(service_quota.get("Value", -1.0))
service_name: str = QUOTA_TO_SERVICE_MAP[service].get(quota_name) # type: ignore
if service_name:
quotas[service_name] = quota_value
else:
for key, value in QUOTA_TO_SERVICE_MAP[service].items():
if isinstance(key, re.Pattern):
m = key.search(quota_name)
if m:
if isinstance(value, int):
try:
quotas[m.group(value)] = quota_value
except IndexError:
log.error(f"Group {value} specified for regex {key} does not exist")
else:
quotas[value] = quota_value
return quotas
@lru_cache()
def get_raw_service_quotas(self, region: AWSRegion, service: str) -> List[Json]:
log.debug(
(
f"Retrieving raw AWS Service Quotas in account {self.account.dname} region {region.id} for "
f"service {service}"
)
)
service_quotas: List[Json] = []
if "quotas" in Config.aws.no_collect:
log.debug(
(
f"Skipping quotas collection in account {self.account.dname} region {region.id} for "
f"service {service}"
)
)
return service_quotas
try:
session = aws_session(self.account.id, self.account.role, self.account.profile)
client = session.client("service-quotas", region_name=region.id)
response = client.list_service_quotas(ServiceCode=service)
service_quotas = response.get("Quotas", [])
while response.get("NextToken") is not None:
response = client.list_service_quotas(ServiceCode=service, NextToken=response["NextToken"])
service_quotas.extend(response.get("Quotas", []))
except (
socket.gaierror,
urllib3.exceptions.NewConnectionError,
botocore.exceptions.EndpointConnectionError,
):
log.error(f"AWS Service Quotas Endpoint not available in region {region.id}")
return service_quotas
@metrics_collect_volumes.time() # type: ignore
def collect_volumes(self, region: AWSRegion, graph: Graph) -> None:
log.info(f"Collecting AWS EBS Volumes in account {self.account.dname} region {region.id}")
session = aws_session(self.account.id, self.account.role, self.account.profile)
ec2 = session.resource("ec2", region_name=region.id)
volumes = []
now = datetime.utcnow().replace(tzinfo=timezone.utc)
volume_status_map: Dict[str, VolumeStatus] = {
"creating": VolumeStatus.BUSY,
"available": VolumeStatus.AVAILABLE,
"in-use": VolumeStatus.IN_USE,
"deleting": VolumeStatus.BUSY,
"deleted": VolumeStatus.DELETED,
"error": VolumeStatus.ERROR,
"busy": VolumeStatus.BUSY,
}
for volume in ec2.volumes.all():
try:
v = AWSEC2Volume(
id=volume.id,
tags=tags_as_dict(volume.tags),
account=self.account,
region=region,
ctime=volume.create_time,
atime=now,
volume_status=volume_status_map.get(volume.state, VolumeStatus.UNKNOWN),
)
v.name = v.tags.get("Name") or v.id
v.volume_size = volume.size
v.volume_type = volume.volume_type
v.volume_encrypted = volume.encrypted
v.volume_throughput = volume.throughput
v.volume_iops = volume.iops
v.volume_kms_key_id = volume.kms_key_id
v.volume_multi_attach_enabled = volume.multi_attach_enabled
v.volume_outpost_arn = volume.outpost_arn
v.volume_snapshot_id = volume.snapshot_id
log.debug(f"Found volume {v.id} of type {v.volume_type} size {v.volume_size} status {v.volume_status}")
graph.add_resource(region, v)
volumes.append(v)
try:
volume_type_info = self.get_volume_type_info(region, graph, v.volume_type)
except Exception:
log.exception(f"Unable to retrieve volume type info for {v.rtdname}")
volume_type_info = None
if volume_type_info:
graph.add_edge(volume_type_info, v)
for attachment in volume.attachments:
if "InstanceId" in attachment:
instance_id = attachment["InstanceId"]
log.debug(f"Volume {volume.id} is attached to instance {instance_id}")
instance = graph.search_first("id", instance_id)
if instance:
graph.add_edge(instance, v)
graph.add_edge(v, instance, edge_type=EdgeType.delete)
except botocore.exceptions.ClientError:
log.exception(f"Some boto3 call failed on resource {volume} - skipping")
self.collect_volume_metrics(region, volumes)
@metrics_collect_volume_metrics.time() # type: ignore
def collect_volume_metrics(self, region: AWSRegion, volumes: List[AWSEC2Volume]) -> None:
resources = [volume for volume in volumes if volume.volume_status == "available"]
log.info(
(
f"Collecting AWS EBS Volume Metrics for {len(resources)} volumes in "
f"account {self.account.dname} region {region.id}"
)
)
atime_metric = "VolumeReadOps"
mtime_metric = "VolumeWriteOps"
namespace = "AWS/EBS"
dimension_name = "VolumeId"
dimension_attr = "id"
resource_prefix = "vol"
for chunk in chunks(resources, 100):
self.set_metrics(
region,
chunk,
atime_metric,
mtime_metric,
namespace,
dimension_name,
dimension_attr,
resource_prefix,
)
@metrics_collect_rds_metrics.time() # type: ignore
def collect_rds_metrics(self, region: AWSRegion, resources: List[BaseResource]) -> None:
log.info(
(
f"Collecting AWS RDS Metrics for {len(resources)} databases in "
f"account {self.account.dname} region {region.id}"
)
)
atime_metric = mtime_metric = "DatabaseConnections"
namespace = "AWS/RDS"
dimension_name = "DBInstanceIdentifier"
dimension_attr = "name"
resource_prefix = "db"
for chunk in chunks(resources, 100):
self.set_metrics(
region,
chunk,
atime_metric,
mtime_metric,
namespace,
dimension_name,
dimension_attr,
resource_prefix,
)
def set_metrics(
self,
region: AWSRegion,
resources: List[BaseResource],
atime_metric: str,
mtime_metric: str,
namespace: str,
dimension_name: str,
dimension_attr: str,
resource_prefix: str,
) -> None:
log.debug(
f"Setting AWS Metrics for {len(resources)} resources in account {self.account.dname} region {region.id}"
)
session = aws_session(self.account.id, self.account.role, self.account.profile)
cw = session.client("cloudwatch", region_name=region.id)
end_time = datetime.now()
start_time = end_time - timedelta(days=60)
if atime_metric == mtime_metric:
metric_names = [atime_metric]
else:
metric_names = [atime_metric, mtime_metric]
query = []
for resource in resources:
for metric_name in metric_names:
query.append(
{
"Id": "metric_" + metric_name + "_" + re.sub("[^0-9a-zA-Z]+", "_", resource.id),
"MetricStat": {
"Metric": {
"Namespace": namespace,
"MetricName": metric_name,
"Dimensions": [
{
"Name": dimension_name,
"Value": getattr(resource, dimension_attr),
}
],
},
"Period": 3600,
"Stat": "Sum",
"Unit": "Count",
},
"ReturnData": True,
}
)
response = self.get_metrics(cw, query, start_time, end_time)
metrics = response.get("MetricDataResults", [])
while response.get("NextToken") is not None and any(
(len(metric["Values"]) > 0 for metric in response.get("MetricDataResults", []))
):
response = self.get_metrics(cw, query, start_time, end_time, response.get("NextToken"))
metrics.extend(response.get("MetricDataResults", []))
try:
atime, mtime = self.get_atime_mtime_from_metrics(metrics, resource_prefix, atime_metric, mtime_metric)
# if after we retrieved a resources's metrics we don't find any atime/mtime for it
# we will fall back to setting atime/mtime to either the earliest date we tried to
# retrieve metrics for or the creation time of the volume, whichever is more recent
fallback_time = make_valid_timestamp(start_time)
for resource in resources:
if resource.ctime and fallback_time and resource.ctime > fallback_time:
fallback_time = resource.ctime
if resource.id in atime:
resource.atime = atime[resource.id]
else:
resource.atime = fallback_time
if resource.id in mtime:
resource.mtime = mtime[resource.id]
else:
resource.mtime = fallback_time
except ValueError:
log.exception("Error while processing resource metrics")
def get_atime_mtime_from_metrics(
self,
metrics: List[Any],
resource_prefix: str,
atime_metric: str,
mtime_metric: str,
) -> Tuple[Json, Json]:
atime: Json = {}
mtime: Json = {}
for metric in metrics:
id = metric.get("Id")
_, metric_name, resource_id = id.split("_", 2)
if not resource_id.startswith(f"{resource_prefix}_"):
raise ValueError(f"Invalid resource Id {resource_id}")
resource_prefix_idx = len(resource_prefix) + 1
resource_id = f"{resource_prefix}-" + resource_id[resource_prefix_idx:]
timestamps = metric.get("Timestamps", [])
values = metric.get("Values", [])
if len(timestamps) != len(values):
raise ValueError(f"Number of timestamps {len(timestamps)} doesn't match number of values {len(values)}")
if metric_name not in (atime_metric, mtime_metric):
raise ValueError(f"Retrieved unknown metric {metric_name}")
if (metric_name == atime_metric and resource_id in atime) or (
metric_name == mtime_metric and resource_id in mtime
):
continue
for timestamp, value in zip(timestamps, values):
if value > 0:
if metric_name == atime_metric and atime.get(resource_id) is None:
log.debug(f"Setting atime for {resource_id} to {timestamp}")
atime[resource_id] = timestamp
if metric_name == mtime_metric and mtime.get(resource_id) is None:
log.debug(f"Setting mtime for {resource_id} to {timestamp}")
mtime[resource_id] = timestamp
break
return (atime, mtime)
@retry( # type: ignore
stop_max_attempt_number=10,
wait_exponential_multiplier=3000,
wait_exponential_max=300000,
retry_on_exception=retry_on_request_limit_exceeded,
)
def get_metrics(
self, cw: BaseClient, query: Json, start_time: datetime, end_time: datetime, next_token: Optional[str] = None
) -> Dict[str, Any]:
log.debug("Fetching CloudWatch metrics")
if next_token:
response = cw.get_metric_data(
MetricDataQueries=query,
StartTime=start_time,
EndTime=end_time,
ScanBy="TimestampDescending",
NextToken=next_token,
)
else:
response = cw.get_metric_data(
MetricDataQueries=query,
StartTime=start_time,
EndTime=end_time,
ScanBy="TimestampDescending",
)
return response # type: ignore
# noinspection PyUnusedLocal
@metrics_collect_iam_account_summary.time() # type: ignore
def collect_iam_account_summary(self, region: AWSRegion, graph: Graph) -> None:
log.info(f"Collecting AWS IAM Account Summary in account {self.account.dname} region {region.name}")
session = aws_session(self.account.id, self.account.role, self.account.profile)
client = session.client("iam", region_name=region.id)
response_as = client.get_account_summary()
sm = response_as.get("SummaryMap", {})
self.account.users = int(sm.get("Users", 0))
self.account.groups = int(sm.get("Groups", 0))
self.account.account_mfa_enabled = int(sm.get("AccountMFAEnabled", 0))
self.account.account_access_keys_present = int(sm.get("AccountAccessKeysPresent", 0))
self.account.account_signing_certificates_present = int(sm.get("AccountSigningCertificatesPresent", 0))
self.account.mfa_devices = int(sm.get("MFADevices", 0))
self.account.mfa_devices_in_use = int(sm.get("MFADevicesInUse", 0))
self.account.policies = int(sm.get("Policies", 0))
self.account.policy_versions_in_use = int(sm.get("PolicyVersionsInUse", 0))
self.account.global_endpoint_token_version = int(sm.get("GlobalEndpointTokenVersion", 0))
self.account.server_certificates = int(sm.get("ServerCertificates", 0))
# boto will fail, when there is no Custom PasswordPolicy defined (only AWS Default). This is intended behaviour.
try:
response_app = client.get_account_password_policy()
app = response_app.get("PasswordPolicy", {})
self.account.minimum_password_length = int(app.get("MinimumPasswordLength", 0))
self.account.require_symbols = bool(app.get("RequireSymbols", None))
self.account.require_numbers = bool(app.get("RequireNumbers", None))
self.account.require_uppercase_characters = bool(app.get("RequireUppercaseCharacters", None))
self.account.require_lowercase_characters = bool(app.get("RequireLowercaseCharacters", None))
self.account.allow_users_to_change_password = bool(app.get("AllowUsersToChangePassword", None))
self.account.expire_passwords = bool(app.get("ExpirePasswords", None))
self.account.max_password_age = int(app.get("MaxPasswordAge", 0))
self.account.password_reuse_prevention = int(app.get("PasswordReusePrevention", 0))
self.account.hard_expiry = bool(app.get("HardExpiry", None))
except client.exceptions.NoSuchEntityException:
log.debug(f"The Password Policy for account {self.account.dname} cannot be found.")
@metrics_collect_iam_server_certificates.time() # type: ignore
def collect_iam_server_certificates(self, region: AWSRegion, graph: Graph) -> None:
log.info(f"Collecting AWS IAM Server Certificates in account {self.account.dname} region {region.id}")
cq = AWSIAMServerCertificateQuota(
id="iam_server_certificates_quota", tags={}, account=self.account, region=region
)
cq.quota = self.get_iam_service_quotas(region).get("server_certificates", -1.0)
graph.add_resource(region, cq)
session = aws_session(self.account.id, self.account.role, self.account.profile)
client = session.client("iam", region_name=region.id)
response = client.list_server_certificates()
certificates = response.get("ServerCertificateMetadataList", [])
while response.get("Marker") is not None:
response = client.list_server_certificates(Marker=response["Marker"])
certificates.extend(response.get("ServerCertificateMetadataList", []))
for certificate in certificates:
c = AWSIAMServerCertificate(
id=certificate["ServerCertificateId"],
tags={},
account=self.account,
region=region,
ctime=certificate.get("UploadDate"),
)
c.path = certificate.get("Path")
c.name = certificate.get("ServerCertificateName")
c.arn = certificate.get("Arn")
c.expires = certificate.get("Expiration")
log.debug(f"Found IAM Server Certificate {c.dname} in account {self.account.dname} region {region.id}")
graph.add_resource(region, c)
graph.add_edge(cq, c)
@metrics_collect_iam_policies.time() # type: ignore
def collect_iam_policies(self, region: AWSRegion, graph: Graph) -> None:
log.info(f"Collecting AWS IAM Policies in account {self.account.dname} region {region.id}")
session = aws_session(self.account.id, self.account.role, self.account.profile)
client = session.client("iam", region_name=region.id)
response = client.list_policies(Scope="Local", OnlyAttached=False)
policies = response.get("Policies", [])
while response.get("Marker") is not None:
response = client.list_policies(Scope="Local", OnlyAttached=False, Marker=response["Marker"])
policies.extend(response.get("Policies", []))
response = client.list_policies(Scope="AWS", OnlyAttached=True)
policies.extend(response.get("Policies", []))
while response.get("Marker") is not None:
response = client.list_policies(Scope="Local", OnlyAttached=True, Marker=response["Marker"])
policies.extend(response.get("Policies", []))
for policy in policies:
p = AWSIAMPolicy(
id=policy["PolicyId"],
tags={},
account=self.account,
region=region,
ctime=policy.get("CreateDate"),
)
p.name = policy.get("PolicyName")
p.arn = policy.get("Arn")
p.mtime = policy.get("UpdateDate")
# We can not delete AWS pre-defined policies
# so we mark them as phantom resource
if p.arn.startswith("arn:aws:iam::aws:"):
p.phantom = True
log.debug(f"Found {p.rtdname} ({p.id}) {self.account.dname} region {region.id}")
graph.add_resource(region, p)
@metrics_collect_iam_groups.time() # type: ignore
def collect_iam_groups(self, region: AWSRegion, graph: Graph) -> None:
log.info(f"Collecting AWS IAM Groups in account {self.account.dname} region {region.id}")
session = aws_session(self.account.id, self.account.role, self.account.profile)
client = session.client("iam", region_name=region.id)
response = client.list_groups()
groups = response.get("Groups", [])
while response.get("Marker") is not None:
response = client.list_policies(Marker=response["Marker"])
groups.extend(response.get("Groups", []))
for group in groups:
g = AWSIAMGroup(
id=group["GroupId"],
tags={},
account=self.account,
region=region,
ctime=group.get("CreateDate"),
)
g.name = group.get("GroupName")
g.arn = group.get("Arn")
log.debug(f"Found {g.rtdname} in account {self.account.dname} region {region.id}")
graph.add_resource(region, g)
group_session = aws_session(self.account.id, self.account.role, self.account.profile)
group_client = group_session.client("iam", region_name=region.id)
try:
group_response = group_client.list_group_policies(GroupName=g.name)
group_policies = group_response.get("PolicyNames", [])
while group_response.get("Marker") is not None:
group_response = group_client.list_group_policies(GroupName=g.name, Marker=group_response["Marker"])
group_policies.extend(group_response.get("PolicyNames", []))
g.group_policies = list(group_policies)
group_response = group_client.list_attached_group_policies(GroupName=g.name)
policies = group_response.get("AttachedPolicies", [])
while group_response.get("Marker") is not None:
group_response = group_client.list_attached_group_policies(
GroupName=g.name, Marker=group_response["Marker"]
)
policies.extend(group_response.get("AttachedPolicies", []))
for policy in policies:
p = graph.search_first("arn", policy["PolicyArn"])
if p:
graph.add_edge(p, g)
graph.add_edge(g, p, edge_type=EdgeType.delete)
except botocore.exceptions.ClientError as e:
if e.response["Error"]["Code"] == "NoSuchEntity":
log.exception(
(
f"An error occurred when trying to retrieve group information for "
f"group {g.name} in account {self.account.dname} region {region.name}"
)
)
continue
else:
raise
@metrics_collect_iam_instance_profiles.time() # type: ignore
def collect_iam_instance_profiles(self, region: AWSRegion, graph: Graph) -> None:
log.info(f"Collecting AWS IAM Instance Profiles in account {self.account.dname} region {region.id}")
session = aws_session(self.account.id, self.account.role, self.account.profile)
client = session.client("iam", region_name=region.id)
response = client.list_instance_profiles()
instance_profiles = response.get("InstanceProfiles", [])
while response.get("Marker") is not None:
response = client.list_instance_profiles(Marker=response["Marker"])
instance_profiles.extend(response.get("InstanceProfiles", []))
for instance_profile in instance_profiles:
ip = AWSIAMInstanceProfile(
id=instance_profile["InstanceProfileId"],
tags={},
account=self.account,
region=region,
ctime=instance_profile.get("CreateDate"),
)
ip.name = instance_profile.get("InstanceProfileName")
ip.arn = instance_profile.get("Arn")
log.debug(f"Found {ip.rtdname} in account {self.account.dname} region {region.id}")
graph.add_resource(region, ip)
@metrics_collect_iam_roles.time() # type: ignore
def collect_iam_roles(self, region: AWSRegion, graph: Graph) -> None:
log.info(f"Collecting AWS IAM Roles in account {self.account.dname} region {region.id}")
session = aws_session(self.account.id, self.account.role, self.account.profile)
client = session.client("iam", region_name=region.id)
response = client.list_roles()
roles = response.get("Roles", [])
while response.get("Marker") is not None: