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,489 @@
1
+ """Subprocess runner for aws / az.
2
+
3
+ Forked from cloud-cli-fixture-generator's runner so maproom-cli installs and
4
+ runs without that package. The two copies may diverge; this module is the
5
+ one maproom calls.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import errno
11
+ import json
12
+ import os
13
+ import platform
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import time
19
+ import uuid
20
+ from dataclasses import dataclass, field
21
+ from datetime import datetime, timezone
22
+ from pathlib import Path
23
+ from typing import Any, Literal, Mapping, MutableMapping, Sequence
24
+
25
+ from maproom.cliio.registry import REGISTRY as PROVISIONED_APIS
26
+ from maproom.cliio.registry import authorize_cli_call
27
+ from maproom.paths import data_root, data_subdir, prepare_data_write
28
+ from maproom.redaction import redact_text, redact_tree
29
+
30
+ CloudName = Literal["aws", "azure"]
31
+ PaginationMode = Literal["none", "merge"]
32
+
33
+ # Floor versions: AWS CLI v2 2.15.0, Azure CLI 2.60.0.
34
+ AWS_FLOOR = (2, 15, 0)
35
+ AZURE_FLOOR = (2, 60, 0)
36
+
37
+ DEFAULT_TIMEOUT_S = 120.0
38
+
39
+ _ENV_CONTRACT_COMMON: dict[str, str] = {
40
+ "AWS_PAGER": "",
41
+ "AWS_CLI_AUTO_PROMPT": "off",
42
+ "AZURE_CORE_NO_COLOR": "1",
43
+ "AZURE_CORE_DISABLE_PROGRESS_BAR": "1",
44
+ "NO_COLOR": "1",
45
+ }
46
+
47
+ _SEMVER_RE = re.compile(
48
+ r"(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)",
49
+ )
50
+
51
+
52
+ class CliRunnerError(Exception):
53
+ """Base error for the runner."""
54
+
55
+
56
+ class CliTimeoutError(CliRunnerError):
57
+ """Subprocess exceeded the configured timeout."""
58
+
59
+
60
+ class CliExecutableNotFoundError(CliRunnerError):
61
+ """Resolved CLI binary could not be started."""
62
+
63
+ def __init__(self, cloud: CloudName, path: str) -> None:
64
+ self.cloud = cloud
65
+ self.path = path
66
+ super().__init__(f"{cloud} CLI executable not found: {path}")
67
+
68
+
69
+ class CliBelowFloorError(CliRunnerError):
70
+ """Installed CLI version is below the supported floor."""
71
+
72
+ def __init__(self, cloud: CloudName, version: str, floor: str) -> None:
73
+ self.cloud = cloud
74
+ self.version = version
75
+ self.floor = floor
76
+ super().__init__(
77
+ f"{cloud} CLI {version} is below supported floor {floor}; "
78
+ f"please upgrade and retry"
79
+ )
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class CliResult:
84
+ """Outcome of one subprocess invocation."""
85
+
86
+ argv: list[str]
87
+ exit_code: int
88
+ stdout: str
89
+ stderr: str
90
+ duration_ms: int
91
+ cloud: CloudName
92
+ cli_path: str
93
+ cli_version: str | None = None
94
+
95
+
96
+ @dataclass
97
+ class Runner:
98
+ """Resolve binaries, apply the env contract, optionally record calls."""
99
+
100
+ default_timeout_s: float = DEFAULT_TIMEOUT_S
101
+ aws_floor: tuple[int, int, int] = AWS_FLOOR
102
+ azure_floor: tuple[int, int, int] = AZURE_FLOOR
103
+ # Injected for tests.
104
+ env: MutableMapping[str, str] | None = None
105
+ _version_cache: dict[CloudName, str | None] = field(default_factory=dict)
106
+ _record_seq: int = 0
107
+
108
+ def probe_copy(self) -> Runner:
109
+ """Return a sibling runner for parallel version probes."""
110
+ probe = Runner(
111
+ default_timeout_s=self.default_timeout_s,
112
+ aws_floor=self.aws_floor,
113
+ azure_floor=self.azure_floor,
114
+ env=dict(self.env) if self.env is not None else None,
115
+ )
116
+ probe._version_cache.update(self._version_cache)
117
+ return probe
118
+
119
+ def _environ(self) -> MutableMapping[str, str]:
120
+ return self.env if self.env is not None else os.environ
121
+
122
+ # --- resolution ---------------------------------------------------------
123
+
124
+ def resolve_binary(self, cloud: CloudName) -> str:
125
+ environ = self._environ()
126
+ if cloud == "aws":
127
+ for key in ("MAPROOM_AWS_CLI", "CLOUD_CLI_AWS"):
128
+ val = environ.get(key)
129
+ if val:
130
+ return val
131
+ found = shutil.which("aws", path=environ.get("PATH"))
132
+ return found or "aws"
133
+ for key in ("MAPROOM_AZ_CLI", "CLOUD_CLI_AZ"):
134
+ val = environ.get(key)
135
+ if val:
136
+ return val
137
+ found = shutil.which("az", path=environ.get("PATH"))
138
+ return found or "az"
139
+
140
+ def resolve_record_dir(self) -> Path:
141
+ """Return the request-ledger directory, always under the data root.
142
+
143
+ ``MAPROOM_CLI_RECORD_DIR`` and ``CLOUD_CLI_RECORD_DIR`` select a
144
+ directory only when that path is inside ``data_root()``. Any other
145
+ value is ignored and the ledger stays at ``request_ledger``.
146
+ """
147
+ default = data_subdir("request_ledger")
148
+ root = data_root().resolve()
149
+ environ = self._environ()
150
+ for key in ("MAPROOM_CLI_RECORD_DIR", "CLOUD_CLI_RECORD_DIR"):
151
+ val = environ.get(key)
152
+ if not val:
153
+ continue
154
+ try:
155
+ candidate = Path(val).resolve()
156
+ except OSError:
157
+ return default
158
+ if candidate.is_relative_to(root):
159
+ return candidate
160
+ return default
161
+ return default
162
+
163
+ # --- argv helpers -------------------------------------------------------
164
+
165
+ @staticmethod
166
+ def with_json_output(cloud: CloudName, argv: Sequence[str]) -> list[str]:
167
+ """Ensure machine-readable flags are present (idempotent)."""
168
+ out = list(argv)
169
+ if "--output" not in out and "-o" not in out:
170
+ out.extend(["--output", "json"])
171
+ if cloud == "azure" and "--only-show-errors" not in out:
172
+ out.append("--only-show-errors")
173
+ return out
174
+
175
+ @staticmethod
176
+ def apply_pagination(
177
+ cloud: CloudName,
178
+ argv: Sequence[str],
179
+ pagination: PaginationMode,
180
+ ) -> list[str]:
181
+ out = list(argv)
182
+ if pagination == "none" and cloud == "aws" and "--no-paginate" not in out:
183
+ out.append("--no-paginate")
184
+ # Azure has no universal --no-paginate; callers pass explicit paging args.
185
+ return out
186
+
187
+ # --- env contract -------------------------------------------------------
188
+
189
+ def build_env(
190
+ self,
191
+ cloud: CloudName,
192
+ *,
193
+ extra: Mapping[str, str] | None = None,
194
+ ) -> dict[str, str]:
195
+ merged = dict(self._environ())
196
+ merged.update(_ENV_CONTRACT_COMMON)
197
+ if cloud == "azure":
198
+ merged["PYTHONIOENCODING"] = "utf-8"
199
+ if extra:
200
+ for key, value in extra.items():
201
+ # Empty string means unset (clears AWS_PROFILE etc.).
202
+ if value == "":
203
+ merged.pop(key, None)
204
+ else:
205
+ merged[key] = value
206
+ return merged
207
+
208
+ def env_deltas(
209
+ self,
210
+ cloud: CloudName,
211
+ *,
212
+ extra: Mapping[str, str] | None = None,
213
+ ) -> dict[str, str]:
214
+ """Env keys the runner forces relative to the base environ."""
215
+ base = dict(self._environ())
216
+ full = self.build_env(cloud, extra=extra)
217
+ deltas = {k: v for k, v in full.items() if base.get(k) != v}
218
+ if extra:
219
+ for key, value in extra.items():
220
+ if value == "" and key in base:
221
+ deltas[key] = "" # record cleared keys
222
+ return deltas
223
+
224
+ # --- version detection --------------------------------------------------
225
+
226
+ def detect_version(
227
+ self,
228
+ cloud: CloudName,
229
+ *,
230
+ force: bool = False,
231
+ check_floor: bool = True,
232
+ ) -> str | None:
233
+ if not force and cloud in self._version_cache:
234
+ return self._version_cache[cloud]
235
+
236
+ try:
237
+ if cloud == "aws":
238
+ result = self.run(
239
+ "aws",
240
+ ["--version"],
241
+ api_id="aws_cli_version",
242
+ timeout_s=30.0,
243
+ record=False,
244
+ )
245
+ else:
246
+ result = self.run(
247
+ "azure",
248
+ ["version", "--output", "json", "--only-show-errors"],
249
+ api_id="azure_cli_version",
250
+ timeout_s=30.0,
251
+ record=False,
252
+ )
253
+ except CliRunnerError:
254
+ self._version_cache[cloud] = None
255
+ return None
256
+
257
+ version = self._parse_version(cloud, result.stdout, result.stderr)
258
+ self._version_cache[cloud] = version
259
+ if version is None:
260
+ # Unparseable: warn and proceed (forward-compat posture).
261
+ print(
262
+ f"warning: could not parse {cloud} CLI version; assuming newer-than-known",
263
+ file=sys.stderr,
264
+ )
265
+ return None
266
+ if check_floor and self._is_below_floor(cloud, version):
267
+ floor = self.aws_floor if cloud == "aws" else self.azure_floor
268
+ floor_s = ".".join(str(p) for p in floor)
269
+ raise CliBelowFloorError(cloud, version, floor_s)
270
+ return version
271
+
272
+ @staticmethod
273
+ def _parse_version(cloud: CloudName, stdout: str, stderr: str) -> str | None:
274
+ text = stdout or stderr
275
+ if cloud == "azure":
276
+ try:
277
+ data = json.loads(stdout)
278
+ azure_cli = data.get("azure-cli") or data.get("azure-cli-core")
279
+ if isinstance(azure_cli, str):
280
+ m = _SEMVER_RE.search(azure_cli)
281
+ if m:
282
+ return f"{m.group('major')}.{m.group('minor')}.{m.group('patch')}"
283
+ except json.JSONDecodeError:
284
+ pass
285
+ m = _SEMVER_RE.search(text)
286
+ if not m:
287
+ return None
288
+ return f"{m.group('major')}.{m.group('minor')}.{m.group('patch')}"
289
+
290
+ def _is_below_floor(self, cloud: CloudName, version: str) -> bool:
291
+ parts = tuple(int(p) for p in version.split("."))
292
+ floor = self.aws_floor if cloud == "aws" else self.azure_floor
293
+ return parts < floor
294
+
295
+ # --- run ----------------------------------------------------------------
296
+
297
+ def run(
298
+ self,
299
+ cloud: CloudName,
300
+ argv: Sequence[str],
301
+ *,
302
+ api_id: str,
303
+ timeout_s: float | None = None,
304
+ extra_env: Mapping[str, str] | None = None,
305
+ pagination: PaginationMode | None = None,
306
+ ensure_json: bool = False,
307
+ record: bool = True,
308
+ state_id: str | None = None,
309
+ write_token: str | None = None,
310
+ ) -> CliResult:
311
+ """Run a registered ``argv`` (without the binary) against the resolved CLI.
312
+
313
+ ``api_id`` must name an entry in ``maproom.cliio.registry``. Unregistered
314
+ commands, cloud mismatches, and writes without a consent-issued token
315
+ raise ``UnregisteredApiError`` before any subprocess starts.
316
+ """
317
+ authorize_cli_call(cloud, argv, api_id, write_token=write_token)
318
+ binary = self.resolve_binary(cloud)
319
+ args = list(argv)
320
+ if ensure_json:
321
+ args = self.with_json_output(cloud, args)
322
+ if pagination is not None:
323
+ args = self.apply_pagination(cloud, args, pagination)
324
+ full_argv = [binary, *args]
325
+ version = self._version_cache.get(cloud)
326
+ return self._spawn(
327
+ cloud,
328
+ full_argv,
329
+ timeout_s=timeout_s if timeout_s is not None else self.default_timeout_s,
330
+ extra_env=extra_env,
331
+ record=record,
332
+ api_id=api_id,
333
+ state_id=state_id,
334
+ cli_version=version,
335
+ )
336
+
337
+ def _spawn(
338
+ self,
339
+ cloud: CloudName,
340
+ full_argv: Sequence[str],
341
+ *,
342
+ timeout_s: float,
343
+ extra_env: Mapping[str, str] | None = None,
344
+ record: bool,
345
+ api_id: str | None = None,
346
+ state_id: str | None = None,
347
+ cli_version: str | None = None,
348
+ capture_meta: bool = True,
349
+ ) -> CliResult:
350
+ env = self.build_env(cloud, extra=extra_env)
351
+ deltas = self.env_deltas(cloud, extra=extra_env)
352
+ started = time.perf_counter()
353
+ argv_list = list(full_argv)
354
+ # Windows: .cmd / .bat (including real az.cmd) need cmd.exe /c.
355
+ if os.name == "nt" and argv_list:
356
+ first = str(argv_list[0]).lower()
357
+ if first.endswith(".cmd") or first.endswith(".bat"):
358
+ argv_list = ["cmd.exe", "/c", *argv_list]
359
+ try:
360
+ completed = subprocess.run(
361
+ argv_list,
362
+ input=b"", # stdin closed / empty
363
+ capture_output=True,
364
+ timeout=timeout_s,
365
+ env=env,
366
+ check=False,
367
+ )
368
+ except subprocess.TimeoutExpired as exc:
369
+ raise CliTimeoutError(
370
+ f"{cloud} CLI timed out after {timeout_s}s: {full_argv!r}"
371
+ ) from exc
372
+ except FileNotFoundError as exc:
373
+ raise CliExecutableNotFoundError(cloud, str(full_argv[0])) from exc
374
+ except OSError as exc:
375
+ if exc.errno in (errno.ENOENT, errno.ENOEXEC) or getattr(exc, "winerror", None) == 2:
376
+ raise CliExecutableNotFoundError(cloud, str(full_argv[0])) from exc
377
+ raise
378
+
379
+ duration_ms = int((time.perf_counter() - started) * 1000)
380
+ stdout = redact_text(completed.stdout.decode("utf-8", errors="replace"))
381
+ stderr = redact_text(completed.stderr.decode("utf-8", errors="replace"))
382
+ result = CliResult(
383
+ argv=list(full_argv),
384
+ exit_code=int(completed.returncode),
385
+ stdout=stdout,
386
+ stderr=stderr,
387
+ duration_ms=duration_ms,
388
+ cloud=cloud,
389
+ cli_path=str(full_argv[0]),
390
+ cli_version=cli_version,
391
+ )
392
+
393
+ if record and capture_meta:
394
+ record_dir = self.resolve_record_dir()
395
+ if record_dir is not None:
396
+ self._write_recording(
397
+ record_dir,
398
+ cloud=cloud,
399
+ result=result,
400
+ env_overrides=deltas,
401
+ api_id=api_id,
402
+ state_id=state_id,
403
+ )
404
+ return result
405
+
406
+ def _write_recording(
407
+ self,
408
+ record_dir: Path,
409
+ *,
410
+ cloud: CloudName,
411
+ result: CliResult,
412
+ env_overrides: Mapping[str, str],
413
+ api_id: str | None,
414
+ state_id: str | None,
415
+ ) -> None:
416
+ prepare_data_write()
417
+ record_dir.mkdir(parents=True, exist_ok=True)
418
+ self._record_seq += 1
419
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
420
+ token = f"{stamp}_{self._record_seq:04d}_{uuid.uuid4().hex[:8]}"
421
+ req_path = record_dir / f"{token}.request.json"
422
+ resp_path = record_dir / f"{token}.response.json"
423
+
424
+ stdout_json: Any = None
425
+ stdout_field = result.stdout
426
+ if result.stdout.strip():
427
+ try:
428
+ stdout_json = json.loads(result.stdout)
429
+ except json.JSONDecodeError:
430
+ stdout_field = redact_text(result.stdout)
431
+ else:
432
+ stdout_json = redact_tree(stdout_json)
433
+ stdout_field = json.dumps(stdout_json, ensure_ascii=False)
434
+
435
+ request_doc = redact_tree(
436
+ {
437
+ "api_id": api_id,
438
+ "state_id": state_id,
439
+ "argv": result.argv[1:], # without binary, matching fixture layout
440
+ "cli": {
441
+ "name": "aws" if cloud == "aws" else "az",
442
+ "version": result.cli_version,
443
+ "python": platform.python_version(),
444
+ "os": platform.system().lower(),
445
+ "path": result.cli_path,
446
+ },
447
+ "env_overrides": dict(env_overrides),
448
+ "captured_at": datetime.now(timezone.utc)
449
+ .isoformat()
450
+ .replace("+00:00", "Z"),
451
+ }
452
+ )
453
+ response_doc = redact_tree(
454
+ {
455
+ "exit_code": result.exit_code,
456
+ "duration_ms": result.duration_ms,
457
+ "stdout": stdout_field,
458
+ "stdout_json": stdout_json,
459
+ "stderr": result.stderr,
460
+ }
461
+ )
462
+ req_path.write_text(json.dumps(request_doc, indent=2) + "\n", encoding="utf-8")
463
+ resp_path.write_text(
464
+ json.dumps(response_doc, indent=2) + "\n", encoding="utf-8"
465
+ )
466
+
467
+
468
+ # Module-level default instance for simple callers.
469
+ _default_runner = Runner()
470
+
471
+
472
+ def resolve_binary(cloud: CloudName) -> str:
473
+ return _default_runner.resolve_binary(cloud)
474
+
475
+
476
+ def resolve_record_dir() -> Path:
477
+ return _default_runner.resolve_record_dir()
478
+
479
+
480
+ def run(
481
+ cloud: CloudName,
482
+ argv: Sequence[str],
483
+ **kwargs: Any,
484
+ ) -> CliResult:
485
+ return _default_runner.run(cloud, argv, **kwargs)
486
+
487
+
488
+ def detect_version(cloud: CloudName, **kwargs: Any) -> str | None:
489
+ return _default_runner.detect_version(cloud, **kwargs)
@@ -0,0 +1,33 @@
1
+ """Cloud-read and service-upload consent gates and storage helpers."""
2
+
3
+ from maproom.consent.gate import CloudReadGateOutcome, require_cloud_read_consent
4
+ from maproom.consent.policy import ManagedPolicyEvaluator, default_policy_evaluator
5
+ from maproom.consent.prompt import CLOUD_READ_PROMPT, NON_INTERACTIVE_PROVENANCE, cloud_read_prompt
6
+ from maproom.consent.service_upload_gate import (
7
+ ServiceUploadGateOutcome,
8
+ require_service_upload_consent,
9
+ )
10
+ from maproom.consent.service_upload_prompt import (
11
+ ENABLE_UPLOADS_HINT,
12
+ LOCAL_ASSESSMENT_WARNING,
13
+ SERVICE_UPLOAD_NON_INTERACTIVE_PROVENANCE,
14
+ service_upload_prompt,
15
+ )
16
+ from maproom.consent.storage import consent_storage_available
17
+
18
+ __all__ = [
19
+ "CLOUD_READ_PROMPT",
20
+ "cloud_read_prompt",
21
+ "CloudReadGateOutcome",
22
+ "ENABLE_UPLOADS_HINT",
23
+ "LOCAL_ASSESSMENT_WARNING",
24
+ "ManagedPolicyEvaluator",
25
+ "NON_INTERACTIVE_PROVENANCE",
26
+ "SERVICE_UPLOAD_NON_INTERACTIVE_PROVENANCE",
27
+ "ServiceUploadGateOutcome",
28
+ "consent_storage_available",
29
+ "default_policy_evaluator",
30
+ "require_cloud_read_consent",
31
+ "require_service_upload_consent",
32
+ "service_upload_prompt",
33
+ ]