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,1134 @@
1
+ """Version 1 analyze: local completely-safe search, no upload."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import sys
9
+ from dataclasses import dataclass
10
+ from datetime import datetime, timezone
11
+ from decimal import Decimal
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from maproom.cliio.runner import CliBelowFloorError
16
+
17
+ from maproom.analyze.catalog import (
18
+ SpecRow,
19
+ load_azure_eastus_hourly,
20
+ load_spec_rows,
21
+ load_safe_move_types,
22
+ load_us_east_1_hourly,
23
+ )
24
+ from maproom.analyze.migration_method import MigrationDecision, decide_migration, migration_json_codes
25
+ from maproom.analyze.provider_comparison import (
26
+ ProviderRecommendation,
27
+ ec2_instance_arn,
28
+ fetch_provider_recommendation,
29
+ )
30
+ from maproom.analyze.safe_move import (
31
+ PRICE_ASSUMPTION,
32
+ UNCHECKED_COVERAGE,
33
+ BootFacts,
34
+ _boot_ok,
35
+ choose_target,
36
+ )
37
+ from maproom.analyze.migration_method import migration_method_human
38
+ from maproom.analyze.safe_moves_catalog import (
39
+ catalog_moves,
40
+ format_summary,
41
+ format_summary_human,
42
+ hourly_savings,
43
+ money,
44
+ source_target_summary,
45
+ )
46
+ from maproom.analyze.workset import (
47
+ AwsInstanceList,
48
+ RegionDescribeFailure,
49
+ WorkItem,
50
+ cloud_listing_error_code,
51
+ detect_logged_in_clouds,
52
+ filter_contains,
53
+ format_metrics_summary,
54
+ list_aws_instances,
55
+ list_azure_instances,
56
+ note_examining,
57
+ note_progress,
58
+ parse_analyze_selectors,
59
+ print_interactive_analyze_command_list,
60
+ print_interactive_analyze_preambles,
61
+ print_interactive_aws_scope,
62
+ resolve_cloud,
63
+ resolve_cloud_error_code,
64
+ )
65
+ from maproom.cli_floors import ensure_cli_floors, fail_cli_floor, format_below_floor
66
+ from maproom.consent import require_cloud_read_consent
67
+ from maproom.exitcodes import SUCCESS, exit_code_for_error
68
+ from maproom.mock_environment import MockEnvironmentError, command_runner
69
+ from maproom.output.json_envelope import (
70
+ build_document,
71
+ command_metadata,
72
+ error_item,
73
+ finish_consent_gate,
74
+ print_error_envelope,
75
+ print_json,
76
+ warning_item,
77
+ )
78
+ from maproom.parsers import parse_sts_identity
79
+ from maproom.paths import data_subdir
80
+ from maproom.plan.errors import PlanError
81
+ from maproom.pricing.prices import load_price_table
82
+ from maproom.quotas import store as quota_store
83
+ from maproom.redaction import redact_text, redact_tree
84
+ from maproom.reservations import store as reservation_store
85
+
86
+ _OFFERED: dict[tuple[str, str], OfferingRead] = {}
87
+ _NOT_READ = object()
88
+
89
+ _AWS_PRICE_ID = "aws_ec2_ondemand_linux"
90
+ _AZURE_PRICE_ID = "azure_vm_linux"
91
+ _RESERVATION_WARNING = "Reservation coverage was not used."
92
+ _QUOTA_WARNING = "Quota coverage was not used."
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class OfferingRead:
97
+ """A region catalog, or a failed read. An empty set is a real catalog."""
98
+
99
+ types: frozenset[str] | None
100
+ message: str = ""
101
+
102
+ @property
103
+ def ok(self) -> bool:
104
+ return self.types is not None
105
+
106
+
107
+ def _strip_human_only_analyze_row(row: dict[str, Any]) -> dict[str, Any]:
108
+ cleaned = dict(row)
109
+ lookup = cleaned.get("size_lookup")
110
+ if isinstance(lookup, dict):
111
+ stripped = dict(lookup)
112
+ stripped.pop("metric_readings", None)
113
+ cleaned["size_lookup"] = stripped
114
+ return cleaned
115
+
116
+
117
+ @dataclass
118
+ class _Assessment:
119
+ text: str
120
+ recommendation: dict[str, Any] | None = None
121
+ examined: dict[str, Any] | None = None
122
+ spec_missing: bool = False
123
+ offerings_message: str | None = None
124
+ scored: bool = False
125
+ cross_family_target: str | None = None
126
+
127
+
128
+ @dataclass
129
+ class AnalyzeRunBanners:
130
+ spot_missing_policy: bool = False
131
+ size_missing_policy: bool = False
132
+ size_unreachable_line: str | None = None
133
+ recommend_unreachable_line: str | None = None
134
+ series_declined: bool = False
135
+ series_missing_policy: bool = False
136
+ series_not_configured: bool = False
137
+ series_not_implemented: bool = False
138
+
139
+
140
+ def _print_lookup_run_banners(banners: AnalyzeRunBanners) -> None:
141
+ from maproom.analyze.series_lookup import (
142
+ DECLINED_LINE,
143
+ MISSING_POLICY_LINE as SERIES_MISSING,
144
+ NOT_CONFIGURED_LINE,
145
+ NOT_IMPLEMENTED_LINE,
146
+ )
147
+ from maproom.analyze.size_analyze import MISSING_POLICY_LINE as SIZE_MISSING
148
+ from maproom.analyze.spot_analyze import MISSING_POLICY_LINE as SPOT_MISSING
149
+
150
+ lines: list[str] = []
151
+ if banners.spot_missing_policy:
152
+ lines.append(SPOT_MISSING)
153
+ if banners.size_missing_policy:
154
+ lines.append(SIZE_MISSING)
155
+ if banners.size_unreachable_line:
156
+ lines.append(banners.size_unreachable_line)
157
+ if banners.recommend_unreachable_line:
158
+ lines.append(banners.recommend_unreachable_line)
159
+ if banners.series_missing_policy:
160
+ lines.append(SERIES_MISSING)
161
+ if banners.series_declined:
162
+ lines.append(DECLINED_LINE)
163
+ if banners.series_not_configured:
164
+ lines.append(NOT_CONFIGURED_LINE)
165
+ if banners.series_not_implemented:
166
+ lines.append(NOT_IMPLEMENTED_LINE)
167
+ for index, line in enumerate(lines):
168
+ if index:
169
+ print()
170
+ print(line, flush=True)
171
+
172
+
173
+ def _fail(
174
+ message: str,
175
+ *,
176
+ as_json: bool,
177
+ code: str,
178
+ started_at: datetime | None = None,
179
+ ) -> int:
180
+ if as_json:
181
+ metadata = (
182
+ command_metadata("analyze", started_at=started_at)
183
+ if started_at is not None
184
+ else None
185
+ )
186
+ return print_error_envelope(
187
+ code,
188
+ message,
189
+ invoked="analyze",
190
+ metadata=metadata,
191
+ )
192
+ print(message, file=sys.stderr)
193
+ return exit_code_for_error(code)
194
+
195
+
196
+ def _fail_listing(
197
+ err: PlanError,
198
+ *,
199
+ as_json: bool,
200
+ started_at: datetime,
201
+ ) -> int:
202
+ return _fail(
203
+ err.message,
204
+ as_json=as_json,
205
+ code=cloud_listing_error_code(err.message),
206
+ started_at=started_at,
207
+ )
208
+
209
+
210
+ def _service_code(cloud: str) -> str:
211
+ if cloud == "azure":
212
+ return "Microsoft.Compute"
213
+ return "ec2"
214
+
215
+
216
+ def _price_id(cloud: str) -> str:
217
+ if cloud == "azure":
218
+ return _AZURE_PRICE_ID
219
+ return _AWS_PRICE_ID
220
+
221
+
222
+ def _price_entry(cloud: str) -> dict[str, Any]:
223
+ if cloud == "azure":
224
+ return {"id": _AZURE_PRICE_ID, "published_at": None}
225
+ published = load_price_table().published_at or None
226
+ return {"id": _AWS_PRICE_ID, "published_at": published}
227
+
228
+
229
+ def _price_entries(selected: str | None, items: list[WorkItem]) -> list[dict[str, Any]]:
230
+ """Price ids for clouds that were consulted.
231
+
232
+ A cloud with instances is included. When nothing matched, the selected
233
+ cloud is included. When the run was not cloud-specific and nothing
234
+ matched, both price ids are included.
235
+ """
236
+ clouds: list[str] = []
237
+ if items:
238
+ for item in items:
239
+ if item.cloud in {"aws", "azure"} and item.cloud not in clouds:
240
+ clouds.append(item.cloud)
241
+ elif selected in {"aws", "azure"}:
242
+ clouds = [selected]
243
+ else:
244
+ clouds = ["aws", "azure"]
245
+ return [_price_entry(cloud) for cloud in clouds]
246
+
247
+
248
+ def _identity(item: WorkItem) -> dict[str, Any]:
249
+ return {
250
+ "cloud": item.cloud,
251
+ "service_code": _service_code(item.cloud),
252
+ "region": item.region,
253
+ "instance_id": item.instance_id,
254
+ "instance_name": item.name,
255
+ "current": {"instance_type": item.instance_type},
256
+ }
257
+
258
+
259
+ def _has_reservations(payload: dict[str, Any]) -> bool:
260
+ records = payload.get("records")
261
+ if isinstance(records, list) and len(records) > 0:
262
+ return True
263
+ count = payload.get("record_count")
264
+ return isinstance(count, int) and count > 0
265
+
266
+
267
+ def _coverage_warnings(
268
+ scored: bool,
269
+ *,
270
+ coverage_checked: bool = False,
271
+ reservations_in_scope: bool = True,
272
+ quotas_in_scope: bool = True,
273
+ ) -> list[dict[str, Any]]:
274
+ if not scored:
275
+ return []
276
+ warnings: list[dict[str, Any]] = []
277
+ if reservations_in_scope:
278
+ if coverage_checked:
279
+ pass
280
+ else:
281
+ warnings.append(
282
+ warning_item("reservation_coverage_not_used", UNCHECKED_COVERAGE)
283
+ )
284
+ reservations = reservation_store.read_snapshot()
285
+ if isinstance(reservations, dict) and _has_reservations(reservations):
286
+ warnings.append(
287
+ warning_item("reservation_coverage_not_used", _RESERVATION_WARNING)
288
+ )
289
+ if quotas_in_scope and quota_store.has_snapshot():
290
+ warnings.append(warning_item("quota_coverage_not_used", _QUOTA_WARNING))
291
+ return warnings
292
+
293
+
294
+ def _listing(
295
+ listed: AwsInstanceList | list[WorkItem] | PlanError,
296
+ ) -> tuple[list[WorkItem], list[RegionDescribeFailure], str, dict[str, list[dict[str, Any]]]] | PlanError:
297
+ if isinstance(listed, PlanError):
298
+ return listed
299
+ if isinstance(listed, AwsInstanceList):
300
+ return list(listed.items), list(listed.failures), listed.region, dict(listed.block_devices or {})
301
+ return list(listed), [], "", {}
302
+
303
+
304
+
305
+
306
+ def _stdout_is_interactive(*, as_json: bool) -> bool:
307
+ """Human layout for a terminal. Piped and --json output stay line-oriented."""
308
+ if as_json:
309
+ return False
310
+ try:
311
+ return bool(sys.stdout.isatty())
312
+ except (AttributeError, ValueError):
313
+ return False
314
+
315
+
316
+ def _instance_title(item: WorkItem) -> str:
317
+ name = item.name.strip()
318
+ if name and name != item.instance_id:
319
+ return name
320
+ return item.instance_id
321
+
322
+
323
+ def _interactive_identity_line(item: WorkItem) -> str:
324
+ title = _instance_title(item)
325
+ if title == item.instance_id:
326
+ return item.instance_id
327
+ return f"{title} ({item.instance_id})"
328
+
329
+
330
+ def _interactive_type_metrics_line(
331
+ item: WorkItem,
332
+ assessment: _Assessment,
333
+ *,
334
+ product_version: int,
335
+ ) -> str:
336
+ row = assessment.recommendation or assessment.examined
337
+ metrics = format_metrics_summary(item, row if isinstance(row, dict) else None, product_version=product_version)
338
+ kind = item.instance_type.strip() or "unknown type"
339
+ if metrics:
340
+ return f"{kind} · {metrics}"
341
+ return kind
342
+
343
+
344
+ NO_RECOMMENDATION_HEADLINE = (
345
+ "No instance size or type change recommendations at this time."
346
+ )
347
+ _LEGACY_NO_LOWER_PRICE = "No lower-priced instance with better specs."
348
+ _NOT_EVALUATED_AZURE = (
349
+ "Not evaluated: maproom has no Azure price or spec table in this release."
350
+ )
351
+ _FLEETFIT_POLICY_OFFER_NOTE = (
352
+ " If you have not accepted the current FleetFit data-handling policy yet, "
353
+ "maproom will show it next and ask you to accept it (see maproom privacy fleetfit)."
354
+ )
355
+ _SPOT_OFFER = (
356
+ "Some of these instances are Spot. Maproom can also check for a lower-priced "
357
+ "Spot instance in each Availability Zone. That is product version 3. May we "
358
+ "send an anonymous price lookup to FleetFit Analyze?"
359
+ + _FLEETFIT_POLICY_OFFER_NOTE
360
+ )
361
+ _SIZE_OFFER = (
362
+ "Maproom can pull CloudWatch metrics and recommend sizing up and sizing down. "
363
+ "That is product version 2. May we do that?"
364
+ + _FLEETFIT_POLICY_OFFER_NOTE
365
+ )
366
+ _SERIES_OFFER = (
367
+ "Maproom can compare a week of CloudWatch metrics across instance families via "
368
+ "FleetFit Analyze. That is product version 4. May we do that?"
369
+ + _FLEETFIT_POLICY_OFFER_NOTE
370
+ )
371
+ _RESERVATION_OFFER = (
372
+ "Maproom can read reservations you already have and prefer a type those "
373
+ "reservations cover. That is product version 5. May we do that?"
374
+ + _FLEETFIT_POLICY_OFFER_NOTE
375
+ )
376
+ _LATER_HINTS = {
377
+ 3: (
378
+ "Product version 4 can compare a week of CloudWatch metrics across instance "
379
+ "families. Every shape attribute except burstable may change until you "
380
+ "pass --shape; burstable stays fixed unless you name modify_burstable."
381
+ ),
382
+ 4: (
383
+ "Run maproom settings set product_version 5 to include unused reservation "
384
+ "positions in the Analyze recommendation."
385
+ ),
386
+ 5: (
387
+ "Run maproom settings set product_version 6 to check whether a type outside "
388
+ "the current quota family is launchable after a cross-family recommendation."
389
+ ),
390
+ }
391
+
392
+ _RUN_VERSION_SAFE_ONLY = 1
393
+ _RUN_VERSION_SIZE = 2
394
+ _RUN_VERSION_SPOT = 3
395
+ _RUN_VERSION_SERIES = 4
396
+ _RUN_VERSION_RESERVATIONS = 5
397
+ _RUN_VERSION_QUOTA = 6
398
+
399
+
400
+ def _run_version(
401
+ *,
402
+ spot_lookup: bool,
403
+ size_lookup: bool,
404
+ reservation_reorder: bool,
405
+ series_lookup: bool,
406
+ quota_management: bool,
407
+ ) -> int:
408
+ if quota_management:
409
+ return _RUN_VERSION_QUOTA
410
+ if reservation_reorder:
411
+ return _RUN_VERSION_RESERVATIONS
412
+ if series_lookup:
413
+ return _RUN_VERSION_SERIES
414
+ if spot_lookup:
415
+ return _RUN_VERSION_SPOT
416
+ if size_lookup:
417
+ return _RUN_VERSION_SIZE
418
+ return _RUN_VERSION_SAFE_ONLY
419
+
420
+
421
+ def next_product_offer(version: int, items: list[WorkItem]) -> tuple[int, str] | None:
422
+ """The next recommendation level an interactive low-version run can offer."""
423
+ aws_items = [item for item in items if item.cloud == "aws"]
424
+ if not aws_items or version >= 5:
425
+ return None
426
+ from maproom.analyze.spot_analyze import is_spot_instance
427
+
428
+ if version < 2:
429
+ return 2, _SIZE_OFFER
430
+ if version < 3 and any(is_spot_instance(item) for item in aws_items):
431
+ return 3, _SPOT_OFFER
432
+ if version < 4:
433
+ return 4, _SERIES_OFFER
434
+ return 5, _RESERVATION_OFFER
435
+
436
+
437
+ def _save_product_version(version: int) -> bool:
438
+ """Persist like ``settings set product_version``: operator block, then consent prompts."""
439
+ from maproom.paths import prepare_settings_write
440
+ from maproom.settings.model import load_effective_settings
441
+ from maproom.settings.product_version_change import (
442
+ print_product_version_operator_block,
443
+ prompt_product_version_consent_changes,
444
+ )
445
+ from maproom.settings.product_versions import product_version_name
446
+ from maproom.settings.write import persist_settings
447
+
448
+ path = prepare_settings_write()
449
+ before, _ = load_effective_settings(path)
450
+ old = int(before.get("product_version", 1))
451
+ err = persist_settings(path, {"product_version": version})
452
+ if err is not None:
453
+ print(f"error: {err.message}", file=sys.stderr)
454
+ return False
455
+ print(f"product_version is now {version} ({product_version_name(version)}).")
456
+ after, _ = load_effective_settings(path)
457
+ print_product_version_operator_block(version, after)
458
+ prompt_product_version_consent_changes(
459
+ path,
460
+ old_version=old,
461
+ new_version=version,
462
+ settings=after,
463
+ )
464
+ return True
465
+
466
+
467
+ def _print_fleetfit_handling_policy(
468
+ policy: dict[str, Any],
469
+ *,
470
+ settings: dict[str, Any] | None,
471
+ ) -> None:
472
+ from maproom.privacy.fleetfit_statement import format_fleetfit_tty
473
+
474
+ print(format_fleetfit_tty(policy, settings=settings), end="")
475
+
476
+
477
+ def _accept_fleetfit_policy_for_version(
478
+ *,
479
+ chosen: int,
480
+ read_path: Path,
481
+ ) -> bool:
482
+ from maproom.analyze.fleetfit_policy import persist_fleetfit_policy_grant, stored_fleetfit_policy_id
483
+ from maproom.paths import prepare_settings_write
484
+ from maproom.privacy.fleetfit_policy import FleetFitPolicyFetchError, fetch_current_handling_policy
485
+ from maproom.settings.model import load_effective_settings
486
+
487
+ print("Loading the FleetFit handling policy...", flush=True)
488
+ settings, _ = load_effective_settings(read_path)
489
+ try:
490
+ policy = fetch_current_handling_policy(settings)
491
+ except FleetFitPolicyFetchError as exc:
492
+ print(f"Could not load the FleetFit handling policy: {exc}", file=sys.stderr)
493
+ return False
494
+ stored = stored_fleetfit_policy_id(settings)
495
+ if stored == policy["policy_id"]:
496
+ return True
497
+ _print_fleetfit_handling_policy(policy, settings=settings)
498
+ print()
499
+ print(
500
+ f"Accept FleetFit policy {policy['policy_id']} to enable product version {chosen}?"
501
+ )
502
+ print("y = yes, Enter = not now")
503
+ try:
504
+ answer = input().strip().lower()
505
+ except EOFError:
506
+ return False
507
+ if answer not in {"y", "yes"}:
508
+ return False
509
+ err = persist_fleetfit_policy_grant(
510
+ prepare_settings_write(),
511
+ policy_id=policy["policy_id"],
512
+ policy_url=policy["document_url"],
513
+ )
514
+ if err is not None:
515
+ print(f"error: {err.message}", file=sys.stderr)
516
+ return False
517
+ return True
518
+
519
+
520
+ def accept_next_product_version(version: int, items: list[WorkItem]) -> int | None:
521
+ """Ask to raise to the next recommendation level. None means keep the current level."""
522
+ from maproom.consent.stdin import stdin_allows_prompt
523
+ from maproom.paths import settings_read_file
524
+
525
+ offer = next_product_offer(version, items)
526
+ if offer is None or not stdin_allows_prompt():
527
+ return None
528
+ chosen, question = offer
529
+ print()
530
+ print(question)
531
+ print("y = yes, Enter = not now")
532
+ try:
533
+ answer = input().strip().lower()
534
+ except EOFError:
535
+ return None
536
+ if answer not in {"y", "yes"}:
537
+ return None
538
+ if chosen >= _RUN_VERSION_SIZE:
539
+ if not _accept_fleetfit_policy_for_version(chosen=chosen, read_path=settings_read_file()):
540
+ print(
541
+ "The next-version offer was skipped. The results above are complete.",
542
+ flush=True,
543
+ )
544
+ return None
545
+ if not _save_product_version(chosen):
546
+ return None
547
+ return chosen
548
+
549
+
550
+ def _rest_has_size_lookup_move(rest: list[str]) -> bool:
551
+ """True when size lookup appended a move line after a v1 no-recommendation head."""
552
+ return any(line.strip().startswith("Move from ") for line in rest)
553
+
554
+
555
+ def interactive_conclusion(item: WorkItem, text: str) -> str:
556
+ """Drop the repeated identity prefix and lead with the result."""
557
+ label = item.label()
558
+ lines = (text or "").splitlines()
559
+ if not lines:
560
+ return NO_RECOMMENDATION_HEADLINE
561
+ first = lines[0]
562
+ rest = lines[1:]
563
+ move_prefix = f"{label} -> "
564
+ detail_prefix = f"{label}: "
565
+ no_recommendation_heads = {
566
+ NO_RECOMMENDATION_HEADLINE,
567
+ _LEGACY_NO_LOWER_PRICE,
568
+ f"{label} does not have a recommend default safe move.",
569
+ f"{label}: No completely safe move.",
570
+ f"{label}: {NO_RECOMMENDATION_HEADLINE}",
571
+ f"{label}: {_LEGACY_NO_LOWER_PRICE}",
572
+ "no completely safe type.",
573
+ "No completely safe type.",
574
+ }
575
+ if first in no_recommendation_heads:
576
+ first = NO_RECOMMENDATION_HEADLINE
577
+ elif first.startswith(move_prefix):
578
+ first = f"Move to {first[len(move_prefix):]}"
579
+ elif first.startswith(detail_prefix):
580
+ first = first[len(detail_prefix):]
581
+ if first in {"no completely safe type.", "No completely safe type."}:
582
+ first = NO_RECOMMENDATION_HEADLINE
583
+ elif first in {_LEGACY_NO_LOWER_PRICE, NO_RECOMMENDATION_HEADLINE, "No completely safe move."}:
584
+ first = NO_RECOMMENDATION_HEADLINE
585
+ elif first.startswith(label):
586
+ stripped = first[len(label):].lstrip(" :")
587
+ if stripped in {_LEGACY_NO_LOWER_PRICE, NO_RECOMMENDATION_HEADLINE}:
588
+ first = NO_RECOMMENDATION_HEADLINE
589
+ else:
590
+ first = stripped
591
+ if first == NO_RECOMMENDATION_HEADLINE and _rest_has_size_lookup_move(rest):
592
+ body = "\n".join(rest).strip()
593
+ return body or NO_RECOMMENDATION_HEADLINE
594
+ body = "\n".join([first, *rest]).strip()
595
+ if body and rest:
596
+ return body
597
+ return body or NO_RECOMMENDATION_HEADLINE
598
+
599
+
600
+ def _print_active_shapes(shape: Any) -> None:
601
+ from maproom.analyze.shape import format_active_shapes
602
+
603
+ print(format_active_shapes(shape), flush=True)
604
+ print(flush=True)
605
+
606
+
607
+ def _print_interactive_conclusion(
608
+ item: WorkItem,
609
+ text: str,
610
+ *,
611
+ metrics_line: str | None = None,
612
+ product_version: int = 1,
613
+ ) -> None:
614
+ conclusion = interactive_conclusion(item, text)
615
+ if metrics_line:
616
+ filtered = [
617
+ line
618
+ for line in conclusion.splitlines()
619
+ if line.strip() and line.strip() != metrics_line
620
+ ]
621
+ conclusion = "\n".join(filtered)
622
+ if not conclusion.strip():
623
+ return
624
+ stripped_lines = [line.strip() for line in conclusion.splitlines() if line.strip()]
625
+ if stripped_lines == [NO_RECOMMENDATION_HEADLINE]:
626
+ return
627
+ for line in conclusion.splitlines():
628
+ if line.strip():
629
+ print(f" {line}", flush=True)
630
+ if product_version == 1 and UNCHECKED_COVERAGE not in conclusion:
631
+ print(f" {UNCHECKED_COVERAGE}", flush=True)
632
+
633
+
634
+ def _print_interactive_results(
635
+ held: list[tuple[Any, Any]],
636
+ *,
637
+ product_version: int,
638
+ ) -> None:
639
+ print("Results:", flush=True)
640
+ for index, (item, assessment) in enumerate(held, start=1):
641
+ if index > 1:
642
+ print(flush=True)
643
+ print(_interactive_identity_line(item), flush=True)
644
+ row = assessment.recommendation or assessment.examined
645
+ metrics_summary = format_metrics_summary(
646
+ item,
647
+ row if isinstance(row, dict) else None,
648
+ product_version=product_version,
649
+ )
650
+ print(
651
+ _interactive_type_metrics_line(item, assessment, product_version=product_version),
652
+ flush=True,
653
+ )
654
+ row_for_size = assessment.recommendation or assessment.examined
655
+ size_lookup = (
656
+ row_for_size.get("size_lookup")
657
+ if isinstance(row_for_size, dict)
658
+ else None
659
+ )
660
+ omit_no_rec = (
661
+ isinstance(size_lookup, dict)
662
+ and size_lookup.get("omitted")
663
+ and interactive_conclusion(item, assessment.text).strip()
664
+ == NO_RECOMMENDATION_HEADLINE
665
+ )
666
+ if not omit_no_rec:
667
+ _print_interactive_conclusion(
668
+ item,
669
+ assessment.text,
670
+ metrics_line=metrics_summary,
671
+ product_version=product_version,
672
+ )
673
+
674
+
675
+ def render_item(item: WorkItem, *, runner: Any, specs: dict[tuple[str, str], SpecRow]) -> str:
676
+ return assess_item(item, runner=runner, specs=specs).text
677
+
678
+
679
+ def assess_item(
680
+ item: WorkItem,
681
+ *,
682
+ runner: Any,
683
+ specs: dict[tuple[str, str], SpecRow],
684
+ use_catalog: bool = False,
685
+ product_version: int = 0,
686
+ ) -> _Assessment:
687
+ """Score one instance. The run document is built from these pieces."""
688
+ identity = _identity(item)
689
+ if item.cloud == "azure":
690
+ from maproom.analyze.catalog import load_azure_eastus_hourly
691
+
692
+ has_azure_specs = any(cloud == "azure" for (cloud, _type) in specs)
693
+ if use_catalog and not load_azure_eastus_hourly() and not has_azure_specs:
694
+ return _Assessment(
695
+ text=f"{item.label()}: {_NOT_EVALUATED_AZURE}",
696
+ examined={**identity, "outcome": "not_evaluated"},
697
+ )
698
+ if use_catalog:
699
+ published = catalog_moves(item.cloud, item.instance_type)
700
+ if published:
701
+ return _assess_catalog_moves(item, runner=runner, specs=specs, moves=published)
702
+ move_targets = _move_targets(item.instance_type)
703
+ safe_move_types = set(load_safe_move_types(item.cloud))
704
+ current = specs.get((item.cloud, item.instance_type))
705
+ if move_targets is None and item.instance_type not in safe_move_types:
706
+ if product_version == 1:
707
+ optimizer_offer = _optimizer_offer(item, runner)
708
+ provider = _optimizer_sentence(optimizer_offer)
709
+ return _Assessment(
710
+ text="\n".join(
711
+ [
712
+ f"{item.label()}: {NO_RECOMMENDATION_HEADLINE}",
713
+ provider,
714
+ UNCHECKED_COVERAGE,
715
+ ]
716
+ ),
717
+ examined={**identity, "outcome": "no_recommendation"},
718
+ )
719
+ return _Assessment(
720
+ text=f"{item.label()}: {NO_RECOMMENDATION_HEADLINE}",
721
+ examined={**identity, "outcome": "no_recommendation"},
722
+ )
723
+ if current is None:
724
+ return _Assessment(
725
+ text=f"{item.label()}: {item.instance_type} is missing from the spec table.",
726
+ spec_missing=True,
727
+ )
728
+
729
+ offered, offer_message = _offering_set(item, runner, specs)
730
+ if offered is None:
731
+ return _Assessment(
732
+ text=f"{item.label()}: offerings were not read.",
733
+ offerings_message=offer_message or "offerings were not read",
734
+ )
735
+
736
+ prices = load_us_east_1_hourly() if item.cloud == "aws" else load_azure_eastus_hourly()
737
+ if move_targets is None:
738
+ candidates = [row for (spec_cloud, _), row in specs.items() if spec_cloud == item.cloud]
739
+ else:
740
+ candidates = [
741
+ row
742
+ for (spec_cloud, _), row in specs.items()
743
+ if spec_cloud == item.cloud and row.instance_type in move_targets
744
+ ]
745
+ boot = _boot_facts(item, runner, current, candidates)
746
+ target = choose_target(
747
+ current,
748
+ candidates,
749
+ prices,
750
+ offered,
751
+ safe_move_types,
752
+ boot,
753
+ same_family=move_targets is None,
754
+ require_safe_move=move_targets is None,
755
+ )
756
+ cross_family = choose_target(
757
+ current,
758
+ candidates,
759
+ prices,
760
+ offered,
761
+ safe_move_types,
762
+ boot,
763
+ same_family=False,
764
+ require_safe_move=True,
765
+ )
766
+ cross_family_target = None
767
+ if (
768
+ cross_family is not None
769
+ and cross_family.family.strip().lower() != current.family.strip().lower()
770
+ ):
771
+ cross_family_target = cross_family.instance_type
772
+ current_price = prices.get(current.instance_type)
773
+ target_price = prices.get(target.instance_type) if target is not None else None
774
+ optimizer_offer = _optimizer_offer(item, runner)
775
+ provider = _optimizer_sentence(optimizer_offer)
776
+ if (
777
+ target is None
778
+ or current_price is None
779
+ or target_price is None
780
+ or current.cpu_performance_rank is None
781
+ or target.cpu_performance_rank is None
782
+ ):
783
+ return _Assessment(
784
+ text="\n".join(
785
+ [f"{item.label()}: no completely safe type.", provider, UNCHECKED_COVERAGE]
786
+ ),
787
+ examined={**identity, "outcome": "no_recommendation"},
788
+ scored=True,
789
+ cross_family_target=cross_family_target,
790
+ )
791
+
792
+ decision = _migration(item, current, target, runner)
793
+ method_code, reason_code = migration_json_codes(decision)
794
+ column = "us-east-1 Linux" if item.cloud == "aws" else "eastus Linux"
795
+ human_method = (
796
+ decision.method if decision.reason is None else f"{decision.method} ({decision.reason})"
797
+ )
798
+ alternative: dict[str, Any] = {
799
+ "rank": 1,
800
+ "instance_type": target.instance_type,
801
+ "justification": {
802
+ "fleetfit_recommended_safe_move": {
803
+ "cpu_performance_rank": {
804
+ "direction": "higher_is_faster",
805
+ "current": _decimal_str(current.cpu_performance_rank),
806
+ "targeted": _decimal_str(target.cpu_performance_rank),
807
+ },
808
+ "effective_price": {
809
+ "price_id": _price_id(item.cloud),
810
+ "reading": "relative_order_only",
811
+ "units": "USD/hour",
812
+ "current": _decimal_str(current_price),
813
+ "targeted": _decimal_str(target_price),
814
+ "assumption": PRICE_ASSUMPTION,
815
+ },
816
+ }
817
+ },
818
+ "how_to_migrate_to_new_type": method_code,
819
+ "migration_reason": reason_code,
820
+ }
821
+ recommendation = {
822
+ **identity,
823
+ "recommended_alternatives": [alternative],
824
+ }
825
+ if item.cloud == "aws":
826
+ recommendation["aws_cloud_optimizer_recommendation"] = _optimizer_block(optimizer_offer)
827
+ text = "\n".join(
828
+ [
829
+ f"{item.label()} -> {target.instance_type}",
830
+ (
831
+ f"CPU performance rank {current.cpu_performance_rank} -> "
832
+ f"{target.cpu_performance_rank}"
833
+ ),
834
+ f"{column} price USD {target_price}/hour. {PRICE_ASSUMPTION}",
835
+ migration_method_human(decision),
836
+ provider,
837
+ UNCHECKED_COVERAGE,
838
+ ]
839
+ )
840
+ return _Assessment(
841
+ text=text,
842
+ recommendation=recommendation,
843
+ scored=True,
844
+ cross_family_target=cross_family_target,
845
+ )
846
+
847
+
848
+ def _assess_catalog_moves(
849
+ item: WorkItem,
850
+ *,
851
+ runner: Any,
852
+ specs: dict[tuple[str, str], SpecRow],
853
+ moves: tuple[dict[str, Any], ...],
854
+ ) -> _Assessment:
855
+ """List shipped moves for this type, largest hourly savings first."""
856
+
857
+ identity = _identity(item)
858
+ current = specs.get((item.cloud, item.instance_type))
859
+ if current is None:
860
+ return _Assessment(
861
+ text=f"{item.label()}: {item.instance_type} is missing from the spec table.",
862
+ spec_missing=True,
863
+ )
864
+ offered, offer_message = _offering_set(item, runner, specs)
865
+ if offered is None:
866
+ return _Assessment(
867
+ text=f"{item.label()}: offerings were not read.",
868
+ offerings_message=offer_message or "offerings were not read",
869
+ )
870
+ paired: list[tuple[dict[str, Any], SpecRow]] = []
871
+ for move in moves:
872
+ row = specs.get((item.cloud, str(move.get("target") or "")))
873
+ if row is not None:
874
+ paired.append((move, row))
875
+ boot = _boot_facts(item, runner, current, [row for _move, row in paired])
876
+ passing = [
877
+ (move, row)
878
+ for move, row in paired
879
+ if row.instance_type in offered and _boot_ok(current, row, boot)
880
+ ]
881
+ passing.sort(key=lambda pair: (-hourly_savings(pair[0]), pair[1].instance_type))
882
+ optimizer_offer = _optimizer_offer(item, runner)
883
+ provider = _optimizer_sentence(optimizer_offer)
884
+ if not passing:
885
+ return _Assessment(
886
+ text="\n".join(
887
+ [f"{item.label()}: no completely safe type.", provider, UNCHECKED_COVERAGE]
888
+ ),
889
+ examined={**identity, "outcome": "no_recommendation"},
890
+ scored=True,
891
+ )
892
+
893
+ alternatives: list[dict[str, Any]] = []
894
+ lines: list[str] = []
895
+ for rank, (move, row) in enumerate(passing, start=1):
896
+ decision = _migration(item, current, row, runner)
897
+ method_code, reason_code = migration_json_codes(decision)
898
+ human_method = (
899
+ decision.method if decision.reason is None else f"{decision.method} ({decision.reason})"
900
+ )
901
+ source_price = money(move["source_hourly_usd"])
902
+ target_price = money(move["target_hourly_usd"])
903
+ summary = source_target_summary(move)
904
+ block: dict[str, Any] = {
905
+ "effective_price": {
906
+ "price_id": _price_id(item.cloud),
907
+ "reading": "relative_order_only",
908
+ "units": "USD/hour",
909
+ "current": _decimal_str(source_price),
910
+ "targeted": _decimal_str(target_price),
911
+ "assumption": PRICE_ASSUMPTION,
912
+ },
913
+ "source_target_summary": summary,
914
+ }
915
+ if current.cpu_performance_rank is not None and row.cpu_performance_rank is not None:
916
+ block["cpu_performance_rank"] = {
917
+ "direction": "higher_is_faster",
918
+ "current": _decimal_str(current.cpu_performance_rank),
919
+ "targeted": _decimal_str(row.cpu_performance_rank),
920
+ }
921
+ alternatives.append(
922
+ {
923
+ "rank": rank,
924
+ "instance_type": row.instance_type,
925
+ "justification": {"fleetfit_recommended_safe_move": block},
926
+ "how_to_migrate_to_new_type": method_code,
927
+ "migration_reason": reason_code,
928
+ }
929
+ )
930
+ savings = source_price - target_price
931
+ if savings <= 0:
932
+ price_line = f"Move to {row.instance_type} (same price)"
933
+ else:
934
+ price_line = (
935
+ f"Move to {row.instance_type} "
936
+ f"(saves USD {format(savings, '.4f')}/hour)"
937
+ )
938
+ lines.append(price_line)
939
+ lines.append(format_summary_human(summary))
940
+ lines.append(migration_method_human(decision))
941
+ lines.extend([provider, UNCHECKED_COVERAGE])
942
+ if passing:
943
+ lines.append(PRICE_ASSUMPTION)
944
+ recommendation: dict[str, Any] = {
945
+ **identity,
946
+ "recommended_alternatives": alternatives,
947
+ }
948
+ if item.cloud == "aws":
949
+ recommendation["aws_cloud_optimizer_recommendation"] = _optimizer_block(optimizer_offer)
950
+ best = passing[0][1]
951
+ cross_family_target = None
952
+ if best.family.strip().lower() != current.family.strip().lower():
953
+ cross_family_target = best.instance_type
954
+ return _Assessment(
955
+ text="\n".join(lines),
956
+ recommendation=recommendation,
957
+ scored=True,
958
+ cross_family_target=cross_family_target,
959
+ )
960
+
961
+
962
+ def _decimal_str(value: Decimal | None) -> str | None:
963
+ if value is None:
964
+ return None
965
+ return format(value, "f")
966
+
967
+
968
+ def _move_targets(instance_type: str) -> set[str] | None:
969
+ """Targets from ``MAPROOM_MOVE_LIST`` for this type, or None when unset."""
970
+
971
+ path_text = os.environ.get("MAPROOM_MOVE_LIST", "").strip()
972
+ if not path_text:
973
+ return None
974
+ from maproom.analyze.move_list import targets_for_source
975
+
976
+ return targets_for_source(Path(path_text), instance_type)
977
+
978
+
979
+ def _offering_set(
980
+ item: WorkItem,
981
+ runner: Any,
982
+ specs: dict[tuple[str, str], SpecRow],
983
+ ) -> tuple[set[str] | None, str]:
984
+ raw = _offered_types(item, runner, specs)
985
+ if isinstance(raw, OfferingRead):
986
+ if not raw.ok:
987
+ return None, raw.message
988
+ return set(raw.types or ()), ""
989
+ if raw is None:
990
+ return None, "could not read instance type offerings"
991
+ return set(raw), ""
992
+
993
+
994
+ def _offered_types(
995
+ item: WorkItem,
996
+ runner: Any,
997
+ specs: dict[tuple[str, str], SpecRow] | None = None,
998
+ ) -> OfferingRead | set[str]:
999
+ _ = runner
1000
+ key = (item.cloud, item.region)
1001
+ cached = _OFFERED.get(key)
1002
+ if cached is not None:
1003
+ return cached
1004
+ if specs is not None:
1005
+ types = frozenset(
1006
+ row.instance_type
1007
+ for (spec_cloud, _), row in specs.items()
1008
+ if spec_cloud == item.cloud
1009
+ )
1010
+ else:
1011
+ from maproom.analyze.catalog import load_spec_rows
1012
+
1013
+ types = frozenset(
1014
+ instance_type
1015
+ for spec_cloud, instance_type in load_spec_rows()
1016
+ if spec_cloud == item.cloud
1017
+ )
1018
+ found = OfferingRead(types)
1019
+ _OFFERED[key] = found
1020
+ return found
1021
+
1022
+
1023
+ def _boot_facts(
1024
+ item: WorkItem,
1025
+ runner: Any,
1026
+ current: SpecRow,
1027
+ candidates: list[SpecRow],
1028
+ ) -> BootFacts:
1029
+ """ENA is read once when any other type in the catalog requires it."""
1030
+ needs_ena = any(
1031
+ row.ena_required and row.instance_type != current.instance_type for row in candidates
1032
+ )
1033
+ if item.cloud == "azure" and needs_ena:
1034
+ enabled, failed = _azure_accelerated_networking(item.primary_nic_id, runner)
1035
+ return BootFacts(item.virtualization_type, enabled, failed)
1036
+ return BootFacts(
1037
+ virtualization_type=item.virtualization_type,
1038
+ ena_enabled=item.ena_support,
1039
+ ena_read_failed=item.ena_support is None,
1040
+ )
1041
+
1042
+
1043
+ def _migration(item: WorkItem, current: SpecRow, target: SpecRow, runner: Any) -> MigrationDecision:
1044
+ ena_enabled = item.ena_support
1045
+ ena_failed = False
1046
+ if item.cloud == "azure" and target.ena_required:
1047
+ ena_enabled, ena_failed = _azure_accelerated_networking(item.primary_nic_id, runner)
1048
+ return decide_migration(
1049
+ current_nvme_boot=current.nvme_boot,
1050
+ target_nvme_boot=target.nvme_boot,
1051
+ target_ena_required=target.ena_required,
1052
+ virtualization_type=item.virtualization_type,
1053
+ root_kind=item.root_device_type,
1054
+ ena_enabled=ena_enabled,
1055
+ ena_read_failed=ena_failed,
1056
+ )
1057
+
1058
+
1059
+ def _azure_accelerated_networking(nic_id: str, runner: Any) -> tuple[bool | None, bool]:
1060
+ if not nic_id:
1061
+ return None, True
1062
+ result = runner.run(
1063
+ "azure",
1064
+ ["network", "nic", "show", "--ids", nic_id, "--output", "json"],
1065
+ record=False,
1066
+ api_id="azure_network_nic_show",
1067
+ )
1068
+ if int(result.exit_code) != 0:
1069
+ return None, True
1070
+ try:
1071
+ payload = json.loads(result.stdout or "{}")
1072
+ except json.JSONDecodeError:
1073
+ return None, True
1074
+ if not isinstance(payload, dict):
1075
+ return None, True
1076
+ return bool(payload.get("enableAcceleratedNetworking")), False
1077
+
1078
+
1079
+ def _optimizer_offer(item: WorkItem, runner: Any) -> Any:
1080
+ """Return the offered type, None when Optimizer offered nothing, or _NOT_READ."""
1081
+ if item.cloud != "aws":
1082
+ return _NOT_READ
1083
+ account_id = _account_id(runner)
1084
+ if not account_id:
1085
+ return _NOT_READ
1086
+ arn = ec2_instance_arn(account_id, item.region, item.instance_id)
1087
+ fetched = fetch_provider_recommendation(arn, item.region, runner)
1088
+ offered = fetched.instance_type if isinstance(fetched, ProviderRecommendation) else None
1089
+ _save_grade(item.instance_id, {"offered": offered, "region": item.region})
1090
+ return offered
1091
+
1092
+
1093
+ def _optimizer_block(offer: Any) -> dict[str, Any]:
1094
+ if offer is _NOT_READ:
1095
+ return {"status": "not_read", "offered_type": None}
1096
+ if isinstance(offer, str) and offer.strip():
1097
+ return {"status": "offered", "offered_type": offer}
1098
+ return {"status": "no_offer_found", "offered_type": None}
1099
+
1100
+
1101
+ def _optimizer_sentence(offer: Any) -> str:
1102
+ if offer is _NOT_READ:
1103
+ return "Provider grade was not read."
1104
+ if offer:
1105
+ return f"Compute Optimizer offered {offer}."
1106
+ return "Compute Optimizer offered nothing."
1107
+
1108
+
1109
+ def _account_id(runner: Any) -> str:
1110
+ result = runner.run(
1111
+ "aws",
1112
+ ["sts", "get-caller-identity", "--output", "json"],
1113
+ record=False,
1114
+ api_id="aws_sts_get_caller_identity",
1115
+ )
1116
+ if int(result.exit_code) != 0:
1117
+ return ""
1118
+ try:
1119
+ identity = parse_sts_identity(
1120
+ {"exit_code": result.exit_code, "stdout_json": json.loads(result.stdout or "{}"), "stderr": result.stderr}
1121
+ )
1122
+ except Exception:
1123
+ return ""
1124
+ return str(identity.get("Account") or "")
1125
+
1126
+
1127
+ def _save_grade(instance_id: str, payload: dict[str, Any]) -> None:
1128
+ folder = data_subdir("optimizer-grades")
1129
+ folder.mkdir(parents=True, exist_ok=True)
1130
+ safe = re.sub(r"[^A-Za-z0-9_.-]+", "_", instance_id).strip("._") or "instance"
1131
+ path = folder / f"{safe}.json"
1132
+ path.write_text(json.dumps(redact_tree(payload)), encoding="utf-8")
1133
+
1134
+ from maproom.analyze.analyze_v1_orchestration import cmd_analyze_v1 # noqa: E402