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,762 @@
1
+ """Choose the analyze working set: one id, one cloud, or a contains match."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from dataclasses import dataclass, field
8
+ from typing import Any
9
+
10
+ from maproom.analyze.migration_method import azure_primary_nic_id, azure_root_kind
11
+ from maproom.aws_region import resolve_current_aws_region
12
+ from maproom.plan.errors import PlanError
13
+ from maproom.resources import EC2_INSTANCE_ARN_RE, EC2_INSTANCE_ID_RE
14
+
15
+ _CLOUDS = frozenset({"aws", "azure"})
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class WorkItem:
20
+ cloud: str
21
+ region: str
22
+ instance_id: str
23
+ name: str
24
+ instance_type: str
25
+ virtualization_type: str = ""
26
+ root_device_type: str = ""
27
+ ena_support: bool | None = None
28
+ primary_nic_id: str = ""
29
+ lifecycle: str = ""
30
+ availability_zone: str = ""
31
+ availability_zone_id: str = ""
32
+ architecture: str = ""
33
+ platform: str = ""
34
+ instance_store_count: int = 0
35
+
36
+ def haystack(self) -> str:
37
+ return " ".join(
38
+ (
39
+ self.cloud,
40
+ self.region,
41
+ self.instance_id,
42
+ self.name,
43
+ self.instance_type,
44
+ )
45
+ ).lower()
46
+
47
+ def label(self) -> str:
48
+ if self.cloud == "azure" and self.instance_id.startswith("/"):
49
+ parts = self.instance_id.rstrip("/").split("/")
50
+ short = self.instance_id
51
+ if "virtualMachines" in parts:
52
+ vm_index = parts.index("virtualMachines")
53
+ if vm_index + 1 < len(parts):
54
+ vm_name = parts[vm_index + 1]
55
+ resource_group = ""
56
+ if "resourceGroups" in parts:
57
+ group_index = parts.index("resourceGroups")
58
+ if group_index + 1 < len(parts):
59
+ resource_group = parts[group_index + 1]
60
+ short = f"{resource_group}/{vm_name}" if resource_group else vm_name
61
+ size = f" {self.instance_type}" if self.instance_type else ""
62
+ return f"{self.cloud} {self.region} {short}{size}"
63
+ name = f" {self.name}" if self.name and self.name != self.instance_id else ""
64
+ size = f" {self.instance_type}" if self.instance_type else ""
65
+ return f"{self.cloud} {self.region} {self.instance_id}{name}{size}"
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class RegionDescribeFailure:
70
+ """One region whose instance describe did not succeed."""
71
+
72
+ cloud: str
73
+ region: str
74
+ message: str
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class AwsInstanceList:
79
+ """Instances from the regions that described, plus regions that did not."""
80
+
81
+ items: list[WorkItem]
82
+ failures: tuple[RegionDescribeFailure, ...] = ()
83
+ region: str = ""
84
+ block_devices: dict[str, list[dict[str, Any]]] | None = None
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class AnalyzeRequest:
89
+ cloud: str | None = None
90
+ contains: str | None = None
91
+ resource: str | None = None
92
+ resource_cloud: str | None = None
93
+
94
+
95
+ @dataclass
96
+ class CloudLogin:
97
+ logged_in: list[str] = field(default_factory=list)
98
+
99
+
100
+ def parse_analyze_selectors(tokens: list[str]) -> AnalyzeRequest | PlanError:
101
+ """Parse `analyze [aws|azure] [id|arn|*text]`."""
102
+ cloud: str | None = None
103
+ contains: str | None = None
104
+ resource: str | None = None
105
+ for token in tokens:
106
+ text = token.strip()
107
+ if not text:
108
+ continue
109
+ lowered = text.lower()
110
+ if lowered in _CLOUDS:
111
+ if cloud is not None:
112
+ return PlanError("pass only one cloud, aws or azure")
113
+ cloud = lowered
114
+ continue
115
+ if text.startswith("*"):
116
+ needle = text[1:].strip()
117
+ if not needle:
118
+ return PlanError("contains search needs text after *, for example *api")
119
+ if contains is not None:
120
+ return PlanError("pass only one *contains term")
121
+ contains = needle
122
+ continue
123
+ if resource is not None:
124
+ return PlanError(
125
+ "pass one instance id, or a cloud, or *text. "
126
+ "Example: maproom analyze aws *api"
127
+ )
128
+ resource = text
129
+
130
+ if resource and contains:
131
+ return PlanError("pass either an instance id or *text, not both")
132
+
133
+ resource_cloud: str | None = None
134
+ if resource:
135
+ if EC2_INSTANCE_ID_RE.match(resource) or EC2_INSTANCE_ARN_RE.match(resource):
136
+ resource_cloud = "aws"
137
+ elif resource.lower().startswith("/subscriptions/") or "/virtualmachines/" in resource.lower():
138
+ resource_cloud = "azure"
139
+ if cloud and resource_cloud and cloud != resource_cloud:
140
+ return PlanError(
141
+ f"{resource} is a {resource_cloud} id, not {cloud}"
142
+ )
143
+ return AnalyzeRequest(
144
+ cloud=cloud,
145
+ contains=contains,
146
+ resource=resource,
147
+ resource_cloud=resource_cloud,
148
+ )
149
+
150
+
151
+ def _cloud_label(cloud: str) -> str:
152
+ if cloud == "aws":
153
+ return "AWS"
154
+ if cloud == "azure":
155
+ return "Azure"
156
+ return cloud
157
+
158
+
159
+ def _login_command(cloud: str) -> str:
160
+ if cloud == "aws":
161
+ return "aws sso login"
162
+ if cloud == "azure":
163
+ return "az login"
164
+ return f"log in to {cloud}"
165
+
166
+
167
+ def resolve_cloud(
168
+ requested: str | None,
169
+ logged_in: list[str],
170
+ *,
171
+ resource_cloud: str | None = None,
172
+ ) -> str | PlanError:
173
+ """Pick aws or azure from the flag, the id, or the single logged-in cloud."""
174
+ if resource_cloud:
175
+ if requested and requested != resource_cloud:
176
+ return PlanError(f"that id is {resource_cloud}, not {requested}")
177
+ return resource_cloud
178
+ if requested:
179
+ if requested not in logged_in:
180
+ if len(logged_in) == 1:
181
+ signed_in = logged_in[0]
182
+ return PlanError(
183
+ f"Not logged in to {_cloud_label(requested)}. "
184
+ f"You are logged in to {_cloud_label(signed_in)}. "
185
+ f"Run `{_login_command(requested)}`, or run "
186
+ f"`maproom analyze {signed_in}`."
187
+ )
188
+ joined = ", ".join(_cloud_label(c) for c in logged_in) or "none"
189
+ return PlanError(
190
+ f"Not logged in to {_cloud_label(requested)}. "
191
+ f"You are logged in to {joined}. "
192
+ f"Run `{_login_command(requested)}`."
193
+ )
194
+ return requested
195
+ if len(logged_in) == 1:
196
+ return logged_in[0]
197
+ if not logged_in:
198
+ return PlanError(
199
+ "Not logged in to AWS or Azure. "
200
+ "Run `maproom doctor`, then `aws sso login` or `az login`."
201
+ )
202
+ return PlanError(
203
+ "Logged in to more than one cloud. Name one: "
204
+ "`maproom analyze aws` or `maproom analyze azure`."
205
+ )
206
+
207
+
208
+ def resolve_cloud_error_code(message: str) -> str:
209
+ """Map resolve_cloud PlanError text to an error document code."""
210
+ lowered = message.lower()
211
+ if "logged in to more than one cloud" in lowered:
212
+ return "usage"
213
+ if "not logged in" in lowered:
214
+ return "auth_failed"
215
+ return "usage"
216
+
217
+
218
+ def detect_logged_in_clouds(runner: Any) -> list[str]:
219
+ """Return clouds whose CLI is logged in. Missing CLIs count as logged out."""
220
+ found: list[str] = []
221
+ try:
222
+ aws = runner.run(
223
+ "aws",
224
+ ["sts", "get-caller-identity", "--output", "json"],
225
+ record=False,
226
+ api_id="aws_sts_get_caller_identity",
227
+ )
228
+ if int(getattr(aws, "exit_code", 1)) == 0:
229
+ found.append("aws")
230
+ except Exception:
231
+ pass
232
+ try:
233
+ azure = runner.run(
234
+ "azure",
235
+ ["account", "show", "--output", "json"],
236
+ record=False,
237
+ api_id="azure_account_show",
238
+ )
239
+ if int(getattr(azure, "exit_code", 1)) == 0:
240
+ found.append("azure")
241
+ except Exception:
242
+ pass
243
+ return found
244
+
245
+
246
+ def note_progress(message: str) -> None:
247
+ """Live progress. stderr stays off the JSON document and is flushed immediately."""
248
+ print(message, file=sys.stderr, flush=True)
249
+
250
+
251
+ _ACCOUNT_LEVEL_AWS = frozenset(
252
+ {
253
+ "aws_ce_get_reservation_utilization",
254
+ "aws_configure_get_region",
255
+ "aws_ec2_describe_instances",
256
+ "aws_ec2_describe_reserved_instances",
257
+ "aws_service_quotas_list_requested_service_quota_change_history",
258
+ "aws_sts_get_caller_identity",
259
+ }
260
+ )
261
+ _ACCOUNT_LEVEL_AZURE = frozenset(
262
+ {
263
+ "azure_vm_list",
264
+ "azure_reservations_list",
265
+ "azure_monitor_activity_log_list",
266
+ "azure_quota_request_list",
267
+ }
268
+ )
269
+ _SIZE_TRIM_APIS = frozenset(
270
+ {
271
+ "aws_cloudtrail_lookup_events",
272
+ "aws_config_get_resource_config_history",
273
+ }
274
+ )
275
+ def examining_display_id(item: WorkItem) -> str:
276
+ name = item.name.strip()
277
+ if name and name != item.instance_id:
278
+ return name
279
+ return item.instance_id
280
+
281
+
282
+ def examining_progress_line(item: WorkItem) -> str:
283
+ return f"Inspecting {item.cloud} {item.region} {examining_display_id(item)}..."
284
+
285
+
286
+ def note_examining(item: WorkItem) -> None:
287
+ note_progress(examining_progress_line(item))
288
+
289
+
290
+ def registry_command_line(entry: Any) -> str:
291
+ prefix = "aws" if entry.cloud == "aws" else "az"
292
+ return f"{prefix} {' '.join(entry.argv_prefix)}"
293
+
294
+
295
+ def account_level_analyze_command_lines(
296
+ cloud: str,
297
+ *,
298
+ product_version: int,
299
+ account_context: bool,
300
+ ) -> tuple[str, ...]:
301
+ if not account_context or product_version < 3:
302
+ return ()
303
+ from maproom.cliio.registry import entries_for
304
+
305
+ lines: list[str] = []
306
+ for entry in entries_for("analyze"):
307
+ if entry.cloud != cloud or entry.access != "read":
308
+ continue
309
+ if cloud == "aws":
310
+ if entry.api_id == "aws_cloudtrail_lookup_events":
311
+ lines.append(registry_command_line(entry))
312
+ if product_version >= 6 and entry.api_id == (
313
+ "aws_service_quotas_list_requested_service_quota_change_history"
314
+ ):
315
+ lines.append(registry_command_line(entry))
316
+ if product_version >= 5 and entry.api_id in {
317
+ "aws_ce_get_reservation_utilization",
318
+ "aws_ec2_describe_reserved_instances",
319
+ }:
320
+ lines.append(registry_command_line(entry))
321
+ elif cloud == "azure":
322
+ if entry.api_id == "azure_monitor_activity_log_list":
323
+ lines.append(registry_command_line(entry))
324
+ if product_version >= 6 and entry.api_id == "azure_quota_request_list":
325
+ lines.append(registry_command_line(entry))
326
+ if product_version >= 5 and entry.api_id == "azure_reservations_list":
327
+ lines.append(registry_command_line(entry))
328
+ return tuple(sorted(set(lines)))
329
+
330
+
331
+ def per_instance_analyze_command_lines(
332
+ cloud: str,
333
+ *,
334
+ product_version: int,
335
+ size_lookup: bool,
336
+ series_lookup: bool,
337
+ ) -> tuple[str, ...]:
338
+ from maproom.cliio.registry import entries_for
339
+
340
+ account_ids = _ACCOUNT_LEVEL_AWS if cloud == "aws" else _ACCOUNT_LEVEL_AZURE
341
+ lines: list[str] = []
342
+ for entry in entries_for("analyze"):
343
+ if entry.cloud != cloud or entry.access != "read":
344
+ continue
345
+ if entry.api_id in account_ids:
346
+ continue
347
+ if entry.api_id in _SIZE_TRIM_APIS and not size_lookup:
348
+ continue
349
+ if entry.api_id == "aws_cloudwatch_get_metric_data" and not (
350
+ size_lookup or series_lookup or product_version >= 2
351
+ ):
352
+ continue
353
+ lines.append(registry_command_line(entry))
354
+ return tuple(sorted(set(lines)))
355
+
356
+
357
+ def interactive_account_preamble(
358
+ *,
359
+ cloud: str,
360
+ region: str | None,
361
+ regions_in_scope: tuple[str, ...],
362
+ reservation_reorder: bool,
363
+ product_version: int,
364
+ region_free: bool = False,
365
+ ) -> str:
366
+ from maproom.settings.product_versions import product_version_name
367
+
368
+ version_line = (
369
+ f"product_version {product_version} is "
370
+ f"{product_version_name(product_version)}."
371
+ )
372
+ if cloud == "azure":
373
+ parts = [
374
+ version_line,
375
+ "This run lists Azure virtual machines across enabled regions.",
376
+ ]
377
+ if reservation_reorder or product_version >= 5:
378
+ parts.append(
379
+ "It also reads Azure reserved capacity inventory for this subscription."
380
+ )
381
+ return " ".join(parts)
382
+ if region_free:
383
+ if product_version < 5:
384
+ scope = (
385
+ f"{version_line} This run lists EC2 instance types in the chosen AWS region. "
386
+ )
387
+ if product_version < 2:
388
+ return scope + (
389
+ "It does not examine utilization or reservation inventory."
390
+ )
391
+ return scope + "It does not examine quotas or reservation history."
392
+ return (
393
+ f"{version_line} Maproom examines EC2 instance utilization and reservations, "
394
+ "and then makes recommendations."
395
+ )
396
+ named = (region or "").strip()
397
+ if named:
398
+ scope = f"This run lists and describes EC2 instances in {named}."
399
+ elif len(regions_in_scope) == 1:
400
+ scope = f"This run lists and describes EC2 instances in {regions_in_scope[0]}."
401
+ elif regions_in_scope:
402
+ joined = ", ".join(regions_in_scope)
403
+ scope = f"This run lists and describes EC2 instances in {joined}."
404
+ else:
405
+ scope = (
406
+ "This run lists and describes EC2 instances in the chosen AWS region."
407
+ )
408
+ if reservation_reorder or product_version >= 5:
409
+ scope += (
410
+ " It also reads Reserved Instance inventory and utilization for this account."
411
+ )
412
+ return f"{version_line} {scope}"
413
+
414
+
415
+ def print_interactive_aws_scope(
416
+ *,
417
+ reservation_reorder: bool,
418
+ product_version: int,
419
+ ) -> None:
420
+ print(
421
+ interactive_account_preamble(
422
+ cloud="aws",
423
+ region=None,
424
+ regions_in_scope=(),
425
+ reservation_reorder=reservation_reorder,
426
+ product_version=product_version,
427
+ region_free=True,
428
+ ),
429
+ flush=True,
430
+ )
431
+ print(flush=True)
432
+
433
+
434
+ def print_interactive_analyze_command_list(
435
+ *,
436
+ cloud: str,
437
+ product_version: int,
438
+ size_lookup: bool,
439
+ series_lookup: bool,
440
+ account_context: bool = False,
441
+ ) -> None:
442
+ account_lines = account_level_analyze_command_lines(
443
+ cloud,
444
+ product_version=product_version,
445
+ account_context=account_context,
446
+ )
447
+ if account_lines:
448
+ print("AWS commands that will be run once for this account:", flush=True)
449
+ for line in account_lines:
450
+ print(f" {line}", flush=True)
451
+ print(flush=True)
452
+ heading = (
453
+ "AWS commands that will be run on each instance:"
454
+ if cloud == "aws"
455
+ else "Azure commands that will be run on each instance:"
456
+ )
457
+ print(heading, flush=True)
458
+ for line in per_instance_analyze_command_lines(
459
+ cloud,
460
+ product_version=product_version,
461
+ size_lookup=size_lookup,
462
+ series_lookup=series_lookup,
463
+ ):
464
+ print(f" {line}", flush=True)
465
+ print(flush=True)
466
+
467
+
468
+ def print_interactive_analyze_preambles(
469
+ *,
470
+ cloud: str,
471
+ region: str | None,
472
+ regions_in_scope: tuple[str, ...],
473
+ reservation_reorder: bool,
474
+ product_version: int,
475
+ size_lookup: bool,
476
+ series_lookup: bool,
477
+ ) -> None:
478
+ print(
479
+ interactive_account_preamble(
480
+ cloud=cloud,
481
+ region=region,
482
+ regions_in_scope=regions_in_scope,
483
+ reservation_reorder=reservation_reorder,
484
+ product_version=product_version,
485
+ ),
486
+ flush=True,
487
+ )
488
+ print(flush=True)
489
+ from maproom.settings.model import product_version as _settings_product_version
490
+
491
+ print_interactive_analyze_command_list(
492
+ cloud=cloud,
493
+ product_version=product_version,
494
+ size_lookup=size_lookup,
495
+ series_lookup=series_lookup,
496
+ account_context=_settings_product_version() >= 3,
497
+ )
498
+
499
+
500
+ def format_metrics_summary(
501
+ item: WorkItem,
502
+ row: dict[str, Any] | None,
503
+ *,
504
+ product_version: int,
505
+ ) -> str:
506
+ from maproom.analyze.size_analyze import size_collected_metrics_summary
507
+
508
+ if isinstance(row, dict):
509
+ size = row.get("size_lookup")
510
+ if isinstance(size, dict):
511
+ collected = size_collected_metrics_summary(size)
512
+ if collected:
513
+ return collected
514
+ spot = row.get("spot_lookup")
515
+ if isinstance(spot, dict) and spot.get("status") == "returned":
516
+ parts: list[str] = []
517
+ pool = spot.get("pool")
518
+ risk = spot.get("interrupt_risk")
519
+ if isinstance(pool, str) and pool.strip():
520
+ parts.append(f"pool {pool.strip()}")
521
+ if isinstance(risk, str) and risk.strip():
522
+ parts.append(f"interrupt risk {risk.strip()}")
523
+ if parts:
524
+ return "; ".join(parts)
525
+ series = row.get("series_fit")
526
+ if isinstance(series, dict):
527
+ detail = series.get("detail")
528
+ if isinstance(detail, str) and detail.strip():
529
+ return detail.strip()
530
+ optimizer = row.get("aws_cloud_optimizer_recommendation")
531
+ if isinstance(optimizer, dict) and item.cloud == "aws":
532
+ status = optimizer.get("status")
533
+ offered = optimizer.get("offered_type")
534
+ if status == "offered" and isinstance(offered, str) and offered.strip():
535
+ return f"Compute Optimizer offered {offered.strip()}."
536
+ if status == "no_offer_found":
537
+ return "Compute Optimizer offered nothing."
538
+ if status == "not_read":
539
+ return "Compute Optimizer grade was not read."
540
+ if product_version >= 2:
541
+ return "Utilization metrics were not collected for this instance."
542
+ return ""
543
+
544
+
545
+ def _loads_object(stdout: str) -> Any:
546
+ text = (stdout or "").strip()
547
+ if not text:
548
+ return None
549
+ return json.loads(text)
550
+
551
+
552
+ def cloud_listing_error_code(message: str) -> str:
553
+ """Map a cloud list/describe failure message to an error document code."""
554
+ lowered = message.lower()
555
+ if "no aws region is set" in lowered:
556
+ return "usage"
557
+ if (
558
+ "not logged in" in lowered
559
+ or "unable to locate credentials" in lowered
560
+ or "az login" in lowered
561
+ or ("credential" in lowered and "expired" in lowered)
562
+ ):
563
+ return "auth_failed"
564
+ if (
565
+ "unauthorizedoperation" in lowered
566
+ or "accessdenied" in lowered
567
+ or "access denied" in lowered
568
+ or "not authorized" in lowered
569
+ ):
570
+ return "permission_denied"
571
+ return "runtime"
572
+
573
+
574
+ def list_aws_instances(
575
+ runner: Any,
576
+ *,
577
+ region: str | None = None,
578
+ block_devices: dict[str, list[dict[str, Any]]] | None = None,
579
+ ) -> AwsInstanceList | PlanError:
580
+ """List running and stopped EC2 instances in one region.
581
+
582
+ When ``region`` is omitted, the current AWS CLI region is used. A describe
583
+ failure in that region is an error. An empty list with exit success means
584
+ the describe succeeded and no instances matched. Stderr progress stays.
585
+
586
+ ``block_devices`` is an optional caller-owned scratch map for Spot
587
+ instances. Analyze reduces each list through ``volumes_that_cannot_move``
588
+ and does not keep it. Volume ids are not stored on ``WorkItem``.
589
+ """
590
+ chosen = (region or "").strip().lower()
591
+ if not chosen:
592
+ chosen = resolve_current_aws_region(runner) or ""
593
+ if not chosen:
594
+ return PlanError(
595
+ "No AWS region is set. Pass --region, or set one with `aws configure set region`."
596
+ )
597
+ regions = [chosen]
598
+
599
+ items: list[WorkItem] = []
600
+ failed_regions: list[RegionDescribeFailure] = []
601
+ devices: dict[str, list[dict[str, Any]]] = {}
602
+ total = len(regions)
603
+ for index, name in enumerate(regions, start=1):
604
+ if sys.stderr.isatty():
605
+ note_progress(f"Reading {name}...")
606
+ else:
607
+ note_progress(f"Describing instances in {name} ({index}/{total})...")
608
+ described = runner.run(
609
+ "aws",
610
+ [
611
+ "ec2",
612
+ "describe-instances",
613
+ "--region",
614
+ name,
615
+ "--filters",
616
+ "Name=instance-state-name,Values=running,stopped",
617
+ "--output",
618
+ "json",
619
+ ],
620
+ record=False,
621
+ api_id="aws_ec2_describe_instances",
622
+ )
623
+ if int(described.exit_code) != 0:
624
+ detail = (described.stderr or "").strip()
625
+ failed_regions.append(
626
+ RegionDescribeFailure(
627
+ cloud="aws",
628
+ region=name,
629
+ message=detail or f"could not describe AWS instances in {name}",
630
+ )
631
+ )
632
+ continue
633
+ try:
634
+ payload = _loads_object(described.stdout)
635
+ except json.JSONDecodeError:
636
+ failed_regions.append(
637
+ RegionDescribeFailure(
638
+ cloud="aws",
639
+ region=name,
640
+ message=f"AWS describe-instances in {name} returned invalid JSON",
641
+ )
642
+ )
643
+ continue
644
+ if not isinstance(payload, dict):
645
+ failed_regions.append(
646
+ RegionDescribeFailure(
647
+ cloud="aws",
648
+ region=name,
649
+ message=f"AWS describe-instances in {name} returned an unexpected payload",
650
+ )
651
+ )
652
+ continue
653
+ for reservation in payload.get("Reservations") or []:
654
+ if not isinstance(reservation, dict):
655
+ continue
656
+ for inst in reservation.get("Instances") or []:
657
+ if not isinstance(inst, dict):
658
+ continue
659
+ instance_id = str(inst.get("InstanceId") or "").strip()
660
+ if not instance_id:
661
+ continue
662
+ tag_name = ""
663
+ for tag in inst.get("Tags") or []:
664
+ if isinstance(tag, dict) and tag.get("Key") == "Name":
665
+ tag_name = str(tag.get("Value") or "")
666
+ break
667
+ ena_raw = inst.get("EnaSupport")
668
+ placement = inst.get("Placement") if isinstance(inst.get("Placement"), dict) else {}
669
+ lifecycle = str(inst.get("InstanceLifecycle") or "").strip()
670
+ platform = str(inst.get("PlatformDetails") or "").strip() or str(
671
+ inst.get("Platform") or ""
672
+ ).strip()
673
+ mappings = inst.get("BlockDeviceMappings")
674
+ mapping_rows = [row for row in mappings if isinstance(row, dict)] if isinstance(mappings, list) else []
675
+ store_count = sum(1 for row in mapping_rows if str(row.get("VirtualName") or "").strip())
676
+ if lifecycle.lower() == "spot" and mapping_rows:
677
+ devices[instance_id] = mapping_rows
678
+ if block_devices is not None:
679
+ block_devices[instance_id] = mapping_rows
680
+ items.append(
681
+ WorkItem(
682
+ cloud="aws",
683
+ region=name,
684
+ instance_id=instance_id,
685
+ name=tag_name,
686
+ instance_type=str(inst.get("InstanceType") or ""),
687
+ virtualization_type=str(inst.get("VirtualizationType") or ""),
688
+ root_device_type=str(inst.get("RootDeviceType") or ""),
689
+ ena_support=None if ena_raw is None else bool(ena_raw),
690
+ lifecycle=lifecycle,
691
+ availability_zone=str(placement.get("AvailabilityZone") or "").strip(),
692
+ availability_zone_id=str(placement.get("AvailabilityZoneId") or "").strip(),
693
+ architecture=str(inst.get("Architecture") or "").strip(),
694
+ platform=platform,
695
+ instance_store_count=store_count,
696
+ )
697
+ )
698
+ if failed_regions:
699
+ listed = ", ".join(failure.region for failure in failed_regions)
700
+ if len(failed_regions) == 1:
701
+ return PlanError(failed_regions[0].message)
702
+ combined = "; ".join(failure.message for failure in failed_regions)
703
+ return PlanError(combined or f"could not describe AWS instances in {listed}")
704
+ return AwsInstanceList(items, (), chosen, devices)
705
+
706
+
707
+ def list_azure_instances(runner: Any) -> list[WorkItem] | PlanError:
708
+ note_progress("Listing Azure virtual machines...")
709
+ listed = runner.run(
710
+ "azure",
711
+ ["vm", "list", "-d", "--output", "json"],
712
+ record=False,
713
+ api_id="azure_vm_list",
714
+ )
715
+ if int(listed.exit_code) != 0:
716
+ detail = (listed.stderr or "").strip() or "az vm list failed"
717
+ return PlanError(detail)
718
+ try:
719
+ payload = _loads_object(listed.stdout)
720
+ except json.JSONDecodeError:
721
+ return PlanError("az vm list returned invalid JSON")
722
+ if not isinstance(payload, list):
723
+ return PlanError("az vm list returned an unexpected payload")
724
+ items: list[WorkItem] = []
725
+ for row in payload:
726
+ if not isinstance(row, dict):
727
+ continue
728
+ resource_id = str(row.get("id") or "").strip()
729
+ name = str(row.get("name") or "").strip()
730
+ if not resource_id and not name:
731
+ continue
732
+ hardware = row.get("hardwareProfile") if isinstance(row.get("hardwareProfile"), dict) else {}
733
+ items.append(
734
+ WorkItem(
735
+ cloud="azure",
736
+ region=str(row.get("location") or ""),
737
+ instance_id=resource_id or name,
738
+ name=name,
739
+ instance_type=str((hardware or {}).get("vmSize") or ""),
740
+ root_device_type=azure_root_kind(row),
741
+ primary_nic_id=azure_primary_nic_id(row),
742
+ virtualization_type="hvm",
743
+ )
744
+ )
745
+ return items
746
+
747
+
748
+ def filter_contains(items: list[WorkItem], needle: str | None) -> list[WorkItem]:
749
+ if not needle:
750
+ return items
751
+ folded = needle.lower()
752
+ return [item for item in items if folded in item.haystack()]
753
+
754
+
755
+ def azure_local_only_message(item: WorkItem) -> str:
756
+ size = item.instance_type or "unknown size"
757
+ return (
758
+ f"Target: AZURE · {item.region or 'unknown region'} · {item.name or item.instance_id} · {size}\n"
759
+ "The local pricing file covers EC2 on-demand Linux only, so this Azure VM "
760
+ "gets no sized recommendation. Calls to aws and az still run locally. "
761
+ "A fleetfit.ai recommendation would be a separate remote call."
762
+ )