maproom 0.2.0__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.
- maproom/__init__.py +14 -0
- maproom/__main__.py +10 -0
- maproom/analyze/__init__.py +1 -0
- maproom/analyze/accel_families.py +45 -0
- maproom/analyze/account_azure_activity.py +260 -0
- maproom/analyze/account_azure_quota_requests.py +177 -0
- maproom/analyze/account_cloudtrail.py +316 -0
- maproom/analyze/account_quota_requests.py +180 -0
- maproom/analyze/analyze_v1_orchestration.py +1194 -0
- maproom/analyze/catalog.py +353 -0
- maproom/analyze/change_detection.py +652 -0
- maproom/analyze/context_client.py +99 -0
- maproom/analyze/context_lookup.py +142 -0
- maproom/analyze/cover_analyze.py +344 -0
- maproom/analyze/cover_client.py +65 -0
- maproom/analyze/cover_lookup.py +242 -0
- maproom/analyze/engine.py +644 -0
- maproom/analyze/fleetfit_endpoints.py +217 -0
- maproom/analyze/fleetfit_policy.py +66 -0
- maproom/analyze/instance_price_analyze.py +221 -0
- maproom/analyze/instance_price_client.py +108 -0
- maproom/analyze/instance_price_lookup.py +60 -0
- maproom/analyze/local_reads.py +484 -0
- maproom/analyze/lookup_http.py +280 -0
- maproom/analyze/metric_format.py +20 -0
- maproom/analyze/migration_method.py +130 -0
- maproom/analyze/move_list.py +93 -0
- maproom/analyze/operator_context.py +156 -0
- maproom/analyze/performance_rank.py +97 -0
- maproom/analyze/primary_recommendation.py +422 -0
- maproom/analyze/provider_comparison.py +401 -0
- maproom/analyze/quota_analyze.py +481 -0
- maproom/analyze/quota_client.py +75 -0
- maproom/analyze/quota_lookup.py +110 -0
- maproom/analyze/quota_outcome_steer.py +105 -0
- maproom/analyze/recommend_batch.py +199 -0
- maproom/analyze/recommend_client.py +362 -0
- maproom/analyze/recommend_share.py +118 -0
- maproom/analyze/recommendation.py +591 -0
- maproom/analyze/reservation_pack.py +883 -0
- maproom/analyze/reservation_read.py +461 -0
- maproom/analyze/safe_analyze.py +1134 -0
- maproom/analyze/safe_move.py +195 -0
- maproom/analyze/safe_moves.py +571 -0
- maproom/analyze/safe_moves_catalog.py +127 -0
- maproom/analyze/safe_moves_client.py +70 -0
- maproom/analyze/series_analyze.py +491 -0
- maproom/analyze/series_client.py +106 -0
- maproom/analyze/series_lookup.py +663 -0
- maproom/analyze/shape.py +254 -0
- maproom/analyze/size_analyze.py +883 -0
- maproom/analyze/size_client.py +81 -0
- maproom/analyze/size_keep.py +409 -0
- maproom/analyze/size_lookup.py +368 -0
- maproom/analyze/specs.py +325 -0
- maproom/analyze/spot_analyze.py +392 -0
- maproom/analyze/spot_client.py +74 -0
- maproom/analyze/spot_lookup.py +213 -0
- maproom/analyze/token_client.py +97 -0
- maproom/analyze/utilization.py +190 -0
- maproom/analyze/workload.py +104 -0
- maproom/analyze/workset.py +762 -0
- maproom/aws_region.py +78 -0
- maproom/cache/__init__.py +1 -0
- maproom/cache/catalog.py +372 -0
- maproom/cache/commands.py +215 -0
- maproom/cache/instances.py +460 -0
- maproom/cli.py +2084 -0
- maproom/cli_argv.py +329 -0
- maproom/cli_floors.py +89 -0
- maproom/cliio/__init__.py +1 -0
- maproom/cliio/registry.py +377 -0
- maproom/cliio/runner.py +489 -0
- maproom/consent/__init__.py +33 -0
- maproom/consent/gate.py +238 -0
- maproom/consent/policy.py +20 -0
- maproom/consent/prompt.py +61 -0
- maproom/consent/service_upload_gate.py +318 -0
- maproom/consent/service_upload_prompt.py +62 -0
- maproom/consent/stdin.py +45 -0
- maproom/consent/storage.py +24 -0
- maproom/consent/write_token.py +29 -0
- maproom/contracts/__init__.py +6 -0
- maproom/contracts/schema_diff.py +119 -0
- maproom/contracts/validate.py +113 -0
- maproom/data/__init__.py +1 -0
- maproom/data/clear.py +76 -0
- maproom/data/commands.py +14 -0
- maproom/doctor/__init__.py +1 -0
- maproom/doctor/aws_session.py +226 -0
- maproom/doctor/checks.py +701 -0
- maproom/doctor/context.py +32 -0
- maproom/doctor/display.py +96 -0
- maproom/doctor/inventory_display.py +377 -0
- maproom/doctor/runner.py +1467 -0
- maproom/errors.py +43 -0
- maproom/exitcodes.py +70 -0
- maproom/inventory/__init__.py +1 -0
- maproom/inventory/account_identity.py +79 -0
- maproom/inventory/accounts.py +155 -0
- maproom/inventory/command.py +961 -0
- maproom/inventory/messages.py +264 -0
- maproom/inventory/reservations_refresh.py +37 -0
- maproom/mock_environment/__init__.py +28 -0
- maproom/mock_environment/load.py +241 -0
- maproom/mock_environment/runner.py +387 -0
- maproom/output/__init__.py +1 -0
- maproom/output/json_envelope.py +241 -0
- maproom/output/redact.py +11 -0
- maproom/output/terminal.py +129 -0
- maproom/parsers.py +284 -0
- maproom/paths.py +105 -0
- maproom/plan/__init__.py +1 -0
- maproom/plan/accept.py +59 -0
- maproom/plan/analysis_context.py +78 -0
- maproom/plan/analyze_selection.py +279 -0
- maproom/plan/commands.py +586 -0
- maproom/plan/current.py +59 -0
- maproom/plan/errors.py +10 -0
- maproom/plan/export.py +36 -0
- maproom/plan/formatting.py +91 -0
- maproom/plan/ids.py +13 -0
- maproom/plan/migration_options.py +75 -0
- maproom/plan/model.py +265 -0
- maproom/plan/names.py +24 -0
- maproom/plan/store.py +193 -0
- maproom/plan/tty.py +34 -0
- maproom/pricing/__init__.py +5 -0
- maproom/pricing/prices.py +119 -0
- maproom/privacy/__init__.py +6 -0
- maproom/privacy/commands.py +159 -0
- maproom/privacy/delete_uploads.py +204 -0
- maproom/privacy/fleetfit_policy.py +125 -0
- maproom/privacy/fleetfit_statement.py +104 -0
- maproom/privacy/format.py +76 -0
- maproom/privacy/manifests.py +342 -0
- maproom/privacy/statement.py +58 -0
- maproom/quotas/__init__.py +21 -0
- maproom/quotas/aws.py +204 -0
- maproom/quotas/azure.py +75 -0
- maproom/quotas/commands.py +240 -0
- maproom/quotas/family_coverage.py +122 -0
- maproom/quotas/fetch.py +124 -0
- maproom/quotas/load.py +41 -0
- maproom/quotas/model.py +178 -0
- maproom/quotas/outcome_ledger.py +245 -0
- maproom/quotas/quota_request_sync.py +221 -0
- maproom/quotas/show.py +73 -0
- maproom/quotas/status.py +206 -0
- maproom/quotas/store.py +161 -0
- maproom/redaction.py +157 -0
- maproom/reference_data/__init__.py +1 -0
- maproom/reference_data/aws/aws_prices.csv +25562 -0
- maproom/reference_data/aws/capabilities.csv +1346 -0
- maproom/reference_data/aws/instance_types.csv +1346 -0
- maproom/reference_data/azure/azure_prices.csv +1 -0
- maproom/reference_data/azure/vm_types.csv +1 -0
- maproom/reference_data/benchmarks/cpu-lscpu-v2-instances.json +27 -0
- maproom/reference_data/benchmarks/safe-moves-v1.json +328 -0
- maproom/reference_data/manifest.json +174 -0
- maproom/reference_data/manifest.py +69 -0
- maproom/reservations/__init__.py +17 -0
- maproom/reservations/aws.py +76 -0
- maproom/reservations/azure.py +36 -0
- maproom/reservations/commands.py +149 -0
- maproom/reservations/load.py +41 -0
- maproom/reservations/model.py +316 -0
- maproom/reservations/show.py +64 -0
- maproom/reservations/status.py +181 -0
- maproom/reservations/store.py +391 -0
- maproom/resources.py +54 -0
- maproom/root_help.py +251 -0
- maproom/saving_plans/__init__.py +15 -0
- maproom/saving_plans/aws.py +73 -0
- maproom/saving_plans/commands.py +122 -0
- maproom/saving_plans/load.py +41 -0
- maproom/saving_plans/model.py +101 -0
- maproom/saving_plans/show.py +64 -0
- maproom/saving_plans/status.py +118 -0
- maproom/saving_plans/store.py +173 -0
- maproom/secret_egress_gate.py +108 -0
- maproom/service/install_id.py +60 -0
- maproom/settings/__init__.py +1 -0
- maproom/settings/defaults.py +73 -0
- maproom/settings/init.py +143 -0
- maproom/settings/model.py +105 -0
- maproom/settings/product_version_change.py +343 -0
- maproom/settings/product_versions.py +68 -0
- maproom/settings/set.py +347 -0
- maproom/settings/show.py +227 -0
- maproom/settings/write.py +273 -0
- maproom/snapshot_time.py +27 -0
- maproom-0.2.0.dist-info/METADATA +263 -0
- maproom-0.2.0.dist-info/RECORD +199 -0
- maproom-0.2.0.dist-info/WHEEL +5 -0
- maproom-0.2.0.dist-info/entry_points.txt +2 -0
- maproom-0.2.0.dist-info/licenses/LICENSE +201 -0
- maproom-0.2.0.dist-info/licenses/NOTICE +72 -0
- maproom-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,652 @@
|
|
|
1
|
+
"""Detect recent EC2 instance-type changes for utilization trimming and cooldown."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from datetime import datetime, timedelta, timezone
|
|
8
|
+
from typing import Any, Literal, Protocol
|
|
9
|
+
|
|
10
|
+
from maproom.analyze.utilization import (
|
|
11
|
+
UTILIZATION_LOOKBACK_DAYS,
|
|
12
|
+
_iso_z,
|
|
13
|
+
build_cpu_utilization_argv,
|
|
14
|
+
cpu_percentiles_from_values,
|
|
15
|
+
summarize_cpu_utilization,
|
|
16
|
+
)
|
|
17
|
+
from maproom.errors import AccessDeniedError, MaproomParseError
|
|
18
|
+
from maproom.parsers import (
|
|
19
|
+
parse_cloudtrail_lookup_events,
|
|
20
|
+
parse_config_resource_config_history,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
DetectionSource = Literal[
|
|
24
|
+
"cloudtrail",
|
|
25
|
+
"aws_config",
|
|
26
|
+
"metric_gap",
|
|
27
|
+
"launch_time",
|
|
28
|
+
"none",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
METRIC_GAP_MIN_MINUTES = 5
|
|
32
|
+
POST_CHANGE_MIN_HOURS = 24
|
|
33
|
+
CLOUDTRAIL_MAX_PAGES = 5
|
|
34
|
+
CLOUDTRAIL_LOOKBACK_EXTRA_DAYS = 1
|
|
35
|
+
CONFIG_MAX_PAGES = 20
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class AwsRunner(Protocol):
|
|
39
|
+
def run(self, executable: str, argv: list[str], **kwargs: Any) -> Any: ...
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class InstanceTypeChange:
|
|
44
|
+
changed_at: datetime | None = None
|
|
45
|
+
previous_instance_type: str | None = None
|
|
46
|
+
detection_source: DetectionSource = "none"
|
|
47
|
+
detection_notes: list[str] = field(default_factory=list)
|
|
48
|
+
|
|
49
|
+
def cooldown_until(self, now: datetime, min_days_since_change: int) -> datetime | None:
|
|
50
|
+
if self.changed_at is None:
|
|
51
|
+
return None
|
|
52
|
+
return self.changed_at + timedelta(days=min_days_since_change)
|
|
53
|
+
|
|
54
|
+
def cooldown_active(self, now: datetime, min_days_since_change: int) -> bool:
|
|
55
|
+
until = self.cooldown_until(now, min_days_since_change)
|
|
56
|
+
if until is None:
|
|
57
|
+
return False
|
|
58
|
+
return now < until
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def build_cloudtrail_lookup_argv(
|
|
62
|
+
instance_id: str,
|
|
63
|
+
*,
|
|
64
|
+
start: datetime,
|
|
65
|
+
end: datetime,
|
|
66
|
+
region: str,
|
|
67
|
+
next_token: str | None = None,
|
|
68
|
+
) -> list[str]:
|
|
69
|
+
argv = [
|
|
70
|
+
"cloudtrail",
|
|
71
|
+
"lookup-events",
|
|
72
|
+
"--lookup-attributes",
|
|
73
|
+
f"AttributeKey=ResourceName,AttributeValue={instance_id}",
|
|
74
|
+
"--start-time",
|
|
75
|
+
_iso_z(start),
|
|
76
|
+
"--end-time",
|
|
77
|
+
_iso_z(end),
|
|
78
|
+
"--region",
|
|
79
|
+
region,
|
|
80
|
+
"--output",
|
|
81
|
+
"json",
|
|
82
|
+
]
|
|
83
|
+
if next_token:
|
|
84
|
+
argv.extend(["--next-token", next_token])
|
|
85
|
+
return argv
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def build_config_history_argv(
|
|
89
|
+
instance_id: str,
|
|
90
|
+
*,
|
|
91
|
+
earlier_time: datetime,
|
|
92
|
+
later_time: datetime,
|
|
93
|
+
region: str,
|
|
94
|
+
next_token: str | None = None,
|
|
95
|
+
) -> list[str]:
|
|
96
|
+
argv = [
|
|
97
|
+
"configservice",
|
|
98
|
+
"get-resource-config-history",
|
|
99
|
+
"--resource-type",
|
|
100
|
+
"AWS::EC2::Instance",
|
|
101
|
+
"--resource-id",
|
|
102
|
+
instance_id,
|
|
103
|
+
"--earlier-time",
|
|
104
|
+
_iso_z(earlier_time),
|
|
105
|
+
"--later-time",
|
|
106
|
+
_iso_z(later_time),
|
|
107
|
+
"--region",
|
|
108
|
+
region,
|
|
109
|
+
"--output",
|
|
110
|
+
"json",
|
|
111
|
+
]
|
|
112
|
+
if next_token:
|
|
113
|
+
argv.extend(["--next-token", next_token])
|
|
114
|
+
return argv
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _runner_response(result: Any) -> dict[str, Any]:
|
|
118
|
+
if isinstance(result, dict):
|
|
119
|
+
return result
|
|
120
|
+
stdout = getattr(result, "stdout", "") or ""
|
|
121
|
+
stderr = getattr(result, "stderr", "") or ""
|
|
122
|
+
exit_code = int(getattr(result, "exit_code", 0))
|
|
123
|
+
payload: dict[str, Any] = {
|
|
124
|
+
"exit_code": exit_code,
|
|
125
|
+
"stderr": stderr,
|
|
126
|
+
}
|
|
127
|
+
if stdout.strip():
|
|
128
|
+
try:
|
|
129
|
+
payload["stdout_json"] = json.loads(stdout)
|
|
130
|
+
except json.JSONDecodeError:
|
|
131
|
+
payload["stdout"] = stdout
|
|
132
|
+
return payload
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _parse_aws_time(text: str) -> datetime:
|
|
136
|
+
normalized = text.replace("Z", "+00:00")
|
|
137
|
+
if normalized.endswith("+0000"):
|
|
138
|
+
normalized = normalized[:-5] + "+00:00"
|
|
139
|
+
dt = datetime.fromisoformat(normalized)
|
|
140
|
+
if dt.tzinfo is None:
|
|
141
|
+
dt = dt.replace(tzinfo=timezone.utc)
|
|
142
|
+
return dt.astimezone(timezone.utc)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _launch_time_in_window(
|
|
146
|
+
instance: dict[str, Any],
|
|
147
|
+
*,
|
|
148
|
+
window_start: datetime,
|
|
149
|
+
window_end: datetime,
|
|
150
|
+
) -> datetime | None:
|
|
151
|
+
raw = instance.get("LaunchTime")
|
|
152
|
+
if not raw:
|
|
153
|
+
return None
|
|
154
|
+
try:
|
|
155
|
+
launch = _parse_aws_time(str(raw))
|
|
156
|
+
except ValueError:
|
|
157
|
+
return None
|
|
158
|
+
if window_start <= launch <= window_end:
|
|
159
|
+
return launch
|
|
160
|
+
return None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _metric_period_seconds(metric_row: dict[str, Any] | None) -> int:
|
|
164
|
+
if not metric_row:
|
|
165
|
+
return 300
|
|
166
|
+
period = metric_row.get("Period")
|
|
167
|
+
if isinstance(period, int) and period > 0:
|
|
168
|
+
return period
|
|
169
|
+
return 300
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _pairs_from_metric_row(metric_row: dict[str, Any]) -> list[tuple[datetime, float]]:
|
|
173
|
+
timestamps = metric_row.get("Timestamps") or []
|
|
174
|
+
values = metric_row.get("Values") or []
|
|
175
|
+
pairs: list[tuple[datetime, float]] = []
|
|
176
|
+
for ts_raw, val in zip(timestamps, values):
|
|
177
|
+
if ts_raw is None or val is None:
|
|
178
|
+
continue
|
|
179
|
+
pairs.append((_parse_aws_time(str(ts_raw)), float(val)))
|
|
180
|
+
pairs.sort(key=lambda item: item[0])
|
|
181
|
+
return pairs
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def detect_metric_gap_change(
|
|
185
|
+
metric_row: dict[str, Any] | None,
|
|
186
|
+
*,
|
|
187
|
+
period_seconds: int,
|
|
188
|
+
window_start: datetime,
|
|
189
|
+
window_end: datetime,
|
|
190
|
+
) -> datetime | None:
|
|
191
|
+
"""Return changed_at from the first datapoint after a stop/modify/start gap."""
|
|
192
|
+
if not metric_row:
|
|
193
|
+
return None
|
|
194
|
+
pairs = _pairs_from_metric_row(metric_row)
|
|
195
|
+
if not pairs:
|
|
196
|
+
return None
|
|
197
|
+
|
|
198
|
+
expected_step = timedelta(seconds=period_seconds)
|
|
199
|
+
gap_threshold = timedelta(minutes=METRIC_GAP_MIN_MINUTES)
|
|
200
|
+
|
|
201
|
+
for index in range(len(pairs) - 1):
|
|
202
|
+
t0, _ = pairs[index]
|
|
203
|
+
t1, _ = pairs[index + 1]
|
|
204
|
+
if t0 < window_start or t1 > window_end:
|
|
205
|
+
continue
|
|
206
|
+
delta = t1 - t0
|
|
207
|
+
if delta >= gap_threshold and delta > expected_step * 1.5:
|
|
208
|
+
return t1
|
|
209
|
+
|
|
210
|
+
return None
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def trim_cpu_metric_row(
|
|
214
|
+
metric_row: dict[str, Any] | None,
|
|
215
|
+
changed_at: datetime,
|
|
216
|
+
) -> dict[str, Any] | None:
|
|
217
|
+
if not metric_row:
|
|
218
|
+
return None
|
|
219
|
+
pairs = _pairs_from_metric_row(metric_row)
|
|
220
|
+
filtered = [(t, v) for t, v in pairs if t >= changed_at]
|
|
221
|
+
if not filtered:
|
|
222
|
+
return {
|
|
223
|
+
**metric_row,
|
|
224
|
+
"Timestamps": [],
|
|
225
|
+
"Values": [],
|
|
226
|
+
}
|
|
227
|
+
return {
|
|
228
|
+
**metric_row,
|
|
229
|
+
"Timestamps": [_iso_z(t) for t, _ in filtered],
|
|
230
|
+
"Values": [v for _, v in filtered],
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def post_change_utilization_reliable(
|
|
235
|
+
*,
|
|
236
|
+
changed_at: datetime | None,
|
|
237
|
+
metric_row: dict[str, Any] | None,
|
|
238
|
+
now: datetime,
|
|
239
|
+
) -> bool:
|
|
240
|
+
if changed_at is None:
|
|
241
|
+
return True
|
|
242
|
+
if not metric_row:
|
|
243
|
+
return False
|
|
244
|
+
pairs = [(t, v) for t, v in _pairs_from_metric_row(metric_row) if t >= changed_at]
|
|
245
|
+
if not pairs:
|
|
246
|
+
return False
|
|
247
|
+
span_hours = (now - changed_at).total_seconds() / 3600.0
|
|
248
|
+
if span_hours < POST_CHANGE_MIN_HOURS:
|
|
249
|
+
return False
|
|
250
|
+
if len(pairs) < 2:
|
|
251
|
+
return False
|
|
252
|
+
data_span = (pairs[-1][0] - pairs[0][0]).total_seconds() / 3600.0
|
|
253
|
+
return data_span >= POST_CHANGE_MIN_HOURS or span_hours >= POST_CHANGE_MIN_HOURS
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def effective_utilization_bounds(
|
|
257
|
+
*,
|
|
258
|
+
window_start: datetime,
|
|
259
|
+
window_end: datetime,
|
|
260
|
+
changed_at: datetime | None,
|
|
261
|
+
) -> tuple[datetime, float]:
|
|
262
|
+
start = changed_at if changed_at and changed_at > window_start else window_start
|
|
263
|
+
days = max(0.0, (window_end - start).total_seconds() / 86400.0)
|
|
264
|
+
return start, days
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def change_detection_document(
|
|
268
|
+
change: InstanceTypeChange,
|
|
269
|
+
*,
|
|
270
|
+
now: datetime,
|
|
271
|
+
min_days_since_change: int,
|
|
272
|
+
) -> dict[str, Any]:
|
|
273
|
+
cooldown_until_dt = change.cooldown_until(now, min_days_since_change)
|
|
274
|
+
active = change.cooldown_active(now, min_days_since_change)
|
|
275
|
+
return {
|
|
276
|
+
"changed_at": _iso_z(change.changed_at) if change.changed_at else None,
|
|
277
|
+
"previous_instance_type": change.previous_instance_type,
|
|
278
|
+
"detection_source": change.detection_source,
|
|
279
|
+
"detection_notes": list(change.detection_notes),
|
|
280
|
+
"cooldown_days": min_days_since_change,
|
|
281
|
+
"cooldown_until": _iso_z(cooldown_until_dt) if cooldown_until_dt else None,
|
|
282
|
+
"cooldown_active": active,
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _cloudtrail_modify_event(
|
|
287
|
+
events: list[dict[str, Any]],
|
|
288
|
+
) -> tuple[datetime | None, str | None]:
|
|
289
|
+
best_time: datetime | None = None
|
|
290
|
+
new_type: str | None = None
|
|
291
|
+
for event in events:
|
|
292
|
+
if event.get("EventName") != "ModifyInstanceAttribute":
|
|
293
|
+
continue
|
|
294
|
+
raw = event.get("CloudTrailEvent")
|
|
295
|
+
if not raw:
|
|
296
|
+
continue
|
|
297
|
+
try:
|
|
298
|
+
payload = json.loads(raw) if isinstance(raw, str) else raw
|
|
299
|
+
except (json.JSONDecodeError, TypeError):
|
|
300
|
+
continue
|
|
301
|
+
params = payload.get("requestParameters") or {}
|
|
302
|
+
inst_type = params.get("instanceType")
|
|
303
|
+
value = None
|
|
304
|
+
if isinstance(inst_type, dict):
|
|
305
|
+
value = inst_type.get("value")
|
|
306
|
+
elif isinstance(inst_type, str):
|
|
307
|
+
value = inst_type
|
|
308
|
+
if not value:
|
|
309
|
+
continue
|
|
310
|
+
event_time_raw = event.get("EventTime") or payload.get("eventTime")
|
|
311
|
+
if not event_time_raw:
|
|
312
|
+
continue
|
|
313
|
+
event_time = _parse_aws_time(str(event_time_raw))
|
|
314
|
+
if best_time is None or event_time > best_time:
|
|
315
|
+
best_time = event_time
|
|
316
|
+
new_type = str(value)
|
|
317
|
+
return best_time, new_type
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _config_type_change(
|
|
321
|
+
items: list[dict[str, Any]],
|
|
322
|
+
) -> tuple[datetime | None, str | None]:
|
|
323
|
+
sorted_items = sorted(
|
|
324
|
+
items,
|
|
325
|
+
key=lambda row: _parse_aws_time(str(row.get("configurationItemCaptureTime") or "")),
|
|
326
|
+
)
|
|
327
|
+
previous_type: str | None = None
|
|
328
|
+
for item in sorted_items:
|
|
329
|
+
config = item.get("configuration") or {}
|
|
330
|
+
current_type = config.get("instanceType")
|
|
331
|
+
if not current_type:
|
|
332
|
+
continue
|
|
333
|
+
if previous_type is not None and current_type != previous_type:
|
|
334
|
+
capture = item.get("configurationItemCaptureTime")
|
|
335
|
+
if capture:
|
|
336
|
+
return _parse_aws_time(str(capture)), previous_type
|
|
337
|
+
previous_type = str(current_type)
|
|
338
|
+
return None, None
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def detect_from_cloudtrail(
|
|
342
|
+
*,
|
|
343
|
+
instance_id: str,
|
|
344
|
+
region: str,
|
|
345
|
+
window_start: datetime,
|
|
346
|
+
window_end: datetime,
|
|
347
|
+
runner: AwsRunner,
|
|
348
|
+
) -> InstanceTypeChange:
|
|
349
|
+
notes: list[str] = []
|
|
350
|
+
lookback_start = window_start - timedelta(days=CLOUDTRAIL_LOOKBACK_EXTRA_DAYS)
|
|
351
|
+
events: list[dict[str, Any]] = []
|
|
352
|
+
next_token: str | None = None
|
|
353
|
+
for page_index in range(CLOUDTRAIL_MAX_PAGES):
|
|
354
|
+
argv = build_cloudtrail_lookup_argv(
|
|
355
|
+
instance_id,
|
|
356
|
+
start=lookback_start,
|
|
357
|
+
end=window_end,
|
|
358
|
+
region=region,
|
|
359
|
+
next_token=next_token,
|
|
360
|
+
)
|
|
361
|
+
from maproom.analyze.local_reads import run_cached_analyze_read, window_cache_suffix
|
|
362
|
+
|
|
363
|
+
result = run_cached_analyze_read(
|
|
364
|
+
runner,
|
|
365
|
+
"aws",
|
|
366
|
+
argv,
|
|
367
|
+
api_id="aws_cloudtrail_lookup_events",
|
|
368
|
+
region=region,
|
|
369
|
+
instance_id=instance_id,
|
|
370
|
+
suffix=window_cache_suffix(
|
|
371
|
+
start=lookback_start,
|
|
372
|
+
end=window_end,
|
|
373
|
+
token=next_token or "",
|
|
374
|
+
label=f"page-{page_index}",
|
|
375
|
+
),
|
|
376
|
+
record=False,
|
|
377
|
+
)
|
|
378
|
+
response = _runner_response(result)
|
|
379
|
+
cli_version = getattr(result, "cli_version", None)
|
|
380
|
+
try:
|
|
381
|
+
page_events, next_token = parse_cloudtrail_lookup_events(
|
|
382
|
+
response,
|
|
383
|
+
cli_version=cli_version,
|
|
384
|
+
)
|
|
385
|
+
except AccessDeniedError:
|
|
386
|
+
notes.append("cloudtrail: access_denied")
|
|
387
|
+
return InstanceTypeChange(detection_notes=notes)
|
|
388
|
+
except MaproomParseError:
|
|
389
|
+
notes.append("cloudtrail: parse_error")
|
|
390
|
+
return InstanceTypeChange(detection_notes=notes)
|
|
391
|
+
events.extend(page_events)
|
|
392
|
+
if not next_token:
|
|
393
|
+
break
|
|
394
|
+
changed_at, _new_type = _cloudtrail_modify_event(events)
|
|
395
|
+
if changed_at is None:
|
|
396
|
+
notes.append("cloudtrail: no_modify_instance_type_event")
|
|
397
|
+
return InstanceTypeChange(detection_notes=notes)
|
|
398
|
+
return InstanceTypeChange(
|
|
399
|
+
changed_at=changed_at,
|
|
400
|
+
previous_instance_type=None,
|
|
401
|
+
detection_source="cloudtrail",
|
|
402
|
+
detection_notes=notes,
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _config_page_next_token(response: dict[str, Any]) -> str | None:
|
|
407
|
+
"""Read the Config history page token (API nextToken or CLI NextToken)."""
|
|
408
|
+
payload = response.get("stdout_json")
|
|
409
|
+
if not isinstance(payload, dict):
|
|
410
|
+
return None
|
|
411
|
+
for key in ("nextToken", "NextToken"):
|
|
412
|
+
token = payload.get(key)
|
|
413
|
+
if token:
|
|
414
|
+
return str(token)
|
|
415
|
+
return None
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def detect_from_config(
|
|
419
|
+
*,
|
|
420
|
+
instance_id: str,
|
|
421
|
+
region: str,
|
|
422
|
+
window_start: datetime,
|
|
423
|
+
window_end: datetime,
|
|
424
|
+
runner: AwsRunner,
|
|
425
|
+
) -> InstanceTypeChange:
|
|
426
|
+
notes: list[str] = []
|
|
427
|
+
items: list[dict[str, Any]] = []
|
|
428
|
+
next_token: str | None = None
|
|
429
|
+
for page_index in range(CONFIG_MAX_PAGES):
|
|
430
|
+
argv = build_config_history_argv(
|
|
431
|
+
instance_id,
|
|
432
|
+
earlier_time=window_start,
|
|
433
|
+
later_time=window_end,
|
|
434
|
+
region=region,
|
|
435
|
+
next_token=next_token,
|
|
436
|
+
)
|
|
437
|
+
from maproom.analyze.local_reads import run_cached_analyze_read, window_cache_suffix
|
|
438
|
+
|
|
439
|
+
result = run_cached_analyze_read(
|
|
440
|
+
runner,
|
|
441
|
+
"aws",
|
|
442
|
+
argv,
|
|
443
|
+
api_id="aws_config_get_resource_config_history",
|
|
444
|
+
region=region,
|
|
445
|
+
instance_id=instance_id,
|
|
446
|
+
suffix=window_cache_suffix(
|
|
447
|
+
start=window_start,
|
|
448
|
+
end=window_end,
|
|
449
|
+
token=next_token or "",
|
|
450
|
+
label=f"page-{page_index}",
|
|
451
|
+
),
|
|
452
|
+
record=False,
|
|
453
|
+
)
|
|
454
|
+
response = _runner_response(result)
|
|
455
|
+
cli_version = getattr(result, "cli_version", None)
|
|
456
|
+
try:
|
|
457
|
+
page_items = parse_config_resource_config_history(
|
|
458
|
+
response,
|
|
459
|
+
cli_version=cli_version,
|
|
460
|
+
)
|
|
461
|
+
except AccessDeniedError as exc:
|
|
462
|
+
err = str(exc).lower()
|
|
463
|
+
if "recorder not enabled" in err:
|
|
464
|
+
notes.append("aws_config: recorder_not_enabled")
|
|
465
|
+
elif "resource not discovered" in err:
|
|
466
|
+
notes.append("aws_config: resource_not_discovered")
|
|
467
|
+
else:
|
|
468
|
+
notes.append("aws_config: access_denied")
|
|
469
|
+
return InstanceTypeChange(detection_notes=notes)
|
|
470
|
+
except MaproomParseError:
|
|
471
|
+
notes.append("aws_config: parse_error")
|
|
472
|
+
return InstanceTypeChange(detection_notes=notes)
|
|
473
|
+
items.extend(page_items)
|
|
474
|
+
next_token = _config_page_next_token(response)
|
|
475
|
+
if not next_token:
|
|
476
|
+
break
|
|
477
|
+
|
|
478
|
+
changed_at, previous_type = _config_type_change(items)
|
|
479
|
+
if changed_at is None:
|
|
480
|
+
notes.append("aws_config: no_instance_type_change")
|
|
481
|
+
return InstanceTypeChange(detection_notes=notes)
|
|
482
|
+
return InstanceTypeChange(
|
|
483
|
+
changed_at=changed_at,
|
|
484
|
+
previous_instance_type=previous_type,
|
|
485
|
+
detection_source="aws_config",
|
|
486
|
+
detection_notes=notes,
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def detect_from_metrics_and_launch(
|
|
491
|
+
*,
|
|
492
|
+
instance: dict[str, Any],
|
|
493
|
+
metric_row: dict[str, Any] | None,
|
|
494
|
+
gap_metric_row: dict[str, Any] | None,
|
|
495
|
+
window_start: datetime,
|
|
496
|
+
window_end: datetime,
|
|
497
|
+
) -> InstanceTypeChange:
|
|
498
|
+
notes: list[str] = []
|
|
499
|
+
period = _metric_period_seconds(gap_metric_row or metric_row)
|
|
500
|
+
gap_at = detect_metric_gap_change(
|
|
501
|
+
gap_metric_row or metric_row,
|
|
502
|
+
period_seconds=period,
|
|
503
|
+
window_start=window_start,
|
|
504
|
+
window_end=window_end,
|
|
505
|
+
)
|
|
506
|
+
launch_at = _launch_time_in_window(
|
|
507
|
+
instance,
|
|
508
|
+
window_start=window_start,
|
|
509
|
+
window_end=window_end,
|
|
510
|
+
)
|
|
511
|
+
|
|
512
|
+
candidates: list[tuple[datetime, DetectionSource]] = []
|
|
513
|
+
if gap_at is not None:
|
|
514
|
+
candidates.append((gap_at, "metric_gap"))
|
|
515
|
+
if launch_at is not None:
|
|
516
|
+
candidates.append((launch_at, "launch_time"))
|
|
517
|
+
|
|
518
|
+
if not candidates:
|
|
519
|
+
notes.append("metric_gap: no_gap_detected")
|
|
520
|
+
if launch_at is None:
|
|
521
|
+
notes.append("launch_time: outside_window")
|
|
522
|
+
return InstanceTypeChange(detection_source="none", detection_notes=notes)
|
|
523
|
+
|
|
524
|
+
changed_at, source = max(candidates, key=lambda item: item[0])
|
|
525
|
+
if gap_at is None:
|
|
526
|
+
notes.append("metric_gap: no_gap_detected")
|
|
527
|
+
if launch_at is None:
|
|
528
|
+
notes.append("launch_time: outside_window")
|
|
529
|
+
return InstanceTypeChange(
|
|
530
|
+
changed_at=changed_at,
|
|
531
|
+
previous_instance_type=None,
|
|
532
|
+
detection_source=source,
|
|
533
|
+
detection_notes=notes,
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def detect_instance_type_change(
|
|
538
|
+
*,
|
|
539
|
+
instance_id: str,
|
|
540
|
+
region: str,
|
|
541
|
+
instance: dict[str, Any],
|
|
542
|
+
window_start: datetime,
|
|
543
|
+
window_end: datetime,
|
|
544
|
+
cpu_metric_row: dict[str, Any] | None,
|
|
545
|
+
runner: AwsRunner,
|
|
546
|
+
local_only: bool,
|
|
547
|
+
now: datetime,
|
|
548
|
+
allow_metric_fallbacks: bool = True,
|
|
549
|
+
) -> InstanceTypeChange:
|
|
550
|
+
"""Resolve the most recent instance-type change within the utilization window."""
|
|
551
|
+
del now # reserved for future bounded lookups
|
|
552
|
+
if local_only:
|
|
553
|
+
return detect_from_metrics_and_launch(
|
|
554
|
+
instance=instance,
|
|
555
|
+
metric_row=cpu_metric_row,
|
|
556
|
+
gap_metric_row=cpu_metric_row,
|
|
557
|
+
window_start=window_start,
|
|
558
|
+
window_end=window_end,
|
|
559
|
+
)
|
|
560
|
+
|
|
561
|
+
trail = detect_from_cloudtrail(
|
|
562
|
+
instance_id=instance_id,
|
|
563
|
+
region=region,
|
|
564
|
+
window_start=window_start,
|
|
565
|
+
window_end=window_end,
|
|
566
|
+
runner=runner,
|
|
567
|
+
)
|
|
568
|
+
if trail.changed_at is not None:
|
|
569
|
+
return trail
|
|
570
|
+
|
|
571
|
+
notes = list(trail.detection_notes)
|
|
572
|
+
config = detect_from_config(
|
|
573
|
+
instance_id=instance_id,
|
|
574
|
+
region=region,
|
|
575
|
+
window_start=window_start,
|
|
576
|
+
window_end=window_end,
|
|
577
|
+
runner=runner,
|
|
578
|
+
)
|
|
579
|
+
if config.changed_at is not None:
|
|
580
|
+
config.detection_notes = notes + config.detection_notes
|
|
581
|
+
return config
|
|
582
|
+
|
|
583
|
+
notes.extend(config.detection_notes)
|
|
584
|
+
if not allow_metric_fallbacks:
|
|
585
|
+
return InstanceTypeChange(detection_source="none", detection_notes=notes)
|
|
586
|
+
|
|
587
|
+
gap_row = cpu_metric_row
|
|
588
|
+
period = _metric_period_seconds(cpu_metric_row)
|
|
589
|
+
if period > 60:
|
|
590
|
+
gap_argv = build_cpu_utilization_argv(
|
|
591
|
+
instance_id,
|
|
592
|
+
start=window_start,
|
|
593
|
+
end=window_end,
|
|
594
|
+
period=60,
|
|
595
|
+
) + ["--region", region]
|
|
596
|
+
from maproom.analyze.local_reads import run_cached_analyze_read, window_cache_suffix
|
|
597
|
+
|
|
598
|
+
gap_result = run_cached_analyze_read(
|
|
599
|
+
runner,
|
|
600
|
+
"aws",
|
|
601
|
+
gap_argv,
|
|
602
|
+
api_id="aws_cloudwatch_get_metric_data",
|
|
603
|
+
region=region,
|
|
604
|
+
instance_id=instance_id,
|
|
605
|
+
suffix=window_cache_suffix(
|
|
606
|
+
start=window_start, end=window_end, label="gap"
|
|
607
|
+
),
|
|
608
|
+
record=False,
|
|
609
|
+
)
|
|
610
|
+
gap_response = _runner_response(gap_result)
|
|
611
|
+
cli_version = getattr(gap_result, "cli_version", None)
|
|
612
|
+
try:
|
|
613
|
+
from maproom.parsers import parse_cloudwatch_get_metric_data
|
|
614
|
+
|
|
615
|
+
rows = parse_cloudwatch_get_metric_data(
|
|
616
|
+
gap_response,
|
|
617
|
+
cli_version=cli_version,
|
|
618
|
+
)
|
|
619
|
+
gap_row = rows[0] if rows else cpu_metric_row
|
|
620
|
+
except Exception:
|
|
621
|
+
notes.append("metric_gap: fine_grained_fetch_failed")
|
|
622
|
+
gap_row = cpu_metric_row
|
|
623
|
+
|
|
624
|
+
metric_change = detect_from_metrics_and_launch(
|
|
625
|
+
instance=instance,
|
|
626
|
+
metric_row=cpu_metric_row,
|
|
627
|
+
gap_metric_row=gap_row,
|
|
628
|
+
window_start=window_start,
|
|
629
|
+
window_end=window_end,
|
|
630
|
+
)
|
|
631
|
+
metric_change.detection_notes = notes + metric_change.detection_notes
|
|
632
|
+
if metric_change.changed_at is None:
|
|
633
|
+
return InstanceTypeChange(detection_source="none", detection_notes=metric_change.detection_notes)
|
|
634
|
+
return metric_change
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def summarize_trimmed_cpu(
|
|
638
|
+
metric_row: dict[str, Any] | None,
|
|
639
|
+
) -> dict[str, Any] | None:
|
|
640
|
+
return summarize_cpu_utilization(metric_row)
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def cpu_values_after_change(
|
|
644
|
+
metric_row: dict[str, Any] | None,
|
|
645
|
+
changed_at: datetime | None,
|
|
646
|
+
) -> list[float]:
|
|
647
|
+
if not metric_row or changed_at is None:
|
|
648
|
+
if not metric_row:
|
|
649
|
+
return []
|
|
650
|
+
return [float(v) for v in (metric_row.get("Values") or []) if v is not None]
|
|
651
|
+
pairs = _pairs_from_metric_row(metric_row)
|
|
652
|
+
return [v for t, v in pairs if t >= changed_at]
|