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,701 @@
1
+ """Data-driven doctor check registry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import platform
9
+ import sys
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from dataclasses import dataclass
12
+ from typing import Callable
13
+
14
+ from maproom.cliio.runner import Runner
15
+ from maproom.mock_environment.runner import MockEnvironmentRunner
16
+ from maproom.doctor.aws_session import aws_likely_has_credentials
17
+
18
+ from maproom.aws_region import aws_login_remediation
19
+ from maproom.cli_floors import AWS_CLI_INSTALL_REMEDIATION, check_aws_floor, check_az_floor
20
+ from maproom.cliio.runner import AZURE_FLOOR
21
+ from maproom.consent import consent_storage_available
22
+ from maproom.consent.prompt import snooze_block_message
23
+ from maproom.doctor.context import DoctorContext
24
+ from maproom.doctor.inventory_display import (
25
+ QUOTAS_GET_HINT,
26
+ USER_LOCAL_DATA_CLEAR_HINT,
27
+ inventory_detail_lines,
28
+ )
29
+ from maproom.errors import NotLoggedInError, MaproomParseError
30
+ from maproom.parsers import (
31
+ aws_principal_display_name,
32
+ azure_account_identity_display,
33
+ parse_sts_identity,
34
+ )
35
+ from maproom.paths import data_root, settings_read_file
36
+ from maproom.pricing import load_price_table
37
+ from maproom.quotas.status import (
38
+ doctor_quotas_message,
39
+ read_quota_state,
40
+ stale_quota_warning,
41
+ )
42
+ from maproom.reservations.status import (
43
+ doctor_reservations_message,
44
+ read_inventory_state,
45
+ stale_reservation_warning,
46
+ )
47
+ from maproom.saving_plans.status import (
48
+ doctor_saving_plans_message,
49
+ read_saving_plan_state,
50
+ stale_saving_plan_warning,
51
+ )
52
+ from maproom.settings.model import load_consent_state
53
+
54
+ MIN_PYTHON = (3, 11)
55
+
56
+ AZURE_CLI_INSTALL_REMEDIATION = (
57
+ "Install the Azure CLI (https://aka.ms/installazurecliwindows)"
58
+ )
59
+ CLOUD_READ_CONSENT_REMEDIATION = "maproom settings set cloud_read_consent true"
60
+
61
+
62
+ @dataclass
63
+ class CheckResult:
64
+ name: str
65
+ status: str
66
+ message: str | None = None
67
+ remediation: str | None = None
68
+ reason_code: str | None = None
69
+ detail_lines: tuple[str, ...] = ()
70
+ impact: str | None = None
71
+ loaded_at: str | None = None
72
+ max_age_seconds: int | None = None
73
+ price_path: str | None = None
74
+ published_at: str | None = None
75
+ row_count: int | None = None
76
+ source_kind: str | None = None
77
+
78
+
79
+ def _python_version(_ctx: DoctorContext) -> CheckResult:
80
+ current = sys.version_info[:3]
81
+ floor = ".".join(str(p) for p in MIN_PYTHON)
82
+ version = ".".join(str(p) for p in current[:3])
83
+ if current[:2] >= MIN_PYTHON[:2]:
84
+ return CheckResult(
85
+ "python_version",
86
+ "pass",
87
+ f"Python {version} >= {floor}",
88
+ )
89
+ return CheckResult(
90
+ "python_version",
91
+ "fail",
92
+ f"Python {version} below minimum {floor}",
93
+ remediation=f"Install Python {floor} or newer",
94
+ impact="MapRoom cannot run until Python meets the minimum version.",
95
+ )
96
+
97
+
98
+ def _platform_info(_ctx: DoctorContext) -> CheckResult:
99
+ return CheckResult(
100
+ "platform_info",
101
+ "pass",
102
+ f"{platform.system()} {platform.machine()}",
103
+ )
104
+
105
+
106
+ def _parent_creatable(path) -> bool:
107
+ existing = path
108
+ while not existing.exists() and existing != existing.parent:
109
+ existing = existing.parent
110
+ if not existing.exists():
111
+ return False
112
+ return os.access(existing, os.W_OK)
113
+
114
+
115
+ def _user_local_data(_ctx: DoctorContext) -> CheckResult:
116
+ try:
117
+ root = data_root()
118
+ except OSError as exc:
119
+ return CheckResult(
120
+ "user_local_data",
121
+ "fail",
122
+ str(exc),
123
+ remediation="Check HOME/APPDATA/XDG_DATA_HOME environment variables",
124
+ impact="MapRoom cannot store local data until the data directory is writable.",
125
+ )
126
+ parent = root.parent
127
+ if parent.exists() or _parent_creatable(parent):
128
+ return CheckResult(
129
+ "user_local_data",
130
+ "pass",
131
+ str(root),
132
+ detail_lines=(USER_LOCAL_DATA_CLEAR_HINT,),
133
+ )
134
+ return CheckResult(
135
+ "user_local_data",
136
+ "fail",
137
+ f"Cannot resolve data path: {root}",
138
+ remediation="Check HOME/APPDATA/XDG_DATA_HOME environment variables",
139
+ impact="MapRoom cannot store local data until the data directory is writable.",
140
+ )
141
+
142
+
143
+ def _inventory_max_age_seconds(state) -> int | None:
144
+ hours = getattr(state, "cache_max_age_hours", None)
145
+ if hours is None:
146
+ return None
147
+ return int(hours) * 3600
148
+
149
+
150
+ def _inventory_part(state, stale_fn) -> str:
151
+ if state.parse_error:
152
+ return "fail"
153
+ if not state.exists:
154
+ return "missing"
155
+ if stale_fn(state):
156
+ return "stale"
157
+ return "pass"
158
+
159
+
160
+ def _inventory(_ctx: DoctorContext) -> CheckResult:
161
+ """One check for quotas, reservations, and savings plans."""
162
+ quotas = read_quota_state()
163
+ reservations = read_inventory_state()
164
+ plans = read_saving_plan_state()
165
+ parts = (
166
+ (quotas, doctor_quotas_message(quotas), _inventory_part(quotas, stale_quota_warning)),
167
+ (
168
+ reservations,
169
+ doctor_reservations_message(reservations),
170
+ _inventory_part(reservations, stale_reservation_warning),
171
+ ),
172
+ (
173
+ plans,
174
+ doctor_saving_plans_message(plans),
175
+ _inventory_part(plans, stale_saving_plan_warning),
176
+ ),
177
+ )
178
+ details = inventory_detail_lines(quotas, reservations, plans)
179
+ kinds = {kind for _state, _message, kind in parts}
180
+ if "fail" in kinds:
181
+ message = " | ".join(message for _state, message, kind in parts if kind == "fail")
182
+ return CheckResult(
183
+ "inventory",
184
+ "fail",
185
+ message,
186
+ detail_lines=details,
187
+ impact="Inventory cannot be estimated until the snapshot is fixed.",
188
+ )
189
+ if "missing" in kinds or "stale" in kinds:
190
+ stale_states = [state for state, _message, kind in parts if kind == "stale"]
191
+ if "missing" in kinds:
192
+ reason = "no_snapshot"
193
+ impact = (
194
+ "Quota availability, reserved-instance coverage, and Savings Plans "
195
+ "estimates are unavailable."
196
+ )
197
+ loaded_at = None
198
+ max_age = None
199
+ else:
200
+ reason = "stale"
201
+ impact = (
202
+ "Quota availability, reserved-instance coverage, and Savings Plans "
203
+ "estimates may be outdated."
204
+ )
205
+ oldest = min(stale_states, key=lambda state: state.loaded_as_of or "")
206
+ loaded_at = oldest.loaded_as_of
207
+ max_age = _inventory_max_age_seconds(oldest)
208
+ return CheckResult(
209
+ "inventory",
210
+ "optional",
211
+ None,
212
+ reason_code=reason,
213
+ remediation=QUOTAS_GET_HINT,
214
+ impact=impact,
215
+ loaded_at=loaded_at,
216
+ max_age_seconds=max_age,
217
+ detail_lines=details,
218
+ )
219
+ return CheckResult(
220
+ "inventory",
221
+ "pass",
222
+ None,
223
+ detail_lines=details,
224
+ )
225
+
226
+
227
+ def _price_human_message(table, *, age_days: int | None = None) -> str:
228
+ published = table.published_at or "unknown date"
229
+ rows = table.row_count if table.row_count is not None else 0
230
+ base = f"AWS on-demand prices ({published}), {rows} rows"
231
+ if age_days is not None:
232
+ return f"{base}; age {age_days} days exceeds warn threshold"
233
+ return base
234
+
235
+
236
+ def _price_file(_ctx: DoctorContext) -> CheckResult:
237
+ table = load_price_table()
238
+ warn_days = 60
239
+ age = table.age_days()
240
+ kind = table.source_kind or "unknown"
241
+ meta = {
242
+ "price_path": table.package_path,
243
+ "published_at": table.published_at,
244
+ "row_count": table.row_count,
245
+ "source_kind": kind,
246
+ }
247
+ if age > warn_days:
248
+ return CheckResult(
249
+ "aws_price_file",
250
+ "warn",
251
+ _price_human_message(table, age_days=age),
252
+ remediation="pipx upgrade maproom",
253
+ impact="On-demand price estimates may be outdated.",
254
+ **meta,
255
+ )
256
+ return CheckResult(
257
+ "aws_price_file",
258
+ "pass",
259
+ _price_human_message(table),
260
+ **meta,
261
+ )
262
+
263
+
264
+ def _aws_cli_version_floor(ctx: DoctorContext) -> CheckResult:
265
+ status, message, reason = check_aws_floor(runner=ctx.runner)
266
+ if status == "fail":
267
+ not_installed = reason == "not_installed"
268
+ return CheckResult(
269
+ "aws_cli_version_floor",
270
+ "fail",
271
+ message,
272
+ remediation=AWS_CLI_INSTALL_REMEDIATION if not_installed else message,
273
+ reason_code=reason or "cli_too_old",
274
+ impact=(
275
+ "AWS analysis cannot run until the AWS CLI is installed."
276
+ if not_installed
277
+ else "AWS analysis cannot run until the AWS CLI meets the version floor."
278
+ ),
279
+ )
280
+ return CheckResult("aws_cli_version_floor", "pass", message)
281
+
282
+
283
+ def _az_cli_version_floor(ctx: DoctorContext) -> CheckResult:
284
+ status, message, reason = check_az_floor(runner=ctx.runner)
285
+ if status == "skipped":
286
+ install = (
287
+ AZURE_CLI_INSTALL_REMEDIATION if reason == "not_installed" else None
288
+ )
289
+ if reason == "version_unreadable":
290
+ impact = (
291
+ "Azure analysis is unavailable until the Azure CLI version "
292
+ "can be read."
293
+ )
294
+ else:
295
+ impact = "Azure analysis is unavailable until the Azure CLI is installed."
296
+ return CheckResult(
297
+ "az_cli_version_floor",
298
+ "skipped",
299
+ message,
300
+ reason_code=reason,
301
+ remediation=install,
302
+ impact=impact,
303
+ )
304
+ if status == "fail":
305
+ return CheckResult(
306
+ "az_cli_version_floor",
307
+ "fail",
308
+ message,
309
+ remediation="az upgrade",
310
+ reason_code=reason or "cli_too_old",
311
+ impact=(
312
+ "Azure analysis cannot run until the Azure CLI meets the version "
313
+ f"floor ({'.'.join(str(p) for p in AZURE_FLOOR)})."
314
+ ),
315
+ )
316
+ return CheckResult("az_cli_version_floor", "pass", message)
317
+
318
+
319
+ def _azure_not_logged_in(stderr: str) -> bool:
320
+ text = stderr.lower()
321
+ return "az login" in text or "not logged in" in text
322
+
323
+
324
+ def relax_unsigned_identity(results: list[CheckResult]) -> list[CheckResult]:
325
+ """When one cloud identity is logged in, the other not-logged-in probe is optional.
326
+
327
+ Both stay failures when neither provider is logged in.
328
+ """
329
+ logged_in = any(
330
+ result.status == "pass" and result.name.startswith("cloud_identity_")
331
+ for result in results
332
+ )
333
+ if not logged_in:
334
+ return results
335
+ relaxed: list[CheckResult] = []
336
+ for result in results:
337
+ if (
338
+ result.name.startswith("cloud_identity_")
339
+ and result.status == "fail"
340
+ and result.reason_code == "not_logged_in"
341
+ ):
342
+ relaxed.append(
343
+ CheckResult(
344
+ result.name,
345
+ "optional",
346
+ result.message,
347
+ remediation=result.remediation,
348
+ reason_code=result.reason_code,
349
+ detail_lines=result.detail_lines,
350
+ impact="This cloud account is not logged in; only the other provider can be analyzed.",
351
+ )
352
+ )
353
+ continue
354
+ relaxed.append(result)
355
+ return relaxed
356
+
357
+
358
+ def _identity_blocked_by_gate(ctx: DoctorContext, cloud: str) -> CheckResult | None:
359
+ if not consent_storage_available():
360
+ return CheckResult(
361
+ f"cloud_identity_{cloud}",
362
+ "skipped",
363
+ "Identity probe deferred until consent storage exists (FB-2)",
364
+ reason_code="consent_not_implemented",
365
+ )
366
+ outcome = ctx.cloud_read_gate_outcome
367
+ if outcome is None:
368
+ return CheckResult(
369
+ f"cloud_identity_{cloud}",
370
+ "skipped",
371
+ "Consent gate not evaluated",
372
+ reason_code="consent_required",
373
+ )
374
+ if outcome.allowed:
375
+ return None
376
+ reason = outcome.reason_code or "consent_declined"
377
+ message = "Cloud read consent not granted"
378
+ if reason == "consent_snoozed":
379
+ state = load_consent_state(settings_read_file())
380
+ expiry = state.get("cloud_read_consent_snoozed_until")
381
+ if isinstance(expiry, str):
382
+ message = snooze_block_message(expiry)
383
+ elif reason == "consent_required":
384
+ message = (
385
+ "Cloud read consent is required; pass --consent-cloud-reads "
386
+ "or run maproom settings set cloud_read_consent true"
387
+ )
388
+ elif reason == "consent_declined":
389
+ message = "Cloud read consent declined for this run"
390
+ elif reason == "consent_managed_deny":
391
+ message = "Cloud read consent denied by managed policy"
392
+ return CheckResult(
393
+ f"cloud_identity_{cloud}",
394
+ "skipped",
395
+ message,
396
+ reason_code=reason,
397
+ remediation=CLOUD_READ_CONSENT_REMEDIATION,
398
+ impact="Cloud identity cannot be checked until cloud read consent is granted.",
399
+ )
400
+
401
+
402
+ def _merge_version_cache(target: Runner, source: Runner) -> None:
403
+ source_cache = getattr(source, "_version_cache", None)
404
+ if not isinstance(source_cache, dict):
405
+ return
406
+ for cloud in ("aws", "azure"):
407
+ if cloud in source_cache:
408
+ target._version_cache[cloud] = source_cache[cloud]
409
+
410
+
411
+ def _runner_cli_version(runner: Runner, cloud: str) -> str | None:
412
+ cache = getattr(runner, "_version_cache", None)
413
+ if isinstance(cache, dict):
414
+ return cache.get(cloud) # type: ignore[arg-type]
415
+ return None
416
+
417
+
418
+ def _identity_context(ctx: DoctorContext, *, runner: Runner) -> DoctorContext:
419
+ return DoctorContext(
420
+ runner=runner,
421
+ cloud_read_gate_outcome=ctx.cloud_read_gate_outcome,
422
+ gate_evaluated=ctx.gate_evaluated,
423
+ fleetfit_gate_outcome=ctx.fleetfit_gate_outcome,
424
+ fleetfit_evaluated=ctx.fleetfit_evaluated,
425
+ cloud_read_allowed=ctx.cloud_read_allowed,
426
+ progress=ctx.progress,
427
+ az_cli_floor=ctx.az_cli_floor,
428
+ )
429
+
430
+
431
+ def run_prerequisite_checks(context: DoctorContext) -> list[CheckResult]:
432
+ """Run prerequisite doctor checks; overlap AWS and Azure version probes."""
433
+ results: dict[str, CheckResult] = {}
434
+ for check in (_python_version, _platform_info):
435
+ item = check(context)
436
+ results[item.name] = item
437
+
438
+ def _probe_runner() -> Runner:
439
+ return context.runner.probe_copy()
440
+
441
+ def aws_floor() -> CheckResult:
442
+ probe = _probe_runner()
443
+ item = _aws_cli_version_floor(_identity_context(context, runner=probe))
444
+ _merge_version_cache(context.runner, probe)
445
+ return item
446
+
447
+ def az_floor() -> tuple[CheckResult, tuple[str, str | None, str | None]]:
448
+ probe = _probe_runner()
449
+ item = _az_cli_version_floor(_identity_context(context, runner=probe))
450
+ _merge_version_cache(context.runner, probe)
451
+ floor = (item.status, item.message, item.reason_code)
452
+ return item, floor
453
+
454
+ with ThreadPoolExecutor(max_workers=2) as pool:
455
+ aws_future = pool.submit(aws_floor)
456
+ az_future = pool.submit(az_floor)
457
+ aws_item = aws_future.result()
458
+ az_item, az_probe = az_future.result()
459
+ results[aws_item.name] = aws_item
460
+ results[az_item.name] = az_item
461
+ context.az_cli_floor = az_probe
462
+ order = (
463
+ "python_version",
464
+ "platform_info",
465
+ "aws_cli_version_floor",
466
+ "az_cli_version_floor",
467
+ )
468
+ return [results[name] for name in order]
469
+
470
+
471
+ def _azure_floor_tuple(ctx: DoctorContext) -> tuple[str, str | None, str | None]:
472
+ if ctx.az_cli_floor is not None:
473
+ return ctx.az_cli_floor
474
+ return check_az_floor(runner=ctx.runner)
475
+
476
+
477
+ def _aws_not_logged_in_result(*, cli_version: str | None) -> CheckResult:
478
+ response = {
479
+ "exit_code": 253,
480
+ "stdout_json": {},
481
+ "stderr": (
482
+ "Unable to locate credentials. You can configure credentials by running "
483
+ '"aws login".'
484
+ ),
485
+ }
486
+ try:
487
+ parse_sts_identity(response, cli_version=cli_version)
488
+ except NotLoggedInError:
489
+ return CheckResult(
490
+ "cloud_identity_aws",
491
+ "fail",
492
+ "Not logged in to the AWS CLI",
493
+ remediation=aws_login_remediation(),
494
+ reason_code="not_logged_in",
495
+ impact="AWS analysis cannot list instances until you sign in to the AWS CLI.",
496
+ )
497
+ raise MaproomParseError(
498
+ "local credential probe disagreed with parse_sts_identity",
499
+ api_id="aws_sts_get_caller_identity",
500
+ cli_version=cli_version,
501
+ )
502
+
503
+
504
+ def _aws_cli_absent(runner: Runner) -> bool:
505
+ if isinstance(runner, MockEnvironmentRunner):
506
+ return False
507
+ overridden = bool(os.environ.get("CLOUD_CLI_AWS") or os.environ.get("MAPROOM_AWS_CLI"))
508
+ return not overridden and shutil.which("aws") is None
509
+
510
+
511
+ def _cloud_identity_aws(ctx: DoctorContext) -> CheckResult:
512
+ blocked = _identity_blocked_by_gate(ctx, "aws")
513
+ if blocked is not None:
514
+ return blocked
515
+ if _aws_cli_absent(ctx.runner):
516
+ return CheckResult(
517
+ "cloud_identity_aws",
518
+ "skipped",
519
+ "AWS CLI not installed",
520
+ reason_code="not_installed",
521
+ remediation=AWS_CLI_INSTALL_REMEDIATION,
522
+ impact="AWS analysis is unavailable until the AWS CLI is installed.",
523
+ )
524
+ cli_version = _runner_cli_version(ctx.runner, "aws")
525
+ if (
526
+ isinstance(ctx.runner, Runner)
527
+ and not isinstance(ctx.runner, MockEnvironmentRunner)
528
+ and not aws_likely_has_credentials()
529
+ ):
530
+ return _aws_not_logged_in_result(cli_version=cli_version)
531
+ result = ctx.runner.run(
532
+ "aws",
533
+ ["sts", "get-caller-identity", "--output", "json"],
534
+ record=False,
535
+ api_id="aws_sts_get_caller_identity",
536
+ )
537
+ response = {
538
+ "exit_code": result.exit_code,
539
+ "stdout_json": {},
540
+ "stderr": result.stderr,
541
+ }
542
+ if result.stdout.strip():
543
+ try:
544
+ response["stdout_json"] = json.loads(result.stdout)
545
+ except json.JSONDecodeError:
546
+ response["stdout_json"] = {"_raw_stdout": result.stdout}
547
+ try:
548
+ identity = parse_sts_identity(response, cli_version=result.cli_version)
549
+ except NotLoggedInError:
550
+ return CheckResult(
551
+ "cloud_identity_aws",
552
+ "fail",
553
+ "Not logged in to the AWS CLI",
554
+ remediation=aws_login_remediation(),
555
+ reason_code="not_logged_in",
556
+ impact="AWS analysis cannot list instances until you sign in to the AWS CLI.",
557
+ )
558
+ except MaproomParseError as exc:
559
+ return CheckResult(
560
+ "cloud_identity_aws",
561
+ "fail",
562
+ str(exc),
563
+ impact="AWS identity could not be verified; analysis is blocked.",
564
+ )
565
+ return CheckResult(
566
+ "cloud_identity_aws",
567
+ "pass",
568
+ aws_principal_display_name(identity["Arn"]),
569
+ )
570
+
571
+
572
+ def run_identity_checks(context: DoctorContext) -> list[CheckResult]:
573
+ """Run identity probes in parallel when the consent gate allows them."""
574
+ if not isinstance(context.runner, Runner):
575
+ return relax_unsigned_identity([check(context) for check in IDENTITY_CHECKS])
576
+
577
+ def run_one(check: Callable[[DoctorContext], CheckResult]) -> CheckResult:
578
+ probe = context.runner.probe_copy()
579
+ _merge_version_cache(probe, context.runner)
580
+ return check(_identity_context(context, runner=probe))
581
+
582
+ with ThreadPoolExecutor(max_workers=2) as pool:
583
+ aws_future = pool.submit(run_one, _cloud_identity_aws)
584
+ az_future = pool.submit(run_one, _cloud_identity_azure)
585
+ results = [aws_future.result(), az_future.result()]
586
+ return relax_unsigned_identity(results)
587
+
588
+
589
+ def _cloud_identity_azure(ctx: DoctorContext) -> CheckResult:
590
+ status, message, reason = _azure_floor_tuple(ctx)
591
+ if status == "skipped" and reason == "not_installed":
592
+ return CheckResult(
593
+ "cloud_identity_azure",
594
+ "skipped",
595
+ message,
596
+ reason_code=reason,
597
+ remediation=AZURE_CLI_INSTALL_REMEDIATION,
598
+ impact="Azure analysis is unavailable until the Azure CLI is installed.",
599
+ )
600
+ blocked = _identity_blocked_by_gate(ctx, "azure")
601
+ if blocked is not None:
602
+ return blocked
603
+ if status == "skipped":
604
+ if reason == "version_unreadable":
605
+ impact = (
606
+ "Azure analysis is unavailable until the Azure CLI version "
607
+ "can be read."
608
+ )
609
+ else:
610
+ impact = "Azure analysis is unavailable until the Azure CLI is installed."
611
+ return CheckResult(
612
+ "cloud_identity_azure",
613
+ "skipped",
614
+ message,
615
+ reason_code=reason,
616
+ impact=impact,
617
+ )
618
+ if status == "fail":
619
+ return CheckResult(
620
+ "cloud_identity_azure",
621
+ "skipped",
622
+ message,
623
+ reason_code="prerequisite_failed",
624
+ impact="Azure identity was not probed because the Azure CLI floor check failed.",
625
+ )
626
+ result = ctx.runner.run(
627
+ "azure",
628
+ ["account", "show", "--output", "json"],
629
+ record=False,
630
+ api_id="azure_account_show",
631
+ )
632
+ if result.exit_code != 0:
633
+ stderr = result.stderr.strip()
634
+ not_logged_in = _azure_not_logged_in(stderr)
635
+ return CheckResult(
636
+ "cloud_identity_azure",
637
+ "fail",
638
+ stderr or "Azure account show failed",
639
+ remediation="Run `az login`" if not_logged_in else None,
640
+ reason_code="not_logged_in" if not_logged_in else None,
641
+ impact=(
642
+ "Azure analysis cannot list instances until you sign in to the Azure CLI."
643
+ if not_logged_in
644
+ else "Azure identity could not be verified; analysis is blocked."
645
+ ),
646
+ )
647
+ if not result.stdout.strip():
648
+ return CheckResult(
649
+ "cloud_identity_azure",
650
+ "fail",
651
+ "Azure account show returned empty output",
652
+ impact="Azure identity could not be verified; analysis is blocked.",
653
+ )
654
+ try:
655
+ account = json.loads(result.stdout)
656
+ except json.JSONDecodeError:
657
+ return CheckResult(
658
+ "cloud_identity_azure",
659
+ "fail",
660
+ "Azure account show returned invalid JSON",
661
+ impact="Azure identity could not be verified; analysis is blocked.",
662
+ )
663
+ if not isinstance(account, dict):
664
+ return CheckResult(
665
+ "cloud_identity_azure",
666
+ "fail",
667
+ "Azure account show returned unexpected JSON",
668
+ impact="Azure identity could not be verified; analysis is blocked.",
669
+ )
670
+ return CheckResult(
671
+ "cloud_identity_azure",
672
+ "pass",
673
+ azure_account_identity_display(account),
674
+ )
675
+
676
+
677
+ PREREQUISITE_CHECKS: tuple[Callable[[DoctorContext], CheckResult], ...] = (
678
+ _python_version,
679
+ _platform_info,
680
+ _aws_cli_version_floor,
681
+ _az_cli_version_floor,
682
+ )
683
+
684
+ DATA_SOURCE_CHECKS: tuple[Callable[[DoctorContext], CheckResult], ...] = (
685
+ _price_file,
686
+ _user_local_data,
687
+ _inventory,
688
+ )
689
+
690
+ IDENTITY_CHECKS: tuple[Callable[[DoctorContext], CheckResult], ...] = (
691
+ _cloud_identity_aws,
692
+ _cloud_identity_azure,
693
+ )
694
+
695
+ LOCAL_CHECKS: tuple[Callable[[DoctorContext], CheckResult], ...] = (
696
+ PREREQUISITE_CHECKS + DATA_SOURCE_CHECKS
697
+ )
698
+
699
+ CHECKS: tuple[Callable[[DoctorContext], CheckResult], ...] = (
700
+ PREREQUISITE_CHECKS + IDENTITY_CHECKS + DATA_SOURCE_CHECKS
701
+ )