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,461 @@
|
|
|
1
|
+
"""Read Reserved Instances and utilization during product version 4 analyze."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import datetime, timedelta, timezone
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from maproom.reservations.aws import fetch_reserved_instances
|
|
11
|
+
from maproom.reservations.azure import fetch_azure_inventory
|
|
12
|
+
from maproom.reservations.model import ReservationError, normalize_records_from_aws
|
|
13
|
+
from maproom.reservations.status import InventoryState, read_inventory_state
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class AnalyzeReservationRead:
|
|
18
|
+
records: tuple[dict[str, Any], ...]
|
|
19
|
+
read_ok: bool
|
|
20
|
+
loaded_as_of: str | None = None
|
|
21
|
+
inventory_stale: bool = False
|
|
22
|
+
used_snapshot: bool = False
|
|
23
|
+
inventory_refresh_failed: bool = False
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _utilization_window(now: datetime | None = None) -> tuple[str, str]:
|
|
27
|
+
end = now or datetime.now(timezone.utc)
|
|
28
|
+
start = end - timedelta(days=30)
|
|
29
|
+
return start.date().isoformat(), end.date().isoformat()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _parse_utilization_payload(payload: dict[str, Any]) -> dict[tuple[str, str, str], dict[str, float]]:
|
|
33
|
+
"""Map (region, instance_type, platform) -> utilization_fraction and unused_quantity."""
|
|
34
|
+
grouped: dict[tuple[str, str, str], dict[str, float]] = {}
|
|
35
|
+
for bucket in payload.get("UtilizationsByTime") or []:
|
|
36
|
+
if not isinstance(bucket, dict):
|
|
37
|
+
continue
|
|
38
|
+
for group in bucket.get("Groups") or []:
|
|
39
|
+
if not isinstance(group, dict):
|
|
40
|
+
continue
|
|
41
|
+
attrs = group.get("Attributes")
|
|
42
|
+
util = group.get("Utilization")
|
|
43
|
+
if not isinstance(attrs, dict) or not isinstance(util, dict):
|
|
44
|
+
continue
|
|
45
|
+
region = str(attrs.get("region") or attrs.get("REGION") or "").strip().lower()
|
|
46
|
+
instance_type = str(
|
|
47
|
+
attrs.get("instanceType") or attrs.get("INSTANCE_TYPE") or ""
|
|
48
|
+
).strip()
|
|
49
|
+
platform = str(attrs.get("platform") or attrs.get("PLATFORM") or "").strip()
|
|
50
|
+
if not region or not instance_type:
|
|
51
|
+
continue
|
|
52
|
+
try:
|
|
53
|
+
fraction = float(str(util.get("UtilizationPercentage") or "0"))
|
|
54
|
+
except ValueError:
|
|
55
|
+
fraction = 0.0
|
|
56
|
+
fraction = max(0.0, min(fraction, 100.0)) / 100.0
|
|
57
|
+
try:
|
|
58
|
+
unused_hours = float(str(util.get("UnusedHours") or "0"))
|
|
59
|
+
except ValueError:
|
|
60
|
+
unused_hours = 0.0
|
|
61
|
+
key = (region, instance_type, platform)
|
|
62
|
+
grouped[key] = {
|
|
63
|
+
"utilization_fraction": fraction,
|
|
64
|
+
"unused_quantity": unused_hours,
|
|
65
|
+
}
|
|
66
|
+
return grouped
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def fetch_reservation_utilization(runner: Any, *, now: datetime | None = None) -> dict[tuple[str, str, str], dict[str, float]]:
|
|
70
|
+
from maproom.analyze.local_reads import run_cached_analyze_read, window_cache_suffix
|
|
71
|
+
|
|
72
|
+
start, end = _utilization_window(now)
|
|
73
|
+
result = run_cached_analyze_read(
|
|
74
|
+
runner,
|
|
75
|
+
"aws",
|
|
76
|
+
[
|
|
77
|
+
"ce",
|
|
78
|
+
"get-reservation-utilization",
|
|
79
|
+
"--time-period",
|
|
80
|
+
f"Start={start},End={end}",
|
|
81
|
+
"--granularity",
|
|
82
|
+
"MONTHLY",
|
|
83
|
+
"--group-by",
|
|
84
|
+
"Type=DIMENSION,Key=INSTANCE_TYPE",
|
|
85
|
+
"--group-by",
|
|
86
|
+
"Type=DIMENSION,Key=REGION",
|
|
87
|
+
"--group-by",
|
|
88
|
+
"Type=DIMENSION,Key=PLATFORM",
|
|
89
|
+
"--output",
|
|
90
|
+
"json",
|
|
91
|
+
],
|
|
92
|
+
api_id="aws_ce_get_reservation_utilization",
|
|
93
|
+
region="global",
|
|
94
|
+
suffix=window_cache_suffix(start=start, end=end, granularity="MONTHLY"),
|
|
95
|
+
record=False,
|
|
96
|
+
now=now,
|
|
97
|
+
)
|
|
98
|
+
if int(result.exit_code) != 0:
|
|
99
|
+
return {}
|
|
100
|
+
try:
|
|
101
|
+
payload = json.loads(result.stdout or "{}")
|
|
102
|
+
except json.JSONDecodeError:
|
|
103
|
+
return {}
|
|
104
|
+
if not isinstance(payload, dict):
|
|
105
|
+
return {}
|
|
106
|
+
return _parse_utilization_payload(payload)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _merge_utilization(
|
|
110
|
+
records: list[dict[str, Any]],
|
|
111
|
+
util_map: dict[tuple[str, str, str], dict[str, float]],
|
|
112
|
+
) -> list[dict[str, Any]]:
|
|
113
|
+
merged: list[dict[str, Any]] = []
|
|
114
|
+
for record in records:
|
|
115
|
+
row = dict(record)
|
|
116
|
+
region = str(row.get("region") or "").strip().lower()
|
|
117
|
+
instance_type = str(row.get("instance_type") or "").strip()
|
|
118
|
+
platform = str(row.get("platform") or "").strip()
|
|
119
|
+
stats = util_map.get((region, instance_type, platform))
|
|
120
|
+
if stats:
|
|
121
|
+
row["utilization_fraction"] = stats["utilization_fraction"]
|
|
122
|
+
quantity = int(row.get("quantity") or 1)
|
|
123
|
+
unused_hours = stats.get("unused_quantity", 0.0)
|
|
124
|
+
fraction = stats.get("utilization_fraction", 0.0)
|
|
125
|
+
row["unused_quantity"] = max(
|
|
126
|
+
float(unused_hours),
|
|
127
|
+
float(quantity) * max(0.0, 1.0 - float(fraction)),
|
|
128
|
+
)
|
|
129
|
+
merged.append(row)
|
|
130
|
+
return merged
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _occupancy_windows(now: datetime | None) -> dict[str, tuple[str, str, str]]:
|
|
134
|
+
end = now or datetime.now(timezone.utc)
|
|
135
|
+
day = end.date()
|
|
136
|
+
return {
|
|
137
|
+
"occupancy_24h": ((day - timedelta(days=1)).isoformat(), day.isoformat(), "DAILY"),
|
|
138
|
+
"occupancy_7d": ((day - timedelta(days=7)).isoformat(), day.isoformat(), "DAILY"),
|
|
139
|
+
"occupancy_30d": ((day - timedelta(days=30)).isoformat(), day.isoformat(), "DAILY"),
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _fetch_occupancy_window(
|
|
144
|
+
runner: Any,
|
|
145
|
+
*,
|
|
146
|
+
start: str,
|
|
147
|
+
end: str,
|
|
148
|
+
granularity: str,
|
|
149
|
+
suffix: str | None = None,
|
|
150
|
+
) -> dict[str, float]:
|
|
151
|
+
from maproom.analyze.local_reads import run_cached_analyze_read, window_cache_suffix
|
|
152
|
+
|
|
153
|
+
result = run_cached_analyze_read(
|
|
154
|
+
runner,
|
|
155
|
+
"aws",
|
|
156
|
+
[
|
|
157
|
+
"ce",
|
|
158
|
+
"get-reservation-utilization",
|
|
159
|
+
"--time-period",
|
|
160
|
+
f"Start={start},End={end}",
|
|
161
|
+
"--granularity",
|
|
162
|
+
granularity,
|
|
163
|
+
"--group-by",
|
|
164
|
+
"Type=DIMENSION,Key=SUBSCRIPTION_ID",
|
|
165
|
+
"--output",
|
|
166
|
+
"json",
|
|
167
|
+
],
|
|
168
|
+
api_id="aws_ce_get_reservation_utilization",
|
|
169
|
+
region="global",
|
|
170
|
+
suffix=suffix
|
|
171
|
+
or window_cache_suffix(start=start, end=end, granularity=granularity),
|
|
172
|
+
record=False,
|
|
173
|
+
)
|
|
174
|
+
if int(result.exit_code) != 0:
|
|
175
|
+
return {}
|
|
176
|
+
try:
|
|
177
|
+
payload = json.loads(result.stdout or "{}")
|
|
178
|
+
except json.JSONDecodeError:
|
|
179
|
+
return {}
|
|
180
|
+
if not isinstance(payload, dict):
|
|
181
|
+
return {}
|
|
182
|
+
samples: dict[str, list[float]] = {}
|
|
183
|
+
for bucket in payload.get("UtilizationsByTime") or []:
|
|
184
|
+
if not isinstance(bucket, dict):
|
|
185
|
+
continue
|
|
186
|
+
for group in bucket.get("Groups") or []:
|
|
187
|
+
if not isinstance(group, dict):
|
|
188
|
+
continue
|
|
189
|
+
attrs = group.get("Attributes")
|
|
190
|
+
util = group.get("Utilization")
|
|
191
|
+
if not isinstance(attrs, dict) or not isinstance(util, dict):
|
|
192
|
+
continue
|
|
193
|
+
subscription = str(
|
|
194
|
+
attrs.get("subscriptionId") or attrs.get("SUBSCRIPTION_ID") or ""
|
|
195
|
+
).strip()
|
|
196
|
+
if not subscription:
|
|
197
|
+
continue
|
|
198
|
+
try:
|
|
199
|
+
fraction = float(str(util.get("UtilizationPercentage") or "0"))
|
|
200
|
+
except ValueError:
|
|
201
|
+
fraction = 0.0
|
|
202
|
+
samples.setdefault(subscription, []).append(max(0.0, min(fraction, 100.0)) / 100.0)
|
|
203
|
+
return {key: sum(values) / len(values) for key, values in samples.items() if values}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _merge_occupancy_windows(runner: Any, records: list[dict[str, Any]], *, now: datetime | None) -> None:
|
|
207
|
+
windows: dict[str, dict[str, float]] = {}
|
|
208
|
+
for field, (start, end, granularity) in _occupancy_windows(now).items():
|
|
209
|
+
try:
|
|
210
|
+
windows[field] = _fetch_occupancy_window(
|
|
211
|
+
runner,
|
|
212
|
+
start=start,
|
|
213
|
+
end=end,
|
|
214
|
+
granularity=granularity,
|
|
215
|
+
suffix=window_cache_suffix(
|
|
216
|
+
start=start, end=end, granularity=granularity, label=field
|
|
217
|
+
),
|
|
218
|
+
)
|
|
219
|
+
except Exception:
|
|
220
|
+
windows[field] = {}
|
|
221
|
+
for record in records:
|
|
222
|
+
subscription = str(record.get("subscription_id") or "").strip()
|
|
223
|
+
for field, grouped in windows.items():
|
|
224
|
+
if subscription and subscription in grouped:
|
|
225
|
+
record[field] = grouped[subscription]
|
|
226
|
+
else:
|
|
227
|
+
record[field] = None
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _normalized_region_names(regions: set[str] | None) -> set[str]:
|
|
231
|
+
if not regions:
|
|
232
|
+
return set()
|
|
233
|
+
return {name.strip().lower() for name in regions if str(name).strip()}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _structural_key(record: dict[str, Any]) -> tuple[str, str, str, str]:
|
|
237
|
+
return (
|
|
238
|
+
str(record.get("kind") or ""),
|
|
239
|
+
str(record.get("region") or "").strip().lower(),
|
|
240
|
+
str(record.get("instance_type") or ""),
|
|
241
|
+
str(record.get("platform") or ""),
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _live_row_covers_snapshot(live: dict[str, Any], snapshot: dict[str, Any]) -> bool:
|
|
246
|
+
live_sub = str(live.get("subscription_id") or "").strip()
|
|
247
|
+
snap_sub = str(snapshot.get("subscription_id") or "").strip()
|
|
248
|
+
if live_sub and snap_sub:
|
|
249
|
+
return live_sub == snap_sub
|
|
250
|
+
return _structural_key(live) == _structural_key(snapshot)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _snapshot_rows_missing_from_live(
|
|
254
|
+
live: list[dict[str, Any]],
|
|
255
|
+
snapshot: list[dict[str, Any]],
|
|
256
|
+
) -> list[dict[str, Any]]:
|
|
257
|
+
missing: list[dict[str, Any]] = []
|
|
258
|
+
for record in snapshot:
|
|
259
|
+
if any(_live_row_covers_snapshot(live_row, record) for live_row in live):
|
|
260
|
+
continue
|
|
261
|
+
missing.append(record)
|
|
262
|
+
return missing
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _filter_records_for_workset(
|
|
266
|
+
records: list[dict[str, Any]],
|
|
267
|
+
*,
|
|
268
|
+
aws_regions: set[str],
|
|
269
|
+
azure_regions: set[str],
|
|
270
|
+
) -> list[dict[str, Any]]:
|
|
271
|
+
wanted_aws = _normalized_region_names(aws_regions)
|
|
272
|
+
wanted_azure = _normalized_region_names(azure_regions)
|
|
273
|
+
filtered: list[dict[str, Any]] = []
|
|
274
|
+
for record in records:
|
|
275
|
+
if not isinstance(record, dict):
|
|
276
|
+
continue
|
|
277
|
+
region = str(record.get("region") or "").strip().lower()
|
|
278
|
+
kind = str(record.get("kind") or "ec2_reserved_instance")
|
|
279
|
+
if kind == "azure_reserved_vm":
|
|
280
|
+
if region in wanted_azure:
|
|
281
|
+
filtered.append(record)
|
|
282
|
+
elif wanted_aws and region in wanted_aws:
|
|
283
|
+
filtered.append(record)
|
|
284
|
+
return filtered
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _read_live_records(
|
|
288
|
+
runner: Any,
|
|
289
|
+
regions: set[str],
|
|
290
|
+
*,
|
|
291
|
+
azure_regions: set[str] | None,
|
|
292
|
+
) -> tuple[list[dict[str, Any]], bool]:
|
|
293
|
+
records: list[dict[str, Any]] = []
|
|
294
|
+
describe_ok = False
|
|
295
|
+
for region in sorted(regions):
|
|
296
|
+
try:
|
|
297
|
+
reserved = fetch_reserved_instances(runner, region=region)
|
|
298
|
+
except ReservationError:
|
|
299
|
+
continue
|
|
300
|
+
describe_ok = True
|
|
301
|
+
records.extend(normalize_records_from_aws(reserved, region=region))
|
|
302
|
+
if azure_regions:
|
|
303
|
+
try:
|
|
304
|
+
azure_records = [
|
|
305
|
+
record
|
|
306
|
+
for record in fetch_azure_inventory(runner)
|
|
307
|
+
if str(record.get("region") or "").strip().lower()
|
|
308
|
+
in _normalized_region_names(azure_regions)
|
|
309
|
+
]
|
|
310
|
+
except ReservationError:
|
|
311
|
+
azure_records = []
|
|
312
|
+
else:
|
|
313
|
+
describe_ok = True
|
|
314
|
+
records.extend(azure_records)
|
|
315
|
+
return records, describe_ok
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _snapshot_rows_for_workset(
|
|
319
|
+
inventory: InventoryState,
|
|
320
|
+
*,
|
|
321
|
+
regions: set[str],
|
|
322
|
+
azure: set[str],
|
|
323
|
+
) -> tuple[bool, list[dict[str, Any]]]:
|
|
324
|
+
snapshot_usable = inventory.exists and inventory.parse_error is None
|
|
325
|
+
if not snapshot_usable:
|
|
326
|
+
return False, []
|
|
327
|
+
filtered = _filter_records_for_workset(
|
|
328
|
+
list(inventory.records),
|
|
329
|
+
aws_regions=regions,
|
|
330
|
+
azure_regions=azure,
|
|
331
|
+
)
|
|
332
|
+
return True, filtered
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _select_reservation_records(
|
|
336
|
+
*,
|
|
337
|
+
snapshot_usable: bool,
|
|
338
|
+
snapshot_records: list[dict[str, Any]],
|
|
339
|
+
live_filtered: list[dict[str, Any]],
|
|
340
|
+
live_ok: bool,
|
|
341
|
+
) -> tuple[list[dict[str, Any]], bool, bool, bool]:
|
|
342
|
+
used_snapshot = False
|
|
343
|
+
live_records_used = False
|
|
344
|
+
if live_ok and live_filtered:
|
|
345
|
+
records = list(live_filtered)
|
|
346
|
+
read_ok = True
|
|
347
|
+
live_records_used = True
|
|
348
|
+
if snapshot_usable:
|
|
349
|
+
extra = _snapshot_rows_missing_from_live(live_filtered, snapshot_records)
|
|
350
|
+
if extra:
|
|
351
|
+
records.extend(extra)
|
|
352
|
+
used_snapshot = True
|
|
353
|
+
elif snapshot_usable:
|
|
354
|
+
records = snapshot_records
|
|
355
|
+
read_ok = True
|
|
356
|
+
used_snapshot = True
|
|
357
|
+
elif live_ok:
|
|
358
|
+
records = live_filtered
|
|
359
|
+
read_ok = True
|
|
360
|
+
else:
|
|
361
|
+
records = []
|
|
362
|
+
read_ok = False
|
|
363
|
+
return records, read_ok, used_snapshot, live_records_used
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def read_analyze_reservation_records(
|
|
367
|
+
runner: Any,
|
|
368
|
+
regions: set[str],
|
|
369
|
+
*,
|
|
370
|
+
azure_regions: set[str] | None = None,
|
|
371
|
+
now: datetime | None = None,
|
|
372
|
+
as_json: bool = False,
|
|
373
|
+
refresh: bool | None = None,
|
|
374
|
+
) -> AnalyzeReservationRead:
|
|
375
|
+
"""Return normalized records with optional utilization fields and whether a read succeeded."""
|
|
376
|
+
from maproom.analyze.local_reads import analyze_cache_refresh
|
|
377
|
+
|
|
378
|
+
azure = azure_regions or set()
|
|
379
|
+
force_refresh = refresh if refresh is not None else analyze_cache_refresh()
|
|
380
|
+
inventory = read_inventory_state(now_utc=now)
|
|
381
|
+
snapshot_usable, snapshot_records = _snapshot_rows_for_workset(
|
|
382
|
+
inventory,
|
|
383
|
+
regions=regions,
|
|
384
|
+
azure=azure,
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
# Prefer the on-disk multi-account pool only when every account folder is fresh.
|
|
388
|
+
prefer_snapshot = snapshot_usable and not inventory.is_stale and not force_refresh
|
|
389
|
+
inventory_refresh_failed = False
|
|
390
|
+
if prefer_snapshot:
|
|
391
|
+
records = list(snapshot_records)
|
|
392
|
+
read_ok = True
|
|
393
|
+
used_snapshot = True
|
|
394
|
+
live_records_used = False
|
|
395
|
+
else:
|
|
396
|
+
live_records, live_ok = _read_live_records(
|
|
397
|
+
runner,
|
|
398
|
+
regions,
|
|
399
|
+
azure_regions=azure,
|
|
400
|
+
)
|
|
401
|
+
live_filtered = _filter_records_for_workset(
|
|
402
|
+
live_records, aws_regions=regions, azure_regions=azure
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
records, read_ok, used_snapshot, live_records_used = _select_reservation_records(
|
|
406
|
+
snapshot_usable=snapshot_usable,
|
|
407
|
+
snapshot_records=snapshot_records,
|
|
408
|
+
live_filtered=live_filtered,
|
|
409
|
+
live_ok=live_ok,
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
# Refresh only the signed-in account; other account folders stay on disk and
|
|
413
|
+
# remain available as snapshot extras for the coverage pool.
|
|
414
|
+
if read_ok and used_snapshot and snapshot_usable and inventory.is_stale:
|
|
415
|
+
from maproom.inventory.reservations_refresh import refresh_reservations_inventory
|
|
416
|
+
|
|
417
|
+
refreshed = refresh_reservations_inventory(runner, as_json=as_json)
|
|
418
|
+
inventory = read_inventory_state(now_utc=now)
|
|
419
|
+
snapshot_usable, snapshot_records = _snapshot_rows_for_workset(
|
|
420
|
+
inventory,
|
|
421
|
+
regions=regions,
|
|
422
|
+
azure=azure,
|
|
423
|
+
)
|
|
424
|
+
if refreshed:
|
|
425
|
+
records, read_ok, used_snapshot, live_records_used = _select_reservation_records(
|
|
426
|
+
snapshot_usable=snapshot_usable,
|
|
427
|
+
snapshot_records=snapshot_records,
|
|
428
|
+
live_filtered=live_filtered,
|
|
429
|
+
live_ok=live_ok,
|
|
430
|
+
)
|
|
431
|
+
inventory = read_inventory_state(now_utc=now)
|
|
432
|
+
else:
|
|
433
|
+
inventory_refresh_failed = True
|
|
434
|
+
|
|
435
|
+
if not read_ok:
|
|
436
|
+
return AnalyzeReservationRead(
|
|
437
|
+
records=tuple(),
|
|
438
|
+
read_ok=False,
|
|
439
|
+
loaded_as_of=None,
|
|
440
|
+
inventory_stale=False,
|
|
441
|
+
used_snapshot=False,
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
util_map = fetch_reservation_utilization(runner, now=now)
|
|
445
|
+
merged = _merge_utilization(records, util_map)
|
|
446
|
+
_merge_occupancy_windows(runner, merged, now=now)
|
|
447
|
+
records = merged
|
|
448
|
+
|
|
449
|
+
pool_stale = bool(snapshot_usable and inventory.is_stale)
|
|
450
|
+
loaded_as_of: str | None = None
|
|
451
|
+
if snapshot_usable and (used_snapshot or pool_stale):
|
|
452
|
+
loaded_as_of = inventory.loaded_as_of
|
|
453
|
+
|
|
454
|
+
return AnalyzeReservationRead(
|
|
455
|
+
records=tuple(records),
|
|
456
|
+
read_ok=True,
|
|
457
|
+
loaded_as_of=loaded_as_of,
|
|
458
|
+
inventory_stale=pool_stale,
|
|
459
|
+
used_snapshot=used_snapshot,
|
|
460
|
+
inventory_refresh_failed=inventory_refresh_failed,
|
|
461
|
+
)
|