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
maproom/aws_region.py ADDED
@@ -0,0 +1,78 @@
1
+ """Resolve the active AWS CLI default region from local configuration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import configparser
6
+ import os
7
+ from pathlib import Path
8
+
9
+
10
+ def _aws_config_path() -> Path | None:
11
+ explicit = os.environ.get("AWS_CONFIG_FILE")
12
+ if explicit:
13
+ return Path(explicit)
14
+ home = os.environ.get("HOME") or os.environ.get("USERPROFILE")
15
+ if not home:
16
+ return None
17
+ return Path(home) / ".aws" / "config"
18
+
19
+
20
+ def resolve_aws_profile_name() -> str:
21
+ """Return the AWS CLI profile name implied by the environment (default ``default``)."""
22
+ raw = os.environ.get("AWS_PROFILE", "").strip()
23
+ if raw:
24
+ return raw
25
+ return "default"
26
+
27
+
28
+ def aws_login_remediation() -> str:
29
+ profile = resolve_aws_profile_name()
30
+ return f"Run 'aws login' or configure profile '{profile}'"
31
+
32
+
33
+ def resolve_default_aws_region() -> str | None:
34
+ """Return the default region from the active profile in local AWS config."""
35
+ path = _aws_config_path()
36
+ if path is None or not path.is_file():
37
+ return None
38
+
39
+ profile = resolve_aws_profile_name()
40
+ section = profile if profile == "default" else f"profile {profile}"
41
+ parser = configparser.ConfigParser()
42
+ parser.read(path, encoding="utf-8")
43
+ if section not in parser:
44
+ return None
45
+ value = (parser[section].get("region") or "").strip()
46
+ return value.lower() if value else None
47
+
48
+
49
+ def _region_from_environ() -> str | None:
50
+ """Region the AWS CLI would use from the process environment."""
51
+ for key in ("AWS_REGION", "AWS_DEFAULT_REGION"):
52
+ value = os.environ.get(key, "").strip()
53
+ if value:
54
+ return value.lower()
55
+ return None
56
+
57
+
58
+ def resolve_current_aws_region(runner: object | None = None) -> str | None:
59
+ """Return the region an AWS CLI command would use when ``--region`` is omitted.
60
+
61
+ Environment variables win, matching the CLI. Otherwise this asks
62
+ ``aws configure get region``, then the local config file.
63
+ """
64
+ from_env = _region_from_environ()
65
+ if from_env:
66
+ return from_env
67
+ if runner is not None:
68
+ result = runner.run( # type: ignore[attr-defined]
69
+ "aws",
70
+ ["configure", "get", "region"],
71
+ record=False,
72
+ api_id="aws_configure_get_region",
73
+ )
74
+ if int(getattr(result, "exit_code", 1)) == 0:
75
+ text = (getattr(result, "stdout", "") or "").strip().lower()
76
+ if text:
77
+ return text
78
+ return resolve_default_aws_region()
@@ -0,0 +1 @@
1
+ """Local reservation, quota, and instance cache commands."""
@@ -0,0 +1,372 @@
1
+ """Local instance cache: list it, or clear all or one cloud."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import shutil
7
+ from dataclasses import dataclass
8
+ from fnmatch import fnmatch
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from maproom.cache.instances import (
13
+ _LEGACY_FILENAME,
14
+ _account_matches,
15
+ _legacy_region_dir,
16
+ _resolve_account_id,
17
+ instances_root,
18
+ )
19
+ from maproom.inventory.accounts import parse_account_folder
20
+ from maproom.paths import data_root
21
+ from maproom.quotas.store import snapshot_root, write_snapshot as write_quota_snapshot
22
+ from maproom.reservations.store import inventory_root, write_snapshot as write_reservation_snapshot
23
+
24
+ _COLLECTIONS: tuple[tuple[str, str], ...] = (
25
+ ("instances", _LEGACY_FILENAME),
26
+ )
27
+
28
+
29
+ class CachePatternError(Exception):
30
+ """The clear pattern is not a cache wildcard."""
31
+
32
+ def __init__(self, message: str) -> None:
33
+ self.message = message
34
+ super().__init__(message)
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class CacheEntry:
39
+ kind: str
40
+ path: Path
41
+ folder: str | None
42
+ cloud: str | None
43
+ account_id: str | None
44
+ region: str | None
45
+ record_count: int | None
46
+ loaded_as_of: str | None
47
+ error: str | None = None
48
+
49
+
50
+ def collection_root(kind: str) -> Path:
51
+ if kind == "reservations":
52
+ return inventory_root()
53
+ if kind == "quotas":
54
+ return snapshot_root()
55
+ if kind == "instances":
56
+ return instances_root()
57
+ raise CachePatternError(f"unknown cache collection: {kind}")
58
+
59
+
60
+ def list_cache(*, runner: Any | None = None) -> list[CacheEntry]:
61
+ """Every instance snapshot, including a legacy file at the collection root."""
62
+ entries: list[CacheEntry] = []
63
+ for kind, filename in _COLLECTIONS:
64
+ root = collection_root(kind)
65
+ if not root.is_dir():
66
+ continue
67
+ legacy = root / filename
68
+ if legacy.is_file():
69
+ entry = _entry_for_file(kind, legacy, folder=None, runner=runner)
70
+ if entry is not None:
71
+ entries.append(entry)
72
+ for child in sorted(root.iterdir(), key=lambda path: path.name):
73
+ if not child.is_dir():
74
+ continue
75
+ parsed = parse_account_folder(child.name)
76
+ if kind == "instances" and parsed is not None:
77
+ cloud, account_id = parsed
78
+ region_files = sorted(child.glob("instances-*.json"))
79
+ if region_files:
80
+ for snapshot in region_files:
81
+ entry = _entry_for_file(kind, snapshot, folder=child.name, runner=runner)
82
+ if entry is not None:
83
+ entries.append(entry)
84
+ continue
85
+ legacy = child / filename
86
+ if legacy.is_file():
87
+ entry = _entry_for_file(kind, legacy, folder=child.name, runner=runner)
88
+ if entry is not None:
89
+ entries.append(entry)
90
+ continue
91
+ entries.append(
92
+ CacheEntry(
93
+ kind=kind,
94
+ path=child,
95
+ folder=child.name,
96
+ cloud=cloud,
97
+ account_id=account_id,
98
+ region=None,
99
+ record_count=None,
100
+ loaded_as_of=None,
101
+ error="folder has no instance snapshot file",
102
+ )
103
+ )
104
+ continue
105
+ if kind == "instances" and _legacy_region_dir(child.name, "aws"):
106
+ snapshot = child / filename
107
+ if snapshot.is_file():
108
+ entry = _entry_for_file(kind, snapshot, folder=child.name, runner=runner)
109
+ if entry is not None:
110
+ entries.append(entry)
111
+ continue
112
+ if kind == "instances" and _legacy_region_dir(child.name, "azure"):
113
+ snapshot = child / filename
114
+ if snapshot.is_file():
115
+ entry = _entry_for_file(kind, snapshot, folder=child.name, runner=runner)
116
+ if entry is not None:
117
+ entries.append(entry)
118
+ continue
119
+ snapshot = child / filename
120
+ if snapshot.is_file():
121
+ entry = _entry_for_file(kind, snapshot, folder=child.name, runner=runner)
122
+ if entry is not None:
123
+ entries.append(entry)
124
+ else:
125
+ cloud, account_id = parsed if parsed else (None, None)
126
+ entries.append(
127
+ CacheEntry(
128
+ kind=kind,
129
+ path=child,
130
+ folder=child.name,
131
+ cloud=cloud,
132
+ account_id=account_id,
133
+ region=None,
134
+ record_count=None,
135
+ loaded_as_of=None,
136
+ error="folder has no snapshot file",
137
+ )
138
+ )
139
+ return entries
140
+
141
+
142
+ def normalize_pattern(pattern: str | None) -> str:
143
+ """``None``, ``*``, and ``all`` clear everything. ``aws`` / ``aws*`` and ``azure`` / ``azure*`` select a cloud."""
144
+ text = (pattern or "*").strip().lower()
145
+ if not text:
146
+ text = "*"
147
+ if any(mark in text for mark in ("/", "\\", "..")):
148
+ raise CachePatternError(
149
+ "cache pattern must be *, aws*, or azure*. It cannot be a path."
150
+ )
151
+ if text in {"*", "all"}:
152
+ return "*"
153
+ if text in {"aws", "aws*"}:
154
+ return "aws*"
155
+ if text in {"azure", "azure*"}:
156
+ return "azure*"
157
+ if "*" not in text and "?" not in text:
158
+ raise CachePatternError(
159
+ f'unknown cache pattern "{pattern}". Use *, aws*, or azure*.'
160
+ )
161
+ return text
162
+
163
+
164
+ def matching_entries(pattern: str | None) -> list[CacheEntry]:
165
+ """Instance cache rows that ``clear_cache`` would remove."""
166
+ selected = normalize_pattern(pattern)
167
+ return [entry for entry in list_cache(runner=None) if _entry_matches_pattern(entry, selected)]
168
+
169
+
170
+ def _entry_matches_pattern(entry: CacheEntry, pattern: str) -> bool:
171
+ if entry.kind != "instances":
172
+ return False
173
+ if pattern == "*":
174
+ return True
175
+ if pattern == "aws*":
176
+ return entry.cloud == "aws"
177
+ if pattern == "azure*":
178
+ return entry.cloud == "azure"
179
+ folder = (entry.folder or entry.path.name).lower()
180
+ return fnmatch(folder, pattern)
181
+
182
+
183
+ def clear_cache(pattern: str | None) -> list[str]:
184
+ """Remove matching cache folders and files. Returns paths relative to the data root.
185
+
186
+ Account folders are removed entirely, not only the snapshot file inside them.
187
+ """
188
+ selected = normalize_pattern(pattern)
189
+ removed: list[str] = []
190
+ root = _safe_data_root()
191
+ for kind, filename in _COLLECTIONS:
192
+ directory = collection_root(kind)
193
+ if not directory.is_dir():
194
+ continue
195
+ if selected == "*":
196
+ if directory.is_dir():
197
+ for child in list(directory.iterdir()):
198
+ if child.is_dir() and _inside(root, child):
199
+ removed.append(_relative(root, child))
200
+ elif (
201
+ child.is_file()
202
+ and child.name == filename
203
+ and _inside(root, child)
204
+ ):
205
+ removed.append(_relative(root, child))
206
+ if _inside(root, directory):
207
+ shutil.rmtree(directory)
208
+ continue
209
+ removed.extend(_clear_matching(root, directory, filename, selected))
210
+ return removed
211
+
212
+
213
+ def _clear_matching(root: Path, directory: Path, filename: str, pattern: str) -> list[str]:
214
+ removed: list[str] = []
215
+ cloud = "aws" if pattern == "aws*" else "azure" if pattern == "azure*" else None
216
+ for child in list(directory.iterdir()):
217
+ if child.is_dir() and _folder_matches(child.name, pattern):
218
+ if _inside(root, child):
219
+ shutil.rmtree(child)
220
+ removed.append(_relative(root, child))
221
+ continue
222
+ if child.is_file() and child.name == filename and cloud is not None:
223
+ changed = _drop_cloud_from_legacy(child, cloud)
224
+ if changed:
225
+ removed.append(_relative(root, child))
226
+ return removed
227
+
228
+
229
+ def _folder_matches(name: str, pattern: str) -> bool:
230
+ if pattern in {"aws*", "azure*"}:
231
+ cloud = pattern[:-1]
232
+ parsed = parse_account_folder(name)
233
+ if parsed is not None:
234
+ return parsed[0] == cloud
235
+ return name.lower().startswith(f"{cloud}-")
236
+ return fnmatch(name.lower(), pattern)
237
+
238
+
239
+ def _drop_cloud_from_legacy(path: Path, cloud: str) -> bool:
240
+ try:
241
+ data = json.loads(path.read_text(encoding="utf-8"))
242
+ except (OSError, json.JSONDecodeError):
243
+ return False
244
+ if not isinstance(data, dict):
245
+ return False
246
+ records = data.get("records")
247
+ if not isinstance(records, list):
248
+ path.unlink(missing_ok=True)
249
+ return True
250
+ kept = [row for row in records if not isinstance(row, dict) or _record_cloud(row) != cloud]
251
+ if len(kept) == len(records):
252
+ return False
253
+ if not kept:
254
+ path.unlink(missing_ok=True)
255
+ return True
256
+ data["records"] = kept
257
+ data["record_count"] = len(kept)
258
+ if path.parent.name == "reservations":
259
+ write_reservation_snapshot(data)
260
+ else:
261
+ write_quota_snapshot(data)
262
+ return True
263
+
264
+
265
+ def _instance_snapshot_visible(data: dict[str, Any], runner: Any | None) -> bool:
266
+ if runner is None:
267
+ return True
268
+ cloud = str(data.get("cloud") or "aws").strip().lower()
269
+ account_id = _resolve_account_id(cloud, runner)
270
+ if account_id is None:
271
+ return False
272
+ return _account_matches(data, account_id)
273
+
274
+
275
+ def _entry_for_file(
276
+ kind: str,
277
+ path: Path,
278
+ *,
279
+ folder: str | None,
280
+ runner: Any | None = None,
281
+ ) -> CacheEntry | None:
282
+ parsed = parse_account_folder(folder) if folder else None
283
+ cloud, account_id = parsed if parsed else (None, None)
284
+ try:
285
+ data = json.loads(path.read_text(encoding="utf-8"))
286
+ except (OSError, json.JSONDecodeError) as exc:
287
+ return CacheEntry(
288
+ kind=kind,
289
+ path=path,
290
+ folder=folder,
291
+ cloud=cloud,
292
+ account_id=account_id,
293
+ region=_region_from_path(path),
294
+ record_count=None,
295
+ loaded_as_of=None,
296
+ error=str(exc),
297
+ )
298
+ if not isinstance(data, dict):
299
+ return CacheEntry(
300
+ kind=kind,
301
+ path=path,
302
+ folder=folder,
303
+ cloud=cloud,
304
+ account_id=account_id,
305
+ region=_region_from_path(path),
306
+ record_count=None,
307
+ loaded_as_of=None,
308
+ error="snapshot is not a JSON object",
309
+ )
310
+ if kind == "instances" and not _instance_snapshot_visible(data, runner):
311
+ return None
312
+ records = data.get("records")
313
+ count = data.get("record_count")
314
+ if not isinstance(count, int):
315
+ count = len(records) if isinstance(records, list) else None
316
+ loaded = str(data.get("loaded_as_of") or "") or None
317
+ file_cloud = cloud
318
+ if file_cloud is None and isinstance(records, list) and records:
319
+ clouds = {_record_cloud(row) for row in records if isinstance(row, dict)}
320
+ if len(clouds) == 1:
321
+ file_cloud = clouds.pop()
322
+ region = str(data.get("region") or "") or None
323
+ if not region:
324
+ region = _region_from_path(path)
325
+ return CacheEntry(
326
+ kind=kind,
327
+ path=path,
328
+ folder=folder,
329
+ cloud=file_cloud or (str(data.get("cloud") or "") or None),
330
+ account_id=account_id
331
+ or (str(data.get("account_id") or "") or None),
332
+ region=region,
333
+ record_count=count,
334
+ loaded_as_of=loaded,
335
+ )
336
+
337
+
338
+ def _region_from_path(path: Path) -> str | None:
339
+ name = path.name
340
+ if name.startswith("instances-") and name.endswith(".json"):
341
+ return name[len("instances-") : -len(".json")]
342
+ return None
343
+
344
+
345
+ def _record_cloud(record: dict[str, Any]) -> str:
346
+ if str(record.get("kind") or "") in {"azure_reserved_vm", "azure_compute_usage"}:
347
+ return "azure"
348
+ if str(record.get("cloud") or "") == "azure":
349
+ return "azure"
350
+ return "aws"
351
+
352
+
353
+ def _safe_data_root() -> Path:
354
+ root = data_root()
355
+ if root.name != "maproom":
356
+ raise OSError(f"refusing to clear unexpected data root: {root}")
357
+ return root
358
+
359
+
360
+ def _inside(root: Path, path: Path) -> bool:
361
+ try:
362
+ path.resolve().relative_to(root.resolve())
363
+ except ValueError:
364
+ return False
365
+ return True
366
+
367
+
368
+ def _relative(root: Path, path: Path) -> str:
369
+ try:
370
+ return path.resolve().relative_to(root.resolve()).as_posix()
371
+ except ValueError:
372
+ return path.as_posix()
@@ -0,0 +1,215 @@
1
+ """CLI handlers for ``maproom cache``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from typing import Any
8
+
9
+ from maproom.cache.catalog import (
10
+ CacheEntry,
11
+ CachePatternError,
12
+ clear_cache,
13
+ list_cache,
14
+ matching_entries,
15
+ normalize_pattern,
16
+ )
17
+ from maproom.cliio.runner import CliRunnerError, Runner
18
+ from maproom.mock_environment import MockEnvironmentError, command_runner
19
+ from maproom.consent.stdin import stdin_allows_prompt
20
+ from maproom.exitcodes import RUNTIME, SUCCESS, USAGE
21
+ from maproom.output.json_envelope import build_document, command_metadata, print_error_envelope, print_json
22
+ from maproom.plan.tty import PromptClosed, confirm_yes_no
23
+
24
+
25
+ def cmd_cache(args: argparse.Namespace) -> int:
26
+ command = getattr(args, "cache_command", None)
27
+ if command == "clear":
28
+ return cmd_cache_clear(args)
29
+ return cmd_cache_show(args)
30
+
31
+
32
+ def cmd_cache_show(args: argparse.Namespace) -> int:
33
+ as_json = bool(getattr(args, "json", False))
34
+ runner = command_runner()
35
+ try:
36
+ entries = list_cache(runner=runner)
37
+ except MockEnvironmentError as exc:
38
+ return _fail(str(exc), as_json=as_json, invoked="cache")
39
+ except (OSError, CliRunnerError) as exc:
40
+ if isinstance(exc, CliRunnerError):
41
+ message = (
42
+ "cannot tell which AWS account is signed in: AWS CLI not found. "
43
+ "Install the AWS CLI, then rerun maproom cache show."
44
+ )
45
+ else:
46
+ message = str(exc)
47
+ return _fail(message, as_json=as_json, invoked="cache")
48
+ if as_json:
49
+ print_json(
50
+ build_document(
51
+ schema_type="cache",
52
+ schema_id="maproom.cache",
53
+ metadata=command_metadata("cache"),
54
+ payload={"entries": [_entry_json(entry) for entry in entries]},
55
+ )
56
+ )
57
+ return SUCCESS
58
+ if not entries:
59
+ print("No cached instances.")
60
+ return SUCCESS
61
+ print("Cached instances")
62
+ print()
63
+ for entry in entries:
64
+ print(f" {_entry_line(entry)}")
65
+ return SUCCESS
66
+
67
+
68
+ def cmd_cache_clear(args: argparse.Namespace) -> int:
69
+ as_json = bool(getattr(args, "json", False))
70
+ pattern = getattr(args, "pattern", None)
71
+ try:
72
+ selected = normalize_pattern(pattern)
73
+ except CachePatternError as exc:
74
+ return _fail(exc.message, as_json=as_json, invoked="cache clear", code="usage")
75
+
76
+ if not matching_entries(selected):
77
+ message = _empty_cache_message(selected)
78
+ if as_json:
79
+ print_json(
80
+ build_document(
81
+ schema_type="cache_clear",
82
+ schema_id="maproom.cache_clear",
83
+ metadata=command_metadata("cache clear"),
84
+ payload={"pattern": selected, "removed": []},
85
+ )
86
+ )
87
+ else:
88
+ print(message)
89
+ return SUCCESS
90
+
91
+ if not bool(getattr(args, "force", False)):
92
+ if not stdin_allows_prompt():
93
+ return _fail(
94
+ "confirm cache clear in a TTY or pass --force",
95
+ as_json=as_json,
96
+ invoked="cache clear",
97
+ code="usage",
98
+ )
99
+ prompt = _confirm_prompt(selected)
100
+ try:
101
+ confirmed = confirm_yes_no(prompt, default_no=True)
102
+ except PromptClosed as exc:
103
+ return _fail(exc.message, as_json=as_json, invoked="cache clear", code="usage")
104
+ if not confirmed:
105
+ if as_json:
106
+ print_json(
107
+ build_document(
108
+ schema_type="cache_clear",
109
+ schema_id="maproom.cache_clear",
110
+ metadata=command_metadata("cache clear"),
111
+ payload={"pattern": selected, "removed": []},
112
+ )
113
+ )
114
+ else:
115
+ print("Nothing deleted.")
116
+ return SUCCESS
117
+
118
+ try:
119
+ removed = clear_cache(selected)
120
+ except (CachePatternError, OSError) as exc:
121
+ message = getattr(exc, "message", None) or str(exc)
122
+ code = "usage" if isinstance(exc, CachePatternError) else "runtime"
123
+ return _fail(message, as_json=as_json, invoked="cache clear", code=code)
124
+
125
+ if as_json:
126
+ print_json(
127
+ build_document(
128
+ schema_type="cache_clear",
129
+ schema_id="maproom.cache_clear",
130
+ metadata=command_metadata("cache clear"),
131
+ payload={"pattern": selected, "removed": removed},
132
+ )
133
+ )
134
+ return SUCCESS
135
+ if not removed:
136
+ print(f"No cached instances matched {selected}.")
137
+ return SUCCESS
138
+ print(f"Removed {len(removed)} cached item(s):")
139
+ for path in removed:
140
+ print(f" {path}")
141
+ return SUCCESS
142
+
143
+
144
+ def _empty_cache_message(pattern: str) -> str:
145
+ if pattern == "aws*":
146
+ return "No cached AWS instances."
147
+ if pattern == "azure*":
148
+ return "No cached Azure instances."
149
+ return "No cached instances."
150
+
151
+
152
+ def _confirm_prompt(pattern: str) -> str:
153
+ if pattern == "*":
154
+ return (
155
+ "Delete all cached instances? "
156
+ "Quotas, reservations, savings plans, settings, and plans are kept."
157
+ )
158
+ if pattern == "aws*":
159
+ return "Delete cached AWS instances?"
160
+ if pattern == "azure*":
161
+ return "Delete cached Azure instances?"
162
+ return f"Delete cached instances matching {pattern}?"
163
+
164
+
165
+ def _entry_line(entry: CacheEntry) -> str:
166
+ if entry.error:
167
+ name = entry.folder or entry.path.name
168
+ return f"{name} unreadable ({entry.error})"
169
+ parts: list[str] = []
170
+ if entry.account_id:
171
+ parts.append(entry.account_id)
172
+ if entry.folder:
173
+ alias = entry.folder.split("-", 2)[-1] if "-" in entry.folder else ""
174
+ if alias and alias != entry.account_id:
175
+ parts[-1] = f"{entry.account_id} ({alias})"
176
+ elif entry.folder:
177
+ parts.append(entry.folder)
178
+ else:
179
+ parts.append(entry.path.name)
180
+ if entry.region:
181
+ parts.append(entry.region)
182
+ count = entry.record_count if entry.record_count is not None else "unknown"
183
+ noun = "record" if count == 1 else "records"
184
+ when = f" as of {entry.loaded_as_of}" if entry.loaded_as_of else ""
185
+ return f"{' '.join(parts)} {count} {noun}{when}"
186
+
187
+
188
+ def _entry_json(entry: CacheEntry) -> dict[str, Any]:
189
+ body: dict[str, Any] = {
190
+ "kind": entry.kind,
191
+ "path": str(entry.path),
192
+ "cloud": entry.cloud,
193
+ "account_id": entry.account_id,
194
+ "record_count": entry.record_count,
195
+ "loaded_as_of": entry.loaded_as_of,
196
+ "region": entry.region,
197
+ }
198
+ if entry.folder:
199
+ body["folder"] = entry.folder
200
+ if entry.error:
201
+ body["error"] = entry.error
202
+ return body
203
+
204
+
205
+ def _fail(message: str, *, as_json: bool, invoked: str, code: str = "runtime") -> int:
206
+ if as_json:
207
+ return print_error_envelope(code, message, invoked=invoked)
208
+ print(f"error: {message}", file=sys.stderr)
209
+ if code == "usage":
210
+ return USAGE
211
+ if code == "runtime":
212
+ return RUNTIME
213
+ from maproom.exitcodes import exit_code_for_error
214
+
215
+ return exit_code_for_error(code)