aws-finops-agent 1.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- aws_finops_agent/__init__.py +3 -0
- aws_finops_agent/analyze.py +75 -0
- aws_finops_agent/analyzers/__init__.py +80 -0
- aws_finops_agent/analyzers/amazon_q_analyzer.py +117 -0
- aws_finops_agent/analyzers/analytics_analyzer.py +351 -0
- aws_finops_agent/analyzers/apigateway_analyzer.py +571 -0
- aws_finops_agent/analyzers/backup_analyzer.py +284 -0
- aws_finops_agent/analyzers/bedrock_analyzer.py +461 -0
- aws_finops_agent/analyzers/cloudfront_analyzer.py +292 -0
- aws_finops_agent/analyzers/cloudtrail_analyzer.py +169 -0
- aws_finops_agent/analyzers/cloudwatch_analyzer.py +276 -0
- aws_finops_agent/analyzers/codebuild_analyzer.py +138 -0
- aws_finops_agent/analyzers/config_analyzer.py +307 -0
- aws_finops_agent/analyzers/connect_analyzer.py +114 -0
- aws_finops_agent/analyzers/database_analyzer.py +278 -0
- aws_finops_agent/analyzers/directconnect_analyzer.py +667 -0
- aws_finops_agent/analyzers/documentdb_analyzer.py +231 -0
- aws_finops_agent/analyzers/ebs_analyzer.py +263 -0
- aws_finops_agent/analyzers/ec2_analyzer.py +849 -0
- aws_finops_agent/analyzers/ecr_analyzer.py +221 -0
- aws_finops_agent/analyzers/ecs_comprehensive_analyzer.py +962 -0
- aws_finops_agent/analyzers/eks_analyzer.py +1287 -0
- aws_finops_agent/analyzers/elasticache_analyzer.py +327 -0
- aws_finops_agent/analyzers/elb_analyzer.py +243 -0
- aws_finops_agent/analyzers/fargate_analyzer.py +366 -0
- aws_finops_agent/analyzers/function_adapter.py +162 -0
- aws_finops_agent/analyzers/guardduty_analyzer.py +311 -0
- aws_finops_agent/analyzers/inspector_analyzer.py +123 -0
- aws_finops_agent/analyzers/kms_analyzer.py +126 -0
- aws_finops_agent/analyzers/lambda_analyzer.py +284 -0
- aws_finops_agent/analyzers/macie_analyzer.py +398 -0
- aws_finops_agent/analyzers/messaging_analyzer.py +315 -0
- aws_finops_agent/analyzers/mq_analyzer.py +193 -0
- aws_finops_agent/analyzers/msk_analyzer.py +194 -0
- aws_finops_agent/analyzers/nat_gateway_analyzer.py +507 -0
- aws_finops_agent/analyzers/networking_analyzer.py +476 -0
- aws_finops_agent/analyzers/opensearch_analyzer.py +326 -0
- aws_finops_agent/analyzers/outposts_analyzer.py +81 -0
- aws_finops_agent/analyzers/rds_analyzer.py +339 -0
- aws_finops_agent/analyzers/redshift_analyzer.py +230 -0
- aws_finops_agent/analyzers/route53_analyzer.py +585 -0
- aws_finops_agent/analyzers/s3_analyzer.py +722 -0
- aws_finops_agent/analyzers/sagemaker_analyzer.py +543 -0
- aws_finops_agent/analyzers/storage_analyzer.py +427 -0
- aws_finops_agent/analyzers/support_analyzer.py +387 -0
- aws_finops_agent/analyzers/timestream_analyzer.py +139 -0
- aws_finops_agent/analyzers/transfer_analyzer.py +120 -0
- aws_finops_agent/analyzers/vpc_analyzer.py +224 -0
- aws_finops_agent/analyzers/waf_analyzer.py +243 -0
- aws_finops_agent/analyzers/workflow_analyzer.py +558 -0
- aws_finops_agent/analyzers/workspaces_analyzer.py +146 -0
- aws_finops_agent/analyzers/xray_analyzer.py +95 -0
- aws_finops_agent/aws/__init__.py +1 -0
- aws_finops_agent/aws/context.py +159 -0
- aws_finops_agent/aws/scan_scope.py +86 -0
- aws_finops_agent/cli.py +618 -0
- aws_finops_agent/config.py +29 -0
- aws_finops_agent/data/__init__.py +1 -0
- aws_finops_agent/data/fallback_pricing.py +323 -0
- aws_finops_agent/discovery.py +141 -0
- aws_finops_agent/identity.py +375 -0
- aws_finops_agent/llm.py +577 -0
- aws_finops_agent/mcp/__init__.py +4 -0
- aws_finops_agent/mcp/server.py +179 -0
- aws_finops_agent/mcp/tools.py +430 -0
- aws_finops_agent/models.py +346 -0
- aws_finops_agent/policy.py +185 -0
- aws_finops_agent/progress.py +98 -0
- aws_finops_agent/py.typed +0 -0
- aws_finops_agent/report.py +729 -0
- aws_finops_agent/review.py +495 -0
- aws_finops_agent/savings.py +32 -0
- aws_finops_agent/scan.py +136 -0
- aws_finops_agent/service_mappings.py +111 -0
- aws_finops_agent/services/__init__.py +1 -0
- aws_finops_agent/services/analyzer_registry.py +521 -0
- aws_finops_agent/services/aws_pricing_service.py +819 -0
- aws_finops_agent/services/data_transfer_optimization_service.py +282 -0
- aws_finops_agent/services/reserved_instance_recommender.py +313 -0
- aws_finops_agent/services/right_sizing_service.py +317 -0
- aws_finops_agent/services/savings_plans_service.py +120 -0
- aws_finops_agent/utils/__init__.py +1 -0
- aws_finops_agent/utils/js_number.py +140 -0
- aws_finops_agent-1.0.1.dist-info/METADATA +246 -0
- aws_finops_agent-1.0.1.dist-info/RECORD +88 -0
- aws_finops_agent-1.0.1.dist-info/WHEEL +4 -0
- aws_finops_agent-1.0.1.dist-info/entry_points.txt +3 -0
- aws_finops_agent-1.0.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Scan orchestration: run the analyzers for the billed services, region by region."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Sequence
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from aws_finops_agent.config import DEFAULT_CONCURRENCY
|
|
9
|
+
from aws_finops_agent.identity import join_identity
|
|
10
|
+
from aws_finops_agent.models import ActiveService, ServiceAnalysisResult
|
|
11
|
+
from aws_finops_agent.services.analyzer_registry import AnalyzerCatalog, AnalyzerRegistry
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from aws_finops_agent.aws.context import ScanContext
|
|
15
|
+
|
|
16
|
+
# Called as each analyzer starts (region None for global ones); the returned function
|
|
17
|
+
# is called when it ends.
|
|
18
|
+
OnAnalyzer = Callable[[str, "str | None"], "Callable[[], None] | None"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def analyze_services(
|
|
22
|
+
ctx: ScanContext,
|
|
23
|
+
services: Sequence[ActiveService],
|
|
24
|
+
*,
|
|
25
|
+
regions: Sequence[str],
|
|
26
|
+
concurrency: int | None = None,
|
|
27
|
+
catalog: AnalyzerCatalog | None = None,
|
|
28
|
+
on_analyzer: OnAnalyzer | None = None,
|
|
29
|
+
) -> list[ServiceAnalysisResult]:
|
|
30
|
+
"""Run the analyzers for the billed services from discovery.
|
|
31
|
+
|
|
32
|
+
Global analyzers run once; regional analyzers then run once per region, one region at
|
|
33
|
+
a time. Within each pass the highest-spend services start first, with at most
|
|
34
|
+
`concurrency` analyzers in flight. Findings come back joined to the scan's identity
|
|
35
|
+
index (see join_identity).
|
|
36
|
+
"""
|
|
37
|
+
limit = concurrency if concurrency is not None else DEFAULT_CONCURRENCY
|
|
38
|
+
registry = AnalyzerRegistry(catalog=catalog)
|
|
39
|
+
registry.register_analyzers_for_services([s.service_name for s in services])
|
|
40
|
+
|
|
41
|
+
def callback(region: str | None) -> Callable[[str], Callable[[], None] | None] | None:
|
|
42
|
+
if on_analyzer is None:
|
|
43
|
+
return None
|
|
44
|
+
return lambda name: on_analyzer(name, region)
|
|
45
|
+
|
|
46
|
+
results = registry.analyze_all_services(
|
|
47
|
+
ctx, services, concurrency=limit, scope="global", on_analyzer=callback(None)
|
|
48
|
+
)
|
|
49
|
+
for region in regions:
|
|
50
|
+
# Switch only between passes: use() closes the previous region's clients, and every
|
|
51
|
+
# task of the previous pass has finished by now.
|
|
52
|
+
ctx.use(region)
|
|
53
|
+
regional = registry.analyze_all_services(
|
|
54
|
+
ctx, services, concurrency=limit, scope="regional", on_analyzer=callback(region)
|
|
55
|
+
)
|
|
56
|
+
results.extend(_with_region(result, region) for result in regional)
|
|
57
|
+
# The single join point: identity (name, tags, exclusion) is attached here, before render.
|
|
58
|
+
return join_identity(ctx, results)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _with_region(result: ServiceAnalysisResult, region: str) -> ServiceAnalysisResult:
|
|
62
|
+
"""Stamp the scanned region on a regional result and on findings that did not set one."""
|
|
63
|
+
return result.model_copy(
|
|
64
|
+
update={
|
|
65
|
+
"region": region,
|
|
66
|
+
"recommendations": [
|
|
67
|
+
r if r.region is not None else r.model_copy(update={"region": region})
|
|
68
|
+
for r in result.recommendations
|
|
69
|
+
],
|
|
70
|
+
"waste_detected": [
|
|
71
|
+
w if w.region is not None else w.model_copy(update={"region": region})
|
|
72
|
+
for w in result.waste_detected
|
|
73
|
+
],
|
|
74
|
+
}
|
|
75
|
+
)
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Service analyzers: one module per analyzer, loaded lazily by the analyzer registry.
|
|
2
|
+
|
|
3
|
+
Every analyzer lives directly in this package as `<service>_analyzer.py`, e.g.
|
|
4
|
+
`analyzers/ec2_analyzer.py` or `analyzers/amazon_q_analyzer.py`.
|
|
5
|
+
The registry's catalog (`services/analyzer_registry.py`, `BUILT_IN_ANALYZERS`) names the
|
|
6
|
+
module and attribute each analyzer id imports at run time; a module that is missing or
|
|
7
|
+
fails to import gives a failed result for that service, not a crash.
|
|
8
|
+
|
|
9
|
+
Everything is synchronous. Analyzers run on worker threads, each inside a copy of the
|
|
10
|
+
caller's `contextvars` context with the scan's `ScanContext` set, so client handles from
|
|
11
|
+
`aws_finops_agent.aws.scan_scope` (`regional_client("ec2")`, `global_client("s3")`) and
|
|
12
|
+
`scan_region()` resolve to the active scan and region. Do not build boto3 clients or read
|
|
13
|
+
AWS_REGION directly. Raise on AWS errors (an access-denied call included): the registry
|
|
14
|
+
turns the exception into a failed result with the AWS error message, and the CLI lists it
|
|
15
|
+
as a warning while the other analyzers continue.
|
|
16
|
+
|
|
17
|
+
Two kinds of analyzer module exist.
|
|
18
|
+
|
|
19
|
+
Class analyzer. The module exposes a class (`EC2Analyzer`, `S3Analyzer`, ...) that the
|
|
20
|
+
registry builds with no arguments, so every constructor argument must have a default.
|
|
21
|
+
Building it must not call AWS or need a scan in progress. The instance satisfies `ServiceAnalyzer`::
|
|
22
|
+
|
|
23
|
+
service_name: str
|
|
24
|
+
version: str
|
|
25
|
+
enabled: bool
|
|
26
|
+
priority: int
|
|
27
|
+
def analyze(self, ctx: ScanContext | None = None) -> ServiceAnalysisResult: ...
|
|
28
|
+
def detect_waste(self) -> list[WasteDetectionResult]: ...
|
|
29
|
+
def get_right_sizing_recommendations(self) -> list[RightSizingRecommendation]: ...
|
|
30
|
+
|
|
31
|
+
`analyze` must accept the optional `ctx` argument even when it ignores it. The registry
|
|
32
|
+
finalises every result with `assemble_findings` (drops recommendations that save nothing,
|
|
33
|
+
marks prices of embedded-pricing analyzers) and sets `analysis_time` itself.
|
|
34
|
+
|
|
35
|
+
ECS is the one exception: `ecs_comprehensive_analyzer.ECSComprehensiveAnalyzer().analyze()`
|
|
36
|
+
returns an object with `recommendations: list[RightSizingRecommendation]`,
|
|
37
|
+
`waste_detected: list[WasteDetectionResult]`, `total_monthly_cost: float` and
|
|
38
|
+
`services: list` attributes; the registry wraps it without the function adapter.
|
|
39
|
+
|
|
40
|
+
Function analyzer. The module exposes a function (e.g. `analyze_rds_instances`)
|
|
41
|
+
satisfying `AnalyzerFunction`::
|
|
42
|
+
|
|
43
|
+
def analyze_rds_instances() -> list[OptimizationRecommendation]: ...
|
|
44
|
+
|
|
45
|
+
The registry wraps it in `FunctionBasedAnalyzerAdapter`: RESIZE, MODIFY, SCALE and
|
|
46
|
+
OPTIMIZE_MEMORY actions become right-sizing recommendations, TERMINATE actions become waste
|
|
47
|
+
findings, and other action types are dropped.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
from __future__ import annotations
|
|
51
|
+
|
|
52
|
+
from collections.abc import Callable
|
|
53
|
+
from typing import TYPE_CHECKING, Protocol
|
|
54
|
+
|
|
55
|
+
if TYPE_CHECKING:
|
|
56
|
+
from aws_finops_agent.aws.context import ScanContext
|
|
57
|
+
from aws_finops_agent.models import (
|
|
58
|
+
OptimizationRecommendation,
|
|
59
|
+
RightSizingRecommendation,
|
|
60
|
+
ServiceAnalysisResult,
|
|
61
|
+
WasteDetectionResult,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class ServiceAnalyzer(Protocol):
|
|
66
|
+
"""What the registry runs for one analyzer id. See the module docstring."""
|
|
67
|
+
|
|
68
|
+
service_name: str
|
|
69
|
+
version: str
|
|
70
|
+
enabled: bool
|
|
71
|
+
priority: int
|
|
72
|
+
|
|
73
|
+
def analyze(self, ctx: ScanContext | None = None) -> ServiceAnalysisResult: ...
|
|
74
|
+
|
|
75
|
+
def detect_waste(self) -> list[WasteDetectionResult]: ...
|
|
76
|
+
|
|
77
|
+
def get_right_sizing_recommendations(self) -> list[RightSizingRecommendation]: ...
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
AnalyzerFunction = Callable[[], "list[OptimizationRecommendation]"]
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Amazon Q Business Analyzer.
|
|
2
|
+
|
|
3
|
+
Analyzes Amazon Q Business applications for cost optimization.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from aws_finops_agent.aws.scan_scope import regional_client
|
|
12
|
+
from aws_finops_agent.models import OptimizationRecommendation
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
client = regional_client("qbusiness")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _get_all_applications() -> list[dict[str, str]]:
|
|
20
|
+
apps: list[dict[str, str]] = []
|
|
21
|
+
next_token: str | None = None
|
|
22
|
+
try:
|
|
23
|
+
while True:
|
|
24
|
+
response = (
|
|
25
|
+
client.list_applications(nextToken=next_token)
|
|
26
|
+
if next_token
|
|
27
|
+
else client.list_applications()
|
|
28
|
+
)
|
|
29
|
+
for a in response.get("applications") or []:
|
|
30
|
+
if a.get("applicationId"):
|
|
31
|
+
apps.append({"applicationId": a["applicationId"]})
|
|
32
|
+
next_token = response.get("nextToken")
|
|
33
|
+
if not next_token:
|
|
34
|
+
break
|
|
35
|
+
except Exception:
|
|
36
|
+
logger.exception("Amazon Q ListApplications failed")
|
|
37
|
+
raise
|
|
38
|
+
return apps
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def analyze_amazon_q() -> list[OptimizationRecommendation]:
|
|
42
|
+
logger.info("Starting Amazon Q analysis")
|
|
43
|
+
applications = _get_all_applications()
|
|
44
|
+
recommendations: list[OptimizationRecommendation] = []
|
|
45
|
+
|
|
46
|
+
for app in applications:
|
|
47
|
+
app_id = app["applicationId"]
|
|
48
|
+
try:
|
|
49
|
+
app_detail = client.get_application(applicationId=app_id)
|
|
50
|
+
application: dict[str, Any] = (
|
|
51
|
+
app_detail.get("application")
|
|
52
|
+
if isinstance(app_detail.get("application"), dict)
|
|
53
|
+
else app_detail
|
|
54
|
+
)
|
|
55
|
+
if not application or not application.get("applicationId"):
|
|
56
|
+
continue
|
|
57
|
+
|
|
58
|
+
recs: list[OptimizationRecommendation] = []
|
|
59
|
+
name = application.get("displayName") or app_id
|
|
60
|
+
status = application.get("status")
|
|
61
|
+
|
|
62
|
+
if status in ("FAILED", "CREATING"):
|
|
63
|
+
recs.append(
|
|
64
|
+
OptimizationRecommendation(
|
|
65
|
+
resource_id=application["applicationId"],
|
|
66
|
+
resource_type="AMAZON_Q",
|
|
67
|
+
action_type="MODIFY",
|
|
68
|
+
estimated_monthly_savings=0,
|
|
69
|
+
confidence="LOW",
|
|
70
|
+
reasoning=(
|
|
71
|
+
f'Amazon Q application "{name}" is {status}. Review or remove '
|
|
72
|
+
"if stuck."
|
|
73
|
+
),
|
|
74
|
+
auto_executable=False,
|
|
75
|
+
current_configuration={"status": status},
|
|
76
|
+
recommended_configuration={"action": "Review application status"},
|
|
77
|
+
tags={},
|
|
78
|
+
)
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
index_count = 0
|
|
82
|
+
idx_next_token: str | None = None
|
|
83
|
+
while True:
|
|
84
|
+
params: dict[str, Any] = {"applicationId": app_id}
|
|
85
|
+
if idx_next_token:
|
|
86
|
+
params["nextToken"] = idx_next_token
|
|
87
|
+
idx_res = client.list_indices(**params)
|
|
88
|
+
index_count += len(idx_res.get("indices") or [])
|
|
89
|
+
idx_next_token = idx_res.get("nextToken")
|
|
90
|
+
if not idx_next_token:
|
|
91
|
+
break
|
|
92
|
+
|
|
93
|
+
if index_count > 10:
|
|
94
|
+
recs.append(
|
|
95
|
+
OptimizationRecommendation(
|
|
96
|
+
resource_id=application["applicationId"],
|
|
97
|
+
resource_type="AMAZON_Q",
|
|
98
|
+
action_type="MODIFY",
|
|
99
|
+
estimated_monthly_savings=0,
|
|
100
|
+
confidence="LOW",
|
|
101
|
+
reasoning=(
|
|
102
|
+
f'Amazon Q application "{name}" has {index_count} indices. '
|
|
103
|
+
"Review for consolidation."
|
|
104
|
+
),
|
|
105
|
+
auto_executable=False,
|
|
106
|
+
current_configuration={"indexCount": index_count},
|
|
107
|
+
recommended_configuration={"action": "Review indices"},
|
|
108
|
+
tags={},
|
|
109
|
+
)
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
recommendations.extend(recs)
|
|
113
|
+
except Exception:
|
|
114
|
+
logger.warning("Amazon Q GetApplication failed %s", {"applicationId": app_id})
|
|
115
|
+
|
|
116
|
+
logger.info("Amazon Q analysis complete %s", {"recommendations": len(recommendations)})
|
|
117
|
+
return recommendations
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
"""Analytics Services Analyzer.
|
|
2
|
+
|
|
3
|
+
Analyzes EMR, Glue, and Kinesis for cost optimization opportunities.
|
|
4
|
+
Athena work groups are left out because the scan does not call Athena.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
import math
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from datetime import datetime, timedelta, timezone
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from aws_finops_agent.aws.scan_scope import regional_client
|
|
16
|
+
from aws_finops_agent.models import OptimizationRecommendation
|
|
17
|
+
from aws_finops_agent.utils.js_number import to_fixed
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
emr_client = regional_client("emr")
|
|
22
|
+
glue_client = regional_client("glue")
|
|
23
|
+
kinesis_client = regional_client("kinesis")
|
|
24
|
+
cloudwatch_client = regional_client("cloudwatch")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class KinesisMetrics:
|
|
29
|
+
incoming_records: float
|
|
30
|
+
outgoing_records: float
|
|
31
|
+
incoming_bytes: float
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _analyze_emr_clusters() -> list[OptimizationRecommendation]:
|
|
35
|
+
"""Analyze EMR clusters."""
|
|
36
|
+
recommendations: list[OptimizationRecommendation] = []
|
|
37
|
+
clusters = _get_all_emr_clusters()
|
|
38
|
+
logger.info("Found %d EMR clusters", len(clusters))
|
|
39
|
+
for cluster in clusters:
|
|
40
|
+
if not cluster.get("Id"):
|
|
41
|
+
continue
|
|
42
|
+
try:
|
|
43
|
+
rec = _analyze_emr_cluster(cluster)
|
|
44
|
+
if rec:
|
|
45
|
+
recommendations.append(rec)
|
|
46
|
+
except Exception:
|
|
47
|
+
logger.exception("Error analyzing EMR cluster %s", cluster.get("Id"))
|
|
48
|
+
return recommendations
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _analyze_glue_resources() -> list[OptimizationRecommendation]:
|
|
52
|
+
"""Analyze Glue databases and crawlers."""
|
|
53
|
+
recommendations: list[OptimizationRecommendation] = []
|
|
54
|
+
databases = _get_all_glue_databases()
|
|
55
|
+
crawlers = _get_all_glue_crawlers()
|
|
56
|
+
logger.info(
|
|
57
|
+
"Found %d Glue databases and %d Glue crawlers", len(databases), len(crawlers)
|
|
58
|
+
)
|
|
59
|
+
for database in databases:
|
|
60
|
+
try:
|
|
61
|
+
rec = _analyze_glue_database(database)
|
|
62
|
+
if rec:
|
|
63
|
+
recommendations.append(rec)
|
|
64
|
+
except Exception:
|
|
65
|
+
logger.exception("Error analyzing Glue database %s", database.get("Name"))
|
|
66
|
+
for crawler in crawlers:
|
|
67
|
+
try:
|
|
68
|
+
rec = _analyze_glue_crawler(crawler)
|
|
69
|
+
if rec:
|
|
70
|
+
recommendations.append(rec)
|
|
71
|
+
except Exception:
|
|
72
|
+
logger.exception("Error analyzing Glue crawler %s", crawler.get("Name"))
|
|
73
|
+
return recommendations
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _analyze_kinesis_streams() -> list[OptimizationRecommendation]:
|
|
77
|
+
"""Analyze Kinesis streams."""
|
|
78
|
+
recommendations: list[OptimizationRecommendation] = []
|
|
79
|
+
streams = _get_all_kinesis_streams()
|
|
80
|
+
logger.info("Found %d Kinesis streams", len(streams))
|
|
81
|
+
for stream in streams:
|
|
82
|
+
name = stream.get("StreamName")
|
|
83
|
+
if not name:
|
|
84
|
+
continue
|
|
85
|
+
try:
|
|
86
|
+
metrics = _get_kinesis_metrics(name)
|
|
87
|
+
rec = _analyze_kinesis_stream(stream, metrics)
|
|
88
|
+
if rec:
|
|
89
|
+
recommendations.append(rec)
|
|
90
|
+
except Exception:
|
|
91
|
+
logger.exception("Error analyzing Kinesis stream %s", name)
|
|
92
|
+
return recommendations
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def analyze_analytics_services() -> list[OptimizationRecommendation]:
|
|
96
|
+
logger.info("Starting analytics services analysis (EMR, Glue, Kinesis)...")
|
|
97
|
+
emr_recs = _analyze_emr_clusters()
|
|
98
|
+
glue_recs = _analyze_glue_resources()
|
|
99
|
+
kinesis_recs = _analyze_kinesis_streams()
|
|
100
|
+
all_recommendations = [*emr_recs, *glue_recs, *kinesis_recs]
|
|
101
|
+
logger.info(
|
|
102
|
+
"Generated %d analytics service recommendations", len(all_recommendations)
|
|
103
|
+
)
|
|
104
|
+
return all_recommendations
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# EMR Helper Functions
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _get_all_emr_clusters() -> list[dict[str, Any]]:
|
|
111
|
+
clusters: list[dict[str, Any]] = []
|
|
112
|
+
marker: str | None = None
|
|
113
|
+
while True:
|
|
114
|
+
response = emr_client.list_clusters(Marker=marker) if marker else emr_client.list_clusters()
|
|
115
|
+
for cluster in response.get("Clusters") or []:
|
|
116
|
+
if (cluster.get("Status") or {}).get("State") != "TERMINATED":
|
|
117
|
+
clusters.append(cluster)
|
|
118
|
+
marker = response.get("Marker")
|
|
119
|
+
if not marker:
|
|
120
|
+
break
|
|
121
|
+
return clusters
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _analyze_emr_cluster(cluster: dict[str, Any]) -> OptimizationRecommendation | None:
|
|
125
|
+
cluster_id = cluster.get("Id")
|
|
126
|
+
if not cluster_id:
|
|
127
|
+
return None
|
|
128
|
+
status = cluster.get("Status") or {}
|
|
129
|
+
state = status.get("State")
|
|
130
|
+
creation_time = (status.get("Timeline") or {}).get("CreationDateTime")
|
|
131
|
+
|
|
132
|
+
# Check for long-running EMR clusters (should be terminated after job completion)
|
|
133
|
+
if state == "RUNNING" and creation_time:
|
|
134
|
+
now = datetime.now(timezone.utc)
|
|
135
|
+
hours_running = (now.timestamp() - creation_time.timestamp()) / (60 * 60)
|
|
136
|
+
if hours_running > 24:
|
|
137
|
+
# Estimate cost based on instance count (simplified)
|
|
138
|
+
instance_count = 3 # Default estimate
|
|
139
|
+
estimated_hourly_cost = instance_count * 0.50 # Approximate EMR instance cost
|
|
140
|
+
estimated_monthly_cost = estimated_hourly_cost * 730
|
|
141
|
+
return OptimizationRecommendation(
|
|
142
|
+
resource_id=cluster_id,
|
|
143
|
+
resource_type="EMR",
|
|
144
|
+
action_type="TERMINATE",
|
|
145
|
+
estimated_monthly_savings=estimated_monthly_cost,
|
|
146
|
+
confidence="HIGH",
|
|
147
|
+
reasoning=(
|
|
148
|
+
f"EMR cluster has been running for {to_fixed(hours_running, 1)} hours. EMR "
|
|
149
|
+
"clusters should be terminated after job completion to avoid unnecessary "
|
|
150
|
+
"costs."
|
|
151
|
+
),
|
|
152
|
+
auto_executable=False,
|
|
153
|
+
current_configuration={},
|
|
154
|
+
recommended_configuration={},
|
|
155
|
+
tags={},
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
# Check for clusters in WAITING state (idle)
|
|
159
|
+
if state == "WAITING":
|
|
160
|
+
return OptimizationRecommendation(
|
|
161
|
+
resource_id=cluster_id,
|
|
162
|
+
resource_type="EMR",
|
|
163
|
+
action_type="TERMINATE",
|
|
164
|
+
estimated_monthly_savings=100, # Approximate cost for waiting cluster
|
|
165
|
+
confidence="MEDIUM",
|
|
166
|
+
reasoning=(
|
|
167
|
+
"EMR cluster is in WAITING state. Consider terminating if no jobs are scheduled."
|
|
168
|
+
),
|
|
169
|
+
auto_executable=False,
|
|
170
|
+
current_configuration={},
|
|
171
|
+
recommended_configuration={},
|
|
172
|
+
tags={},
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# Glue Helper Functions
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _get_all_glue_databases() -> list[dict[str, Any]]:
|
|
182
|
+
databases: list[dict[str, Any]] = []
|
|
183
|
+
next_token: str | None = None
|
|
184
|
+
while True:
|
|
185
|
+
params: dict[str, Any] = {"MaxResults": 100}
|
|
186
|
+
if next_token:
|
|
187
|
+
params["NextToken"] = next_token
|
|
188
|
+
response = glue_client.get_databases(**params)
|
|
189
|
+
databases.extend(response.get("DatabaseList") or [])
|
|
190
|
+
next_token = response.get("NextToken")
|
|
191
|
+
if not next_token:
|
|
192
|
+
break
|
|
193
|
+
return databases
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _get_all_glue_crawlers() -> list[dict[str, Any]]:
|
|
197
|
+
crawlers: list[dict[str, Any]] = []
|
|
198
|
+
next_token: str | None = None
|
|
199
|
+
while True:
|
|
200
|
+
params: dict[str, Any] = {"MaxResults": 100}
|
|
201
|
+
if next_token:
|
|
202
|
+
params["NextToken"] = next_token
|
|
203
|
+
response = glue_client.list_crawlers(**params)
|
|
204
|
+
for crawler_name in response.get("CrawlerNames") or []:
|
|
205
|
+
try:
|
|
206
|
+
crawler = glue_client.get_crawler(Name=crawler_name).get("Crawler")
|
|
207
|
+
if crawler:
|
|
208
|
+
crawlers.append(crawler)
|
|
209
|
+
except Exception:
|
|
210
|
+
logger.warning("Could not get details for Glue crawler %s", crawler_name)
|
|
211
|
+
next_token = response.get("NextToken")
|
|
212
|
+
if not next_token:
|
|
213
|
+
break
|
|
214
|
+
return crawlers
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _analyze_glue_database(database: dict[str, Any]) -> OptimizationRecommendation | None:
|
|
218
|
+
# Check for empty databases (simplified check - would need additional API call to get
|
|
219
|
+
# tables). For now, we'll skip this check as it requires additional permissions.
|
|
220
|
+
return None
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _analyze_glue_crawler(crawler: dict[str, Any]) -> OptimizationRecommendation | None:
|
|
224
|
+
# Check for crawlers that haven't run recently. LastCrawl structure is complex; in
|
|
225
|
+
# production, would need proper handling of LastCrawl.LastUpdateTime.
|
|
226
|
+
return None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
# Kinesis Helper Functions
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _get_all_kinesis_streams() -> list[dict[str, Any]]:
|
|
233
|
+
streams: list[dict[str, Any]] = []
|
|
234
|
+
next_token: str | None = None
|
|
235
|
+
while True:
|
|
236
|
+
params: dict[str, Any] = {"Limit": 100}
|
|
237
|
+
if next_token:
|
|
238
|
+
params["NextToken"] = next_token
|
|
239
|
+
list_response = kinesis_client.list_streams(**params)
|
|
240
|
+
for stream_name in list_response.get("StreamNames") or []:
|
|
241
|
+
try:
|
|
242
|
+
description: dict[str, Any] | None = None
|
|
243
|
+
all_shards: list[dict[str, Any]] = []
|
|
244
|
+
start_shard_id: str | None = None
|
|
245
|
+
while True:
|
|
246
|
+
desc_params: dict[str, Any] = {"StreamName": stream_name}
|
|
247
|
+
if start_shard_id:
|
|
248
|
+
desc_params["ExclusiveStartShardId"] = start_shard_id
|
|
249
|
+
page = kinesis_client.describe_stream(**desc_params).get("StreamDescription")
|
|
250
|
+
if not page:
|
|
251
|
+
break
|
|
252
|
+
if description is None:
|
|
253
|
+
description = dict(page)
|
|
254
|
+
page_shards = list(page.get("Shards") or [])
|
|
255
|
+
all_shards.extend(page_shards)
|
|
256
|
+
if not page.get("HasMoreShards") or not page_shards:
|
|
257
|
+
break
|
|
258
|
+
last_shard_id = page_shards[-1].get("ShardId")
|
|
259
|
+
if not last_shard_id or last_shard_id == start_shard_id:
|
|
260
|
+
break
|
|
261
|
+
start_shard_id = last_shard_id
|
|
262
|
+
if description is not None:
|
|
263
|
+
description["Shards"] = all_shards
|
|
264
|
+
streams.append(description)
|
|
265
|
+
except Exception:
|
|
266
|
+
logger.warning("Could not describe Kinesis stream %s", stream_name)
|
|
267
|
+
next_token = list_response.get("NextToken")
|
|
268
|
+
if not next_token:
|
|
269
|
+
break
|
|
270
|
+
return streams
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _get_kinesis_metrics(stream_name: str) -> KinesisMetrics:
|
|
274
|
+
end_time = datetime.now(timezone.utc)
|
|
275
|
+
start_time = end_time - timedelta(days=7) # 7 days
|
|
276
|
+
|
|
277
|
+
def total(metric_name: str) -> float:
|
|
278
|
+
response = cloudwatch_client.get_metric_statistics(
|
|
279
|
+
Namespace="AWS/Kinesis",
|
|
280
|
+
MetricName=metric_name,
|
|
281
|
+
Dimensions=[{"Name": "StreamName", "Value": stream_name}],
|
|
282
|
+
StartTime=start_time,
|
|
283
|
+
EndTime=end_time,
|
|
284
|
+
Period=3600,
|
|
285
|
+
Statistics=["Sum"],
|
|
286
|
+
)
|
|
287
|
+
return sum(dp.get("Sum") or 0 for dp in response.get("Datapoints") or [])
|
|
288
|
+
|
|
289
|
+
try:
|
|
290
|
+
incoming_records = total("IncomingRecords")
|
|
291
|
+
outgoing_records = total("OutgoingRecords")
|
|
292
|
+
incoming_bytes = total("IncomingBytes")
|
|
293
|
+
return KinesisMetrics(incoming_records, outgoing_records, incoming_bytes)
|
|
294
|
+
except Exception:
|
|
295
|
+
logger.warning("Could not fetch Kinesis metrics for %s", stream_name)
|
|
296
|
+
return KinesisMetrics(0, 0, 0)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _analyze_kinesis_stream(
|
|
300
|
+
stream: dict[str, Any], metrics: KinesisMetrics
|
|
301
|
+
) -> OptimizationRecommendation | None:
|
|
302
|
+
name = stream.get("StreamName")
|
|
303
|
+
if not name:
|
|
304
|
+
return None
|
|
305
|
+
|
|
306
|
+
# Check for unused stream
|
|
307
|
+
if metrics.incoming_records == 0 and metrics.outgoing_records == 0:
|
|
308
|
+
shard_count = len(stream.get("Shards") or []) or 1
|
|
309
|
+
estimated_monthly_cost = shard_count * 0.015 * 730 # $0.015 per shard-hour
|
|
310
|
+
return OptimizationRecommendation(
|
|
311
|
+
resource_id=name,
|
|
312
|
+
resource_type="KINESIS",
|
|
313
|
+
action_type="TERMINATE",
|
|
314
|
+
estimated_monthly_savings=estimated_monthly_cost,
|
|
315
|
+
confidence="HIGH",
|
|
316
|
+
reasoning=(
|
|
317
|
+
"Kinesis stream has no incoming or outgoing records. Stream with "
|
|
318
|
+
f"{shard_count} shard(s) is incurring costs."
|
|
319
|
+
),
|
|
320
|
+
auto_executable=False,
|
|
321
|
+
current_configuration={},
|
|
322
|
+
recommended_configuration={},
|
|
323
|
+
tags={},
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
# Check for right-sizing opportunity (too many shards)
|
|
327
|
+
shard_count = len(stream.get("Shards") or []) or 1
|
|
328
|
+
records_per_shard_per_day = metrics.incoming_records / (shard_count * 7)
|
|
329
|
+
|
|
330
|
+
if shard_count > 1 and records_per_shard_per_day < 1000:
|
|
331
|
+
recommended_shards = max(1, math.ceil(shard_count / 2))
|
|
332
|
+
savings = (shard_count - recommended_shards) * 0.015 * 730
|
|
333
|
+
if savings > 5:
|
|
334
|
+
return OptimizationRecommendation(
|
|
335
|
+
resource_id=name,
|
|
336
|
+
resource_type="KINESIS",
|
|
337
|
+
action_type="RESIZE",
|
|
338
|
+
estimated_monthly_savings=savings,
|
|
339
|
+
confidence="MEDIUM",
|
|
340
|
+
reasoning=(
|
|
341
|
+
f"Kinesis stream has {shard_count} shards but low throughput "
|
|
342
|
+
f"({to_fixed(records_per_shard_per_day, 0)} records/shard/day). Consider "
|
|
343
|
+
f"reducing to {recommended_shards} shard(s)."
|
|
344
|
+
),
|
|
345
|
+
auto_executable=False,
|
|
346
|
+
current_configuration={"shardCount": shard_count},
|
|
347
|
+
recommended_configuration={"shardCount": recommended_shards},
|
|
348
|
+
tags={},
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
return None
|