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/quotas/aws.py ADDED
@@ -0,0 +1,204 @@
1
+ """AWS Service Quotas collection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from datetime import datetime, timedelta, timezone
7
+ from typing import Any
8
+
9
+ from maproom.quotas.model import (
10
+ LAUNCH_RELEVANT_QUOTA_CODES,
11
+ QuotaError,
12
+ normalize_records_from_aws,
13
+ )
14
+
15
+ _METRIC_BATCH_SIZE = 100
16
+ _USAGE_LOOKBACK_HOURS = 3
17
+
18
+
19
+ def _parse_runner_json(result: Any, operation: str) -> dict[str, Any]:
20
+ if result.exit_code != 0:
21
+ detail = (result.stderr or "").strip() or f"exit code {result.exit_code}"
22
+ raise QuotaError(f"{operation} failed: {detail}")
23
+ if not result.stdout.strip():
24
+ raise QuotaError(f"{operation} returned empty output")
25
+ try:
26
+ data = json.loads(result.stdout)
27
+ except json.JSONDecodeError as exc:
28
+ raise QuotaError(f"{operation} returned invalid JSON: {exc}") from exc
29
+ if not isinstance(data, dict):
30
+ raise QuotaError(f"{operation} returned unexpected JSON shape")
31
+ return data
32
+
33
+
34
+ def _default_region(runner: Any) -> str:
35
+ result = runner.run(
36
+ "aws",
37
+ ["configure", "get", "region"],
38
+ record=False,
39
+ api_id="aws_configure_get_region",
40
+ )
41
+ if result.exit_code == 0 and result.stdout.strip():
42
+ return result.stdout.strip()
43
+ return "us-east-1"
44
+
45
+
46
+ def _list_ec2_quotas(runner: Any, *, region: str, record: bool = False) -> list[dict[str, Any]]:
47
+ result = runner.run(
48
+ "aws",
49
+ [
50
+ "service-quotas",
51
+ "list-service-quotas",
52
+ "--service-code",
53
+ "ec2",
54
+ "--region",
55
+ region,
56
+ "--output",
57
+ "json",
58
+ ],
59
+ record=record,
60
+ pagination="merge",
61
+ api_id="aws_service_quotas_list_service_quotas",
62
+ )
63
+ data = _parse_runner_json(
64
+ result,
65
+ f"aws service-quotas list-service-quotas ({region})",
66
+ )
67
+ quotas = data.get("Quotas")
68
+ if quotas is None:
69
+ return []
70
+ if not isinstance(quotas, list):
71
+ raise QuotaError("list-service-quotas Quotas is not a list")
72
+ return [q for q in quotas if isinstance(q, dict)]
73
+
74
+
75
+ def _metric_query_id(quota_code: str) -> str:
76
+ safe = quota_code.replace("-", "")
77
+ return f"q{safe}"
78
+
79
+
80
+ def _metric_query_from_usage_metric(quota_code: str, usage_metric: dict[str, Any]) -> dict[str, Any]:
81
+ namespace = str(usage_metric.get("MetricNamespace") or "AWS/Usage")
82
+ metric_name = str(usage_metric.get("MetricName") or "ResourceCount")
83
+ raw_dims = usage_metric.get("MetricDimensions") or {}
84
+ if not isinstance(raw_dims, dict):
85
+ raw_dims = {}
86
+ dimensions = [{"Name": str(name), "Value": str(value)} for name, value in sorted(raw_dims.items())]
87
+ stat = str(usage_metric.get("MetricStatisticRecommendation") or "Maximum")
88
+ return {
89
+ "Id": _metric_query_id(quota_code),
90
+ "MetricStat": {
91
+ "Metric": {
92
+ "Namespace": namespace,
93
+ "MetricName": metric_name,
94
+ "Dimensions": dimensions,
95
+ },
96
+ "Period": 300,
97
+ "Stat": stat,
98
+ },
99
+ "ReturnData": True,
100
+ }
101
+
102
+
103
+ def _usage_value_from_result(result: dict[str, Any]) -> float:
104
+ values = result.get("Values")
105
+ if not isinstance(values, list) or not values:
106
+ return 0.0
107
+ numeric = [float(v) for v in values if isinstance(v, (int, float))]
108
+ if not numeric:
109
+ return 0.0
110
+ return max(numeric)
111
+
112
+
113
+ def _fetch_usage_by_quota_code(
114
+ runner: Any,
115
+ *,
116
+ region: str,
117
+ quotas: list[dict[str, Any]],
118
+ record: bool = False,
119
+ ) -> dict[str, float]:
120
+ queries: list[dict[str, Any]] = []
121
+ code_for_id: dict[str, str] = {}
122
+ for quota in quotas:
123
+ code = str(quota.get("QuotaCode") or "")
124
+ usage_metric = quota.get("UsageMetric")
125
+ if not code or not isinstance(usage_metric, dict):
126
+ continue
127
+ query_id = _metric_query_id(code)
128
+ queries.append(_metric_query_from_usage_metric(code, usage_metric))
129
+ code_for_id[query_id] = code
130
+
131
+ if not queries:
132
+ return {}
133
+
134
+ end = datetime.now(timezone.utc)
135
+ start = end - timedelta(hours=_USAGE_LOOKBACK_HOURS)
136
+ usage_by_code: dict[str, float] = {}
137
+ for offset in range(0, len(queries), _METRIC_BATCH_SIZE):
138
+ batch = queries[offset : offset + _METRIC_BATCH_SIZE]
139
+ result = runner.run(
140
+ "aws",
141
+ [
142
+ "cloudwatch",
143
+ "get-metric-data",
144
+ "--metric-data-queries",
145
+ json.dumps(batch),
146
+ "--start-time",
147
+ start.strftime("%Y-%m-%dT%H:%M:%SZ"),
148
+ "--end-time",
149
+ end.strftime("%Y-%m-%dT%H:%M:%SZ"),
150
+ "--region",
151
+ region,
152
+ "--output",
153
+ "json",
154
+ ],
155
+ record=record,
156
+ api_id="aws_cloudwatch_usage_get_metric_data",
157
+ )
158
+ data = _parse_runner_json(
159
+ result,
160
+ f"aws cloudwatch get-metric-data ({region})",
161
+ )
162
+ for entry in data.get("MetricDataResults") or []:
163
+ if not isinstance(entry, dict):
164
+ continue
165
+ query_id = str(entry.get("Id") or "")
166
+ code = code_for_id.get(query_id)
167
+ if not code:
168
+ continue
169
+ usage_by_code[code] = _usage_value_from_result(entry)
170
+ return usage_by_code
171
+
172
+
173
+ def _attach_usage(
174
+ quotas: list[dict[str, Any]],
175
+ usage_by_code: dict[str, float],
176
+ ) -> list[dict[str, Any]]:
177
+ enriched: list[dict[str, Any]] = []
178
+ for quota in quotas:
179
+ item = dict(quota)
180
+ code = str(item.get("QuotaCode") or "")
181
+ if code in usage_by_code:
182
+ item["Usage"] = usage_by_code[code]
183
+ enriched.append(item)
184
+ return enriched
185
+
186
+
187
+ def fetch_aws_quotas(
188
+ runner: Any,
189
+ *,
190
+ region: str | None = None,
191
+ launch_relevant_only: bool = False,
192
+ ) -> list[dict[str, Any]]:
193
+ """Fetch EC2 service quotas and CloudWatch usage for the configured region."""
194
+ resolved_region = region or _default_region(runner)
195
+ quotas = _list_ec2_quotas(runner, region=resolved_region)
196
+ if launch_relevant_only:
197
+ quotas = [
198
+ q
199
+ for q in quotas
200
+ if str(q.get("QuotaCode") or "") in LAUNCH_RELEVANT_QUOTA_CODES
201
+ ]
202
+ usage_by_code = _fetch_usage_by_quota_code(runner, region=resolved_region, quotas=quotas)
203
+ quotas_with_usage = _attach_usage(quotas, usage_by_code)
204
+ return normalize_records_from_aws(quotas_with_usage, region=resolved_region)
@@ -0,0 +1,75 @@
1
+ """Azure compute quota / usage collection (`az vm list-usage`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from maproom.quotas.model import QuotaError, normalize_records_from_azure_vm_usage
9
+
10
+ # Regional totals Maproom treats as "general" launch headroom (see USER_JOURNEY §7.1).
11
+ AZURE_GENERAL_USAGE_CODES: frozenset[str] = frozenset({"cores", "lowPriorityCores"})
12
+
13
+
14
+ def _parse_runner_json_list(result: Any, operation: str) -> list[dict[str, Any]]:
15
+ if result.exit_code != 0:
16
+ detail = (result.stderr or "").strip() or f"exit code {result.exit_code}"
17
+ raise QuotaError(f"{operation} failed: {detail}")
18
+ if not result.stdout.strip():
19
+ raise QuotaError(f"{operation} returned empty output")
20
+ try:
21
+ data = json.loads(result.stdout)
22
+ except json.JSONDecodeError as exc:
23
+ raise QuotaError(f"{operation} returned invalid JSON: {exc}") from exc
24
+ if not isinstance(data, list):
25
+ raise QuotaError(f"{operation} returned unexpected JSON shape")
26
+ return [item for item in data if isinstance(item, dict)]
27
+
28
+
29
+ def _default_location(runner: Any) -> str:
30
+ result = runner.run(
31
+ "azure",
32
+ ["config", "get", "defaults.location", "--output", "tsv"],
33
+ record=False,
34
+ api_id="azure_configure_get_location",
35
+ )
36
+ if result.exit_code == 0 and result.stdout.strip():
37
+ return result.stdout.strip()
38
+ return "eastus"
39
+
40
+
41
+ def fetch_azure_quotas(
42
+ runner: Any,
43
+ *,
44
+ location: str | None = None,
45
+ ) -> list[dict[str, Any]]:
46
+ """Fetch compute usage/quota rows for an Azure region."""
47
+ resolved = location or _default_location(runner)
48
+ result = runner.run(
49
+ "azure",
50
+ [
51
+ "vm",
52
+ "list-usage",
53
+ "--location",
54
+ resolved,
55
+ "--output",
56
+ "json",
57
+ "--only-show-errors",
58
+ ],
59
+ record=False,
60
+ api_id="azure_vm_list_usage",
61
+ )
62
+ rows = _parse_runner_json_list(
63
+ result,
64
+ f"az vm list-usage ({resolved})",
65
+ )
66
+ return normalize_records_from_azure_vm_usage(rows, location=resolved)
67
+
68
+
69
+ def includes_general_azure_quotas(records: list[dict[str, Any]]) -> bool:
70
+ for record in records:
71
+ if str(record.get("cloud") or "") != "azure":
72
+ continue
73
+ if str(record.get("quota_code") or "") in AZURE_GENERAL_USAGE_CODES:
74
+ return True
75
+ return False
@@ -0,0 +1,240 @@
1
+ """Fetch and save helpers used by maproom inventory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from maproom.cliio.runner import CliBelowFloorError
11
+
12
+ from maproom.cli_floors import ensure_cli_floors, fail_cli_floor
13
+ from maproom.consent import require_cloud_read_consent
14
+ from maproom.exitcodes import SUCCESS
15
+ from maproom.mock_environment import MockEnvironmentError, MockEnvironmentRunner, command_runner
16
+ from maproom.inventory.account_identity import resolve_aws_account, resolve_azure_account
17
+ from maproom.inventory.accounts import AccountIdentityError, CloudAccount
18
+ from maproom.inventory.messages import (
19
+ QuotasCloudSummary,
20
+ quotas_fetch_progress_line_for,
21
+ quotas_get_human_lines,
22
+ quotas_get_summary_message,
23
+ )
24
+ from maproom.output.json_envelope import (
25
+ finish_consent_gate,
26
+ print_command_error as _print_error,
27
+ print_command_success as _print_success,
28
+ warning_item,
29
+ )
30
+ from maproom.quotas import store
31
+ from maproom.quotas.fetch import cloud_summaries_for_records, fetch_quotas, parse_clouds_arg
32
+ from maproom.quotas.load import load_payer_file
33
+ from maproom.quotas.model import QuotaError, build_snapshot
34
+
35
+
36
+ def _quota_cloud(record: dict[str, Any]) -> str:
37
+ if str(record.get("kind") or "") == "azure_compute_usage":
38
+ return "azure"
39
+ return "azure" if str(record.get("cloud") or "") == "azure" else "aws"
40
+
41
+
42
+ def save_quota_account_snapshots(
43
+ records: list[dict[str, Any]],
44
+ *,
45
+ runner: Any,
46
+ source: str,
47
+ clouds: frozenset[str] | None = None,
48
+ ) -> list[Path]:
49
+ grouped: dict[str, list[dict[str, Any]]] = {}
50
+ for record in records:
51
+ grouped.setdefault(_quota_cloud(record), []).append(record)
52
+ if records:
53
+ targets = [cloud for cloud in ("aws", "azure") if grouped.get(cloud)]
54
+ else:
55
+ targets = [cloud for cloud in ("aws", "azure") if cloud in (clouds or frozenset({"aws"}))]
56
+ written: list[Path] = []
57
+ skipped: list[str] = []
58
+ for cloud in targets:
59
+ rows = grouped.get(cloud, [])
60
+ try:
61
+ account = _account_for(cloud, runner)
62
+ except AccountIdentityError as exc:
63
+ if rows:
64
+ raise
65
+ skipped.append(exc.message)
66
+ continue
67
+ body = build_snapshot(rows, source=source)
68
+ body["cloud"] = account.cloud
69
+ body["account_id"] = account.account_id
70
+ if account.alias:
71
+ body["account_alias"] = account.alias
72
+ err = store.write_account_snapshot(body, account)
73
+ if err is not None:
74
+ raise QuotaError(err.message)
75
+ written.append(store.account_snapshot_path(account))
76
+ if not written:
77
+ detail = skipped[0] if skipped else "no quota records returned from the requested cloud(s)"
78
+ raise QuotaError(detail)
79
+ return written
80
+
81
+
82
+ def _account_for(cloud: str, runner: Any) -> CloudAccount:
83
+ if cloud == "azure":
84
+ return resolve_azure_account(runner)
85
+ return resolve_aws_account(runner)
86
+
87
+
88
+ def cmd_quotas_get(args: argparse.Namespace) -> int:
89
+ as_json = bool(args.json)
90
+ invoked = "quotas get"
91
+ try:
92
+ runner = command_runner()
93
+ except MockEnvironmentError as exc:
94
+ return _print_error(exc.message, as_json=as_json, invoked=invoked)
95
+ try:
96
+ clouds = parse_clouds_arg(getattr(args, "cloud", None))
97
+ except QuotaError as exc:
98
+ return _print_error(exc.message, as_json=as_json, invoked=invoked)
99
+
100
+ if "aws" in clouds:
101
+ try:
102
+ ensure_cli_floors(runner=runner)
103
+ except CliBelowFloorError as exc:
104
+ if clouds == frozenset({"aws"}):
105
+ return fail_cli_floor(exc, as_json=as_json, invoked=invoked)
106
+
107
+ gate = require_cloud_read_consent(
108
+ consent_cloud_reads=bool(getattr(args, "consent_cloud_reads", False)),
109
+ quiet=as_json,
110
+ )
111
+ if not gate.allowed:
112
+ return finish_consent_gate(gate, as_json=as_json, invoked=invoked)
113
+
114
+ aws_region = getattr(args, "region", None) or None
115
+ azure_location = getattr(args, "location", None) or None
116
+ launch_relevant_only = bool(getattr(args, "launch_relevant_only", False))
117
+
118
+ progress_clouds: list[str] = []
119
+
120
+ def _cloud_progress(cloud: str) -> None:
121
+ if not progress_clouds:
122
+ print(file=sys.stderr)
123
+ progress_clouds.append(cloud)
124
+ print(quotas_fetch_progress_line_for(cloud), file=sys.stderr)
125
+
126
+ try:
127
+ if isinstance(runner, MockEnvironmentRunner) and not runner.account.quotas:
128
+ records = []
129
+ partial_errors = []
130
+ else:
131
+ records, partial_errors = fetch_quotas(
132
+ runner,
133
+ clouds=clouds,
134
+ aws_region=aws_region,
135
+ azure_location=azure_location,
136
+ aws_launch_relevant_only=launch_relevant_only,
137
+ on_cloud_start=_cloud_progress if not as_json else None,
138
+ )
139
+ except QuotaError as exc:
140
+ return _print_error(exc.message, as_json=as_json, invoked=invoked)
141
+
142
+ if not as_json and progress_clouds:
143
+ print(file=sys.stderr)
144
+
145
+ has_azure = any(str(r.get("cloud") or "") == "azure" for r in records)
146
+ if not as_json and clouds == frozenset({"aws", "azure"}) and not has_azure:
147
+ print(
148
+ "Note: Azure quotas were not added (install/sign in to Azure CLI, "
149
+ "or run `maproom inventory get --cloud azure`).",
150
+ file=sys.stderr,
151
+ )
152
+
153
+ snapshot = build_snapshot(records, source="cloud_get")
154
+ try:
155
+ written = save_quota_account_snapshots(
156
+ records, runner=runner, source="cloud_get", clouds=clouds
157
+ )
158
+ except AccountIdentityError as exc:
159
+ return _print_error(exc.message, as_json=as_json, invoked=invoked)
160
+ except QuotaError as exc:
161
+ return _print_error(exc.message, as_json=as_json, invoked=invoked)
162
+
163
+ path = written[0] if len(written) == 1 else store.snapshot_root()
164
+ record_count = int(snapshot["record_count"])
165
+ loaded_as_of = str(snapshot["loaded_as_of"])
166
+ summaries = tuple(
167
+ QuotasCloudSummary(
168
+ cloud=cloud,
169
+ record_count=count,
170
+ region=region,
171
+ include_general_line=show_general,
172
+ )
173
+ for cloud, count, region, show_general in cloud_summaries_for_records(records)
174
+ )
175
+ aws_saved = any(_quota_cloud(record) == "aws" for record in records)
176
+ quota_warnings: list[dict[str, Any]] = []
177
+ if "aws" in clouds and not aws_saved and partial_errors:
178
+ for err in partial_errors:
179
+ quota_warnings.append(warning_item("aws_quotas_not_saved", err))
180
+ if as_json:
181
+ summary_message = quotas_get_summary_message(record_count)
182
+ if quota_warnings:
183
+ summary_message = f"{partial_errors[0]} {summary_message}"
184
+ _print_success(
185
+ "quotas_get",
186
+ "maproom.quotas_get",
187
+ invoked,
188
+ {
189
+ "snapshot_path": str(path),
190
+ "loaded_as_of": loaded_as_of,
191
+ "record_count": record_count,
192
+ "source": snapshot["source"],
193
+ "message": summary_message,
194
+ "clouds": [summary.cloud for summary in summaries],
195
+ },
196
+ warnings=quota_warnings,
197
+ )
198
+ else:
199
+ if quota_warnings:
200
+ for err in partial_errors:
201
+ print(f"AWS quotas were not saved: {err}", file=sys.stderr)
202
+ print(file=sys.stderr)
203
+ for line in quotas_get_human_lines(path=str(path), cloud_summaries=summaries):
204
+ print(line)
205
+ return SUCCESS
206
+
207
+
208
+ def cmd_quotas_load(args: argparse.Namespace) -> int:
209
+ as_json = bool(args.json)
210
+ invoked = "quotas load"
211
+ payer_path = Path(args.path)
212
+ try:
213
+ records = load_payer_file(payer_path)
214
+ except QuotaError as exc:
215
+ return _print_error(exc.message, as_json=as_json, invoked=invoked)
216
+
217
+ snapshot = build_snapshot(records, source="payer_file")
218
+ err = store.write_snapshot(snapshot)
219
+ if err is not None:
220
+ return _print_error(err.message, as_json=as_json, invoked=invoked)
221
+
222
+ path = store.snapshot_path()
223
+ if as_json:
224
+ _print_success(
225
+ "quotas_load",
226
+ "maproom.quotas_load",
227
+ invoked,
228
+ {
229
+ "snapshot_path": str(path),
230
+ "loaded_as_of": snapshot["loaded_as_of"],
231
+ "record_count": snapshot["record_count"],
232
+ "source": snapshot["source"],
233
+ },
234
+ )
235
+ else:
236
+ print(
237
+ f"Loaded {snapshot['record_count']} quota rows from file into {path} "
238
+ f"(file dated {snapshot['loaded_as_of']})"
239
+ )
240
+ return SUCCESS
@@ -0,0 +1,122 @@
1
+ """Map loaded quota codes to EC2 instance families (shipped on-demand catalog)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import lru_cache
6
+ from typing import Iterable
7
+
8
+ from maproom.analyze.specs import parse_instance_type_name
9
+ from maproom.pricing import load_price_table
10
+ from maproom.quotas.model import (
11
+ EC2_G_VT_ON_DEMAND_VCPU_QUOTA_CODE,
12
+ EC2_STANDARD_QUOTA_CODE,
13
+ EC2_STANDARD_SPOT_VCPU_QUOTA_CODE,
14
+ LAUNCH_RELEVANT_QUOTA_CODES,
15
+ )
16
+
17
+ _STANDARD_FAMILY_LETTERS = frozenset("acdahimrtz")
18
+
19
+
20
+ def _family_bucket(family: str) -> str:
21
+ text = (family or "").strip().lower()
22
+ if not text:
23
+ return "other"
24
+ if text.startswith("vt") or text[0] == "g":
25
+ return "g_vt"
26
+ if text[0] in _STANDARD_FAMILY_LETTERS:
27
+ return "standard"
28
+ return "other"
29
+
30
+
31
+ @lru_cache(maxsize=1)
32
+ def _catalog_families_by_bucket() -> dict[str, frozenset[str]]:
33
+ table = load_price_table()
34
+ buckets: dict[str, set[str]] = {"standard": set(), "g_vt": set(), "other": set()}
35
+ for instance_type, _region in table._hourly:
36
+ family, _, _ = parse_instance_type_name(instance_type)
37
+ if not family:
38
+ continue
39
+ buckets[_family_bucket(family)].add(family)
40
+ return {key: frozenset(values) for key, values in buckets.items()}
41
+
42
+
43
+ def families_for_quota_code(quota_code: str) -> frozenset[str]:
44
+ code = str(quota_code or "").strip()
45
+ by_bucket = _catalog_families_by_bucket()
46
+ if code == EC2_STANDARD_QUOTA_CODE:
47
+ return by_bucket["standard"]
48
+ if code == EC2_G_VT_ON_DEMAND_VCPU_QUOTA_CODE:
49
+ return by_bucket["g_vt"]
50
+ if code == EC2_STANDARD_SPOT_VCPU_QUOTA_CODE:
51
+ return by_bucket["standard"]
52
+ return frozenset()
53
+
54
+
55
+ def families_for_quota_codes(codes: Iterable[str]) -> tuple[str, ...]:
56
+ merged: set[str] = set()
57
+ for code in codes:
58
+ merged.update(families_for_quota_code(code))
59
+ return tuple(sorted(merged))
60
+
61
+
62
+ def families_for_quota_records(records: Iterable[dict]) -> tuple[str, ...]:
63
+ codes = [
64
+ str(record.get("quota_code") or "")
65
+ for record in records
66
+ if isinstance(record, dict)
67
+ and str(record.get("cloud") or "aws") != "azure"
68
+ and record.get("quota_code")
69
+ ]
70
+ return families_for_quota_codes(codes)
71
+
72
+
73
+ def format_name_preview(names: Iterable[str], *, preview: int = 12) -> str:
74
+ ordered = sorted(names)
75
+ if not ordered:
76
+ return ""
77
+ if len(ordered) <= preview:
78
+ return ", ".join(ordered)
79
+ head = ", ".join(ordered[:preview])
80
+ return f"{head}, ..."
81
+
82
+
83
+ def includes_general_on_demand_quotas(records: Iterable[dict]) -> bool:
84
+ """True when the snapshot includes the main on-demand/Spot CPU quota rows."""
85
+ return bool(families_for_quota_records(records))
86
+
87
+
88
+ def family_coverage_summary_line(
89
+ records: Iterable[dict],
90
+ *,
91
+ preview: int = 12,
92
+ ) -> str | None:
93
+ """Legacy hook for doctor/show; get uses quotas_get_human_lines instead."""
94
+ if not includes_general_on_demand_quotas(records):
95
+ return None
96
+ return (
97
+ "We've downloaded the general AWS EC2 quotas that cover on-demand and "
98
+ "Spot instance launches."
99
+ )
100
+
101
+
102
+ def quota_record_name_preview(
103
+ records: Iterable[dict],
104
+ *,
105
+ preview: int = 12,
106
+ ) -> str | None:
107
+ """When many service quota rows are loaded, preview quota names."""
108
+ rows = [
109
+ r
110
+ for r in records
111
+ if isinstance(r, dict) and str(r.get("cloud") or "aws") != "azure"
112
+ ]
113
+ if len(rows) <= len(LAUNCH_RELEVANT_QUOTA_CODES):
114
+ return None
115
+ labels: list[str] = []
116
+ for record in rows:
117
+ code = str(record.get("quota_code") or "")
118
+ name = str(record.get("quota_name") or code or "unknown")
119
+ labels.append(name if len(name) <= 48 else f"{name[:45]}...")
120
+ if not labels:
121
+ return None
122
+ return f"A few limits in the file: {format_name_preview(labels, preview=preview)}"