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.
Files changed (199) hide show
  1. maproom/__init__.py +14 -0
  2. maproom/__main__.py +10 -0
  3. maproom/analyze/__init__.py +1 -0
  4. maproom/analyze/accel_families.py +45 -0
  5. maproom/analyze/account_azure_activity.py +260 -0
  6. maproom/analyze/account_azure_quota_requests.py +177 -0
  7. maproom/analyze/account_cloudtrail.py +316 -0
  8. maproom/analyze/account_quota_requests.py +180 -0
  9. maproom/analyze/analyze_v1_orchestration.py +1194 -0
  10. maproom/analyze/catalog.py +353 -0
  11. maproom/analyze/change_detection.py +652 -0
  12. maproom/analyze/context_client.py +99 -0
  13. maproom/analyze/context_lookup.py +142 -0
  14. maproom/analyze/cover_analyze.py +344 -0
  15. maproom/analyze/cover_client.py +65 -0
  16. maproom/analyze/cover_lookup.py +242 -0
  17. maproom/analyze/engine.py +644 -0
  18. maproom/analyze/fleetfit_endpoints.py +217 -0
  19. maproom/analyze/fleetfit_policy.py +66 -0
  20. maproom/analyze/instance_price_analyze.py +221 -0
  21. maproom/analyze/instance_price_client.py +108 -0
  22. maproom/analyze/instance_price_lookup.py +60 -0
  23. maproom/analyze/local_reads.py +484 -0
  24. maproom/analyze/lookup_http.py +280 -0
  25. maproom/analyze/metric_format.py +20 -0
  26. maproom/analyze/migration_method.py +130 -0
  27. maproom/analyze/move_list.py +93 -0
  28. maproom/analyze/operator_context.py +156 -0
  29. maproom/analyze/performance_rank.py +97 -0
  30. maproom/analyze/primary_recommendation.py +422 -0
  31. maproom/analyze/provider_comparison.py +401 -0
  32. maproom/analyze/quota_analyze.py +481 -0
  33. maproom/analyze/quota_client.py +75 -0
  34. maproom/analyze/quota_lookup.py +110 -0
  35. maproom/analyze/quota_outcome_steer.py +105 -0
  36. maproom/analyze/recommend_batch.py +199 -0
  37. maproom/analyze/recommend_client.py +362 -0
  38. maproom/analyze/recommend_share.py +118 -0
  39. maproom/analyze/recommendation.py +591 -0
  40. maproom/analyze/reservation_pack.py +883 -0
  41. maproom/analyze/reservation_read.py +461 -0
  42. maproom/analyze/safe_analyze.py +1134 -0
  43. maproom/analyze/safe_move.py +195 -0
  44. maproom/analyze/safe_moves.py +571 -0
  45. maproom/analyze/safe_moves_catalog.py +127 -0
  46. maproom/analyze/safe_moves_client.py +70 -0
  47. maproom/analyze/series_analyze.py +491 -0
  48. maproom/analyze/series_client.py +106 -0
  49. maproom/analyze/series_lookup.py +663 -0
  50. maproom/analyze/shape.py +254 -0
  51. maproom/analyze/size_analyze.py +883 -0
  52. maproom/analyze/size_client.py +81 -0
  53. maproom/analyze/size_keep.py +409 -0
  54. maproom/analyze/size_lookup.py +368 -0
  55. maproom/analyze/specs.py +325 -0
  56. maproom/analyze/spot_analyze.py +392 -0
  57. maproom/analyze/spot_client.py +74 -0
  58. maproom/analyze/spot_lookup.py +213 -0
  59. maproom/analyze/token_client.py +97 -0
  60. maproom/analyze/utilization.py +190 -0
  61. maproom/analyze/workload.py +104 -0
  62. maproom/analyze/workset.py +762 -0
  63. maproom/aws_region.py +78 -0
  64. maproom/cache/__init__.py +1 -0
  65. maproom/cache/catalog.py +372 -0
  66. maproom/cache/commands.py +215 -0
  67. maproom/cache/instances.py +460 -0
  68. maproom/cli.py +2084 -0
  69. maproom/cli_argv.py +329 -0
  70. maproom/cli_floors.py +89 -0
  71. maproom/cliio/__init__.py +1 -0
  72. maproom/cliio/registry.py +377 -0
  73. maproom/cliio/runner.py +489 -0
  74. maproom/consent/__init__.py +33 -0
  75. maproom/consent/gate.py +238 -0
  76. maproom/consent/policy.py +20 -0
  77. maproom/consent/prompt.py +61 -0
  78. maproom/consent/service_upload_gate.py +318 -0
  79. maproom/consent/service_upload_prompt.py +62 -0
  80. maproom/consent/stdin.py +45 -0
  81. maproom/consent/storage.py +24 -0
  82. maproom/consent/write_token.py +29 -0
  83. maproom/contracts/__init__.py +6 -0
  84. maproom/contracts/schema_diff.py +119 -0
  85. maproom/contracts/validate.py +113 -0
  86. maproom/data/__init__.py +1 -0
  87. maproom/data/clear.py +76 -0
  88. maproom/data/commands.py +14 -0
  89. maproom/doctor/__init__.py +1 -0
  90. maproom/doctor/aws_session.py +226 -0
  91. maproom/doctor/checks.py +701 -0
  92. maproom/doctor/context.py +32 -0
  93. maproom/doctor/display.py +96 -0
  94. maproom/doctor/inventory_display.py +377 -0
  95. maproom/doctor/runner.py +1467 -0
  96. maproom/errors.py +43 -0
  97. maproom/exitcodes.py +70 -0
  98. maproom/inventory/__init__.py +1 -0
  99. maproom/inventory/account_identity.py +79 -0
  100. maproom/inventory/accounts.py +155 -0
  101. maproom/inventory/command.py +961 -0
  102. maproom/inventory/messages.py +264 -0
  103. maproom/inventory/reservations_refresh.py +37 -0
  104. maproom/mock_environment/__init__.py +28 -0
  105. maproom/mock_environment/load.py +241 -0
  106. maproom/mock_environment/runner.py +387 -0
  107. maproom/output/__init__.py +1 -0
  108. maproom/output/json_envelope.py +241 -0
  109. maproom/output/redact.py +11 -0
  110. maproom/output/terminal.py +129 -0
  111. maproom/parsers.py +284 -0
  112. maproom/paths.py +105 -0
  113. maproom/plan/__init__.py +1 -0
  114. maproom/plan/accept.py +59 -0
  115. maproom/plan/analysis_context.py +78 -0
  116. maproom/plan/analyze_selection.py +279 -0
  117. maproom/plan/commands.py +586 -0
  118. maproom/plan/current.py +59 -0
  119. maproom/plan/errors.py +10 -0
  120. maproom/plan/export.py +36 -0
  121. maproom/plan/formatting.py +91 -0
  122. maproom/plan/ids.py +13 -0
  123. maproom/plan/migration_options.py +75 -0
  124. maproom/plan/model.py +265 -0
  125. maproom/plan/names.py +24 -0
  126. maproom/plan/store.py +193 -0
  127. maproom/plan/tty.py +34 -0
  128. maproom/pricing/__init__.py +5 -0
  129. maproom/pricing/prices.py +119 -0
  130. maproom/privacy/__init__.py +6 -0
  131. maproom/privacy/commands.py +159 -0
  132. maproom/privacy/delete_uploads.py +204 -0
  133. maproom/privacy/fleetfit_policy.py +125 -0
  134. maproom/privacy/fleetfit_statement.py +104 -0
  135. maproom/privacy/format.py +76 -0
  136. maproom/privacy/manifests.py +342 -0
  137. maproom/privacy/statement.py +58 -0
  138. maproom/quotas/__init__.py +21 -0
  139. maproom/quotas/aws.py +204 -0
  140. maproom/quotas/azure.py +75 -0
  141. maproom/quotas/commands.py +240 -0
  142. maproom/quotas/family_coverage.py +122 -0
  143. maproom/quotas/fetch.py +124 -0
  144. maproom/quotas/load.py +41 -0
  145. maproom/quotas/model.py +178 -0
  146. maproom/quotas/outcome_ledger.py +245 -0
  147. maproom/quotas/quota_request_sync.py +221 -0
  148. maproom/quotas/show.py +73 -0
  149. maproom/quotas/status.py +206 -0
  150. maproom/quotas/store.py +161 -0
  151. maproom/redaction.py +157 -0
  152. maproom/reference_data/__init__.py +1 -0
  153. maproom/reference_data/aws/aws_prices.csv +25562 -0
  154. maproom/reference_data/aws/capabilities.csv +1346 -0
  155. maproom/reference_data/aws/instance_types.csv +1346 -0
  156. maproom/reference_data/azure/azure_prices.csv +1 -0
  157. maproom/reference_data/azure/vm_types.csv +1 -0
  158. maproom/reference_data/benchmarks/cpu-lscpu-v2-instances.json +27 -0
  159. maproom/reference_data/benchmarks/safe-moves-v1.json +328 -0
  160. maproom/reference_data/manifest.json +174 -0
  161. maproom/reference_data/manifest.py +69 -0
  162. maproom/reservations/__init__.py +17 -0
  163. maproom/reservations/aws.py +76 -0
  164. maproom/reservations/azure.py +36 -0
  165. maproom/reservations/commands.py +149 -0
  166. maproom/reservations/load.py +41 -0
  167. maproom/reservations/model.py +316 -0
  168. maproom/reservations/show.py +64 -0
  169. maproom/reservations/status.py +181 -0
  170. maproom/reservations/store.py +391 -0
  171. maproom/resources.py +54 -0
  172. maproom/root_help.py +251 -0
  173. maproom/saving_plans/__init__.py +15 -0
  174. maproom/saving_plans/aws.py +73 -0
  175. maproom/saving_plans/commands.py +122 -0
  176. maproom/saving_plans/load.py +41 -0
  177. maproom/saving_plans/model.py +101 -0
  178. maproom/saving_plans/show.py +64 -0
  179. maproom/saving_plans/status.py +118 -0
  180. maproom/saving_plans/store.py +173 -0
  181. maproom/secret_egress_gate.py +108 -0
  182. maproom/service/install_id.py +60 -0
  183. maproom/settings/__init__.py +1 -0
  184. maproom/settings/defaults.py +73 -0
  185. maproom/settings/init.py +143 -0
  186. maproom/settings/model.py +105 -0
  187. maproom/settings/product_version_change.py +343 -0
  188. maproom/settings/product_versions.py +68 -0
  189. maproom/settings/set.py +347 -0
  190. maproom/settings/show.py +227 -0
  191. maproom/settings/write.py +273 -0
  192. maproom/snapshot_time.py +27 -0
  193. maproom-0.2.0.dist-info/METADATA +263 -0
  194. maproom-0.2.0.dist-info/RECORD +199 -0
  195. maproom-0.2.0.dist-info/WHEEL +5 -0
  196. maproom-0.2.0.dist-info/entry_points.txt +2 -0
  197. maproom-0.2.0.dist-info/licenses/LICENSE +201 -0
  198. maproom-0.2.0.dist-info/licenses/NOTICE +72 -0
  199. maproom-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,391 @@
1
+ """Atomic reservation snapshot persistence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import tempfile
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from maproom.inventory.accounts import (
13
+ CloudAccount,
14
+ drop_replaced_legacy_snapshot,
15
+ parse_account_folder,
16
+ primary_snapshot_path,
17
+ retire_other_account_folders,
18
+ snapshot_files,
19
+ )
20
+ from maproom.paths import data_subdir, prepare_data_write, readable_data_file
21
+ from maproom.redaction import redact_tree
22
+ from maproom.reservations.model import (
23
+ ReservationError,
24
+ build_snapshot,
25
+ dedupe_records_by_subscription_id,
26
+ fetched_regions_from_payload,
27
+ regions_from_records,
28
+ stamp_account_on_records,
29
+ )
30
+
31
+ _FILENAME = "inventory.json"
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class AccountSnapshotPart:
36
+ """One on-disk reservation snapshot (account folder or legacy root file)."""
37
+
38
+ path: Path
39
+ account_id: str | None
40
+ account_alias: str | None
41
+ cloud: str | None
42
+ loaded_as_of: str | None
43
+ source: str | None
44
+ record_count: int
45
+ regions: tuple[str, ...]
46
+ records: tuple[dict[str, Any], ...]
47
+
48
+
49
+ def inventory_root() -> Path:
50
+ return data_subdir("reservations")
51
+
52
+
53
+ def inventory_path() -> Path:
54
+ """Legacy path, or the only account snapshot when that is the file on disk."""
55
+ return primary_snapshot_path(inventory_root(), _FILENAME)
56
+
57
+
58
+ def status_path() -> Path:
59
+ """File when one snapshot exists, otherwise the reservations directory."""
60
+ files = snapshot_files(inventory_root(), _FILENAME)
61
+ if len(files) == 1:
62
+ return files[0]
63
+ if len(files) > 1:
64
+ return inventory_root()
65
+ return inventory_root() / _FILENAME
66
+
67
+
68
+ def account_snapshot_path(account: CloudAccount) -> Path:
69
+ return inventory_root() / account.folder_name() / _FILENAME
70
+
71
+
72
+ def has_snapshot() -> bool:
73
+ root = inventory_root()
74
+ if snapshot_files(root, _FILENAME):
75
+ return True
76
+ legacy = readable_data_file("reservations", _FILENAME)
77
+ return legacy.is_file()
78
+
79
+
80
+ def _atomic_write_json(path: Path, payload: dict[str, Any]) -> ReservationError | None:
81
+ try:
82
+ path.parent.mkdir(parents=True, exist_ok=True)
83
+ fd, tmp_name = tempfile.mkstemp(
84
+ dir=path.parent,
85
+ prefix=f".{path.stem}-",
86
+ suffix=".tmp",
87
+ )
88
+ tmp_path = Path(tmp_name)
89
+ try:
90
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
91
+ json.dump(redact_tree(payload), handle, indent=2)
92
+ handle.write("\n")
93
+ os.replace(tmp_path, path)
94
+ except OSError:
95
+ tmp_path.unlink(missing_ok=True)
96
+ raise
97
+ except OSError as exc:
98
+ return ReservationError(f"could not write reservation snapshot at {path}: {exc}")
99
+ return None
100
+
101
+
102
+ def write_snapshot(payload: dict[str, Any]) -> ReservationError | None:
103
+ prepare_data_write()
104
+ return _atomic_write_json(inventory_root() / _FILENAME, payload)
105
+
106
+
107
+ def _alias_from_folder(folder_name: str, account_id: str, cloud: str) -> str | None:
108
+ prefix = f"{cloud}-{account_id}"
109
+ if folder_name == prefix:
110
+ return None
111
+ if folder_name.startswith(prefix + "-"):
112
+ return folder_name[len(prefix) + 1 :] or None
113
+ return None
114
+
115
+
116
+ def _part_from_payload(path: Path, data: dict[str, Any]) -> AccountSnapshotPart:
117
+ rows_raw = data.get("records") or []
118
+ records = tuple(r for r in rows_raw if isinstance(r, dict))
119
+ account_id = str(data.get("account_id") or "").strip() or None
120
+ cloud = str(data.get("cloud") or "").strip() or None
121
+ alias = str(data.get("account_alias") or "").strip() or None
122
+ if path.parent != inventory_root():
123
+ parsed = parse_account_folder(path.parent.name)
124
+ if parsed:
125
+ cloud = cloud or parsed[0]
126
+ account_id = account_id or parsed[1]
127
+ if alias is None:
128
+ alias = _alias_from_folder(path.parent.name, parsed[1], parsed[0])
129
+ regions = tuple(regions_from_records(list(records)))
130
+ if not regions:
131
+ single = str(data.get("region") or "").strip()
132
+ if single:
133
+ regions = (single,)
134
+ else:
135
+ listed = data.get("regions")
136
+ if isinstance(listed, list):
137
+ regions = tuple(
138
+ str(item).strip() for item in listed if str(item or "").strip()
139
+ )
140
+ return AccountSnapshotPart(
141
+ path=path,
142
+ account_id=account_id,
143
+ account_alias=alias,
144
+ cloud=cloud,
145
+ loaded_as_of=str(data.get("loaded_as_of") or "") or None,
146
+ source=str(data.get("source") or "") or None,
147
+ record_count=int(
148
+ data.get("record_count") if data.get("record_count") is not None else len(records)
149
+ ),
150
+ regions=regions,
151
+ records=records,
152
+ )
153
+
154
+
155
+ def list_account_parts() -> list[AccountSnapshotPart] | ReservationError:
156
+ """Return each on-disk reservation snapshot as a separate part (no merge)."""
157
+ root = inventory_root()
158
+ paths = snapshot_files(root, _FILENAME)
159
+ has_account_snapshots = any(path.parent != root for path in paths)
160
+ legacy = readable_data_file("reservations", _FILENAME)
161
+ if legacy.is_file() and legacy not in paths and not has_account_snapshots:
162
+ paths.insert(0, legacy)
163
+ parts: list[AccountSnapshotPart] = []
164
+ for path in paths:
165
+ data = _read_one(path)
166
+ if isinstance(data, ReservationError):
167
+ return data
168
+ if data is None:
169
+ continue
170
+ parts.append(_part_from_payload(path, data))
171
+ return parts
172
+
173
+
174
+ def pool_summary() -> dict[str, Any]:
175
+ """Counts for human/JSON pool lines after inventory get."""
176
+ parts = list_account_parts()
177
+ if isinstance(parts, ReservationError):
178
+ return {"account_count": 0, "record_count": 0, "regions": []}
179
+ account_ids = {
180
+ part.account_id for part in parts if part.account_id
181
+ }
182
+ # Legacy root file without account_id still counts as one contributor.
183
+ account_count = len(account_ids) if account_ids else len(parts)
184
+ records = 0
185
+ regions: set[str] = set()
186
+ for part in parts:
187
+ records += part.record_count
188
+ regions.update(part.regions)
189
+ return {
190
+ "account_count": account_count,
191
+ "record_count": records,
192
+ "regions": sorted(regions),
193
+ }
194
+
195
+
196
+ def merge_account_region_payload(
197
+ existing: dict[str, Any] | None,
198
+ incoming: dict[str, Any],
199
+ account: CloudAccount,
200
+ ) -> dict[str, Any]:
201
+ """Merge a regional fetch into an existing per-account snapshot."""
202
+ fetched = fetched_regions_from_payload(incoming)
203
+ new_rows_raw = incoming.get("records")
204
+ new_rows = [r for r in new_rows_raw if isinstance(r, dict)] if isinstance(new_rows_raw, list) else []
205
+ new_rows = stamp_account_on_records(
206
+ new_rows,
207
+ account_id=account.account_id,
208
+ account_alias=account.alias,
209
+ )
210
+ kept: list[dict[str, Any]] = []
211
+ if existing is not None:
212
+ old_rows = existing.get("records")
213
+ if isinstance(old_rows, list):
214
+ for row in old_rows:
215
+ if not isinstance(row, dict):
216
+ continue
217
+ region = str(row.get("region") or "").strip()
218
+ if fetched and region in fetched:
219
+ continue
220
+ kept.append(row)
221
+ kept = stamp_account_on_records(
222
+ kept,
223
+ account_id=account.account_id,
224
+ account_alias=account.alias,
225
+ )
226
+ merged_rows = dedupe_records_by_subscription_id(kept + new_rows)
227
+ prior_source = str(existing.get("source") or "") if existing else ""
228
+ source = str(incoming.get("source") or prior_source or "cloud_get")
229
+ loaded_as_of = str(incoming.get("loaded_as_of") or "") or None
230
+ payload = build_snapshot(
231
+ merged_rows,
232
+ source=source,
233
+ loaded_as_of=loaded_as_of,
234
+ )
235
+ payload["cloud"] = account.cloud
236
+ payload["account_id"] = account.account_id
237
+ if account.alias:
238
+ payload["account_alias"] = account.alias
239
+ else:
240
+ payload.pop("account_alias", None)
241
+ return payload
242
+
243
+
244
+ def write_account_snapshot(payload: dict[str, Any], account: CloudAccount) -> ReservationError | None:
245
+ """Save this account's snapshot and remove a previous folder name for the same account.
246
+
247
+ When the account folder already has rows, a regional fetch replaces only those
248
+ regions and keeps other regions on disk.
249
+ """
250
+ prepare_data_write()
251
+ path = account_snapshot_path(account)
252
+ existing: dict[str, Any] | None = None
253
+ if path.is_file():
254
+ prior = _read_one(path)
255
+ if isinstance(prior, ReservationError):
256
+ return prior
257
+ existing = prior
258
+ merged = merge_account_region_payload(existing, payload, account)
259
+ err = _atomic_write_json(path, merged)
260
+ if err is not None:
261
+ return err
262
+ # Callers often still hold the pre-merge payload; refresh common fields.
263
+ payload.clear()
264
+ payload.update(merged)
265
+ retire_other_account_folders(inventory_root(), account, keep=path.parent.name)
266
+ drop_replaced_legacy_snapshot(
267
+ inventory_root(),
268
+ _FILENAME,
269
+ clouds={account.cloud},
270
+ sources={"aws_get", "cloud_get", "payer_file"},
271
+ cloud_of=_reservation_cloud,
272
+ write_json=lambda legacy, body: _atomic_write_json(legacy, body),
273
+ )
274
+ return None
275
+
276
+
277
+ def read_snapshot() -> dict[str, Any] | None | ReservationError:
278
+ root = inventory_root()
279
+ paths = snapshot_files(root, _FILENAME)
280
+ has_account_snapshots = any(path.parent != root for path in paths)
281
+ legacy = readable_data_file("reservations", _FILENAME)
282
+ if legacy.is_file() and legacy not in paths and not has_account_snapshots:
283
+ paths.insert(0, legacy)
284
+ if not paths:
285
+ return None
286
+ loaded: list[dict[str, Any]] = []
287
+ for path in paths:
288
+ data = _read_one(path)
289
+ if isinstance(data, ReservationError):
290
+ return data
291
+ if data is not None:
292
+ loaded.append(data)
293
+ if not loaded:
294
+ return None
295
+ if len(loaded) == 1:
296
+ return loaded[0]
297
+ return _merge(loaded)
298
+
299
+
300
+ def _reservation_cloud(record: dict[str, Any]) -> str:
301
+ if str(record.get("kind") or "") == "azure_reserved_vm":
302
+ return "azure"
303
+ return str(record.get("cloud") or "aws")
304
+
305
+
306
+ def _read_one(path: Path) -> dict[str, Any] | None | ReservationError:
307
+ if not path.is_file():
308
+ return None
309
+ try:
310
+ text = path.read_text(encoding="utf-8")
311
+ except OSError as exc:
312
+ return ReservationError(f"could not read reservation snapshot at {path}: {exc}")
313
+ try:
314
+ data = json.loads(text)
315
+ except json.JSONDecodeError as exc:
316
+ return ReservationError(f"corrupt reservation snapshot {path}: {exc}")
317
+ if not isinstance(data, dict):
318
+ return ReservationError(f"corrupt reservation snapshot {path}: expected JSON object")
319
+ return data
320
+
321
+
322
+ def _newer_as_of(left: str, right: str) -> str:
323
+ """Return the chronologically later ISO stamp; empty strings lose."""
324
+ if not left:
325
+ return right
326
+ if not right:
327
+ return left
328
+ return max(left, right)
329
+
330
+
331
+ def _merge(parts: list[dict[str, Any]]) -> dict[str, Any]:
332
+ """Concatenate account snapshots, dedupe by subscription_id (newest parent wins)."""
333
+ # Pair each row with its parent loaded_as_of for dedupe preference.
334
+ tagged: list[tuple[str, dict[str, Any]]] = []
335
+ for part in parts:
336
+ as_of = str(part.get("loaded_as_of") or "")
337
+ rows = part.get("records")
338
+ if not isinstance(rows, list):
339
+ continue
340
+ for row in rows:
341
+ if isinstance(row, dict):
342
+ tagged.append((as_of, row))
343
+
344
+ by_sub: dict[str, tuple[str, dict[str, Any]]] = {}
345
+ without_id: list[dict[str, Any]] = []
346
+ for as_of, row in tagged:
347
+ sub = str(row.get("subscription_id") or "").strip()
348
+ if not sub:
349
+ without_id.append(row)
350
+ continue
351
+ prior = by_sub.get(sub)
352
+ if prior is None or _newer_as_of(as_of, prior[0]) == as_of:
353
+ by_sub[sub] = (as_of, row)
354
+
355
+ records = [row for _, row in by_sub.values()] + without_id
356
+ loaded = [str(part.get("loaded_as_of") or "") for part in parts if part.get("loaded_as_of")]
357
+ sources = {str(part.get("source") or "") for part in parts}
358
+ region_set: set[str] = set()
359
+ for part in parts:
360
+ single = str(part.get("region") or "").strip()
361
+ if single:
362
+ region_set.add(single)
363
+ listed = part.get("regions")
364
+ if isinstance(listed, list):
365
+ for item in listed:
366
+ text = str(item or "").strip()
367
+ if text:
368
+ region_set.add(text)
369
+ region_set.update(regions_from_records(records))
370
+ payload: dict[str, Any] = {
371
+ "schema_version": parts[0].get("schema_version"),
372
+ # Oldest stamp: conservative pool age for callers that only read one field.
373
+ "loaded_as_of": min(loaded) if loaded else "",
374
+ "source": sources.pop() if len(sources) == 1 else "mixed",
375
+ "record_count": len(records),
376
+ "records": records,
377
+ }
378
+ if len(region_set) == 1:
379
+ payload["region"] = next(iter(region_set))
380
+ elif len(region_set) > 1:
381
+ payload["regions"] = sorted(region_set)
382
+ account_ids = sorted(
383
+ {
384
+ str(part.get("account_id") or "").strip()
385
+ for part in parts
386
+ if str(part.get("account_id") or "").strip()
387
+ }
388
+ )
389
+ if account_ids:
390
+ payload["account_ids"] = account_ids
391
+ return payload
maproom/resources.py ADDED
@@ -0,0 +1,54 @@
1
+ """Local EC2 resource validation and target resolution (USER_JOURNEY section 5)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+
8
+ EC2_INSTANCE_ID_RE = re.compile(r"^i-[0-9a-f]{8,17}$", re.IGNORECASE)
9
+ EC2_INSTANCE_ARN_RE = re.compile(
10
+ r"^arn:aws:ec2:(?P<region>[a-z0-9-]+):\d{12}:instance/(?P<instance_id>i-[0-9a-f]{8,17})$",
11
+ re.IGNORECASE,
12
+ )
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Ec2Target:
17
+ cloud: str
18
+ region: str
19
+ instance_id: str
20
+
21
+
22
+ class ResourceUsageError(ValueError):
23
+ """Invalid resource form or missing required selector (exit USAGE)."""
24
+
25
+
26
+ def parse_ec2_target(resource: str, *, region: str | None = None) -> Ec2Target:
27
+ """Validate resource locally and resolve region before any cloud read."""
28
+ text = (resource or "").strip()
29
+ if not text:
30
+ raise ResourceUsageError("Resource is required. Example: maproom analyze i-0123456789abcdef0 --region us-east-1")
31
+
32
+ match = EC2_INSTANCE_ARN_RE.match(text)
33
+ if match:
34
+ return Ec2Target(
35
+ cloud="aws",
36
+ region=match.group("region").lower(),
37
+ instance_id=match.group("instance_id").lower(),
38
+ )
39
+
40
+ if EC2_INSTANCE_ID_RE.match(text):
41
+ resolved = (region or "").strip().lower()
42
+ if not resolved:
43
+ raise ResourceUsageError(
44
+ "Instance IDs need a region. Add --region us-east-1 or pass the full ARN."
45
+ )
46
+ return Ec2Target(cloud="aws", region=resolved, instance_id=text.lower())
47
+
48
+ raise ResourceUsageError(
49
+ "Invalid EC2 instance id. Expected i-xxxxxxxx or an EC2 instance ARN."
50
+ )
51
+
52
+
53
+ def format_target_preview(target: Ec2Target) -> str:
54
+ return f"Target: {target.cloud.upper()} · {target.region} · {target.instance_id}"
maproom/root_help.py ADDED
@@ -0,0 +1,251 @@
1
+ """Offline product root help for bare `maproom`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import re
7
+ import sys
8
+ import textwrap
9
+
10
+ from maproom.settings.model import product_version
11
+ from maproom.settings.product_versions import (
12
+ MAX_PRODUCT_VERSION,
13
+ RIGHTSIZER_MIN_PRODUCT_VERSION,
14
+ product_version_name,
15
+ )
16
+
17
+ _VERSION_3_HELP_DESCRIPTION = (
18
+ "maproom looks at the AWS and Azure instances you already run. "
19
+ "Approve sending the instance description without ids to fleetfit.ai, "
20
+ "and see whether a Spot instance already running has a cheaper pool. "
21
+ "Declining leaves the completely safe local move."
22
+ )
23
+
24
+ _VERSION_5_HELP_DESCRIPTION = (
25
+ "maproom looks at the AWS and Azure instances you already run and recommends "
26
+ "a safer or cheaper instance type, a Spot pool, a same-type resize, or a "
27
+ "series fit when you approve. "
28
+ "Approve sending a seven-day metric summary and the grading filters to "
29
+ "fleetfit.ai, without names or account ids. "
30
+ "Declining leaves the earlier local moves."
31
+ )
32
+
33
+ # Version 4 and later keep the fuller command list.
34
+ # Versions 1 through 3 show the safer, lower-complexity command groups.
35
+ _FULL_COMMAND_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = (
36
+ ("START", ("doctor", "identity")),
37
+ ("INVENTORY", ("inventory",)),
38
+ ("ANALYZE", ("analyze",)),
39
+ ("LOCAL", ("settings", "data", "cache", "privacy", "version", "help")),
40
+ )
41
+
42
+ _VERSION_1_COMMAND_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = (
43
+ ("START", ("doctor", "identity")),
44
+ ("ANALYZE", ("analyze",)),
45
+ ("LOCAL", ("settings", "privacy", "version", "help")),
46
+ )
47
+
48
+ _VERSION_2_COMMAND_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = (
49
+ ("START", ("doctor", "identity")),
50
+ ("ANALYZE", ("analyze",)),
51
+ ("LOCAL", ("settings", "cache", "privacy", "version", "help")),
52
+ )
53
+
54
+ _VERSION_3_COMMAND_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = (
55
+ ("START", ("doctor", "identity")),
56
+ ("INVENTORY", ("inventory",)),
57
+ ("ANALYZE", ("analyze",)),
58
+ ("LOCAL", ("settings", "data", "cache", "privacy", "version", "help")),
59
+ )
60
+
61
+ HELP_DESCRIPTION = (
62
+ "maproom looks at the AWS and Azure instances you already run. "
63
+ "It names one completely safe type to move to, or none."
64
+ )
65
+
66
+ _VERSION_2_HELP_DESCRIPTION = (
67
+ "maproom looks at the AWS and Azure instances you already run. "
68
+ "Approve sending a closed same-type size change from 5-minute p99 readings on AWS. "
69
+ "Declining leaves the completely safe local move."
70
+ )
71
+
72
+ _FULL_HELP_DESCRIPTION = (
73
+ "maproom rightsizes AWS and Azure instances to their workloads. "
74
+ "It reads the inventory of quotas, reservations, and savings plans together, "
75
+ "then examines individual instances, and their recent utilization, "
76
+ "to make conservative recommendations. "
77
+ "Operators can set the criteria for the recommendations (cf. maproom analyze -h)."
78
+ )
79
+
80
+ HELP_EPILOG = """
81
+ Examples:
82
+ maproom version
83
+ maproom doctor
84
+ maproom analyze i-0123456789abcdef0 --region us-east-1
85
+
86
+ Cloud reads use the current aws and az login. Consent is stored by maproom settings.
87
+ Run `maproom privacy` for what maproom reads or sends.
88
+ """
89
+
90
+ _FULL_HELP_EPILOG = """
91
+ Examples:
92
+ maproom version
93
+ maproom doctor
94
+ maproom inventory get
95
+ maproom analyze i-0123456789abcdef0 --region us-east-1
96
+
97
+ Cloud reads use the current aws and az login. Consent is stored by maproom settings.
98
+ Run `maproom privacy` for what maproom reads or sends.
99
+ """
100
+
101
+ # Kept for callers that imported the version-1 default groups.
102
+ COMMAND_GROUPS = _VERSION_1_COMMAND_GROUPS
103
+
104
+
105
+ def _named(text: str, version: int) -> str:
106
+ return f"{text} Product version {version} is {product_version_name(version)}."
107
+
108
+
109
+ def command_groups_for(version: int | None = None) -> tuple[tuple[str, tuple[str, ...]], ...]:
110
+ current = product_version() if version is None else version
111
+ if current <= 1:
112
+ return _VERSION_1_COMMAND_GROUPS
113
+ if current == 2:
114
+ return _VERSION_2_COMMAND_GROUPS
115
+ if current < RIGHTSIZER_MIN_PRODUCT_VERSION:
116
+ return _VERSION_3_COMMAND_GROUPS
117
+ return _FULL_COMMAND_GROUPS
118
+
119
+
120
+ # Registered at product version 1 but omitted from grouped root help (FINDING-485).
121
+ _PV1_HELP_TOPICS_BEYOND_GROUPED_ROOT: tuple[str, ...] = ("cache", "inventory")
122
+
123
+
124
+ def help_topics_for(version: int | None = None) -> tuple[str, ...]:
125
+ """Topic names accepted by `maproom help TOPIC` (may exceed grouped root sections)."""
126
+ current = product_version() if version is None else version
127
+ names: list[str] = []
128
+ for _title, group in command_groups_for(current):
129
+ names.extend(group)
130
+ if current <= 1:
131
+ for name in _PV1_HELP_TOPICS_BEYOND_GROUPED_ROOT:
132
+ if name not in names:
133
+ names.append(name)
134
+ return tuple(names)
135
+
136
+
137
+ def usage_choices_for(version: int | None = None) -> str:
138
+ """Brace-list of subcommand names in grouped-help order for the usage line."""
139
+ names = [name for _, group in command_groups_for(version) for name in group]
140
+ return "{" + ",".join(names) + "}"
141
+
142
+
143
+ def help_description_for(version: int | None = None) -> str:
144
+ current = product_version() if version is None else version
145
+ if current <= 1:
146
+ return _named(HELP_DESCRIPTION, 1 if current < 1 else current)
147
+ if current == 2:
148
+ return _named(_VERSION_2_HELP_DESCRIPTION, current)
149
+ if current >= 5 and current <= MAX_PRODUCT_VERSION:
150
+ text = _VERSION_5_HELP_DESCRIPTION
151
+ if current >= 6:
152
+ text += (
153
+ " When series fit names a type outside your quota family, maproom may "
154
+ "read quotas and request an increase after you approve the printed request."
155
+ )
156
+ if current >= 7:
157
+ text += (
158
+ " Analyze may steer candidates using this machine's quota-request "
159
+ "outcome ledger."
160
+ )
161
+ if current == 7:
162
+ text += (
163
+ " Sharing herd quota denial evidence through quota_telemetry "
164
+ "is not finished; quota_telemetry is not a settings set key."
165
+ )
166
+ if current >= 8:
167
+ text += (
168
+ " Capacity availability steering from launch history is the "
169
+ "level-8 ceiling but is not in this release; analyze still "
170
+ "matches version 7."
171
+ )
172
+ return _named(text, current)
173
+ if current <= MAX_PRODUCT_VERSION:
174
+ return _named(_VERSION_3_HELP_DESCRIPTION, current)
175
+ return _FULL_HELP_DESCRIPTION
176
+
177
+
178
+ def help_epilog_for(version: int | None = None) -> str:
179
+ current = product_version() if version is None else version
180
+ if current < RIGHTSIZER_MIN_PRODUCT_VERSION:
181
+ return HELP_EPILOG
182
+ return _FULL_HELP_EPILOG
183
+
184
+
185
+ def print_root_help() -> None:
186
+ print(help_description_for() + "\n" + help_epilog_for(), file=sys.stdout, end="")
187
+
188
+
189
+ def _command_block(name: str, help_text: str) -> str:
190
+ """Lowercase command, then a sentence-case description on the next line, same indent."""
191
+ wrapped = textwrap.wrap(help_text, width=72) or [""]
192
+ return "\n".join([name.lower(), *wrapped])
193
+
194
+
195
+ def format_grouped_root_help(parser: argparse.ArgumentParser) -> str:
196
+ """`maproom -h` with commands grouped by the job, instead of one positional list."""
197
+ version = product_version()
198
+ formatter = parser._get_formatter()
199
+ formatter.add_usage(parser.usage, parser._actions, parser._mutually_exclusive_groups)
200
+ description = help_description_for(version)
201
+ width = max(40, getattr(formatter, "_width", 72))
202
+ sentences: list[str] = []
203
+ for part in description.replace("\n", " ").split(". "):
204
+ part = part.strip()
205
+ if not part:
206
+ continue
207
+ if not part.endswith("."):
208
+ part = f"{part}."
209
+ sentences.append(
210
+ textwrap.fill(part, width=width, break_long_words=False, break_on_hyphens=False)
211
+ )
212
+ formatter.add_text("\n".join(sentences))
213
+
214
+ sub_action = next(
215
+ (action for action in parser._actions if getattr(action, "dest", None) == "command"),
216
+ None,
217
+ )
218
+ helps = {
219
+ action.dest: action.help or ""
220
+ for action in getattr(sub_action, "_choices_actions", ())
221
+ }
222
+ for title, names in command_groups_for(version):
223
+ formatter.start_section(title)
224
+ blocks = [_command_block(name, helps.get(name, "")) for name in names]
225
+ formatter.add_text("\n\n".join(blocks))
226
+ formatter.end_section()
227
+
228
+ for group in parser._action_groups:
229
+ actions = [
230
+ action
231
+ for action in group._group_actions
232
+ if action is not sub_action
233
+ ]
234
+ if not actions:
235
+ continue
236
+ formatter.start_section(group.title)
237
+ formatter.add_text(group.description)
238
+ formatter.add_arguments(actions)
239
+ formatter.end_section()
240
+
241
+ formatter.add_text(help_epilog_for(version))
242
+ rendered = formatter.format_help()
243
+ rendered = rendered.replace(",plan,", ",")
244
+ if version < RIGHTSIZER_MIN_PRODUCT_VERSION:
245
+ rendered = re.sub(
246
+ r"\{[^{}]+\}",
247
+ usage_choices_for(version),
248
+ rendered,
249
+ count=1,
250
+ )
251
+ return rendered