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/cli.py ADDED
@@ -0,0 +1,2084 @@
1
+ """maproom console entrypoint (minimal ASMB-49 surface)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+ from datetime import datetime, timezone
10
+ from typing import Any, Callable
11
+
12
+ from maproom.cliio.runner import (
13
+ CliBelowFloorError,
14
+ CliRunnerError,
15
+ CliTimeoutError,
16
+ Runner,
17
+ )
18
+
19
+ from maproom import __version__
20
+ from maproom.analyze.change_detection import (
21
+ detect_instance_type_change,
22
+ effective_utilization_bounds,
23
+ post_change_utilization_reliable,
24
+ trim_cpu_metric_row,
25
+ )
26
+ from maproom.analyze.utilization import (
27
+ _iso_z,
28
+ build_cpu_utilization_argv,
29
+ utilization_window,
30
+ )
31
+ from maproom.analyze.recommendation import (
32
+ build_recommendation_document,
33
+ format_recommendation_tty,
34
+ )
35
+ from maproom.analyze.provider_comparison import (
36
+ attach_provider_comparison,
37
+ resolve_provider_recommendation,
38
+ )
39
+ from maproom.analyze.specs import resolve_spec_catalog
40
+ from maproom.analyze.fleetfit_endpoints import configured_fleetfit_endpoints, resolve_tokens_url
41
+ from maproom.analyze.recommend_client import recommend_destination
42
+ from maproom.analyze.shape import format_shape_catalog, parse_shape_values
43
+ from maproom.analyze.workload import build_workload_profile
44
+ from maproom.analyze.workset import (
45
+ AnalyzeRequest,
46
+ AwsInstanceList,
47
+ azure_local_only_message,
48
+ cloud_listing_error_code,
49
+ detect_logged_in_clouds,
50
+ filter_contains,
51
+ list_aws_instances,
52
+ list_azure_instances,
53
+ parse_analyze_selectors,
54
+ resolve_cloud,
55
+ resolve_cloud_error_code,
56
+ )
57
+ from maproom.aws_region import aws_login_remediation, resolve_default_aws_region
58
+ from maproom.cli_argv import MaproomArgumentParser, prepare_argv
59
+ from maproom.cli_floors import ensure_cli_floors, fail_cli_floor, format_below_floor # re-exported for tests
60
+ from maproom.consent import require_cloud_read_consent, require_service_upload_consent
61
+ from maproom.cache.commands import cmd_cache
62
+ from maproom.data.commands import cmd_data_clear
63
+ from maproom.doctor.context import DoctorContext
64
+ from maproom.doctor.runner import run_doctor
65
+ from maproom.mock_environment import MockEnvironmentError, command_runner
66
+ from maproom.errors import AccessDeniedError, NotFoundError, NotLoggedInError, MaproomParseError
67
+ from maproom.exitcodes import RUNTIME, SUCCESS, USAGE, exit_code_for_error
68
+ from maproom.output.json_envelope import (
69
+ build_document,
70
+ command_metadata,
71
+ finish_consent_gate,
72
+ print_error_envelope,
73
+ print_json,
74
+ )
75
+ from maproom.parsers import (
76
+ azure_account_identity_display,
77
+ parse_cloudwatch_get_metric_data,
78
+ parse_ec2_describe_instances,
79
+ parse_sts_identity,
80
+ )
81
+ from maproom.paths import settings_read_file
82
+ from maproom.settings.model import load_effective_settings
83
+ from maproom.resources import (
84
+ EC2_INSTANCE_ARN_RE,
85
+ EC2_INSTANCE_ID_RE,
86
+ ResourceUsageError,
87
+ format_target_preview,
88
+ parse_ec2_target,
89
+ )
90
+ from maproom.root_help import (
91
+ format_grouped_root_help,
92
+ help_description_for,
93
+ help_epilog_for,
94
+ )
95
+ from maproom.settings.model import product_version
96
+ from maproom.settings.product_versions import (
97
+ MAX_PRODUCT_VERSION,
98
+ RIGHTSIZER_MIN_PRODUCT_VERSION,
99
+ product_version_name,
100
+ )
101
+ from maproom.plan.analyze_selection import maybe_run_tty_selection, run_accept_selection
102
+ from maproom.plan.errors import PlanError
103
+ from maproom.plan.commands import (
104
+ cmd_plan_clear,
105
+ cmd_plan_create,
106
+ cmd_plan_export,
107
+ cmd_plan_list,
108
+ cmd_plan_remove,
109
+ cmd_plan_show,
110
+ cmd_plan_show_current,
111
+ cmd_plan_use,
112
+ plan_summary_line,
113
+ )
114
+ from maproom.plan import current as current_plan
115
+ from maproom.privacy.commands import cmd_privacy
116
+ from maproom.redaction import redact_tree
117
+ from maproom.inventory.command import cmd_inventory
118
+ from maproom.quotas.status import (
119
+ quota_headroom_missing,
120
+ quotas_tty_segment,
121
+ read_quota_state,
122
+ stale_quota_warning,
123
+ )
124
+ from maproom.reservations.status import (
125
+ read_inventory_state,
126
+ reservation_coverage_missing,
127
+ reservations_tty_segment,
128
+ stale_reservation_warning,
129
+ )
130
+ from maproom.saving_plans.status import (
131
+ read_saving_plan_state,
132
+ saving_plans_tty_segment,
133
+ stale_saving_plan_warning,
134
+ )
135
+ from maproom.paths import settings_read_file
136
+ from maproom.settings.init import run_settings_init
137
+ from maproom.settings.model import load_effective_settings
138
+ from maproom.settings.set import (
139
+ run_settings_set,
140
+ settings_set_key_names_csv,
141
+ settings_set_short_help,
142
+ settings_set_value_epilog,
143
+ )
144
+ from maproom.settings.show import run_settings_show
145
+
146
+
147
+ def _aws_not_signed_in_message() -> str:
148
+ return f"Not logged in to the AWS CLI. {aws_login_remediation()}."
149
+
150
+
151
+ def _azure_not_signed_in_message() -> str:
152
+ return "Not logged in to the Azure CLI. Run 'az login'."
153
+
154
+
155
+ def _azure_cli_failure_message(stderr: str) -> str:
156
+ text = stderr.strip()
157
+ lowered = text.lower()
158
+ if not text or "az login" in lowered or "not logged in" in lowered:
159
+ return _azure_not_signed_in_message()
160
+ return text
161
+
162
+
163
+ def _probe_aws_identity(runner: Runner) -> tuple[dict[str, str] | None, str | None]:
164
+ try:
165
+ result = runner.run(
166
+ "aws",
167
+ ["sts", "get-caller-identity", "--output", "json"],
168
+ record=False,
169
+ api_id="aws_sts_get_caller_identity",
170
+ )
171
+ except OSError:
172
+ return None, "AWS CLI is not installed."
173
+ except CliRunnerError as exc:
174
+ return None, str(exc)
175
+ try:
176
+ identity = parse_sts_identity(
177
+ _runner_response(result),
178
+ cli_version=result.cli_version,
179
+ )
180
+ except NotLoggedInError:
181
+ return None, _aws_not_signed_in_message()
182
+ except MaproomParseError as exc:
183
+ return None, str(exc)
184
+ return identity, None
185
+
186
+
187
+ def _probe_azure_identity(runner: Runner) -> tuple[dict[str, Any] | None, str | None]:
188
+ try:
189
+ result = runner.run(
190
+ "azure",
191
+ ["account", "show", "--output", "json"],
192
+ record=False,
193
+ api_id="azure_account_show",
194
+ )
195
+ except OSError:
196
+ return None, "Azure CLI is not installed."
197
+ except CliRunnerError as exc:
198
+ return None, str(exc)
199
+ if result.exit_code != 0:
200
+ return None, _azure_cli_failure_message(result.stderr or "")
201
+ if not result.stdout.strip():
202
+ return None, "Azure account show returned empty output"
203
+ try:
204
+ account = json.loads(result.stdout)
205
+ except json.JSONDecodeError:
206
+ return None, "Azure account show returned invalid JSON"
207
+ if not isinstance(account, dict):
208
+ return None, "Azure account show returned unexpected JSON"
209
+ return account, None
210
+
211
+
212
+ def _aws_identity_json(
213
+ identity: dict[str, str] | None,
214
+ message: str | None,
215
+ ) -> dict[str, Any]:
216
+ if identity is None:
217
+ return {"signed_in": False, "message": message or _aws_not_signed_in_message()}
218
+ return {
219
+ "signed_in": True,
220
+ "Account": identity["Account"],
221
+ "Arn": identity["Arn"],
222
+ "UserId": identity["UserId"],
223
+ }
224
+
225
+
226
+ def _azure_identity_json(
227
+ account: dict[str, Any] | None,
228
+ message: str | None,
229
+ ) -> dict[str, Any]:
230
+ if account is None:
231
+ return {"signed_in": False, "message": message or _azure_not_signed_in_message()}
232
+ body: dict[str, Any] = {
233
+ "signed_in": True,
234
+ "user": azure_account_identity_display(account),
235
+ }
236
+ name = account.get("name")
237
+ if isinstance(name, str) and name.strip():
238
+ body["subscription_name"] = name.strip()
239
+ subscription_id = account.get("id")
240
+ if isinstance(subscription_id, str) and subscription_id.strip():
241
+ body["subscription_id"] = subscription_id.strip()
242
+ return body
243
+
244
+
245
+ def _print_aws_identity(identity: dict[str, str] | None, message: str | None) -> None:
246
+ if identity is not None:
247
+ print(f"AwsAccount={identity['Account']}")
248
+ print(f"AwsArn={identity['Arn']}")
249
+ return
250
+ if message:
251
+ print(f"AWS: {message}" if not message.startswith("AWS") else message)
252
+
253
+
254
+ def _print_azure_identity(account: dict[str, Any] | None, message: str | None) -> None:
255
+ if account is not None:
256
+ print(f"AzureUser={azure_account_identity_display(account)}")
257
+ name = account.get("name")
258
+ if isinstance(name, str) and name.strip():
259
+ print(f"AzureSubscription={name.strip()}")
260
+ return
261
+ if message:
262
+ print(message)
263
+
264
+
265
+ _CLI_TIMEOUT_MESSAGE = "A cloud CLI command timed out."
266
+
267
+
268
+ def _fleetfit_host_key(name: str) -> str:
269
+ return f"{name}_host"
270
+
271
+
272
+ def _fleetfit_identity_json(settings: dict[str, Any], *, product_version: int) -> dict[str, Any]:
273
+ endpoints = configured_fleetfit_endpoints(settings, product_version=product_version)
274
+ if not endpoints:
275
+ return {
276
+ "configured": False,
277
+ "message": "FleetFit lookup URLs are not configured.",
278
+ }
279
+ body: dict[str, Any] = {"configured": True}
280
+ for name, url in endpoints.items():
281
+ body[_fleetfit_host_key(name)] = url
282
+ return body
283
+
284
+
285
+ def identity_subcommand_help(*, product_version: int) -> str:
286
+ """Help text for maproom identity; matches runtime FleetFit inclusion."""
287
+ if product_version > 1:
288
+ return "Show AWS, Azure, and FleetFit identities."
289
+ settings, _ = load_effective_settings(settings_read_file())
290
+ if configured_fleetfit_endpoints(settings, product_version=product_version):
291
+ return "Show AWS, Azure, and FleetFit identities."
292
+ return "Show AWS and Azure identities."
293
+
294
+
295
+ def _print_fleetfit_identity(settings: dict[str, Any], *, product_version: int) -> None:
296
+ block = _fleetfit_identity_json(settings, product_version=product_version)
297
+ if not block.get("configured"):
298
+ print("FleetFit: lookup URLs are not configured.")
299
+ return
300
+ for key, value in block.items():
301
+ if key == "configured":
302
+ continue
303
+ label = key.removesuffix("_host").replace("_", " ")
304
+ print(f"FleetFit {label}={value}")
305
+
306
+
307
+ def _neither_cloud_signed_in(messages: list[str], *, as_json: bool) -> int:
308
+ text = " ".join(message for message in messages if message)
309
+ if as_json:
310
+ return print_error_envelope("runtime", text, invoked="identity")
311
+ for message in messages:
312
+ if not message:
313
+ continue
314
+ print(f"error: {message}", file=sys.stderr)
315
+ print(message)
316
+ return RUNTIME
317
+
318
+
319
+ def cmd_identity(args: argparse.Namespace) -> int:
320
+ started_at = datetime.now(timezone.utc)
321
+ as_json = bool(getattr(args, "json", False))
322
+ try:
323
+ runner = command_runner() if os.environ.get("MAPROOM_MOCK_ENVIRONMENT", "").strip() else Runner()
324
+ except MockEnvironmentError as exc:
325
+ if as_json:
326
+ return print_error_envelope("runtime", exc.message, invoked="identity")
327
+ print(exc.message, file=sys.stderr)
328
+ return exit_code_for_error("runtime")
329
+ try:
330
+ ensure_cli_floors(runner=runner)
331
+ except CliBelowFloorError as exc:
332
+ if as_json:
333
+ return print_error_envelope(
334
+ "runtime", format_below_floor(exc), invoked="identity"
335
+ )
336
+ return fail_cli_floor(exc, as_json=False)
337
+
338
+ gate = require_cloud_read_consent(
339
+ consent_cloud_reads=bool(getattr(args, "consent_cloud_reads", False)),
340
+ quiet=as_json,
341
+ )
342
+ if not gate.allowed:
343
+ return finish_consent_gate(gate, as_json=as_json, invoked="identity")
344
+
345
+ aws_identity, aws_message = _probe_aws_identity(runner)
346
+ azure_account, azure_message = _probe_azure_identity(runner)
347
+ if aws_identity is None and azure_account is None:
348
+ return _neither_cloud_signed_in(
349
+ [aws_message or "", azure_message or ""],
350
+ as_json=as_json,
351
+ )
352
+
353
+ version = product_version()
354
+ settings, _ = load_effective_settings(settings_read_file())
355
+ fleetfit_block = _fleetfit_identity_json(settings, product_version=version)
356
+ include_fleetfit = version > 1 or bool(fleetfit_block.get("configured"))
357
+
358
+ if as_json:
359
+ result: dict[str, Any] = {
360
+ "aws": _aws_identity_json(aws_identity, aws_message),
361
+ "azure": _azure_identity_json(azure_account, azure_message),
362
+ }
363
+ if include_fleetfit:
364
+ result["fleetfit"] = fleetfit_block
365
+ print_json(
366
+ build_document(
367
+ schema_type="identity",
368
+ schema_id="maproom.identity",
369
+ metadata=command_metadata("identity", started_at=started_at),
370
+ errors=[],
371
+ warnings=[],
372
+ payload={"result": result},
373
+ )
374
+ )
375
+ else:
376
+ _print_aws_identity(aws_identity, aws_message)
377
+ _print_azure_identity(azure_account, azure_message)
378
+ if include_fleetfit:
379
+ _print_fleetfit_identity(settings, product_version=version)
380
+ return SUCCESS
381
+
382
+
383
+ def _usage_error(message: str, *, as_json: bool) -> int:
384
+ if as_json:
385
+ return print_error_envelope("usage", message, invoked="analyze")
386
+ print(message, file=sys.stderr)
387
+ return exit_code_for_error("usage")
388
+
389
+
390
+ def _progress(message: str, *, as_json: bool) -> None:
391
+ """Progress text. With --json, stdout stays one JSON document."""
392
+ print(message, file=sys.stderr if as_json else None, flush=True)
393
+
394
+
395
+ def _human_or_json_error(
396
+ message: str,
397
+ *,
398
+ as_json: bool,
399
+ code: str,
400
+ started_at: datetime | None = None,
401
+ ) -> int:
402
+ """Failure text. With --json, stdout is one error document."""
403
+ if as_json:
404
+ metadata = (
405
+ command_metadata("analyze", started_at=started_at)
406
+ if started_at is not None
407
+ else None
408
+ )
409
+ return print_error_envelope(
410
+ code,
411
+ message,
412
+ invoked="analyze",
413
+ metadata=metadata,
414
+ )
415
+ print(message)
416
+ return exit_code_for_error(code)
417
+
418
+
419
+ def _examined_service_code(cloud: str) -> str:
420
+ if cloud == "azure":
421
+ return "Microsoft.Compute"
422
+ return "ec2"
423
+
424
+
425
+ def _print_unevaluated_json(items: list[Any]) -> None:
426
+ """One analyze_results document for a rightsizer run that did not score instances."""
427
+ started_at = datetime.now(timezone.utc)
428
+ examined = [
429
+ {
430
+ "cloud": item.cloud,
431
+ "service_code": _examined_service_code(item.cloud),
432
+ "region": item.region,
433
+ "instance_id": item.instance_id,
434
+ "instance_name": item.name,
435
+ "current": {"instance_type": item.instance_type},
436
+ "outcome": "no_recommendation",
437
+ }
438
+ for item in items
439
+ ]
440
+ print_json(
441
+ build_document(
442
+ schema_type="analyze_results",
443
+ schema_id="maproom.analyze",
444
+ metadata=command_metadata("analyze", started_at=started_at),
445
+ errors=[],
446
+ warnings=[],
447
+ payload={
448
+ "finish": "complete",
449
+ "recommendations": [],
450
+ "info": {"examined": examined},
451
+ },
452
+ )
453
+ )
454
+
455
+
456
+ def _runner_response(result: Any) -> dict[str, Any]:
457
+ response: dict[str, Any] = {
458
+ "exit_code": result.exit_code,
459
+ "stdout_json": {},
460
+ "stderr": result.stderr,
461
+ }
462
+ if result.stdout.strip():
463
+ try:
464
+ response["stdout_json"] = json.loads(result.stdout)
465
+ except json.JSONDecodeError:
466
+ response["stdout_json"] = {"_raw_stdout": result.stdout}
467
+ return response
468
+
469
+
470
+ def _resolve_ec2_target(resource: str, *, region_flag: str | None) -> Any:
471
+ text = (resource or "").strip()
472
+ if EC2_INSTANCE_ARN_RE.match(text):
473
+ return parse_ec2_target(text, region=region_flag)
474
+ if not EC2_INSTANCE_ID_RE.match(text):
475
+ raise ResourceUsageError(
476
+ "Invalid EC2 instance id. Expected i-xxxxxxxx or an EC2 instance ARN.\n"
477
+ "hint: maproom analyze i-0123456789abcdef0 --region us-east-1"
478
+ )
479
+ region = (region_flag or "").strip().lower() or resolve_default_aws_region()
480
+ if not region:
481
+ raise ResourceUsageError(
482
+ "Instance IDs need a region. Add --region us-east-1 or pass the full ARN."
483
+ )
484
+ return parse_ec2_target(text, region=region)
485
+
486
+
487
+ def cmd_analyze(
488
+ args: argparse.Namespace,
489
+ *,
490
+ now_utc: Callable[[], datetime] | None = None,
491
+ ) -> int:
492
+ """Analyze one instance, or each instance in a cloud working set."""
493
+ version = product_version()
494
+ if version < RIGHTSIZER_MIN_PRODUCT_VERSION:
495
+ from maproom.analyze.recommend_share import ShareCeilingError, share_groups_from_args
496
+ from maproom.analyze.safe_analyze import cmd_analyze_v1
497
+
498
+ try:
499
+ groups = share_groups_from_args(version, args)
500
+ except ShareCeilingError as exc:
501
+ return _usage_error(str(exc), as_json=bool(args.json))
502
+ shape = None
503
+ if version >= 4 and "series" in groups:
504
+ shape_raw = list(getattr(args, "shape", None) or [])
505
+ if shape_raw:
506
+ parsed_shape = parse_shape_values(shape_raw)
507
+ if isinstance(parsed_shape, PlanError):
508
+ return _usage_error(parsed_shape.message, as_json=bool(args.json))
509
+ shape = parsed_shape
510
+ return cmd_analyze_v1(
511
+ args,
512
+ now_utc=now_utc,
513
+ spot_lookup="purchase_option" in groups and version >= 3,
514
+ size_lookup="metrics" in groups,
515
+ reservation_reorder="reservations" in groups,
516
+ reservation_pack=str(getattr(args, "reservation_pack", "fill") or "fill"),
517
+ series_lookup="series" in groups,
518
+ quota_management="quota" in groups,
519
+ shape=shape,
520
+ )
521
+ as_json = bool(args.json)
522
+ shape = None
523
+ shape_raw = list(getattr(args, "shape", None) or [])
524
+ if shape_raw:
525
+ parsed_shape = parse_shape_values(shape_raw)
526
+ if isinstance(parsed_shape, PlanError):
527
+ return _usage_error(parsed_shape.message, as_json=as_json)
528
+ shape = parsed_shape
529
+
530
+ parsed = parse_analyze_selectors(list(getattr(args, "selectors", None) or []))
531
+ if isinstance(parsed, PlanError):
532
+ return _usage_error(parsed.message, as_json=as_json)
533
+
534
+ if parsed.resource and parsed.resource_cloud == "aws":
535
+ return _analyze_one_ec2(
536
+ args,
537
+ parsed.resource,
538
+ shape=shape,
539
+ fleet=False,
540
+ now_utc=now_utc,
541
+ )
542
+ return _analyze_fleet(args, parsed, shape=shape, now_utc=now_utc)
543
+
544
+
545
+ def _analyze_fleet(
546
+ args: argparse.Namespace,
547
+ parsed: AnalyzeRequest,
548
+ *,
549
+ shape: Any,
550
+ now_utc: Callable[[], datetime] | None,
551
+ ) -> int:
552
+ as_json = bool(args.json)
553
+ started_at = datetime.now(timezone.utc)
554
+ runner = Runner()
555
+ gate = require_cloud_read_consent(
556
+ consent_cloud_reads=bool(getattr(args, "consent_cloud_reads", False)),
557
+ quiet=as_json,
558
+ )
559
+ if not gate.allowed:
560
+ return finish_consent_gate(gate, as_json=as_json, invoked="analyze")
561
+
562
+ try:
563
+ ensure_cli_floors(runner=runner)
564
+ except CliBelowFloorError as exc:
565
+ return fail_cli_floor(exc, as_json=as_json)
566
+
567
+ logged_in = detect_logged_in_clouds(runner)
568
+ cloud = resolve_cloud(
569
+ parsed.cloud,
570
+ logged_in,
571
+ resource_cloud=parsed.resource_cloud,
572
+ )
573
+ if isinstance(cloud, PlanError):
574
+ return _human_or_json_error(
575
+ cloud.message,
576
+ as_json=as_json,
577
+ code=resolve_cloud_error_code(cloud.message),
578
+ started_at=started_at,
579
+ )
580
+
581
+ region = getattr(args, "region", None)
582
+ if cloud == "aws":
583
+ listed = list_aws_instances(runner, region=region)
584
+ else:
585
+ listed = list_azure_instances(runner)
586
+ if isinstance(listed, PlanError):
587
+ return _human_or_json_error(
588
+ listed.message,
589
+ as_json=as_json,
590
+ code=cloud_listing_error_code(listed.message),
591
+ started_at=started_at,
592
+ )
593
+ if isinstance(listed, AwsInstanceList):
594
+ listed_items = list(listed.items)
595
+ else:
596
+ listed_items = list(listed)
597
+
598
+ items = filter_contains(listed_items, parsed.contains)
599
+ if parsed.resource:
600
+ needle = parsed.resource.lower()
601
+ exact = [
602
+ item
603
+ for item in items
604
+ if item.instance_id.lower() == needle or item.name.lower() == needle
605
+ ]
606
+ if len(exact) == 1 and exact[0].cloud == "aws":
607
+ return _analyze_one_ec2(
608
+ args,
609
+ exact[0].instance_id,
610
+ shape=shape,
611
+ fleet=False,
612
+ now_utc=now_utc,
613
+ region_override=exact[0].region,
614
+ )
615
+ if len(exact) == 1 and exact[0].cloud == "azure":
616
+ if as_json:
617
+ _print_unevaluated_json([exact[0]])
618
+ else:
619
+ print(azure_local_only_message(exact[0]))
620
+ return SUCCESS
621
+ if not exact:
622
+ return _usage_error(
623
+ f'no instance matched "{parsed.resource}". '
624
+ "Use an id, or *text for a contains search.",
625
+ as_json=as_json,
626
+ )
627
+ items = exact
628
+
629
+ if not items:
630
+ if as_json:
631
+ _print_unevaluated_json([])
632
+ else:
633
+ print(f"No {cloud} instances matched.")
634
+ return SUCCESS
635
+
636
+ _progress(f"Working set: {len(items)} {cloud} instance(s).", as_json=as_json)
637
+
638
+ exit_code = SUCCESS
639
+ single = len(items) == 1
640
+ pending_azure: list[Any] = []
641
+ accept_values = list(getattr(args, "accept", None) or [])
642
+ captured: list[dict[str, Any]] | None = [] if as_json and not accept_values else None
643
+ saw_ec2 = False
644
+ for index, item in enumerate(items, start=1):
645
+ if not single:
646
+ if not as_json:
647
+ print()
648
+ _progress(f"[{index}/{len(items)}] {item.label()}", as_json=as_json)
649
+ if item.cloud == "azure":
650
+ if as_json:
651
+ pending_azure.append(item)
652
+ else:
653
+ print(azure_local_only_message(item))
654
+ continue
655
+ saw_ec2 = True
656
+ code = _analyze_one_ec2(
657
+ args,
658
+ item.instance_id,
659
+ shape=shape,
660
+ fleet=not single,
661
+ now_utc=now_utc,
662
+ region_override=item.region,
663
+ captured=captured,
664
+ )
665
+ if code != SUCCESS:
666
+ exit_code = code
667
+ if as_json:
668
+ return exit_code
669
+ if captured is not None:
670
+ if captured:
671
+ for item in pending_azure:
672
+ print(azure_local_only_message(item), file=sys.stderr)
673
+ if len(captured) == 1:
674
+ print_json(captured[0])
675
+ else:
676
+ print(json.dumps(redact_tree(captured), indent=2))
677
+ else:
678
+ _print_unevaluated_json(pending_azure)
679
+ elif as_json and pending_azure and not saw_ec2:
680
+ _print_unevaluated_json(pending_azure)
681
+ elif as_json:
682
+ for item in pending_azure:
683
+ print(azure_local_only_message(item), file=sys.stderr)
684
+ return exit_code
685
+
686
+
687
+ def _rightsizer_upload_enabled(settings: dict[str, Any]) -> bool:
688
+ """True when rightsizer analyze may prompt for service-upload consent."""
689
+ if os.environ.get("MAPROOM_RECOMMEND_FIXTURE", "").strip():
690
+ return True
691
+ if not recommend_destination(settings):
692
+ return False
693
+ return resolve_tokens_url(settings) is not None
694
+
695
+
696
+ def _analyze_one_ec2(
697
+ args: argparse.Namespace,
698
+ resource: str,
699
+ *,
700
+ shape: Any,
701
+ fleet: bool,
702
+ now_utc: Callable[[], datetime] | None = None,
703
+ region_override: str | None = None,
704
+ captured: list[dict[str, Any]] | None = None,
705
+ ) -> int:
706
+ """Analyze one EC2 instance: inventory, utilization, workload profile."""
707
+ as_json = bool(args.json)
708
+ runner = Runner()
709
+
710
+ try:
711
+ target = _resolve_ec2_target(
712
+ resource,
713
+ region_flag=region_override or getattr(args, "region", None),
714
+ )
715
+ except ResourceUsageError as exc:
716
+ return _usage_error(str(exc), as_json=as_json)
717
+
718
+ _progress(format_target_preview(target), as_json=as_json)
719
+
720
+ gate = require_cloud_read_consent(
721
+ consent_cloud_reads=bool(getattr(args, "consent_cloud_reads", False)),
722
+ quiet=as_json,
723
+ )
724
+ if not gate.allowed:
725
+ return finish_consent_gate(gate, as_json=as_json, invoked="analyze")
726
+
727
+ try:
728
+ ensure_cli_floors(runner=runner)
729
+ except CliBelowFloorError as exc:
730
+ return fail_cli_floor(exc, as_json=as_json)
731
+
732
+ identity_result = runner.run(
733
+ "aws",
734
+ ["sts", "get-caller-identity", "--output", "json"],
735
+ record=False,
736
+ api_id="aws_sts_get_caller_identity",
737
+ )
738
+ identity_response = _runner_response(identity_result)
739
+ try:
740
+ identity = parse_sts_identity(
741
+ identity_response,
742
+ cli_version=identity_result.cli_version,
743
+ )
744
+ except NotLoggedInError:
745
+ return _human_or_json_error(
746
+ f"Not logged in to the AWS CLI. {aws_login_remediation()}.",
747
+ as_json=as_json,
748
+ code="runtime",
749
+ )
750
+ except MaproomParseError as exc:
751
+ if as_json:
752
+ return print_error_envelope("runtime", str(exc), invoked="analyze")
753
+ print(f"error: {exc}", file=sys.stderr)
754
+ return RUNTIME
755
+
756
+ _progress(f"Account={identity['Account']} · Region={target.region}", as_json=as_json)
757
+
758
+ print("Reading instance details...", file=sys.stderr, flush=True)
759
+ describe_result = runner.run(
760
+ "aws",
761
+ [
762
+ "ec2",
763
+ "describe-instances",
764
+ "--instance-ids",
765
+ target.instance_id,
766
+ "--region",
767
+ target.region,
768
+ "--output",
769
+ "json",
770
+ ],
771
+ record=False,
772
+ api_id="aws_ec2_describe_instances",
773
+ )
774
+ describe_response = _runner_response(describe_result)
775
+ try:
776
+ instances = parse_ec2_describe_instances(
777
+ describe_response,
778
+ cli_version=describe_result.cli_version,
779
+ state_id=None,
780
+ )
781
+ except NotLoggedInError:
782
+ return _human_or_json_error(
783
+ f"Not logged in to the AWS CLI. {aws_login_remediation()}.",
784
+ as_json=as_json,
785
+ code="runtime",
786
+ )
787
+ except NotFoundError:
788
+ return _human_or_json_error(
789
+ f"Instance not found: {target.instance_id}",
790
+ as_json=as_json,
791
+ code="not_found",
792
+ )
793
+ except AccessDeniedError:
794
+ return _human_or_json_error(
795
+ "Permission denied for ec2:DescribeInstances.",
796
+ as_json=as_json,
797
+ code="permission_denied",
798
+ )
799
+ except MaproomParseError as exc:
800
+ if as_json:
801
+ return print_error_envelope("runtime", str(exc), invoked="analyze")
802
+ print(f"error: {exc}", file=sys.stderr)
803
+ return RUNTIME
804
+
805
+ if not instances:
806
+ return _human_or_json_error(
807
+ f"Instance not found: {target.instance_id}",
808
+ as_json=as_json,
809
+ code="not_found",
810
+ )
811
+
812
+ inst = instances[0]
813
+ now = (now_utc or (lambda: datetime.now(timezone.utc)))()
814
+ window_start, window_end = utilization_window(now)
815
+ metric_argv = build_cpu_utilization_argv(
816
+ target.instance_id,
817
+ start=window_start,
818
+ end=window_end,
819
+ )
820
+ metric_argv_with_region = metric_argv + ["--region", target.region]
821
+
822
+ print("Reading utilization...", file=sys.stderr, flush=True)
823
+ metric_result = runner.run(
824
+ "aws",
825
+ metric_argv_with_region,
826
+ record=False,
827
+ api_id="aws_cloudwatch_get_metric_data",
828
+ )
829
+ metric_response = _runner_response(metric_result)
830
+ cpu_metric_row: dict[str, Any] | None = None
831
+ try:
832
+ metric_rows = parse_cloudwatch_get_metric_data(
833
+ metric_response,
834
+ cli_version=metric_result.cli_version,
835
+ )
836
+ cpu_metric_row = metric_rows[0] if metric_rows else None
837
+ except AccessDeniedError:
838
+ print("Permission denied for cloudwatch:GetMetricData.", file=sys.stderr)
839
+ cpu_metric_row = None
840
+ except MaproomParseError as exc:
841
+ if as_json:
842
+ return print_error_envelope("runtime", str(exc), invoked="analyze")
843
+ print(f"error: {exc}", file=sys.stderr)
844
+ return RUNTIME
845
+
846
+ local_only = bool(getattr(args, "local_only", False))
847
+ print("Reading change history...", file=sys.stderr, flush=True)
848
+ instance_type_change = detect_instance_type_change(
849
+ instance_id=target.instance_id,
850
+ region=target.region,
851
+ instance=inst,
852
+ window_start=window_start,
853
+ window_end=window_end,
854
+ cpu_metric_row=cpu_metric_row,
855
+ runner=runner,
856
+ local_only=local_only,
857
+ now=now,
858
+ )
859
+ if instance_type_change.changed_at is not None and cpu_metric_row is not None:
860
+ cpu_metric_row = trim_cpu_metric_row(cpu_metric_row, instance_type_change.changed_at)
861
+ util_window_start, effective_util_days = effective_utilization_bounds(
862
+ window_start=window_start,
863
+ window_end=window_end,
864
+ changed_at=instance_type_change.changed_at,
865
+ )
866
+
867
+ inv_state = read_inventory_state()
868
+ saving_plan_state = read_saving_plan_state()
869
+ quota_state = read_quota_state()
870
+ coverage_missing = reservation_coverage_missing(inv_state)
871
+ headroom_missing = quota_headroom_missing(quota_state)
872
+ profile, missing_evidence = build_workload_profile(
873
+ target=target,
874
+ instance=inst,
875
+ cpu_metric_result=cpu_metric_row,
876
+ account_id=identity["Account"],
877
+ reservation_coverage_missing=coverage_missing,
878
+ quota_headroom_missing=headroom_missing,
879
+ )
880
+ if instance_type_change.changed_at is not None and not post_change_utilization_reliable(
881
+ changed_at=instance_type_change.changed_at,
882
+ metric_row=cpu_metric_row,
883
+ now=now,
884
+ ):
885
+ if "post_change_utilization" not in missing_evidence:
886
+ missing_evidence.append("post_change_utilization")
887
+
888
+ settings, _ = load_effective_settings(settings_read_file())
889
+ headroom_pct = int(settings.get("quota_headroom_pct") or 10)
890
+ extra_warnings_list: list[str] = []
891
+ for warning in (
892
+ stale_reservation_warning(inv_state),
893
+ stale_saving_plan_warning(saving_plan_state),
894
+ stale_quota_warning(quota_state),
895
+ ):
896
+ if warning:
897
+ extra_warnings_list.append(warning)
898
+ show_all = bool(getattr(args, "show_all", False))
899
+
900
+ region = profile.get("region") or target.region
901
+ instance_type = profile.get("instance_type") or ""
902
+ spec_catalog, spec_warnings = resolve_spec_catalog(
903
+ region=region,
904
+ current_instance_type=instance_type,
905
+ runner=runner,
906
+ local_only=local_only,
907
+ )
908
+ if spec_warnings:
909
+ extra_warnings_list.extend(spec_warnings)
910
+ extra_warnings = extra_warnings_list or None
911
+
912
+ if not local_only:
913
+ print("Reading provider recommendation...", file=sys.stderr, flush=True)
914
+ provider_fetch = resolve_provider_recommendation(
915
+ account_id=identity["Account"],
916
+ region=region,
917
+ instance_id=target.instance_id,
918
+ runner=runner,
919
+ local_only=local_only,
920
+ )
921
+
922
+ def _recommendation_doc(
923
+ *,
924
+ local_only_flag: bool,
925
+ declined_upload: bool = False,
926
+ service_upload_disabled: bool = False,
927
+ doc_extra_warnings: list[str] | None = None,
928
+ ) -> dict[str, Any]:
929
+ return build_recommendation_document(
930
+ target=target,
931
+ profile=profile,
932
+ missing_evidence=missing_evidence,
933
+ local_only=local_only_flag,
934
+ declined_upload=declined_upload,
935
+ service_upload_disabled=service_upload_disabled,
936
+ extra_warnings=doc_extra_warnings,
937
+ quota_state=quota_state,
938
+ quota_headroom_pct=headroom_pct,
939
+ spec_catalog=spec_catalog,
940
+ effective_settings=settings,
941
+ provider_fetch=provider_fetch,
942
+ instance_type_change=instance_type_change,
943
+ utilization_window_start=_iso_z(util_window_start),
944
+ effective_utilization_window_days=round(effective_util_days, 2),
945
+ now=now,
946
+ shape=shape,
947
+ )
948
+
949
+ recommendation: dict[str, Any]
950
+ upload_enabled = _rightsizer_upload_enabled(settings)
951
+ if local_only:
952
+ recommendation = _recommendation_doc(
953
+ local_only_flag=True,
954
+ doc_extra_warnings=extra_warnings,
955
+ )
956
+ elif not upload_enabled:
957
+ recommendation = _recommendation_doc(
958
+ local_only_flag=False,
959
+ service_upload_disabled=True,
960
+ doc_extra_warnings=extra_warnings,
961
+ )
962
+ else:
963
+ upload_gate = require_service_upload_consent(
964
+ consent_fleetfit_recommendations=bool(getattr(args, "consent_fleetfit_recommendations", False)),
965
+ quiet=as_json,
966
+ )
967
+ if upload_gate.exit_code != 0:
968
+ return finish_consent_gate(upload_gate, as_json=as_json, invoked="analyze")
969
+ if upload_gate.upload_allowed or upload_gate.reason_code == "upload_required":
970
+ recommendation = _recommendation_doc(
971
+ local_only_flag=False,
972
+ doc_extra_warnings=extra_warnings,
973
+ )
974
+ else:
975
+ recommendation = _recommendation_doc(
976
+ local_only_flag=False,
977
+ declined_upload=True,
978
+ doc_extra_warnings=extra_warnings,
979
+ )
980
+
981
+ accept_values = list(getattr(args, "accept", None) or [])
982
+ force_plan = bool(getattr(args, "force_plan", False))
983
+
984
+ if as_json and not accept_values:
985
+ if captured is not None:
986
+ captured.append(recommendation)
987
+ else:
988
+ print_json(recommendation)
989
+ return SUCCESS
990
+ if as_json and accept_values:
991
+ code, _ = run_accept_selection(
992
+ recommendation,
993
+ profile,
994
+ accept_values,
995
+ force=force_plan,
996
+ as_json=True,
997
+ )
998
+ return code
999
+ else:
1000
+ plan_name = current_plan.get_current_plan_name()
1001
+ summary = plan_summary_line(plan_name)
1002
+ reservations_summary = reservations_tty_segment(inv_state)
1003
+ saving_plans_summary = saving_plans_tty_segment(saving_plan_state)
1004
+ quotas_summary = quotas_tty_segment(quota_state)
1005
+ print(
1006
+ format_recommendation_tty(
1007
+ recommendation,
1008
+ account_id=identity["Account"],
1009
+ show_all=show_all,
1010
+ plan_summary=summary,
1011
+ reservations_summary=reservations_summary,
1012
+ saving_plans_summary=saving_plans_summary,
1013
+ quotas_summary=quotas_summary,
1014
+ )
1015
+ )
1016
+ if accept_values:
1017
+ code, _ = run_accept_selection(
1018
+ recommendation,
1019
+ profile,
1020
+ accept_values,
1021
+ force=force_plan,
1022
+ as_json=False,
1023
+ )
1024
+ return code
1025
+ if fleet:
1026
+ return SUCCESS
1027
+ return maybe_run_tty_selection(
1028
+ recommendation,
1029
+ profile,
1030
+ show_all=show_all,
1031
+ stdin_is_tty=sys.stdin.isatty(),
1032
+ stdout_is_tty=sys.stdout.isatty(),
1033
+ force=force_plan,
1034
+ )
1035
+
1036
+
1037
+ def cmd_doctor(args: argparse.Namespace) -> int:
1038
+ as_json = bool(getattr(args, "json", False))
1039
+ try:
1040
+ runner = command_runner()
1041
+ except MockEnvironmentError as exc:
1042
+ if as_json:
1043
+ return print_error_envelope("runtime", exc.message, invoked="doctor")
1044
+ print(exc.message, file=sys.stderr)
1045
+ return exit_code_for_error("runtime")
1046
+ return run_doctor(
1047
+ as_json=as_json,
1048
+ consent_cloud_reads=bool(getattr(args, "consent_cloud_reads", False)),
1049
+ consent_fleetfit_recommendations=bool(
1050
+ getattr(args, "consent_fleetfit_recommendations", False)
1051
+ ),
1052
+ force_color=bool(getattr(args, "color", False)),
1053
+ no_color=bool(getattr(args, "no_color", False)),
1054
+ redact_identity=bool(getattr(args, "redact_identity", False)),
1055
+ ctx=DoctorContext(runner=runner),
1056
+ )
1057
+
1058
+
1059
+ _COMMAND_PARSERS: dict[str, argparse.ArgumentParser] = {}
1060
+
1061
+
1062
+ def _help_topics() -> tuple[str, ...]:
1063
+ from maproom.root_help import help_topics_for
1064
+
1065
+ return help_topics_for()
1066
+
1067
+
1068
+ def cmd_maproom_version(args: argparse.Namespace) -> int:
1069
+ """Print the installed package version. Offline; no cloud or settings writes."""
1070
+ started_at = datetime.now(timezone.utc)
1071
+ as_json = bool(getattr(args, "json", False))
1072
+ if as_json:
1073
+ print_json(
1074
+ build_document(
1075
+ schema_type="maproom_version",
1076
+ schema_id="maproom.maproom_version",
1077
+ metadata=command_metadata("version", started_at=started_at),
1078
+ errors=[],
1079
+ warnings=[],
1080
+ payload={"version": __version__},
1081
+ )
1082
+ )
1083
+ else:
1084
+ print(f"maproom {__version__}")
1085
+ return SUCCESS
1086
+
1087
+
1088
+ def cmd_help(args: argparse.Namespace) -> int:
1089
+ topic = str(getattr(args, "topic", "") or "").strip().lower()
1090
+ parser = getattr(args, "parser", None)
1091
+ as_json = bool(getattr(args, "json", False))
1092
+ if not topic:
1093
+ if parser is None:
1094
+ parser = build_parser()
1095
+ parser.print_help()
1096
+ return SUCCESS
1097
+ target = _COMMAND_PARSERS.get(topic)
1098
+ visible = set(_help_topics())
1099
+ if target is None or topic not in visible:
1100
+ known = ", ".join(sorted(visible))
1101
+ message = f'unknown help topic "{topic}"'
1102
+ hint = f"topics: {known}"
1103
+ if as_json:
1104
+ return print_error_envelope(
1105
+ "usage",
1106
+ message,
1107
+ invoked="help",
1108
+ hint=hint,
1109
+ )
1110
+ print(f"error: {message}", file=sys.stderr)
1111
+ print(f"hint: {hint}", file=sys.stderr)
1112
+ return USAGE
1113
+ target.print_help()
1114
+ return SUCCESS
1115
+
1116
+
1117
+ def cmd_settings(args: argparse.Namespace) -> int:
1118
+ return run_settings_show(
1119
+ as_json=bool(getattr(args, "json", False)),
1120
+ include_consent_text=bool(getattr(args, "include_consent_text", False)),
1121
+ )
1122
+
1123
+
1124
+ def cmd_settings_init(args: argparse.Namespace) -> int:
1125
+ return run_settings_init(as_json=bool(getattr(args, "json", False)))
1126
+
1127
+
1128
+ def cmd_settings_set(args: argparse.Namespace) -> int:
1129
+ return run_settings_set(args.key, args.value)
1130
+
1131
+
1132
+ def cmd_plan(args: argparse.Namespace) -> int:
1133
+ from maproom.plan.commands import begin_plan_command
1134
+
1135
+ begin_plan_command()
1136
+ command = getattr(args, "plan_command", None)
1137
+ as_json = bool(getattr(args, "json", False))
1138
+ force = bool(getattr(args, "plan_force", False))
1139
+ interactive = sys.stdin.isatty()
1140
+ if command in (None, ""):
1141
+ return cmd_plan_show_current(as_json=as_json)
1142
+ if command == "list":
1143
+ return cmd_plan_list(as_json=as_json)
1144
+ if command == "show":
1145
+ return cmd_plan_show(args.name, as_json=as_json)
1146
+ if command == "use":
1147
+ return cmd_plan_use(args.name, stdin_is_tty=interactive, as_json=as_json)
1148
+ if command == "create":
1149
+ return cmd_plan_create(args.name, as_json=as_json)
1150
+ if command == "export":
1151
+ export_format = str(getattr(args, "plan_format", "markdown"))
1152
+ if as_json:
1153
+ export_format = "json"
1154
+ return cmd_plan_export(export_format)
1155
+ if command == "remove":
1156
+ return cmd_plan_remove(
1157
+ getattr(args, "item_id", None),
1158
+ force=force,
1159
+ stdin_is_tty=interactive,
1160
+ as_json=as_json,
1161
+ )
1162
+ if command == "clear":
1163
+ return cmd_plan_clear(args.name, force=force, stdin_is_tty=interactive)
1164
+ print(f'error: unknown plan command "{command}"', file=sys.stderr)
1165
+ print("hint: maproom plan -h", file=sys.stderr)
1166
+ return USAGE
1167
+
1168
+
1169
+ def _fleetfit_consent_help(version: int) -> str:
1170
+ if version == 1:
1171
+ return (
1172
+ "Approve a fleetfit-analyze price lookup for instance type, region, and platform only. "
1173
+ "Declining keeps the shipped Linux price and its warning."
1174
+ )
1175
+ if version == 2:
1176
+ return (
1177
+ "Approve sending a closed same-type size change body to fleetfit.ai. "
1178
+ "Declining leaves the completely safe local move."
1179
+ )
1180
+ if version == 3:
1181
+ return (
1182
+ "Approve sending descriptions without ids to fleetfit.ai for Spot and "
1183
+ "a same-type size change. Declining leaves the completely safe local move."
1184
+ )
1185
+ if version == 4:
1186
+ return (
1187
+ "Approve sending descriptions without ids to fleetfit.ai for Spot, a same-type "
1188
+ "size change, and a seven-day metric summary with keep-or-modify filters and the "
1189
+ "Optimizer grade. Declining leaves the earlier moves. No reservation inventory."
1190
+ )
1191
+ if version == 5:
1192
+ return (
1193
+ "Approve sending descriptions without ids to fleetfit.ai for Spot, a same-type "
1194
+ "size change, and reservation context. Reservation ids, instance ids, and "
1195
+ "quantities stay on the machine. The upload also includes a seven-day metric "
1196
+ "summary, keep-or-modify filters, and the Optimizer grade. "
1197
+ "Declining leaves the earlier moves."
1198
+ )
1199
+ if version == 6:
1200
+ return (
1201
+ "Approve sending descriptions without ids to fleetfit.ai for Spot, a same-type "
1202
+ "size change, and reservation context. Reservation ids, instance ids, and "
1203
+ "quantities stay on the machine. The upload also includes a seven-day metric "
1204
+ "summary, keep-or-modify filters, the Optimizer grade, and a quota lookup of "
1205
+ "region and instance type. Declining leaves the earlier moves."
1206
+ )
1207
+ return (
1208
+ "Approve sending descriptions without ids to fleetfit.ai, including a seven-day "
1209
+ "metric summary, keep-or-modify filters, and the Optimizer grade. "
1210
+ "Declining leaves the earlier moves."
1211
+ )
1212
+
1213
+
1214
+ def _series_analyze_description(version: int) -> str:
1215
+ quota_note = ""
1216
+ if version >= 6:
1217
+ quota_note = (
1218
+ "When series fit names a type outside the current quota family, maproom may "
1219
+ "ask fleetfit for the quota name, read your applied limit and usage, and print "
1220
+ "a quota increase. The increase is sent only after you approve that text. "
1221
+ "A support case is sent only after you decline the increase and choose that path.\n\n"
1222
+ )
1223
+ quota_help = ""
1224
+ if version < 6:
1225
+ quota_help = " Quota is not read."
1226
+ lead = ""
1227
+ if version >= 6:
1228
+ lead = quota_note
1229
+ quota_note = ""
1230
+ reservation_note = ""
1231
+ if version >= 5:
1232
+ reservation_note = (
1233
+ "--reservation-pack fill and restack both pack reservations the same way: fill reserved "
1234
+ "capacity first with workloads whose performance need that reservation can meet, then keep "
1235
+ "spillover on the cheapest available on-demand types that still meet the need.\n"
1236
+ )
1237
+ steering_note = ""
1238
+ if version >= 7:
1239
+ steering_note = (
1240
+ "\n"
1241
+ "Analyze may steer candidates using this machine's quota-request "
1242
+ "outcome ledger. "
1243
+ )
1244
+ if version == 7:
1245
+ steering_note += (
1246
+ "Sharing herd quota denial evidence through quota_telemetry "
1247
+ "is not finished; quota_telemetry is not a settings set key.\n"
1248
+ )
1249
+ else:
1250
+ steering_note += (
1251
+ "Capacity availability steering from launch history is the "
1252
+ "level-8 ceiling but is not in this release; analyze still "
1253
+ "matches version 7.\n"
1254
+ )
1255
+
1256
+ return (
1257
+ lead
1258
+ + f"product_version {version} is {product_version_name(version)}. "
1259
+ "FleetFit Analyze cross-family (or Stay) is the try-first recommendation when it returns.\n"
1260
+ + steering_note
1261
+ + reservation_note
1262
+ + "Approve sending a seven-day metric summary, the keep-or-modify filters, and the Optimizer grade,\n"
1263
+ "without names or account ids. A fit that exists only while network or disk is bursting does not pass.\n"
1264
+ "Declining leaves the fallback Spot or size move."
1265
+ + quota_help
1266
+ + " MapRoom does not resize, stop, or start an instance.\n"
1267
+ "\n"
1268
+ "Working set:\n"
1269
+ " maproom analyze aws\n"
1270
+ " maproom analyze azure\n"
1271
+ " maproom analyze i-0123456789abcdef0 --region us-east-1 one EC2 instance\n"
1272
+ " maproom analyze *api\n"
1273
+ "\n"
1274
+ "If you omit the cloud and only one of aws or azure is logged in, that cloud\n"
1275
+ "is used. If both are logged in, name the cloud. An instance id or ARN\n"
1276
+ "analyzes that one instance. With no id, analyze lists instances and\n"
1277
+ "walks them one by one. *text keeps instances whose id, name, type, or\n"
1278
+ "region contains that text.\n"
1279
+ "\n"
1280
+ + format_shape_catalog().rstrip("\n")
1281
+ + "\n\n"
1282
+ + quota_note
1283
+ )
1284
+
1285
+
1286
+ def _add_json_flag(parser: argparse.ArgumentParser, *, help_text: str) -> None:
1287
+ parser.add_argument(
1288
+ "--json",
1289
+ action="store_true",
1290
+ default=argparse.SUPPRESS,
1291
+ help=help_text,
1292
+ )
1293
+
1294
+
1295
+ def build_parser() -> argparse.ArgumentParser:
1296
+ version = product_version()
1297
+ parser = MaproomArgumentParser(
1298
+ prog="maproom",
1299
+ description=help_description_for(version),
1300
+ epilog=help_epilog_for(version),
1301
+ formatter_class=argparse.RawDescriptionHelpFormatter,
1302
+ )
1303
+ parser.add_argument(
1304
+ "--version",
1305
+ action="version",
1306
+ version=f"maproom {__version__}",
1307
+ )
1308
+ parser.add_argument(
1309
+ "--json",
1310
+ action="store_true",
1311
+ default=False,
1312
+ help="Machine-readable output",
1313
+ )
1314
+ sub = parser.add_subparsers(dest="command", parser_class=MaproomArgumentParser)
1315
+
1316
+ doctor = sub.add_parser(
1317
+ "doctor",
1318
+ prog="maproom doctor",
1319
+ help="Check Python, paths, and that the AWS and Azure CLIs are new enough",
1320
+ description=(
1321
+ "Preflight checks for Python, platform paths, and that the aws and az "
1322
+ "CLIs are new enough, plus consent-gated identity probes."
1323
+ ),
1324
+ )
1325
+ _add_json_flag(
1326
+ doctor,
1327
+ help_text=(
1328
+ "Emit JSON diagnostic report (schema_type doctor, schema_version 2; "
1329
+ "see docs/OUTPUT_CONTRACT.md)"
1330
+ ),
1331
+ )
1332
+ doctor.add_argument(
1333
+ "--redact-identity",
1334
+ action="store_true",
1335
+ help="Hide AWS role and Azure sign-in in the report",
1336
+ )
1337
+ doctor.add_argument(
1338
+ "--consent-cloud-reads",
1339
+ action="store_true",
1340
+ help="Grant cloud-read consent non-interactively (required in non-TTY without stored consent)",
1341
+ )
1342
+ if 2 <= version <= MAX_PRODUCT_VERSION:
1343
+ doctor.add_argument(
1344
+ "--consent-fleetfit-recommendations",
1345
+ action="store_true",
1346
+ help=_fleetfit_consent_help(version),
1347
+ )
1348
+ elif version >= RIGHTSIZER_MIN_PRODUCT_VERSION:
1349
+ doctor.add_argument(
1350
+ "--consent-fleetfit-recommendations",
1351
+ action="store_true",
1352
+ help=(
1353
+ "Grant consent for remote fleetfit.ai calls. "
1354
+ "Without it, recommendations use the local pricing file only."
1355
+ ),
1356
+ )
1357
+ doctor_color = doctor.add_mutually_exclusive_group()
1358
+ doctor_color.add_argument(
1359
+ "--color",
1360
+ action="store_true",
1361
+ help="Color PASS/FAIL/WARN/SKIPPED on stdout (default: on when stdout is a TTY)",
1362
+ )
1363
+ doctor_color.add_argument(
1364
+ "--no-color",
1365
+ action="store_true",
1366
+ help="Disable ANSI colors (also disabled when NO_COLOR is set or stdout is not a TTY)",
1367
+ )
1368
+ doctor.set_defaults(func=cmd_doctor)
1369
+
1370
+ identity_help = identity_subcommand_help(product_version=version)
1371
+ identity = sub.add_parser(
1372
+ "identity",
1373
+ help=identity_help,
1374
+ description=identity_help,
1375
+ )
1376
+ identity.add_argument(
1377
+ "--consent-cloud-reads",
1378
+ action="store_true",
1379
+ help="Grant cloud-read consent non-interactively (required in non-TTY without stored consent)",
1380
+ )
1381
+ _add_json_flag(identity, help_text="Machine-readable output")
1382
+ identity.set_defaults(func=cmd_identity)
1383
+
1384
+ maproom_version = sub.add_parser(
1385
+ "version",
1386
+ prog="maproom version",
1387
+ help="Print the installed maproom package version",
1388
+ description=(
1389
+ "Print the installed maproom package version. Offline. "
1390
+ "Does not read cloud accounts or write settings. "
1391
+ "--json emits schema_type maproom_version."
1392
+ ),
1393
+ )
1394
+ _add_json_flag(
1395
+ maproom_version,
1396
+ help_text=(
1397
+ "Emit JSON (schema_type maproom_version; see docs/OUTPUT_CONTRACT.md)"
1398
+ ),
1399
+ )
1400
+ maproom_version.set_defaults(func=cmd_maproom_version)
1401
+
1402
+ inventory = sub.add_parser(
1403
+ "inventory",
1404
+ help="Quotas, reservations, and savings plans, refreshed together",
1405
+ description=(
1406
+ "The inventory is quotas, reservations, and savings plans together. "
1407
+ "It is not the list of running instances. "
1408
+ "maproom inventory get refreshes all three. "
1409
+ "maproom inventory status reports each file. "
1410
+ "maproom inventory clear deletes all three. "
1411
+ "maproom inventory load reads one payer file."
1412
+ ),
1413
+ )
1414
+ _add_json_flag(inventory, help_text="Machine-readable output")
1415
+ inventory.set_defaults(func=cmd_inventory)
1416
+ inventory_sub = inventory.add_subparsers(
1417
+ dest="inventory_command", parser_class=MaproomArgumentParser
1418
+ )
1419
+
1420
+ inventory_status = inventory_sub.add_parser(
1421
+ "status",
1422
+ help="Show whether quotas, reservations, and savings plans are missing, fresh, or stale",
1423
+ )
1424
+ _add_json_flag(inventory_status, help_text="Machine-readable output")
1425
+ inventory_status.set_defaults(func=cmd_inventory)
1426
+
1427
+ inventory_get = inventory_sub.add_parser(
1428
+ "get",
1429
+ help="Refresh quotas, reservations, and savings plans together",
1430
+ description=(
1431
+ "Requires cloud-read consent. Downloads quotas, reservations, and "
1432
+ "savings plans in one refresh. There is no way to refresh one of them alone."
1433
+ ),
1434
+ )
1435
+ inventory_get.add_argument(
1436
+ "--consent-cloud-reads",
1437
+ action="store_true",
1438
+ help="Grant cloud-read consent non-interactively",
1439
+ )
1440
+ inventory_get.add_argument(
1441
+ "--cloud",
1442
+ default="all",
1443
+ help="Clouds to query: all, aws, azure, or aws,azure (default: all)",
1444
+ )
1445
+ inventory_get.add_argument(
1446
+ "--region",
1447
+ default=None,
1448
+ help="AWS region for regional reads (default: configured aws CLI region). Savings plans stay account-wide.",
1449
+ )
1450
+ inventory_get.add_argument(
1451
+ "--location",
1452
+ default=None,
1453
+ help="Azure region (default: az configure defaults.location or eastus)",
1454
+ )
1455
+ _add_json_flag(inventory_get, help_text="Machine-readable output")
1456
+ inventory_get.set_defaults(func=cmd_inventory)
1457
+
1458
+ inventory_clear = inventory_sub.add_parser(
1459
+ "clear",
1460
+ help="Delete quotas, reservations, and savings plans",
1461
+ description=(
1462
+ "Deletes the three inventory snapshot trees. "
1463
+ "Instance snapshots, plans, settings, and consent are kept."
1464
+ ),
1465
+ )
1466
+ inventory_clear.add_argument(
1467
+ "--force",
1468
+ action="store_true",
1469
+ help="Skip confirmation (required outside a TTY)",
1470
+ )
1471
+ _add_json_flag(inventory_clear, help_text="Machine-readable output")
1472
+ inventory_clear.set_defaults(func=cmd_inventory)
1473
+
1474
+ inventory_load = inventory_sub.add_parser(
1475
+ "load",
1476
+ help="Load one payer file into the inventory",
1477
+ description=(
1478
+ "Reads a local quotas, reservations, or savings-plans file. "
1479
+ "Does not contact cloud providers. This is not a refresh."
1480
+ ),
1481
+ )
1482
+ inventory_load.add_argument(
1483
+ "kind",
1484
+ choices=("quotas", "reservations", "savings-plans"),
1485
+ help="Which file this is: quotas, reservations, or savings-plans",
1486
+ )
1487
+ inventory_load.add_argument("path", help="Path to the payer JSON file")
1488
+ _add_json_flag(inventory_load, help_text="Machine-readable output")
1489
+ inventory_load.set_defaults(func=cmd_inventory)
1490
+
1491
+ inventory_show = inventory_sub.add_parser(
1492
+ "show",
1493
+ help="List rows in the current quotas, reservations, or savings-plans snapshot",
1494
+ description="Read-only view of one snapshot on disk.",
1495
+ )
1496
+ inventory_show.add_argument(
1497
+ "show_kind",
1498
+ choices=("quotas", "reservations", "savings-plans"),
1499
+ help="Which snapshot to display",
1500
+ )
1501
+ _add_json_flag(inventory_show, help_text="Machine-readable output")
1502
+ inventory_show.set_defaults(func=cmd_inventory)
1503
+
1504
+ if version <= 1:
1505
+ analyze_description = (
1506
+ "Look at AWS and Azure instances in a region and name one completely safe type, or none.\n"
1507
+ "\n"
1508
+ "Working set:\n"
1509
+ " maproom analyze aws\n"
1510
+ " maproom analyze azure\n"
1511
+ " maproom analyze i-0123456789abcdef0 --region us-east-1 one EC2 instance\n"
1512
+ " maproom analyze *api\n"
1513
+ "\n"
1514
+ "If you omit the cloud and only one of aws or azure is logged in, that cloud\n"
1515
+ "is used. If both are logged in, name the cloud. An instance id or ARN\n"
1516
+ "analyzes that one instance. *text keeps instances whose id, name, type, or\n"
1517
+ "region contains that text."
1518
+ )
1519
+ elif version == 2:
1520
+ analyze_description = (
1521
+ f"product_version {version} is {product_version_name(version)}.\n"
1522
+ "Look at AWS and Azure instances in a region and name one completely safe type, or none.\n"
1523
+ "For an AWS on-demand or Spot instance, approve sending a closed same-type size change\n"
1524
+ "body: request type, provider, region, instance, architecture, quota family,\n"
1525
+ "sample length, desired CPU p99, 1-minute or 5-minute p99 readings, and whether\n"
1526
+ "the window was trimmed from CloudTrail or Config. Fleetfit may answer with a\n"
1527
+ "half-size or next-size row. Declining leaves\n"
1528
+ "the completely safe local move. Azure stays on the local result. MapRoom does not\n"
1529
+ "resize, stop, or start an instance.\n"
1530
+ "\n"
1531
+ "Working set:\n"
1532
+ " maproom analyze aws\n"
1533
+ " maproom analyze azure\n"
1534
+ " maproom analyze i-0123456789abcdef0 --region us-east-1 one EC2 instance\n"
1535
+ " maproom analyze *api\n"
1536
+ "\n"
1537
+ "If you omit the cloud and only one of aws or azure is logged in, that cloud\n"
1538
+ "is used. If both are logged in, name the cloud. An instance id or ARN\n"
1539
+ "analyzes that one instance. With no id, analyze lists instances and\n"
1540
+ "walks them one by one. *text keeps instances whose id, name, type, or\n"
1541
+ "region contains that text."
1542
+ )
1543
+ elif version == 3:
1544
+ analyze_description = (
1545
+ f"product_version {version} is {product_version_name(version)}.\n"
1546
+ "Look at AWS and Azure instances in a region and name one completely safe type, or none.\n"
1547
+ "For an instance that is already Spot, approve sending the instance description\n"
1548
+ "without ids to fleetfit.ai, and see whether that instance has a cheaper pool.\n"
1549
+ "For on-demand, the answer comes from the local safe-move list. Declining leaves\n"
1550
+ "the completely safe local move. MapRoom does not resize, stop, or start an instance.\n"
1551
+ "\n"
1552
+ "Working set:\n"
1553
+ " maproom analyze aws\n"
1554
+ " maproom analyze azure\n"
1555
+ " maproom analyze i-0123456789abcdef0 --region us-east-1 one EC2 instance\n"
1556
+ " maproom analyze *api\n"
1557
+ "\n"
1558
+ "If you omit the cloud and only one of aws or azure is logged in, that cloud\n"
1559
+ "is used. If both are logged in, name the cloud. An instance id or ARN\n"
1560
+ "analyzes that one instance. With no id, analyze lists instances and\n"
1561
+ "walks them one by one. *text keeps instances whose id, name, type, or\n"
1562
+ "region contains that text."
1563
+ )
1564
+ elif version <= MAX_PRODUCT_VERSION:
1565
+ analyze_description = _series_analyze_description(version)
1566
+ else:
1567
+ analyze_description = (
1568
+ "Compare instances with the catalog and recommend a cheaper type "
1569
+ "that still fits recent utilization.\n"
1570
+ "\n"
1571
+ "Working set:\n"
1572
+ " maproom analyze aws\n"
1573
+ " maproom analyze azure\n"
1574
+ " maproom analyze i-0123456789abcdef0 --region us-east-1 one EC2 instance\n"
1575
+ " maproom analyze *api\n"
1576
+ "\n"
1577
+ "If you omit the cloud and only one of aws or azure is logged in, that cloud\n"
1578
+ "is used. If both are logged in, name the cloud. An instance id or ARN\n"
1579
+ "analyzes that one instance. With no id, analyze lists instances and\n"
1580
+ "walks them one by one. *text keeps instances whose id, name, type, or\n"
1581
+ "region contains that text.\n"
1582
+ "\n"
1583
+ + format_shape_catalog().rstrip("\n")
1584
+ )
1585
+ analyze = sub.add_parser(
1586
+ "analyze",
1587
+ help="Compare AWS and Azure instances with the catalog",
1588
+ description=analyze_description,
1589
+ formatter_class=argparse.RawDescriptionHelpFormatter,
1590
+ )
1591
+ consent = analyze.add_argument_group("consent")
1592
+ consent.add_argument(
1593
+ "--consent-cloud-reads",
1594
+ action="store_true",
1595
+ help="Grant cloud-read consent non-interactively (required in non-TTY without stored consent)",
1596
+ )
1597
+ if 2 <= version <= MAX_PRODUCT_VERSION:
1598
+ consent.add_argument(
1599
+ "--consent-fleetfit-recommendations",
1600
+ action="store_true",
1601
+ help=_fleetfit_consent_help(version),
1602
+ )
1603
+ consent.add_argument(
1604
+ "--local-only",
1605
+ action="store_true",
1606
+ help="Use the local pricing file only; never contact fleetfit.ai",
1607
+ )
1608
+ elif version >= RIGHTSIZER_MIN_PRODUCT_VERSION:
1609
+ consent.add_argument(
1610
+ "--consent-fleetfit-recommendations",
1611
+ action="store_true",
1612
+ help=(
1613
+ "Grant consent for remote fleetfit.ai calls. "
1614
+ "Without it, recommendations use the local pricing file only."
1615
+ ),
1616
+ )
1617
+ consent.add_argument(
1618
+ "--local-only",
1619
+ action="store_true",
1620
+ help="Use the local pricing file only; never contact fleetfit.ai",
1621
+ )
1622
+ analyze.add_argument(
1623
+ "selectors",
1624
+ nargs="*",
1625
+ help="Optional aws or azure, an instance id or ARN, or *text",
1626
+ )
1627
+ analyze.add_argument(
1628
+ "--region",
1629
+ help=(
1630
+ "AWS region (default: the current AWS CLI region). "
1631
+ "A bare instance id still needs this when no region is configured"
1632
+ ),
1633
+ )
1634
+ if 1 <= version <= MAX_PRODUCT_VERSION:
1635
+ analyze.add_argument(
1636
+ "--refresh",
1637
+ action="store_true",
1638
+ help=(
1639
+ "Ignore local instance, inventory, and analyze-reads caches for this run "
1640
+ "and re-pull from the cloud"
1641
+ ),
1642
+ )
1643
+ analyze.add_argument(
1644
+ "--recommend-kinds",
1645
+ default="",
1646
+ metavar="KINDS",
1647
+ help=(
1648
+ "Comma-separated recommend kinds to request "
1649
+ "(spot,size,safe_moves,cover,series,quota,price). "
1650
+ "spot and price map to purchase_option; omitted kinds follow "
1651
+ "product_version field-share defaults."
1652
+ ),
1653
+ )
1654
+ analyze.add_argument(
1655
+ "--share",
1656
+ action="append",
1657
+ default=[],
1658
+ choices=(
1659
+ "purchase_option",
1660
+ "metrics",
1661
+ "reservations",
1662
+ "series",
1663
+ "quota",
1664
+ "placement",
1665
+ "price",
1666
+ ),
1667
+ help=(
1668
+ "Share a field group on POST /v1/recommend (repeatable). "
1669
+ "placement and price are aliases for purchase_option. "
1670
+ "Groups above product_version are rejected."
1671
+ ),
1672
+ )
1673
+ analyze.add_argument(
1674
+ "--omit",
1675
+ action="append",
1676
+ default=[],
1677
+ choices=(
1678
+ "purchase_option",
1679
+ "metrics",
1680
+ "reservations",
1681
+ "series",
1682
+ "quota",
1683
+ "placement",
1684
+ "price",
1685
+ ),
1686
+ help="Omit a field group that product_version would otherwise share (repeatable).",
1687
+ )
1688
+ if 4 <= version <= MAX_PRODUCT_VERSION:
1689
+ analyze.add_argument(
1690
+ "--reservation-pack",
1691
+ choices=("fill", "restack"),
1692
+ default="fill",
1693
+ help=(
1694
+ "How to pack reservations you already have. fill and restack run the same rule: "
1695
+ "fill the reservation first with workloads that reserved type can meet; when "
1696
+ "some work spills, pick the pack that minimizes the on-demand cost of available "
1697
+ "fitting leftovers."
1698
+ ),
1699
+ )
1700
+ analyze.add_argument(
1701
+ "--shape",
1702
+ action="append",
1703
+ default=[],
1704
+ metavar="TOKENS",
1705
+ help=(
1706
+ "Attributes you will let change (modify_*) and attributes to keep (keep_*). "
1707
+ "Omit this to allow every attribute except burstable to change; "
1708
+ "name modify_burstable to let burstable change. "
1709
+ "When set, only these attributes are in play and the rest stay fixed. "
1710
+ "Repeat or comma-separate."
1711
+ ),
1712
+ )
1713
+ elif version >= RIGHTSIZER_MIN_PRODUCT_VERSION:
1714
+ analyze.add_argument(
1715
+ "--shape",
1716
+ action="append",
1717
+ default=[],
1718
+ metavar="TOKENS",
1719
+ help=(
1720
+ "Attributes you will let change (modify_*) and attributes to keep (keep_*). "
1721
+ "Repeat or comma-separate. The list is in this help."
1722
+ ),
1723
+ )
1724
+ analyze.add_argument(
1725
+ "--all",
1726
+ dest="show_all",
1727
+ action="store_true",
1728
+ help="Show conditional moves and curated rejected candidates",
1729
+ )
1730
+ analyze.add_argument(
1731
+ "--accept",
1732
+ action="append",
1733
+ default=[],
1734
+ metavar="OPTIONS",
1735
+ help=(
1736
+ "Non-interactive migration options to accept (repeatable or comma-separated; "
1737
+ "example: --accept no-migration)"
1738
+ ),
1739
+ )
1740
+ analyze.add_argument(
1741
+ "--force",
1742
+ dest="force_plan",
1743
+ action="store_true",
1744
+ help="Replace an existing plan item for the same resource during analyze selection",
1745
+ )
1746
+ _add_json_flag(analyze, help_text="Machine-readable output")
1747
+ analyze.set_defaults(func=cmd_analyze)
1748
+
1749
+ def _format_analyze_help() -> str:
1750
+ groups = list(analyze._action_groups)
1751
+ analyze._action_groups = [group for group in groups if group.title == "consent"] + [
1752
+ group for group in groups if group.title != "consent"
1753
+ ]
1754
+ try:
1755
+ return argparse.ArgumentParser.format_help(analyze)
1756
+ finally:
1757
+ analyze._action_groups = groups
1758
+
1759
+ analyze.format_help = _format_analyze_help # type: ignore[method-assign]
1760
+
1761
+ plan = sub.add_parser(
1762
+ "plan",
1763
+ help=argparse.SUPPRESS,
1764
+ description=(
1765
+ "Manage local plans under the platform data directory. "
1766
+ "Examples: maproom plan list; maproom plan show NAME; maproom plan use NAME; "
1767
+ "maproom plan create NAME; maproom plan clear NAME; maproom plan export "
1768
+ "[--format markdown|json]; maproom plan remove [ITEM-ID] [--force]."
1769
+ ),
1770
+ )
1771
+ _add_json_flag(plan, help_text="Machine-readable output for plan subcommands")
1772
+ plan_sub = plan.add_subparsers(dest="plan_command", parser_class=MaproomArgumentParser)
1773
+ plan_list = plan_sub.add_parser("list", help="List local plans")
1774
+ _add_json_flag(plan_list, help_text="Machine-readable plan list")
1775
+ plan_list.set_defaults(func=cmd_plan)
1776
+ plan_show = plan_sub.add_parser("show", help="Show one plan without making it current")
1777
+ plan_show.add_argument("name", help="Plan name")
1778
+ _add_json_flag(plan_show, help_text="Machine-readable plan")
1779
+ plan_show.set_defaults(func=cmd_plan)
1780
+ plan_use = plan_sub.add_parser(
1781
+ "use",
1782
+ help="Select the current plan",
1783
+ description=(
1784
+ "Select the current plan. New analyze selections are added to it."
1785
+ ),
1786
+ )
1787
+ plan_use.add_argument("name", help="Plan name")
1788
+ _add_json_flag(plan_use, help_text="Machine-readable plan selection result")
1789
+ plan_use.set_defaults(func=cmd_plan)
1790
+ plan_create = plan_sub.add_parser("create", help="Create a plan and make it current")
1791
+ plan_create.add_argument("name", help="Plan name")
1792
+ _add_json_flag(plan_create, help_text="Machine-readable plan create result")
1793
+ plan_create.set_defaults(func=cmd_plan)
1794
+ plan_export = plan_sub.add_parser("export", help="Export the current plan")
1795
+ plan_export.add_argument(
1796
+ "--format",
1797
+ dest="plan_format",
1798
+ choices=["markdown", "json"],
1799
+ default="markdown",
1800
+ help="Export format (default: markdown)",
1801
+ )
1802
+ _add_json_flag(plan_export, help_text="Export JSON")
1803
+ plan_export.set_defaults(func=cmd_plan)
1804
+ plan_remove = plan_sub.add_parser("remove", help="Remove one item from the current plan")
1805
+ plan_remove.add_argument("item_id", nargs="?", default=None, help="Item id")
1806
+ plan_remove.add_argument(
1807
+ "--force",
1808
+ dest="plan_force",
1809
+ action="store_true",
1810
+ help="Skip confirmation",
1811
+ )
1812
+ _add_json_flag(plan_remove, help_text="Machine-readable plan remove result")
1813
+ plan_remove.set_defaults(func=cmd_plan)
1814
+ plan_clear = plan_sub.add_parser("clear", help="Remove every item from a plan")
1815
+ plan_clear.add_argument("name", help="Plan name")
1816
+ plan_clear.add_argument(
1817
+ "--force",
1818
+ dest="plan_force",
1819
+ action="store_true",
1820
+ help="Skip confirmation",
1821
+ )
1822
+ plan_clear.set_defaults(func=cmd_plan)
1823
+ plan.set_defaults(func=cmd_plan)
1824
+
1825
+ data = sub.add_parser(
1826
+ "data",
1827
+ help="Manage local AWS and Azure data under the maproom data directory",
1828
+ description=(
1829
+ "Commands for the local data directory (inventory, instances, plans, "
1830
+ "and related files). Settings and consent are not removed by data clear."
1831
+ ),
1832
+ )
1833
+ data_sub = data.add_subparsers(
1834
+ dest="data_command", required=True, parser_class=MaproomArgumentParser
1835
+ )
1836
+ data_clear = data_sub.add_parser(
1837
+ "clear",
1838
+ help="Delete local plans and inventories. Settings and consent are kept.",
1839
+ description=(
1840
+ "Delete saved instance snapshots, quota/reservation/savings-plan "
1841
+ "inventories, local plans, analyze grades, and the request ledger. "
1842
+ "Settings and consent are kept."
1843
+ ),
1844
+ )
1845
+ data_clear.add_argument(
1846
+ "--force",
1847
+ action="store_true",
1848
+ help="Skip confirmation (required outside a TTY)",
1849
+ )
1850
+ data_clear.set_defaults(func=cmd_data_clear)
1851
+
1852
+ cache = sub.add_parser(
1853
+ "cache",
1854
+ help="Show or clear cached instance snapshots",
1855
+ description=(
1856
+ "Show the local instance snapshots, or delete them. "
1857
+ "Analyze writes the instance list into this cache. "
1858
+ "maproom cache clear removes instance snapshots. "
1859
+ "maproom cache clear aws* removes AWS instance snapshots. "
1860
+ "maproom cache clear azure* removes Azure instance snapshots. "
1861
+ "Quotas, reservations, savings plans, settings, and plans are kept."
1862
+ ),
1863
+ )
1864
+ _add_json_flag(cache, help_text="Emit the cache listing as JSON")
1865
+ cache_sub = cache.add_subparsers(
1866
+ dest="cache_command", parser_class=MaproomArgumentParser
1867
+ )
1868
+ cache_show = cache_sub.add_parser(
1869
+ "show",
1870
+ help="List cached instance snapshots for the signed-in account (needs the cloud CLI)",
1871
+ description=(
1872
+ "List local instance snapshots written by analyze. "
1873
+ "Entries are limited to the signed-in account, so the AWS or Azure CLI "
1874
+ "must be available to match account folders."
1875
+ ),
1876
+ )
1877
+ _add_json_flag(cache_show, help_text="Emit the cache listing as JSON")
1878
+ cache_show.set_defaults(func=cmd_cache)
1879
+ cache_clear = cache_sub.add_parser(
1880
+ "clear",
1881
+ help="Delete cached instance snapshots. Pass aws* or azure* to clear one cloud.",
1882
+ description=(
1883
+ "Delete local instance snapshots. Quotas, reservations, savings plans, "
1884
+ "settings, and plans are kept. Asks for confirmation in a terminal unless "
1885
+ "--force is set."
1886
+ ),
1887
+ )
1888
+ cache_clear.add_argument(
1889
+ "pattern",
1890
+ nargs="?",
1891
+ default="*",
1892
+ help="* clears all cached instances; aws* clears AWS; azure* clears Azure.",
1893
+ )
1894
+ cache_clear.add_argument(
1895
+ "--force",
1896
+ action="store_true",
1897
+ help="Skip confirmation (required outside a TTY)",
1898
+ )
1899
+ _add_json_flag(cache_clear, help_text="Emit removed folder names as JSON")
1900
+ cache_clear.set_defaults(func=cmd_cache)
1901
+ cache.set_defaults(func=cmd_cache)
1902
+
1903
+ settings = sub.add_parser(
1904
+ "settings",
1905
+ help="Show AWS and Azure settings path and effective values (read-only; does not create a file)",
1906
+ description=(
1907
+ "Show the settings file path and effective values. Read-only; "
1908
+ "does not create a file. Use `maproom settings init` to bootstrap."
1909
+ ),
1910
+ )
1911
+ _add_json_flag(settings, help_text="Emit settings JSON envelope")
1912
+ settings.add_argument(
1913
+ "--include-consent-text",
1914
+ action="store_true",
1915
+ help="Include the exact consent prompt that was approved",
1916
+ )
1917
+ settings_sub = settings.add_subparsers(
1918
+ dest="settings_command", parser_class=MaproomArgumentParser
1919
+ )
1920
+ settings_init = settings_sub.add_parser(
1921
+ "init",
1922
+ help="Create settings.toml with documented defaults when the file is missing",
1923
+ description=(
1924
+ "Create settings.toml with the documented defaults in the config directory. "
1925
+ "An existing file is left unchanged. "
1926
+ "Run maproom settings to see the path and values. "
1927
+ "Use maproom settings set for supported keys (see maproom settings set --help). "
1928
+ "quota_telemetry, quota_headroom_pct, and denial_suppress_days are init-only: "
1929
+ "edit them in the settings file, not via settings set."
1930
+ ),
1931
+ )
1932
+ _add_json_flag(settings_init, help_text="Emit settings init result as JSON")
1933
+ settings_init.set_defaults(func=cmd_settings_init)
1934
+ settings_show = settings_sub.add_parser(
1935
+ "show",
1936
+ help=argparse.SUPPRESS,
1937
+ description="Same as maproom settings (read-only show).",
1938
+ )
1939
+ _add_json_flag(settings_show, help_text="Emit settings JSON envelope")
1940
+ settings_show.add_argument(
1941
+ "--include-consent-text",
1942
+ action="store_true",
1943
+ help="Include the exact consent prompt that was approved",
1944
+ )
1945
+ settings_show.set_defaults(func=cmd_settings)
1946
+ settings_set = settings_sub.add_parser(
1947
+ "set",
1948
+ help=settings_set_short_help(),
1949
+ description=(
1950
+ "Write one key in settings.toml. Consent keys may prompt on a terminal. "
1951
+ "An unchanged value is reported as (unchanged) and the file is not rewritten."
1952
+ ),
1953
+ epilog=settings_set_value_epilog(),
1954
+ formatter_class=argparse.RawDescriptionHelpFormatter,
1955
+ )
1956
+ settings_set.add_argument(
1957
+ "key",
1958
+ help=settings_set_key_names_csv(),
1959
+ )
1960
+ settings_set.add_argument(
1961
+ "value",
1962
+ help="See the keys and value forms listed below",
1963
+ )
1964
+ settings_set.set_defaults(func=cmd_settings_set)
1965
+ settings.set_defaults(func=cmd_settings)
1966
+
1967
+ privacy_help = (
1968
+ "What Maproom reads from AWS/Azure, keeps on this computer, "
1969
+ "and may send to a recommendation service"
1970
+ )
1971
+ privacy = sub.add_parser(
1972
+ "privacy",
1973
+ help=privacy_help,
1974
+ description=(
1975
+ "Show the privacy statement, or AWS/Azure reads, local files, "
1976
+ "and recommendation-service details for one feature. "
1977
+ "Examples: maproom privacy; maproom privacy analyze; "
1978
+ "maproom privacy delete-uploads; maproom privacy doctor --json."
1979
+ ),
1980
+ )
1981
+ privacy.add_argument(
1982
+ "privacy_feature",
1983
+ nargs="?",
1984
+ default="",
1985
+ help="Feature manifest (analyze, doctor, inventory, fleetfit) or delete-uploads",
1986
+ )
1987
+ _add_json_flag(privacy, help_text="Machine-readable manifest")
1988
+ privacy.add_argument(
1989
+ "--accept",
1990
+ action="store_true",
1991
+ help="Record acceptance of the current FleetFit handling policy (fleetfit only)",
1992
+ )
1993
+ privacy.add_argument(
1994
+ "--force",
1995
+ action="store_true",
1996
+ help="Skip the confirmation prompt (delete-uploads only)",
1997
+ )
1998
+ privacy.set_defaults(func=cmd_privacy)
1999
+
2000
+ help_cmd = sub.add_parser(
2001
+ "help",
2002
+ help="Show this help, or help for one command",
2003
+ )
2004
+ help_cmd.add_argument(
2005
+ "topic",
2006
+ nargs="?",
2007
+ default="",
2008
+ help="Command to explain (same commands root help lists)",
2009
+ )
2010
+ help_cmd.set_defaults(func=cmd_help, parser=parser)
2011
+
2012
+ _COMMAND_PARSERS.clear()
2013
+ _COMMAND_PARSERS.update(
2014
+ {
2015
+ "doctor": doctor,
2016
+ "identity": identity,
2017
+ "version": maproom_version,
2018
+ "inventory": inventory,
2019
+ "analyze": analyze,
2020
+ "plan": plan,
2021
+ "data": data,
2022
+ "cache": cache,
2023
+ "settings": settings,
2024
+ "privacy": privacy,
2025
+ "help": help_cmd,
2026
+ }
2027
+ )
2028
+
2029
+ def _format_root_help() -> str:
2030
+ return format_grouped_root_help(parser)
2031
+
2032
+ parser.format_help = _format_root_help # type: ignore[method-assign]
2033
+ return parser
2034
+
2035
+
2036
+ def main(argv: list[str] | None = None) -> int:
2037
+ from maproom.redaction import install_redacting_sinks
2038
+
2039
+ install_redacting_sinks()
2040
+ parser = build_parser()
2041
+ prepared = prepare_argv(list(sys.argv[1:] if argv is None else argv))
2042
+ args = parser.parse_args(prepared)
2043
+ if not getattr(args, "command", None):
2044
+ if getattr(args, "json", False):
2045
+ return print_error_envelope("usage", "a command is required with --json")
2046
+ print(parser.format_help(), end="")
2047
+ return SUCCESS
2048
+ if getattr(args, "command", None) != "version" and getattr(
2049
+ args, "settings_command", None
2050
+ ) != "init":
2051
+ from maproom.paths import prepare_settings_write
2052
+ from maproom.service.install_id import ensure_anonymous_id
2053
+
2054
+ _settings_path = prepare_settings_write()
2055
+ if _settings_path.is_file():
2056
+ ensure_anonymous_id(_settings_path)
2057
+ if getattr(args, "settings_command", None):
2058
+ return int(args.func(args))
2059
+ if getattr(args, "inventory_command", None):
2060
+ return int(args.func(args))
2061
+ if getattr(args, "data_command", None):
2062
+ return int(args.func(args))
2063
+ try:
2064
+ return int(args.func(args))
2065
+ except CliTimeoutError:
2066
+ as_json = bool(getattr(args, "json", False))
2067
+ invoked = str(getattr(args, "command", None) or "maproom")
2068
+ if as_json:
2069
+ return print_error_envelope(
2070
+ "runtime", _CLI_TIMEOUT_MESSAGE, invoked=invoked
2071
+ )
2072
+ print(_CLI_TIMEOUT_MESSAGE, file=sys.stderr)
2073
+ return RUNTIME
2074
+ except KeyboardInterrupt:
2075
+ as_json = bool(getattr(args, "json", False))
2076
+ if as_json:
2077
+ invoked = str(getattr(args, "command", None) or "maproom")
2078
+ return print_error_envelope("runtime", "Analyze cancelled.", invoked=invoked)
2079
+ print("Analyze cancelled.", file=sys.stderr)
2080
+ return RUNTIME
2081
+
2082
+
2083
+ if __name__ == "__main__":
2084
+ raise SystemExit(main())