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,460 @@
|
|
|
1
|
+
"""Instance lists saved by analyze, one snapshot per cloud and region."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import tempfile
|
|
10
|
+
from datetime import datetime, timedelta, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from maproom.analyze.workset import WorkItem
|
|
15
|
+
from maproom.inventory.account_identity import (
|
|
16
|
+
AccountIdentityError,
|
|
17
|
+
resolve_aws_account,
|
|
18
|
+
resolve_azure_account,
|
|
19
|
+
)
|
|
20
|
+
from maproom.inventory.accounts import CloudAccount, parse_account_folder
|
|
21
|
+
from maproom.paths import data_subdir, prepare_data_write
|
|
22
|
+
from maproom.redaction import redact_tree
|
|
23
|
+
|
|
24
|
+
_LEGACY_FILENAME = "instances.json"
|
|
25
|
+
_REGION_FILE = re.compile(r"^instances-.+\.json$")
|
|
26
|
+
_SLUG = re.compile(r"[^a-z0-9]+")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def instances_root() -> Path:
|
|
30
|
+
return data_subdir("instances")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def region_snapshot_name(region: str) -> str:
|
|
34
|
+
"""On-disk basename for one region under an account folder."""
|
|
35
|
+
slug = _SLUG.sub("-", region.strip().lower()).strip("-") or "unknown"
|
|
36
|
+
return f"instances-{slug}.json"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def save_listed_instances(
|
|
40
|
+
cloud: str,
|
|
41
|
+
items: list[WorkItem],
|
|
42
|
+
*,
|
|
43
|
+
block_devices: dict[str, list[dict[str, Any]]] | None = None,
|
|
44
|
+
region: str = "",
|
|
45
|
+
runner: Any | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
"""Replace this pull in the cache. A write failure leaves analyze on the live list."""
|
|
48
|
+
account = _resolve_account(cloud, runner)
|
|
49
|
+
try:
|
|
50
|
+
_save(cloud, items, block_devices or {}, region, account=account)
|
|
51
|
+
except OSError:
|
|
52
|
+
return
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def listing_cache_state(
|
|
56
|
+
cloud: str,
|
|
57
|
+
region: str | None,
|
|
58
|
+
*,
|
|
59
|
+
max_age_hours: int,
|
|
60
|
+
runner: Any | None = None,
|
|
61
|
+
now: datetime | None = None,
|
|
62
|
+
) -> str:
|
|
63
|
+
"""Return ``fresh``, ``stale``, or ``absent`` for the instance list snapshot."""
|
|
64
|
+
if max_age_hours <= 0:
|
|
65
|
+
return "absent"
|
|
66
|
+
moment = now or datetime.now(timezone.utc)
|
|
67
|
+
limit = timedelta(hours=max_age_hours)
|
|
68
|
+
account = _resolve_account(cloud, runner)
|
|
69
|
+
if account is None:
|
|
70
|
+
return "absent"
|
|
71
|
+
account_id = account.account_id
|
|
72
|
+
if cloud == "aws":
|
|
73
|
+
chosen = (region or "").strip()
|
|
74
|
+
if not chosen:
|
|
75
|
+
return "absent"
|
|
76
|
+
snapshots = _readable_snapshots(cloud, account_id=account_id)
|
|
77
|
+
if not snapshots:
|
|
78
|
+
return "absent"
|
|
79
|
+
payload = _snapshot_for_region(snapshots, chosen)
|
|
80
|
+
if payload is None:
|
|
81
|
+
return "absent"
|
|
82
|
+
age = _age(payload, moment)
|
|
83
|
+
if age is None:
|
|
84
|
+
return "absent"
|
|
85
|
+
if age >= limit:
|
|
86
|
+
return "stale"
|
|
87
|
+
return "fresh"
|
|
88
|
+
payloads = _readable_snapshots("azure", account_id=account_id)
|
|
89
|
+
if not payloads:
|
|
90
|
+
return "absent"
|
|
91
|
+
saw_stale = False
|
|
92
|
+
for payload in payloads:
|
|
93
|
+
age = _age(payload, moment)
|
|
94
|
+
if age is None:
|
|
95
|
+
continue
|
|
96
|
+
if age >= limit:
|
|
97
|
+
saw_stale = True
|
|
98
|
+
break
|
|
99
|
+
if saw_stale:
|
|
100
|
+
return "stale"
|
|
101
|
+
return "fresh"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def fresh_listing(
|
|
105
|
+
cloud: str,
|
|
106
|
+
region: str | None,
|
|
107
|
+
*,
|
|
108
|
+
max_age_hours: int,
|
|
109
|
+
runner: Any | None = None,
|
|
110
|
+
now: datetime | None = None,
|
|
111
|
+
) -> tuple[list[WorkItem], dict[str, list[dict[str, Any]]], str] | None:
|
|
112
|
+
"""A cached list strictly younger than ``max_age_hours``, or None when describe should run.
|
|
113
|
+
|
|
114
|
+
AWS uses the named region. Azure reuses the last full pull when its oldest
|
|
115
|
+
region file is still fresh. The third value is the stderr note.
|
|
116
|
+
"""
|
|
117
|
+
if max_age_hours <= 0:
|
|
118
|
+
return None
|
|
119
|
+
moment = now or datetime.now(timezone.utc)
|
|
120
|
+
limit = timedelta(hours=max_age_hours)
|
|
121
|
+
account = _resolve_account(cloud, runner)
|
|
122
|
+
account_id = account.account_id if account else None
|
|
123
|
+
if account_id is None:
|
|
124
|
+
return None
|
|
125
|
+
if cloud == "aws":
|
|
126
|
+
chosen = (region or "").strip()
|
|
127
|
+
if not chosen:
|
|
128
|
+
return None
|
|
129
|
+
snapshots = _readable_snapshots(cloud, account_id=account_id)
|
|
130
|
+
if not snapshots:
|
|
131
|
+
return None
|
|
132
|
+
payload = _snapshot_for_region(snapshots, chosen)
|
|
133
|
+
if payload is None:
|
|
134
|
+
return None
|
|
135
|
+
age = _age(payload, moment)
|
|
136
|
+
if age is None or age >= limit:
|
|
137
|
+
return None
|
|
138
|
+
items, devices = _items_and_devices(payload)
|
|
139
|
+
return items, devices, f"Using cached aws instances in {chosen} ({_age_phrase(age)})."
|
|
140
|
+
payloads = _readable_snapshots("azure", account_id=account_id)
|
|
141
|
+
if payloads is None or not payloads:
|
|
142
|
+
return None
|
|
143
|
+
oldest = timedelta(0)
|
|
144
|
+
items: list[WorkItem] = []
|
|
145
|
+
devices: dict[str, list[dict[str, Any]]] = {}
|
|
146
|
+
for payload in payloads:
|
|
147
|
+
age = _age(payload, moment)
|
|
148
|
+
if age is None or age >= limit:
|
|
149
|
+
return None
|
|
150
|
+
if age > oldest:
|
|
151
|
+
oldest = age
|
|
152
|
+
listed, mappings = _items_and_devices(payload)
|
|
153
|
+
items.extend(listed)
|
|
154
|
+
devices.update(mappings)
|
|
155
|
+
return items, devices, f"Using cached azure instances ({_age_phrase(oldest)})."
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _save(
|
|
159
|
+
cloud: str,
|
|
160
|
+
items: list[WorkItem],
|
|
161
|
+
block_devices: dict[str, list[dict[str, Any]]],
|
|
162
|
+
region: str,
|
|
163
|
+
*,
|
|
164
|
+
account: CloudAccount | None,
|
|
165
|
+
) -> None:
|
|
166
|
+
if account is None:
|
|
167
|
+
return
|
|
168
|
+
prepare_data_write()
|
|
169
|
+
grouped: dict[str, list[WorkItem]] = {}
|
|
170
|
+
for item in items:
|
|
171
|
+
if item.cloud != cloud:
|
|
172
|
+
continue
|
|
173
|
+
key = (item.region or region or "unknown").strip()
|
|
174
|
+
grouped.setdefault(key, []).append(item)
|
|
175
|
+
if not grouped and region.strip():
|
|
176
|
+
grouped[region.strip()] = []
|
|
177
|
+
root = instances_root()
|
|
178
|
+
account_dir = root / account.folder_name()
|
|
179
|
+
if cloud == "azure":
|
|
180
|
+
_save_azure_atomic(account_dir, grouped, block_devices, account=account)
|
|
181
|
+
return
|
|
182
|
+
account_dir.mkdir(parents=True, exist_ok=True)
|
|
183
|
+
for name, rows in grouped.items():
|
|
184
|
+
_write(
|
|
185
|
+
account_dir / region_snapshot_name(name),
|
|
186
|
+
_payload(cloud, name, rows, block_devices, account_id=account.account_id),
|
|
187
|
+
)
|
|
188
|
+
_retire_legacy_region_folders(root, cloud)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _save_azure_atomic(
|
|
192
|
+
account_dir: Path,
|
|
193
|
+
grouped: dict[str, list[WorkItem]],
|
|
194
|
+
block_devices: dict[str, list[dict[str, Any]]],
|
|
195
|
+
*,
|
|
196
|
+
account: CloudAccount,
|
|
197
|
+
) -> None:
|
|
198
|
+
parent = account_dir.parent
|
|
199
|
+
parent.mkdir(parents=True, exist_ok=True)
|
|
200
|
+
staging = Path(tempfile.mkdtemp(prefix=".azure-instances-", dir=parent))
|
|
201
|
+
try:
|
|
202
|
+
for name, rows in grouped.items():
|
|
203
|
+
_write(
|
|
204
|
+
staging / region_snapshot_name(name),
|
|
205
|
+
_payload("azure", name, rows, block_devices, account_id=account.account_id),
|
|
206
|
+
)
|
|
207
|
+
account_dir.mkdir(parents=True, exist_ok=True)
|
|
208
|
+
for child in list(account_dir.iterdir()):
|
|
209
|
+
if child.is_file() and _REGION_FILE.match(child.name):
|
|
210
|
+
child.unlink()
|
|
211
|
+
for child in staging.iterdir():
|
|
212
|
+
dest = account_dir / child.name
|
|
213
|
+
if dest.exists():
|
|
214
|
+
dest.unlink()
|
|
215
|
+
shutil.move(str(child), str(dest))
|
|
216
|
+
except OSError:
|
|
217
|
+
shutil.rmtree(staging, ignore_errors=True)
|
|
218
|
+
raise
|
|
219
|
+
else:
|
|
220
|
+
shutil.rmtree(staging, ignore_errors=True)
|
|
221
|
+
_retire_legacy_region_folders(account_dir.parent, "azure")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _retire_legacy_region_folders(root: Path, cloud: str) -> None:
|
|
225
|
+
if not root.is_dir():
|
|
226
|
+
return
|
|
227
|
+
prefix = f"{cloud}-"
|
|
228
|
+
for child in list(root.iterdir()):
|
|
229
|
+
if not child.is_dir() or parse_account_folder(child.name) is not None:
|
|
230
|
+
continue
|
|
231
|
+
if not child.name.startswith(prefix):
|
|
232
|
+
continue
|
|
233
|
+
legacy = child / _LEGACY_FILENAME
|
|
234
|
+
if legacy.is_file():
|
|
235
|
+
shutil.rmtree(child, ignore_errors=True)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _payload(
|
|
239
|
+
cloud: str,
|
|
240
|
+
region: str,
|
|
241
|
+
items: list[WorkItem],
|
|
242
|
+
block_devices: dict[str, list[dict[str, Any]]],
|
|
243
|
+
*,
|
|
244
|
+
account_id: str | None,
|
|
245
|
+
) -> dict[str, Any]:
|
|
246
|
+
records = [_record(item, block_devices.get(item.instance_id) or []) for item in items]
|
|
247
|
+
body: dict[str, Any] = {
|
|
248
|
+
"schema_version": 1,
|
|
249
|
+
"kind": "instances",
|
|
250
|
+
"cloud": cloud,
|
|
251
|
+
"region": region,
|
|
252
|
+
"source": "analyze",
|
|
253
|
+
"loaded_as_of": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
254
|
+
"record_count": len(records),
|
|
255
|
+
"records": records,
|
|
256
|
+
}
|
|
257
|
+
if account_id:
|
|
258
|
+
body["account_id"] = account_id
|
|
259
|
+
return body
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _record(item: WorkItem, mappings: list[dict[str, Any]]) -> dict[str, Any]:
|
|
263
|
+
body: dict[str, Any] = {
|
|
264
|
+
"cloud": item.cloud,
|
|
265
|
+
"region": item.region,
|
|
266
|
+
"instance_id": item.instance_id,
|
|
267
|
+
"name": item.name,
|
|
268
|
+
"instance_type": item.instance_type,
|
|
269
|
+
"virtualization_type": item.virtualization_type,
|
|
270
|
+
"root_device_type": item.root_device_type,
|
|
271
|
+
"ena_support": item.ena_support,
|
|
272
|
+
"primary_nic_id": item.primary_nic_id,
|
|
273
|
+
"lifecycle": item.lifecycle,
|
|
274
|
+
"availability_zone": item.availability_zone,
|
|
275
|
+
"availability_zone_id": item.availability_zone_id,
|
|
276
|
+
"architecture": item.architecture,
|
|
277
|
+
"platform": item.platform,
|
|
278
|
+
"instance_store_count": item.instance_store_count,
|
|
279
|
+
}
|
|
280
|
+
if mappings:
|
|
281
|
+
body["block_device_mappings"] = mappings
|
|
282
|
+
return body
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _readable_snapshots(
|
|
286
|
+
cloud: str,
|
|
287
|
+
*,
|
|
288
|
+
account_id: str | None = None,
|
|
289
|
+
) -> list[dict[str, Any]] | None:
|
|
290
|
+
"""Parsed snapshots, or None when a snapshot file for this cloud cannot be read."""
|
|
291
|
+
root = instances_root()
|
|
292
|
+
if not root.is_dir():
|
|
293
|
+
return []
|
|
294
|
+
found: list[dict[str, Any]] = []
|
|
295
|
+
for child in sorted(root.iterdir(), key=lambda path: path.name):
|
|
296
|
+
if not child.is_dir():
|
|
297
|
+
continue
|
|
298
|
+
parsed = parse_account_folder(child.name)
|
|
299
|
+
if parsed is not None:
|
|
300
|
+
cloud_name, folder_account = parsed
|
|
301
|
+
if cloud_name != cloud:
|
|
302
|
+
continue
|
|
303
|
+
if account_id is not None and folder_account != account_id.strip():
|
|
304
|
+
continue
|
|
305
|
+
for path in sorted(child.glob("instances-*.json")):
|
|
306
|
+
payload = _read(path)
|
|
307
|
+
if payload is None:
|
|
308
|
+
return None
|
|
309
|
+
if account_id is not None and not _account_matches(payload, account_id):
|
|
310
|
+
continue
|
|
311
|
+
found.append(payload)
|
|
312
|
+
continue
|
|
313
|
+
if not _legacy_region_dir(child.name, cloud):
|
|
314
|
+
continue
|
|
315
|
+
path = child / _LEGACY_FILENAME
|
|
316
|
+
if not path.is_file():
|
|
317
|
+
continue
|
|
318
|
+
payload = _read(path)
|
|
319
|
+
if payload is None:
|
|
320
|
+
return None
|
|
321
|
+
if account_id is not None and not _account_matches(payload, account_id):
|
|
322
|
+
continue
|
|
323
|
+
found.append(payload)
|
|
324
|
+
return found
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _legacy_region_dir(name: str, cloud: str) -> bool:
|
|
328
|
+
if parse_account_folder(name) is not None:
|
|
329
|
+
return False
|
|
330
|
+
return name.startswith(f"{cloud}-")
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _account_matches(payload: dict[str, Any], account_id: str) -> bool:
|
|
334
|
+
stored = str(payload.get("account_id") or "").strip()
|
|
335
|
+
if not stored:
|
|
336
|
+
return False
|
|
337
|
+
return stored == account_id.strip()
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _resolve_account(cloud: str, runner: Any | None) -> CloudAccount | None:
|
|
341
|
+
if runner is None:
|
|
342
|
+
return None
|
|
343
|
+
try:
|
|
344
|
+
if cloud == "aws":
|
|
345
|
+
return resolve_aws_account(runner)
|
|
346
|
+
return resolve_azure_account(runner)
|
|
347
|
+
except AccountIdentityError:
|
|
348
|
+
return None
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _resolve_account_id(cloud: str, runner: Any | None) -> str | None:
|
|
352
|
+
account = _resolve_account(cloud, runner)
|
|
353
|
+
return account.account_id if account else None
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _age(payload: dict[str, Any], now: datetime) -> timedelta | None:
|
|
357
|
+
text = str(payload.get("loaded_as_of") or "").strip()
|
|
358
|
+
if text.endswith("Z"):
|
|
359
|
+
text = text[:-1] + "+00:00"
|
|
360
|
+
try:
|
|
361
|
+
loaded = datetime.fromisoformat(text)
|
|
362
|
+
except ValueError:
|
|
363
|
+
return None
|
|
364
|
+
if loaded.tzinfo is None:
|
|
365
|
+
loaded = loaded.replace(tzinfo=timezone.utc)
|
|
366
|
+
return now - loaded.astimezone(timezone.utc)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _age_phrase(age: timedelta) -> str:
|
|
370
|
+
minutes = int(age.total_seconds() // 60)
|
|
371
|
+
if minutes < 1:
|
|
372
|
+
return "less than a minute old"
|
|
373
|
+
if minutes == 1:
|
|
374
|
+
return "1 minute old"
|
|
375
|
+
if minutes < 60:
|
|
376
|
+
return f"{minutes} minutes old"
|
|
377
|
+
hours = minutes // 60
|
|
378
|
+
if hours == 1:
|
|
379
|
+
return "1 hour old"
|
|
380
|
+
return f"{hours} hours old"
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _snapshot_for_region(snapshots: list[dict[str, Any]], region: str) -> dict[str, Any] | None:
|
|
384
|
+
wanted = region.strip().lower()
|
|
385
|
+
for payload in snapshots:
|
|
386
|
+
if str(payload.get("region") or "").strip().lower() == wanted:
|
|
387
|
+
return payload
|
|
388
|
+
return None
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _items_and_devices(
|
|
392
|
+
payload: dict[str, Any],
|
|
393
|
+
) -> tuple[list[WorkItem], dict[str, list[dict[str, Any]]]]:
|
|
394
|
+
records = payload.get("records")
|
|
395
|
+
items: list[WorkItem] = []
|
|
396
|
+
devices: dict[str, list[dict[str, Any]]] = {}
|
|
397
|
+
if not isinstance(records, list):
|
|
398
|
+
return items, devices
|
|
399
|
+
for row in records:
|
|
400
|
+
if not isinstance(row, dict):
|
|
401
|
+
continue
|
|
402
|
+
item = _work_item(row)
|
|
403
|
+
if item is None:
|
|
404
|
+
continue
|
|
405
|
+
items.append(item)
|
|
406
|
+
mappings = row.get("block_device_mappings")
|
|
407
|
+
if isinstance(mappings, list):
|
|
408
|
+
devices[item.instance_id] = [entry for entry in mappings if isinstance(entry, dict)]
|
|
409
|
+
return items, devices
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _work_item(row: dict[str, Any]) -> WorkItem | None:
|
|
413
|
+
instance_id = str(row.get("instance_id") or "").strip()
|
|
414
|
+
if not instance_id:
|
|
415
|
+
return None
|
|
416
|
+
ena = row.get("ena_support")
|
|
417
|
+
count = row.get("instance_store_count")
|
|
418
|
+
return WorkItem(
|
|
419
|
+
cloud=str(row.get("cloud") or ""),
|
|
420
|
+
region=str(row.get("region") or ""),
|
|
421
|
+
instance_id=instance_id,
|
|
422
|
+
name=str(row.get("name") or ""),
|
|
423
|
+
instance_type=str(row.get("instance_type") or ""),
|
|
424
|
+
virtualization_type=str(row.get("virtualization_type") or ""),
|
|
425
|
+
root_device_type=str(row.get("root_device_type") or ""),
|
|
426
|
+
ena_support=None if ena is None else bool(ena),
|
|
427
|
+
primary_nic_id=str(row.get("primary_nic_id") or ""),
|
|
428
|
+
lifecycle=str(row.get("lifecycle") or ""),
|
|
429
|
+
availability_zone=str(row.get("availability_zone") or ""),
|
|
430
|
+
availability_zone_id=str(row.get("availability_zone_id") or ""),
|
|
431
|
+
architecture=str(row.get("architecture") or ""),
|
|
432
|
+
platform=str(row.get("platform") or ""),
|
|
433
|
+
instance_store_count=count if isinstance(count, int) and not isinstance(count, bool) else 0,
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _read(path: Path) -> dict[str, Any] | None:
|
|
438
|
+
if not path.is_file():
|
|
439
|
+
return None
|
|
440
|
+
try:
|
|
441
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
442
|
+
except (OSError, json.JSONDecodeError):
|
|
443
|
+
return None
|
|
444
|
+
if not isinstance(data, dict):
|
|
445
|
+
return None
|
|
446
|
+
return data
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _write(path: Path, payload: dict[str, Any]) -> None:
|
|
450
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
451
|
+
fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.stem}-", suffix=".tmp")
|
|
452
|
+
tmp_path = Path(tmp_name)
|
|
453
|
+
try:
|
|
454
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
455
|
+
json.dump(redact_tree(payload), handle, indent=2)
|
|
456
|
+
handle.write("\n")
|
|
457
|
+
os.replace(tmp_path, path)
|
|
458
|
+
except OSError:
|
|
459
|
+
tmp_path.unlink(missing_ok=True)
|
|
460
|
+
raise
|