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,961 @@
1
+ """maproom inventory: one refresh, status, load, and clear for the three snapshots."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import shutil
7
+ import sys
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from maproom.cli_floors import fail_cli_floor
13
+ from maproom.cliio.runner import CliBelowFloorError
14
+ from maproom.consent import require_cloud_read_consent
15
+ from maproom.consent.stdin import stdin_allows_prompt
16
+ from maproom.exitcodes import RUNTIME, SUCCESS, USAGE
17
+ from maproom.inventory.accounts import AccountIdentityError
18
+ from maproom.mock_environment import MockEnvironmentError, MockEnvironmentRunner, command_runner
19
+ from maproom.output.json_envelope import (
20
+ build_document,
21
+ command_metadata,
22
+ error_item,
23
+ finish_consent_gate,
24
+ print_error_envelope,
25
+ print_json,
26
+ warning_item,
27
+ )
28
+ from maproom.paths import data_subdir, settings_read_file
29
+ from maproom.settings.model import cache_max_age_hours, snapshot_is_stale
30
+ from maproom.plan.tty import PromptClosed, confirm_yes_no
31
+ from maproom.quotas.model import QuotaError
32
+ from maproom.reservations.model import ReservationError
33
+ from maproom.saving_plans.model import SavingPlanError
34
+
35
+ _REFRESH = "maproom inventory get"
36
+ _KINDS = ("quotas", "reservations", "savings-plans")
37
+ _DIRS = {
38
+ "quotas": "quotas",
39
+ "reservations": "reservations",
40
+ "savings-plans": "savings-plans",
41
+ }
42
+ _LOAD_NOUN = {
43
+ "quotas": ("quota", "quotas"),
44
+ "reservations": ("reservation", "reservations"),
45
+ "savings-plans": ("savings plan", "savings plans"),
46
+ }
47
+ _SNAPSHOT_SOURCE_ENUM = ("cloud_get", "payer_file", "aws_get")
48
+
49
+
50
+ def cmd_inventory(args: argparse.Namespace) -> int:
51
+ command = getattr(args, "inventory_command", None) or "status"
52
+ if command == "get":
53
+ return cmd_inventory_get(args)
54
+ if command == "clear":
55
+ return cmd_inventory_clear(args)
56
+ if command == "load":
57
+ return cmd_inventory_load(args)
58
+ if command == "show":
59
+ return cmd_inventory_show(args)
60
+ return cmd_inventory_status(args)
61
+
62
+
63
+ def cmd_inventory_status(args: argparse.Namespace) -> int:
64
+ started_at = datetime.now(timezone.utc)
65
+ from maproom.quotas.status import doctor_quotas_message, read_quota_state
66
+ from maproom.reservations.status import doctor_reservations_message, read_inventory_state
67
+ from maproom.saving_plans.status import doctor_saving_plans_message, read_saving_plan_state
68
+
69
+ as_json = bool(getattr(args, "json", False))
70
+ quotas = read_quota_state()
71
+ reservations = read_inventory_state()
72
+ savings = read_saving_plan_state()
73
+ sections = {
74
+ "quotas": _status_section(
75
+ quotas,
76
+ doctor_quotas_message(quotas),
77
+ "Availability stays incomplete.",
78
+ label="Quotas",
79
+ ),
80
+ "reservations": _reservations_status_section(reservations),
81
+ "savings_plans": _status_section(
82
+ savings,
83
+ doctor_saving_plans_message(savings),
84
+ "Savings estimates stay incomplete.",
85
+ label="Savings plans",
86
+ ),
87
+ }
88
+ warnings: list[dict[str, str]] = []
89
+ if (
90
+ quotas.exists
91
+ and not quotas.parse_error
92
+ and not quotas.is_stale
93
+ and quotas.record_count == 0
94
+ ):
95
+ warnings.append(
96
+ warning_item(
97
+ "quotas_empty",
98
+ "Quota snapshot has no rows; refresh with maproom inventory get.",
99
+ )
100
+ )
101
+ sections["quotas"]["message"] = "Quota snapshot has no rows."
102
+ errors = []
103
+ for name, state, label in (
104
+ ("quotas", quotas, "quotas"),
105
+ ("reservations", reservations, "reservations"),
106
+ ("savings_plans", savings, "savings plans"),
107
+ ):
108
+ if state.parse_error:
109
+ errors.append(error_item("runtime", f"{label}: {state.parse_error}"))
110
+ if as_json:
111
+ print_json(
112
+ build_document(
113
+ schema_type="inventory",
114
+ schema_id="maproom.inventory",
115
+ metadata=command_metadata("inventory status", started_at=started_at),
116
+ errors=errors,
117
+ warnings=warnings,
118
+ payload={"sections": sections},
119
+ )
120
+ )
121
+ return RUNTIME if errors else SUCCESS
122
+ print(
123
+ "Inventory is quotas, reservations, and savings plans together. "
124
+ "It is not the list of running instances."
125
+ )
126
+ print()
127
+ print(_status_line("Quotas", sections["quotas"]))
128
+ _print_status_snapshot_detail("quotas", quotas)
129
+ print(_status_line("Reservations", sections["reservations"]))
130
+ _print_status_snapshot_detail("reservations", reservations)
131
+ print(_status_line("Savings plans", sections["savings_plans"]))
132
+ _print_status_snapshot_detail("savings_plans", savings)
133
+ print()
134
+ print(f"Refresh with: {_REFRESH}")
135
+ return RUNTIME if errors else SUCCESS
136
+
137
+
138
+ def cmd_inventory_show(args: argparse.Namespace) -> int:
139
+ kind = str(getattr(args, "show_kind", "") or "")
140
+ as_json = bool(getattr(args, "json", False))
141
+ invoked = "inventory show"
142
+ if kind not in _KINDS:
143
+ return _fail(
144
+ f'unknown inventory kind "{kind}" (use quotas, reservations, or savings-plans)',
145
+ as_json=as_json,
146
+ invoked=invoked,
147
+ code="usage",
148
+ )
149
+ records, meta, parse_error = _read_show_records(kind)
150
+ if parse_error:
151
+ return _fail(parse_error, as_json=as_json, invoked=invoked)
152
+ if as_json:
153
+ print_json(
154
+ build_document(
155
+ schema_type="inventory_show",
156
+ schema_id="maproom.inventory_show",
157
+ metadata=command_metadata(f"inventory show {kind}"),
158
+ payload={
159
+ "kind": kind,
160
+ "records": records,
161
+ **meta,
162
+ },
163
+ )
164
+ )
165
+ return SUCCESS
166
+ if not records:
167
+ print(f"No {kind} records in the current snapshot.")
168
+ if meta.get("snapshot_path"):
169
+ print(f" File: {meta['snapshot_path']}")
170
+ return SUCCESS
171
+ if meta.get("account_id"):
172
+ label = meta.get("account_alias") or meta["account_id"]
173
+ print(f"Account: {label}")
174
+ if meta.get("region"):
175
+ print(f"Region: {meta['region']}")
176
+ if meta.get("snapshot_path"):
177
+ print(f"File: {meta['snapshot_path']}")
178
+ print()
179
+ for line in _format_show_record_lines(kind, records):
180
+ print(line)
181
+ return SUCCESS
182
+
183
+
184
+ def cmd_inventory_get(args: argparse.Namespace) -> int:
185
+ started_at = datetime.now(timezone.utc)
186
+ import maproom.quotas.commands as quota_cmd
187
+ import maproom.reservations.commands as reservation_cmd
188
+ import maproom.saving_plans.commands as saving_cmd
189
+
190
+ as_json = bool(getattr(args, "json", False))
191
+ invoked = "inventory get"
192
+ try:
193
+ runner = command_runner()
194
+ except MockEnvironmentError as exc:
195
+ return _fail(exc.message, as_json=as_json, invoked=invoked)
196
+ try:
197
+ clouds = quota_cmd.parse_clouds_arg(getattr(args, "cloud", None))
198
+ except QuotaError as exc:
199
+ return _fail(exc.message, as_json=as_json, invoked=invoked, code="usage")
200
+
201
+ if "aws" in clouds:
202
+ try:
203
+ saving_cmd.ensure_cli_floors(runner=runner)
204
+ except CliBelowFloorError as exc:
205
+ return fail_cli_floor(exc, as_json=as_json, invoked=invoked)
206
+
207
+ gate = require_cloud_read_consent(
208
+ consent_cloud_reads=bool(getattr(args, "consent_cloud_reads", False)),
209
+ quiet=as_json,
210
+ )
211
+ if not gate.allowed:
212
+ return finish_consent_gate(gate, as_json=as_json, invoked=invoked)
213
+
214
+ aws_region = getattr(args, "region", None) or None
215
+ azure_location = getattr(args, "location", None) or None
216
+ warnings: list[dict[str, Any]] = []
217
+ errors: list[dict[str, Any]] = []
218
+ human_quotas: list[str] = []
219
+ human_reservations: list[str] = []
220
+ human_savings: list[str] = []
221
+
222
+ quotas = _fetch_quotas(
223
+ quota_cmd,
224
+ runner=runner,
225
+ clouds=clouds,
226
+ aws_region=aws_region,
227
+ azure_location=azure_location,
228
+ as_json=as_json,
229
+ warnings=warnings,
230
+ errors=errors,
231
+ human=human_quotas,
232
+ )
233
+ reservations = _fetch_reservations(
234
+ reservation_cmd,
235
+ runner=runner,
236
+ clouds=clouds,
237
+ aws_region=aws_region,
238
+ as_json=as_json,
239
+ errors=errors,
240
+ human=human_reservations,
241
+ )
242
+ savings = _fetch_savings_plans(
243
+ saving_cmd,
244
+ runner=runner,
245
+ clouds=clouds,
246
+ aws_region=aws_region,
247
+ as_json=as_json,
248
+ errors=errors,
249
+ human=human_savings,
250
+ )
251
+ failed = bool(errors)
252
+ message = "Inventory refresh saved quotas, reservations, and savings plans."
253
+ if failed:
254
+ message = errors[0]["message"]
255
+ if as_json:
256
+ print_json(
257
+ build_document(
258
+ schema_type="inventory_get",
259
+ schema_id="maproom.inventory_get",
260
+ metadata=command_metadata(invoked, started_at=started_at),
261
+ errors=errors,
262
+ warnings=warnings,
263
+ payload={
264
+ "message": message,
265
+ "clouds": sorted(clouds),
266
+ "quotas": quotas,
267
+ "reservations": reservations,
268
+ "savings_plans": savings,
269
+ },
270
+ )
271
+ )
272
+ else:
273
+ _print_get_human_sections(
274
+ human_quotas,
275
+ human_reservations,
276
+ human_savings,
277
+ reservations_section=reservations,
278
+ savings_section=savings,
279
+ )
280
+ print(message)
281
+ return RUNTIME if failed else SUCCESS
282
+
283
+
284
+ def cmd_inventory_load(args: argparse.Namespace) -> int:
285
+ as_json = bool(getattr(args, "json", False))
286
+ invoked = "inventory load"
287
+ kind = str(getattr(args, "kind", "") or "")
288
+ payer_path = Path(str(getattr(args, "path", "")))
289
+ file_as_of: str | None = None
290
+ replaced = _existing_snapshot_meta(kind)
291
+ try:
292
+ if kind == "quotas":
293
+ from maproom.quotas.load import load_payer_file_with_timestamp
294
+ from maproom.quotas.commands import store
295
+ from maproom.quotas.model import build_snapshot
296
+
297
+ records, file_as_of = load_payer_file_with_timestamp(payer_path)
298
+ snapshot = build_snapshot(
299
+ records, source="payer_file", loaded_as_of=file_as_of
300
+ )
301
+ err = store.write_snapshot(snapshot)
302
+ if err is not None:
303
+ return _fail(err.message, as_json=as_json, invoked=invoked)
304
+ path = store.snapshot_path()
305
+ elif kind == "reservations":
306
+ from maproom.reservations.load import load_payer_file_with_timestamp
307
+ from maproom.reservations.commands import store
308
+ from maproom.reservations.model import build_snapshot
309
+
310
+ records, file_as_of = load_payer_file_with_timestamp(payer_path)
311
+ snapshot = build_snapshot(
312
+ records, source="payer_file", loaded_as_of=file_as_of
313
+ )
314
+ err = store.write_snapshot(snapshot)
315
+ if err is not None:
316
+ return _fail(err.message, as_json=as_json, invoked=invoked)
317
+ path = store.inventory_path()
318
+ elif kind == "savings-plans":
319
+ from maproom.saving_plans.load import load_payer_file_with_timestamp
320
+ from maproom.saving_plans.model import build_snapshot
321
+ from maproom.saving_plans import store
322
+
323
+ records, file_as_of = load_payer_file_with_timestamp(payer_path)
324
+ snapshot = build_snapshot(
325
+ records, source="payer_file", loaded_as_of=file_as_of
326
+ )
327
+ err = store.write_snapshot(snapshot)
328
+ if err is not None:
329
+ return _fail(err.message, as_json=as_json, invoked=invoked)
330
+ path = store.inventory_path()
331
+ else:
332
+ return _fail(
333
+ f'unknown inventory file kind "{kind}"',
334
+ as_json=as_json,
335
+ invoked=invoked,
336
+ code="usage",
337
+ )
338
+ except (QuotaError, ReservationError, SavingPlanError) as exc:
339
+ return _fail(exc.message, as_json=as_json, invoked=invoked)
340
+
341
+ payload = {
342
+ "kind": kind,
343
+ "source_path": str(payer_path),
344
+ "snapshot_path": str(path),
345
+ "loaded_as_of": snapshot["loaded_as_of"],
346
+ "record_count": snapshot["record_count"],
347
+ "source": snapshot["source"],
348
+ }
349
+ if file_as_of:
350
+ payload["file_as_of"] = file_as_of
351
+ payload["replaced"] = replaced
352
+ max_age = cache_max_age_hours(settings_read_file())
353
+ loaded_at = str(snapshot["loaded_as_of"])
354
+ load_warnings: list[dict[str, str]] = []
355
+ if snapshot_is_stale(loaded_at, max_age):
356
+ stale_msg = (
357
+ f"Snapshot time {loaded_at} is older than cache_max_age_hours "
358
+ f"({max_age}); analyze may treat it as stale. Load a newer file or "
359
+ "raise cache_max_age_hours in settings."
360
+ )
361
+ load_warnings.append(warning_item("snapshot_stale", stale_msg))
362
+ if as_json:
363
+ print_json(
364
+ build_document(
365
+ schema_type="inventory_load",
366
+ schema_id="maproom.inventory_load",
367
+ metadata=command_metadata(invoked),
368
+ warnings=load_warnings,
369
+ payload=payload,
370
+ )
371
+ )
372
+ else:
373
+ singular, plural = _LOAD_NOUN[kind]
374
+ count = int(snapshot["record_count"])
375
+ noun = singular if count == 1 else plural
376
+ print(f"Loaded {count} {noun} from {payer_path}.")
377
+ when = (
378
+ f"file dated {file_as_of}"
379
+ if file_as_of
380
+ else f"loaded at {snapshot['loaded_as_of']}"
381
+ )
382
+ print(f"Saved to {path} ({when}).")
383
+ if replaced:
384
+ print(
385
+ "Replaced the previous snapshot "
386
+ f"({replaced['record_count']} records, source {replaced['source']}, "
387
+ f"as of {replaced['loaded_as_of']})."
388
+ )
389
+ if load_warnings:
390
+ print(f"Note: {load_warnings[0]['message']}")
391
+ return SUCCESS
392
+
393
+
394
+ def cmd_inventory_clear(args: argparse.Namespace) -> int:
395
+ as_json = bool(getattr(args, "json", False))
396
+ invoked = "inventory clear"
397
+ if not bool(getattr(args, "force", False)):
398
+ if not stdin_allows_prompt():
399
+ return _fail(
400
+ "confirm inventory clear in a TTY or pass --force",
401
+ as_json=as_json,
402
+ invoked=invoked,
403
+ code="usage",
404
+ )
405
+ prompt = (
406
+ "Delete quotas, reservations, and savings plans? "
407
+ "Instance snapshots, plans, settings, and consent are kept."
408
+ )
409
+ try:
410
+ confirmed = confirm_yes_no(prompt, default_no=True)
411
+ except PromptClosed as exc:
412
+ return _fail(exc.message, as_json=as_json, invoked=invoked, code="usage")
413
+ if not confirmed:
414
+ return SUCCESS
415
+ removed: list[str] = []
416
+ try:
417
+ for folder in _DIRS.values():
418
+ path = data_subdir(folder)
419
+ if not path.exists():
420
+ continue
421
+ if path.is_dir():
422
+ shutil.rmtree(path)
423
+ else:
424
+ path.unlink()
425
+ removed.append(str(path))
426
+ except OSError as exc:
427
+ return _fail(str(exc), as_json=as_json, invoked=invoked)
428
+ if as_json:
429
+ print_json(
430
+ build_document(
431
+ schema_type="inventory_clear",
432
+ schema_id="maproom.inventory_clear",
433
+ metadata=command_metadata(invoked),
434
+ payload={"removed": removed},
435
+ )
436
+ )
437
+ return SUCCESS
438
+ if not removed:
439
+ print("Inventory is already empty.")
440
+ return SUCCESS
441
+ print(f"Removed {len(removed)} inventory director{'y' if len(removed) == 1 else 'ies'}:")
442
+ for path in removed:
443
+ print(f" {path}")
444
+ return SUCCESS
445
+
446
+
447
+ def _reservation_status_records(state: Any) -> list[dict[str, Any]]:
448
+ if state.parse_error or not state.exists:
449
+ return []
450
+ rows: list[dict[str, Any]] = []
451
+ for row in getattr(state, "records", ()) or ():
452
+ if not isinstance(row, dict):
453
+ continue
454
+ rows.append(
455
+ {
456
+ key: row.get(key)
457
+ for key in (
458
+ "instance_type",
459
+ "quantity",
460
+ "state",
461
+ "region",
462
+ "platform",
463
+ "scope",
464
+ "offering_class",
465
+ "end",
466
+ "account_id",
467
+ "subscription_id",
468
+ )
469
+ }
470
+ )
471
+ return rows
472
+
473
+
474
+ def _status_section(
475
+ state: Any,
476
+ message: str,
477
+ incomplete: str,
478
+ *,
479
+ label: str,
480
+ records: list[dict[str, Any]] | None = None,
481
+ ) -> dict[str, Any]:
482
+ missing = bool(state.parse_error) or not state.exists or state.is_stale
483
+ snapshot_path = getattr(state, "snapshot_path", None)
484
+ path_str = str(snapshot_path) if snapshot_path is not None else ""
485
+ if state.parse_error:
486
+ human_message = message
487
+ elif not state.exists:
488
+ human_message = f"No {label.lower()} snapshot file yet."
489
+ elif state.is_stale:
490
+ human_message = f"{label} snapshot is stale."
491
+ else:
492
+ human_message = f"{label} snapshot is fresh."
493
+ section: dict[str, Any] = {
494
+ "exists": bool(state.exists),
495
+ "is_stale": bool(state.is_stale),
496
+ "record_count": int(state.record_count),
497
+ "loaded_as_of": state.loaded_as_of,
498
+ "snapshot_path": path_str,
499
+ "message": human_message,
500
+ "incomplete": incomplete if missing else "",
501
+ }
502
+ if records is not None:
503
+ section["records"] = records
504
+ return section
505
+
506
+
507
+ def _reservations_status_section(state: Any) -> dict[str, Any]:
508
+ from maproom.reservations.status import doctor_reservations_message
509
+ from maproom.settings.model import snapshot_is_stale
510
+
511
+ section = _status_section(
512
+ state,
513
+ doctor_reservations_message(state),
514
+ "Reservation coverage stays incomplete.",
515
+ label="Reservations",
516
+ records=_reservation_status_records(state),
517
+ )
518
+ account_count = int(getattr(state, "account_count", 0) or 0)
519
+ if account_count:
520
+ section["account_count"] = account_count
521
+ regions = tuple(getattr(state, "regions", ()) or ())
522
+ if regions:
523
+ section["regions"] = list(regions)
524
+ parts = []
525
+ for part in getattr(state, "account_parts", ()) or ():
526
+ part_stale = snapshot_is_stale(
527
+ part.loaded_as_of,
528
+ int(state.cache_max_age_hours),
529
+ )
530
+ parts.append(
531
+ {
532
+ "account_id": part.account_id,
533
+ "account_alias": part.account_alias,
534
+ "loaded_as_of": part.loaded_as_of,
535
+ "record_count": part.record_count,
536
+ "regions": list(part.regions),
537
+ "is_stale": part_stale,
538
+ "snapshot_path": str(part.path),
539
+ }
540
+ )
541
+ if parts:
542
+ section["accounts"] = parts
543
+ return section
544
+
545
+
546
+ def _status_line(label: str, section: dict[str, Any]) -> str:
547
+ if not section["exists"]:
548
+ state = "missing"
549
+ elif section["is_stale"]:
550
+ state = "stale"
551
+ elif section["incomplete"]:
552
+ state = "missing"
553
+ elif label == "Quotas" and section["record_count"] == 0:
554
+ state = "empty"
555
+ else:
556
+ state = "fresh"
557
+ line = f"{label}: {state}"
558
+ if section["exists"] and section["loaded_as_of"]:
559
+ count = section["record_count"]
560
+ noun = "record" if count == 1 else "records"
561
+ line += f" ({count} {noun}, as of {section['loaded_as_of']})"
562
+ account_count = section.get("account_count")
563
+ if label == "Reservations" and isinstance(account_count, int) and account_count > 1:
564
+ line += f" across {account_count} accounts"
565
+ if section["incomplete"]:
566
+ line += f". {section['incomplete']}"
567
+ elif (
568
+ label == "Quotas"
569
+ and section["record_count"] == 0
570
+ and section["exists"]
571
+ and not section["is_stale"]
572
+ ):
573
+ line += ". Refresh with: maproom inventory get."
574
+ if "could not read snapshot" in section["message"]:
575
+ line += f" {section['message']}"
576
+ return line
577
+
578
+
579
+ def _fetch_quotas(quota_cmd, *, runner, clouds, aws_region, azure_location, as_json, warnings, errors, human):
580
+ from maproom.inventory.messages import (
581
+ quotas_fetch_progress_line_for,
582
+ quotas_get_human_lines,
583
+ quotas_get_summary_message,
584
+ )
585
+ from maproom.quotas.fetch import cloud_summaries_for_records
586
+ from maproom.quotas.model import build_snapshot
587
+
588
+ if not as_json:
589
+ for cloud in sorted(clouds):
590
+ print(quotas_fetch_progress_line_for(cloud), file=sys.stderr)
591
+ try:
592
+ records, partial_errors = quota_cmd.fetch_quotas(
593
+ runner,
594
+ clouds=clouds,
595
+ aws_region=aws_region,
596
+ azure_location=azure_location,
597
+ aws_launch_relevant_only=False,
598
+ )
599
+ except QuotaError as exc:
600
+ errors.append(error_item("runtime", exc.message))
601
+ human.append(f"Quotas were not saved: {exc.message}")
602
+ return {"status": "error", "message": exc.message}
603
+ for err in partial_errors:
604
+ warnings.append(warning_item("aws_quotas_not_saved", err))
605
+ errors.append(error_item("runtime", err))
606
+ label = "AWS quotas" if "AWS" in err else "Quotas"
607
+ human.append(f"{label} were not saved: {err}")
608
+ snapshot = build_snapshot(records, source="cloud_get")
609
+ if not records:
610
+ warnings.append(
611
+ warning_item(
612
+ "quotas_empty",
613
+ "Quota read returned no rows; saved an empty snapshot.",
614
+ )
615
+ )
616
+ try:
617
+ written = quota_cmd.save_quota_account_snapshots(
618
+ records, runner=runner, source="cloud_get", clouds=clouds
619
+ )
620
+ except AccountIdentityError as exc:
621
+ errors.append(error_item("runtime", exc.message))
622
+ human.append(f"Quotas were not saved: {exc.message}")
623
+ return {"status": "error", "message": exc.message}
624
+ except QuotaError as exc:
625
+ if records:
626
+ errors.append(error_item("runtime", exc.message))
627
+ human.append(f"Quotas were not saved: {exc.message}")
628
+ return {"status": "error", "message": exc.message}
629
+ written = []
630
+ path = written[0] if len(written) == 1 else quota_cmd.store.snapshot_root()
631
+ summaries = tuple(cloud_summaries_for_records(records))
632
+ if not as_json:
633
+ from maproom.inventory.messages import QuotasCloudSummary
634
+
635
+ human.extend(
636
+ quotas_get_human_lines(
637
+ path=str(path),
638
+ cloud_summaries=tuple(
639
+ QuotasCloudSummary(
640
+ cloud=cloud,
641
+ record_count=count,
642
+ region=region,
643
+ include_general_line=show_general,
644
+ )
645
+ for cloud, count, region, show_general in summaries
646
+ ),
647
+ total_record_count=len(records),
648
+ loaded_as_of=str(snapshot["loaded_as_of"]),
649
+ )
650
+ )
651
+ has_azure = any(str(row.get("cloud") or "") == "azure" for row in records)
652
+ if "azure" in clouds and not has_azure and not partial_errors:
653
+ human.append(
654
+ "Azure quotas were not added. Install and sign in to the Azure CLI, "
655
+ "then run maproom inventory get again."
656
+ )
657
+ return {
658
+ "status": "error" if partial_errors else "ok",
659
+ "message": (
660
+ quotas_get_summary_message(len(records))
661
+ if not partial_errors
662
+ else partial_errors[0]
663
+ ),
664
+ "snapshot_path": str(path),
665
+ "loaded_as_of": str(snapshot["loaded_as_of"]),
666
+ "record_count": int(snapshot["record_count"]),
667
+ "source": "cloud_get",
668
+ **_identity_from_snapshot(snapshot),
669
+ }
670
+
671
+
672
+ def _fetch_reservations(reservation_cmd, *, runner, clouds, aws_region, as_json, errors, human):
673
+ from maproom.inventory.messages import (
674
+ reservations_fetch_progress_line,
675
+ reservations_get_human_lines,
676
+ )
677
+ from maproom.reservations.model import build_snapshot
678
+
679
+ if "aws" not in clouds:
680
+ human.append("Reservations: not requested for this cloud.")
681
+ return {"status": "skipped", "message": "AWS was not included in --cloud"}
682
+ if not as_json:
683
+ print(reservations_fetch_progress_line(), file=sys.stderr)
684
+ try:
685
+ account = reservation_cmd.resolve_aws_account(runner)
686
+ records, region = reservation_cmd.aws.fetch_aws_inventory(runner, region=aws_region)
687
+ except (AccountIdentityError, ReservationError) as exc:
688
+ message = exc.message
689
+ errors.append(error_item("runtime", message))
690
+ human.append(f"Reservations were not saved: {message}")
691
+ return {"status": "error", "message": message}
692
+ snapshot = build_snapshot(records, source="cloud_get", region=region)
693
+ snapshot["cloud"] = account.cloud
694
+ snapshot["account_id"] = account.account_id
695
+ if account.alias:
696
+ snapshot["account_alias"] = account.alias
697
+ err = reservation_cmd.store.write_account_snapshot(snapshot, account)
698
+ if err is not None:
699
+ errors.append(error_item("runtime", err.message))
700
+ human.append(f"Reservations were not saved: {err.message}")
701
+ return {"status": "error", "message": err.message}
702
+ path = reservation_cmd.store.account_snapshot_path(account)
703
+ record_count = int(snapshot["record_count"])
704
+ loaded_as_of = str(snapshot["loaded_as_of"])
705
+ pool = reservation_cmd.store.pool_summary()
706
+ if not as_json:
707
+ human.extend(
708
+ reservations_get_human_lines(
709
+ record_count=record_count,
710
+ path=str(path),
711
+ loaded_as_of=loaded_as_of,
712
+ region=region,
713
+ records=list(snapshot.get("records") or []),
714
+ account_record_count=record_count,
715
+ pool_record_count=int(pool.get("record_count") or 0),
716
+ pool_account_count=int(pool.get("account_count") or 0),
717
+ )
718
+ )
719
+ section = {
720
+ "status": "ok",
721
+ "message": "reservations saved",
722
+ "snapshot_path": str(path),
723
+ "loaded_as_of": loaded_as_of,
724
+ "record_count": record_count,
725
+ "source": "cloud_get",
726
+ "region": region,
727
+ "pool_record_count": int(pool.get("record_count") or 0),
728
+ "pool_account_count": int(pool.get("account_count") or 0),
729
+ **_identity_from_snapshot(snapshot),
730
+ }
731
+ if snapshot.get("regions"):
732
+ section["regions"] = list(snapshot["regions"])
733
+ return section
734
+
735
+
736
+ def _fetch_savings_plans(saving_cmd, *, runner, clouds, aws_region, as_json, errors, human):
737
+ from maproom.inventory.messages import saving_plans_fetch_progress_line, saving_plans_get_human_lines
738
+ from maproom.saving_plans.model import build_snapshot
739
+
740
+ if "aws" not in clouds:
741
+ human.append("Savings plans: not requested for this cloud.")
742
+ return {"status": "skipped", "message": "AWS was not included in --cloud"}
743
+ if not as_json:
744
+ print(saving_plans_fetch_progress_line(), file=sys.stderr)
745
+ from maproom.inventory.account_identity import resolve_aws_account
746
+
747
+ try:
748
+ account = resolve_aws_account(runner)
749
+ records, region = saving_cmd.aws.fetch_aws_savings_plans(runner, region=aws_region)
750
+ except (AccountIdentityError, SavingPlanError) as exc:
751
+ message = getattr(exc, "message", str(exc))
752
+ errors.append(error_item("runtime", message))
753
+ human.append(f"Savings plans were not saved: {message}")
754
+ return {"status": "error", "message": message}
755
+ snapshot = build_snapshot(records, source="cloud_get", region=region)
756
+ snapshot["cloud"] = account.cloud
757
+ snapshot["account_id"] = account.account_id
758
+ if account.alias:
759
+ snapshot["account_alias"] = account.alias
760
+ identity = {k: v for k, v in _identity_from_snapshot(snapshot).items() if k != "region"}
761
+ err = saving_cmd.store.write_account_snapshot(snapshot, account)
762
+ if err is not None:
763
+ errors.append(error_item("runtime", err.message))
764
+ human.append(f"Savings plans were not saved: {err.message}")
765
+ return {"status": "error", "message": err.message}
766
+ path = saving_cmd.store.account_snapshot_path(account)
767
+ record_count = int(snapshot["record_count"])
768
+ loaded_as_of = str(snapshot["loaded_as_of"])
769
+ if not as_json:
770
+ human.extend(
771
+ saving_plans_get_human_lines(
772
+ record_count=record_count,
773
+ path=str(path),
774
+ loaded_as_of=loaded_as_of,
775
+ )
776
+ )
777
+ return {
778
+ "status": "ok",
779
+ "message": "savings plans saved",
780
+ "snapshot_path": str(path),
781
+ "loaded_as_of": loaded_as_of,
782
+ "record_count": record_count,
783
+ "source": "cloud_get",
784
+ **identity,
785
+ }
786
+
787
+
788
+ def _existing_snapshot_meta(kind: str) -> dict[str, Any] | None:
789
+ data: Any
790
+ if kind == "quotas":
791
+ from maproom.quotas import store as quota_store
792
+
793
+ data = quota_store.read_snapshot()
794
+ elif kind == "reservations":
795
+ from maproom.reservations import store as reservation_store
796
+
797
+ data = reservation_store.read_snapshot()
798
+ elif kind == "savings-plans":
799
+ from maproom.saving_plans import store as saving_store
800
+
801
+ data = saving_store.read_snapshot()
802
+ else:
803
+ return None
804
+ if not isinstance(data, dict):
805
+ return None
806
+ return {
807
+ "record_count": int(data.get("record_count") or 0),
808
+ "source": str(data.get("source") or ""),
809
+ "loaded_as_of": str(data.get("loaded_as_of") or ""),
810
+ }
811
+
812
+
813
+ def _identity_from_snapshot(snapshot: dict[str, Any]) -> dict[str, str]:
814
+ out: dict[str, str] = {}
815
+ for key in ("cloud", "account_id", "account_alias", "region"):
816
+ value = snapshot.get(key)
817
+ if isinstance(value, str) and value.strip():
818
+ out[key] = value.strip()
819
+ return out
820
+
821
+
822
+ def _print_get_human_sections(
823
+ quotas: list[str],
824
+ reservation_lines: list[str],
825
+ savings_lines: list[str],
826
+ *,
827
+ reservations_section: dict[str, Any],
828
+ savings_section: dict[str, Any],
829
+ ) -> None:
830
+ def _emit(lines: list[str]) -> None:
831
+ for line in lines:
832
+ failed_line = "were not saved" in line
833
+ print(line, file=sys.stderr if failed_line else sys.stdout)
834
+
835
+ _emit(quotas)
836
+ if reservation_lines:
837
+ print()
838
+ _emit(reservation_lines)
839
+ if savings_lines:
840
+ print()
841
+ _emit(savings_lines)
842
+
843
+
844
+ def _print_status_snapshot_detail(kind: str, state: Any) -> None:
845
+ if state.parse_error or not state.exists:
846
+ return
847
+ if kind == "reservations" and getattr(state, "account_parts", None):
848
+ parts = list(state.account_parts)
849
+ if len(parts) > 1:
850
+ for part in parts:
851
+ label = part.account_alias or part.account_id or "account"
852
+ regions = ",".join(part.regions) if part.regions else "unknown region"
853
+ print(
854
+ f" Account {label}: {part.record_count} records, "
855
+ f"{regions}, as of {part.loaded_as_of}"
856
+ )
857
+ path = str(getattr(state, "snapshot_path", ""))
858
+ if path:
859
+ print(f" Pool: {path}")
860
+ return
861
+ data = _snapshot_data_for_kind(kind)
862
+ if data is None:
863
+ return
864
+ for key in ("account_id", "account_alias", "region"):
865
+ value = data.get(key)
866
+ if isinstance(value, str) and value:
867
+ label = "Account" if key != "region" else "Region"
868
+ if key == "account_alias":
869
+ continue
870
+ if key == "account_id":
871
+ display = data.get("account_alias") or value
872
+ print(f" Account: {display}")
873
+ else:
874
+ print(f" {label}: {value}")
875
+ regions = data.get("regions")
876
+ if isinstance(regions, list) and len(regions) > 1:
877
+ print(f" Regions: {', '.join(str(item) for item in regions)}")
878
+ path = data.get("_path") or str(getattr(state, "snapshot_path", ""))
879
+ if path:
880
+ print(f" File: {path}")
881
+ records = [r for r in (data.get("records") or []) if isinstance(r, dict)]
882
+ if kind == "reservations" and records:
883
+ for row in records[:3]:
884
+ itype = row.get("instance_type", "?")
885
+ qty = row.get("quantity", "?")
886
+ print(f" {itype} x {qty} ({row.get('state', '?')})")
887
+ if len(records) > 3:
888
+ print(f" ... and {len(records) - 3} more (maproom inventory show reservations)")
889
+
890
+
891
+ def _snapshot_data_for_kind(kind: str) -> dict[str, Any] | None:
892
+ if kind == "quotas":
893
+ from maproom.quotas import store as qstore
894
+
895
+ data = qstore.read_snapshot()
896
+ if isinstance(data, Exception):
897
+ return None
898
+ elif kind == "reservations":
899
+ from maproom.reservations import store as rstore
900
+
901
+ data = rstore.read_snapshot()
902
+ if isinstance(data, Exception):
903
+ return None
904
+ elif kind == "savings_plans":
905
+ from maproom.saving_plans import store as sstore
906
+
907
+ data = sstore.read_snapshot()
908
+ if isinstance(data, Exception):
909
+ return None
910
+ else:
911
+ return None
912
+ if not isinstance(data, dict):
913
+ return None
914
+ out = dict(data)
915
+ return out
916
+
917
+
918
+ def _read_show_records(kind: str) -> tuple[list[dict[str, Any]], dict[str, Any], str | None]:
919
+ data = _snapshot_data_for_kind(
920
+ "quotas" if kind == "quotas" else ("reservations" if kind == "reservations" else "savings_plans")
921
+ )
922
+ if data is None:
923
+ return [], {}, None
924
+ records = [r for r in data.get("records", []) if isinstance(r, dict)]
925
+ meta = {
926
+ "snapshot_path": str(data.get("_path") or ""),
927
+ "record_count": len(records),
928
+ "loaded_as_of": data.get("loaded_as_of"),
929
+ "cloud": data.get("cloud"),
930
+ "account_id": data.get("account_id"),
931
+ "account_alias": data.get("account_alias"),
932
+ "region": data.get("region"),
933
+ }
934
+ return records, meta, None
935
+
936
+
937
+ def _format_show_record_lines(kind: str, records: list[dict[str, Any]]) -> list[str]:
938
+ lines: list[str] = []
939
+ if kind == "quotas":
940
+ for row in records:
941
+ code = row.get("quota_code") or row.get("quota_name") or "quota"
942
+ lines.append(f" {code} ({row.get('region', '?')})")
943
+ elif kind == "reservations":
944
+ for row in records:
945
+ lines.append(
946
+ f" {row.get('instance_type', '?')} x {row.get('quantity', '?')} "
947
+ f"{row.get('state', '?')} ({row.get('region', '?')})"
948
+ )
949
+ else:
950
+ for row in records:
951
+ lines.append(f" {row.get('savings_plan_type', 'plan')} ({row.get('state', '?')})")
952
+ return lines
953
+
954
+
955
+ def _fail(message: str, *, as_json: bool, invoked: str, code: str = "runtime") -> int:
956
+ if as_json:
957
+ return print_error_envelope(code, message, invoked=invoked)
958
+ print(f"error: {message}", file=sys.stderr)
959
+ if code == "usage":
960
+ return USAGE
961
+ return RUNTIME