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,481 @@
1
+ """Product version 6: quota read, operator approval, and optional increase."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import sys
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+
11
+ from maproom.analyze.catalog import SpecRow
12
+ from maproom.analyze.quota_client import QuotaLookupError, post_quota_lookup
13
+ from maproom.analyze.quota_lookup import build_quota_lookup_body
14
+ from maproom.consent.write_token import issue_cloud_write_token
15
+ from maproom.plan.tty import PromptClosed, confirm_yes_no
16
+ from maproom.quotas.aws import _fetch_usage_by_quota_code, _list_ec2_quotas
17
+ from maproom.redaction import redact_text
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class QuotaRun:
22
+ upload_allowed: bool
23
+ destination: bool
24
+ settings: dict[str, Any]
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class OutsideQuotaTarget:
29
+ region: str
30
+ instance_type: str
31
+
32
+
33
+ class QuotaManagementError(Exception):
34
+ """Quota read or write step failed."""
35
+
36
+
37
+ def prepare_quota_run_from_service(run: Any) -> QuotaRun:
38
+ return QuotaRun(
39
+ upload_allowed=bool(run.upload_allowed),
40
+ destination=bool(run.quota_destination),
41
+ settings=run.settings,
42
+ )
43
+
44
+
45
+ def collect_outside_quota_targets(
46
+ rows: list[dict[str, Any]],
47
+ *,
48
+ specs: dict[tuple[str, str], SpecRow],
49
+ ) -> list[OutsideQuotaTarget]:
50
+ seen: set[tuple[str, str]] = set()
51
+ targets: list[OutsideQuotaTarget] = []
52
+ for row in rows:
53
+ series = row.get("series_fit")
54
+ if not isinstance(series, dict):
55
+ continue
56
+ if series.get("status") != "returned" or not series.get("passed"):
57
+ continue
58
+ named = series.get("instance_type")
59
+ if not isinstance(named, str) or not named.strip():
60
+ continue
61
+ current_type = (row.get("current") or {}).get("instance_type")
62
+ if not isinstance(current_type, str) or not current_type.strip():
63
+ continue
64
+ region = row.get("region")
65
+ if not isinstance(region, str) or not region.strip():
66
+ continue
67
+ current = specs.get(("aws", current_type.strip()))
68
+ target = specs.get(("aws", named.strip()))
69
+ if current is None or target is None:
70
+ continue
71
+ if (current.quota_family or "").strip() == (target.quota_family or "").strip():
72
+ continue
73
+ key = (region.strip(), named.strip())
74
+ if key in seen:
75
+ continue
76
+ seen.add(key)
77
+ targets.append(OutsideQuotaTarget(region=region.strip(), instance_type=named.strip()))
78
+ return targets
79
+
80
+
81
+ def finish_quota_management(
82
+ rows: list[dict[str, Any]],
83
+ *,
84
+ run: QuotaRun | None,
85
+ runner: Any,
86
+ specs: dict[tuple[str, str], SpecRow],
87
+ as_json: bool,
88
+ product_version: int = 6,
89
+ ) -> None:
90
+ if run is None or not run.upload_allowed or not run.destination:
91
+ return
92
+ targets = collect_outside_quota_targets(rows, specs=specs)
93
+ if not targets:
94
+ return
95
+ settings = _settings_for_post(run.settings)
96
+ for target in targets:
97
+ payload = _process_target(
98
+ target,
99
+ runner=runner,
100
+ settings=settings,
101
+ as_json=as_json,
102
+ specs=specs,
103
+ product_version=product_version,
104
+ )
105
+ if payload is None:
106
+ continue
107
+ _attach_quota_result(rows, target, payload)
108
+
109
+
110
+ def _process_target(
111
+ target: OutsideQuotaTarget,
112
+ *,
113
+ runner: Any,
114
+ settings: dict[str, Any],
115
+ as_json: bool,
116
+ specs: dict[tuple[str, str], SpecRow],
117
+ product_version: int,
118
+ ) -> dict[str, Any] | None:
119
+ body = build_quota_lookup_body(region=target.region, instance=target.instance_type)
120
+ try:
121
+ lookup = post_quota_lookup(body, settings)
122
+ except QuotaLookupError as exc:
123
+ warning = f"warning: Quota lookup failed: {redact_text(str(exc))}"
124
+ if as_json:
125
+ print(warning, file=sys.stderr)
126
+ else:
127
+ print(warning)
128
+ return {
129
+ "status": "error",
130
+ "instance_type": target.instance_type,
131
+ "detail": redact_text(str(exc)),
132
+ }
133
+ try:
134
+ limit, usage = _read_limit_and_usage(
135
+ runner,
136
+ region=target.region,
137
+ quota_code=str(lookup["quota_code"]),
138
+ product_version=product_version,
139
+ )
140
+ except QuotaManagementError as exc:
141
+ detail = redact_text(str(exc))
142
+ if as_json:
143
+ print(f"warning: {detail}", file=sys.stderr)
144
+ else:
145
+ print(f"warning: {detail}")
146
+ return {
147
+ "status": "error",
148
+ "instance_type": target.instance_type,
149
+ "quota_code": lookup["quota_code"],
150
+ "detail": detail,
151
+ }
152
+ required = float(lookup["required_vcpus"])
153
+ desired = _desired_quota_value(limit=limit, usage=usage, required_vcpus=required)
154
+ approval_text = _approval_text(
155
+ region=target.region,
156
+ instance_type=target.instance_type,
157
+ quota_name=str(lookup["quota_name"]),
158
+ quota_code=str(lookup["quota_code"]),
159
+ applied_limit=limit,
160
+ usage=usage,
161
+ desired_value=desired,
162
+ )
163
+ if as_json:
164
+ print(approval_text, file=sys.stderr)
165
+ else:
166
+ print(approval_text)
167
+ if desired <= limit:
168
+ return {
169
+ "status": "sufficient",
170
+ "instance_type": target.instance_type,
171
+ "quota_code": lookup["quota_code"],
172
+ "quota_name": lookup["quota_name"],
173
+ "applied_limit": limit,
174
+ "usage": usage,
175
+ "desired_value": desired,
176
+ "detail": approval_text,
177
+ }
178
+ if sys.stdin.isatty() and sys.stdout.isatty() and not as_json:
179
+ try:
180
+ approved = confirm_yes_no(
181
+ "Submit this quota increase request to AWS?",
182
+ default_no=True,
183
+ )
184
+ except PromptClosed:
185
+ approved = False
186
+ if approved:
187
+ try:
188
+ request_id = _submit_increase(
189
+ runner,
190
+ region=target.region,
191
+ quota_code=str(lookup["quota_code"]),
192
+ desired_value=desired,
193
+ product_version=product_version,
194
+ )
195
+ except QuotaManagementError as exc:
196
+ detail = redact_text(str(exc))
197
+ print(f"warning: {detail}")
198
+ from maproom.quotas.outcome_ledger import record_quota_denial
199
+
200
+ spec = specs.get(("aws", target.instance_type.strip()))
201
+ record_quota_denial(
202
+ cloud="aws",
203
+ region=target.region,
204
+ quota_code=str(lookup["quota_code"]),
205
+ requested_value=float(desired),
206
+ instance_type=target.instance_type,
207
+ quota_family=(spec.quota_family if spec is not None else None),
208
+ )
209
+ return {
210
+ "status": "error",
211
+ "instance_type": target.instance_type,
212
+ "quota_code": lookup["quota_code"],
213
+ "detail": detail,
214
+ }
215
+ if product_version >= 7:
216
+ from maproom.quotas.quota_request_sync import record_quota_request_submitted
217
+
218
+ spec = specs.get(("aws", target.instance_type.strip()))
219
+ record_quota_request_submitted(
220
+ request_id=request_id,
221
+ cloud="aws",
222
+ region=target.region,
223
+ quota_code=str(lookup["quota_code"]),
224
+ desired_value=float(desired),
225
+ instance_type=target.instance_type,
226
+ quota_family=(spec.quota_family if spec is not None else None),
227
+ )
228
+ return {
229
+ "status": "increase_requested",
230
+ "instance_type": target.instance_type,
231
+ "quota_code": lookup["quota_code"],
232
+ "quota_name": lookup["quota_name"],
233
+ "applied_limit": limit,
234
+ "usage": usage,
235
+ "desired_value": desired,
236
+ "request_id": request_id,
237
+ "detail": approval_text,
238
+ }
239
+ try:
240
+ open_case = confirm_yes_no(
241
+ "Open an AWS Support case about this quota limit?",
242
+ default_no=True,
243
+ )
244
+ except PromptClosed:
245
+ open_case = False
246
+ if open_case:
247
+ try:
248
+ case_id = _submit_support_case(
249
+ runner,
250
+ region=target.region,
251
+ quota_name=str(lookup["quota_name"]),
252
+ instance_type=target.instance_type,
253
+ desired_value=desired,
254
+ )
255
+ except QuotaManagementError as exc:
256
+ detail = redact_text(str(exc))
257
+ print(f"warning: {detail}")
258
+ return {
259
+ "status": "error",
260
+ "instance_type": target.instance_type,
261
+ "quota_code": lookup["quota_code"],
262
+ "detail": detail,
263
+ }
264
+ return {
265
+ "status": "support_case_opened",
266
+ "instance_type": target.instance_type,
267
+ "quota_code": lookup["quota_code"],
268
+ "quota_name": lookup["quota_name"],
269
+ "case_id": case_id,
270
+ "detail": approval_text,
271
+ }
272
+ return {
273
+ "status": "declined",
274
+ "instance_type": target.instance_type,
275
+ "quota_code": lookup["quota_code"],
276
+ "quota_name": lookup["quota_name"],
277
+ "applied_limit": limit,
278
+ "usage": usage,
279
+ "desired_value": desired,
280
+ "detail": approval_text,
281
+ }
282
+ return {
283
+ "status": "approval_required",
284
+ "instance_type": target.instance_type,
285
+ "quota_code": lookup["quota_code"],
286
+ "quota_name": lookup["quota_name"],
287
+ "applied_limit": limit,
288
+ "usage": usage,
289
+ "desired_value": desired,
290
+ "detail": approval_text,
291
+ }
292
+
293
+
294
+ def _read_limit_and_usage(
295
+ runner: Any,
296
+ *,
297
+ region: str,
298
+ quota_code: str,
299
+ product_version: int,
300
+ ) -> tuple[float, float]:
301
+ from maproom.quotas.quota_request_sync import resolve_quota_service_record
302
+
303
+ record_flag = resolve_quota_service_record(
304
+ product_version, record=(product_version >= 7)
305
+ )
306
+ quotas = _list_ec2_quotas(runner, region=region, record=record_flag)
307
+ record = next((row for row in quotas if str(row.get("QuotaCode") or "") == quota_code), None)
308
+ if record is None:
309
+ raise QuotaManagementError(f"quota {quota_code} was not found in {region}")
310
+ limit = record.get("Value")
311
+ if isinstance(limit, bool) or not isinstance(limit, (int, float)):
312
+ raise QuotaManagementError(f"quota {quota_code} has no applied limit")
313
+ usage_map = _fetch_usage_by_quota_code(
314
+ runner,
315
+ region=region,
316
+ quotas=[record],
317
+ record=record_flag,
318
+ )
319
+ usage = usage_map.get(quota_code)
320
+ if usage is None:
321
+ raw_usage = record.get("Usage")
322
+ if isinstance(raw_usage, bool) or not isinstance(raw_usage, (int, float)):
323
+ raise QuotaManagementError(
324
+ f"quota {quota_code} usage could not be read in {region}"
325
+ )
326
+ usage = float(raw_usage)
327
+ else:
328
+ usage = float(usage)
329
+ return float(limit), usage
330
+
331
+
332
+ def _desired_quota_value(*, limit: float, usage: float, required_vcpus: float) -> float:
333
+ needed = math.ceil(usage + required_vcpus)
334
+ return max(float(limit), needed)
335
+
336
+
337
+ def _approval_text(
338
+ *,
339
+ region: str,
340
+ instance_type: str,
341
+ quota_name: str,
342
+ quota_code: str,
343
+ applied_limit: float,
344
+ usage: float,
345
+ desired_value: float,
346
+ ) -> str:
347
+ return (
348
+ f"Quota for {instance_type} in {region}: {quota_name} ({quota_code}). "
349
+ f"Applied limit {applied_limit:g}, usage {usage:g}. "
350
+ f"RequestServiceQuotaIncrease desired value {desired_value:g}."
351
+ )
352
+
353
+
354
+ def _submit_increase(
355
+ runner: Any,
356
+ *,
357
+ region: str,
358
+ quota_code: str,
359
+ desired_value: float,
360
+ product_version: int,
361
+ ) -> str:
362
+ from maproom.quotas.quota_request_sync import resolve_quota_service_record
363
+
364
+ token = issue_cloud_write_token("aws_service_quotas_request_service_quota_increase")
365
+ argv = [
366
+ "service-quotas",
367
+ "request-service-quota-increase",
368
+ "--service-code",
369
+ "ec2",
370
+ "--quota-code",
371
+ quota_code,
372
+ "--desired-value",
373
+ str(int(desired_value) if desired_value == int(desired_value) else desired_value),
374
+ "--region",
375
+ region,
376
+ "--output",
377
+ "json",
378
+ ]
379
+ record = resolve_quota_service_record(
380
+ product_version, record=(product_version >= 7)
381
+ )
382
+ result = runner.run(
383
+ "aws",
384
+ argv,
385
+ record=record,
386
+ api_id="aws_service_quotas_request_service_quota_increase",
387
+ write_token=token,
388
+ )
389
+ if result.exit_code != 0:
390
+ detail = (result.stderr or "").strip() or f"exit code {result.exit_code}"
391
+ raise QuotaManagementError(f"quota increase failed: {detail}")
392
+ try:
393
+ payload = json.loads(result.stdout or "{}")
394
+ except json.JSONDecodeError as exc:
395
+ raise QuotaManagementError("quota increase returned invalid JSON") from exc
396
+ request_id = payload.get("RequestedQuota", {}).get("Id") or payload.get("RequestId")
397
+ if isinstance(request_id, str) and request_id.strip():
398
+ return request_id.strip()
399
+ return "submitted"
400
+
401
+
402
+ def _submit_support_case(
403
+ runner: Any,
404
+ *,
405
+ region: str,
406
+ quota_name: str,
407
+ instance_type: str,
408
+ desired_value: float,
409
+ ) -> str:
410
+ token = issue_cloud_write_token("aws_support_create_case")
411
+ body = (
412
+ f"Maproom analyze named {instance_type} in {region}, which needs quota "
413
+ f"{quota_name}. Requested limit {desired_value:g}."
414
+ )
415
+ argv = [
416
+ "support",
417
+ "create-case",
418
+ "--subject",
419
+ f"EC2 quota increase for {instance_type} in {region}",
420
+ "--service-code",
421
+ "amazon-elastic-compute-cloud-cloudwatch",
422
+ "--category-code",
423
+ "general-guidance",
424
+ "--severity-code",
425
+ "low",
426
+ "--communication-body",
427
+ body,
428
+ "--output",
429
+ "json",
430
+ ]
431
+ result = runner.run(
432
+ "aws",
433
+ argv,
434
+ record=False,
435
+ api_id="aws_support_create_case",
436
+ write_token=token,
437
+ )
438
+ if result.exit_code != 0:
439
+ detail = (result.stderr or "").strip() or f"exit code {result.exit_code}"
440
+ raise QuotaManagementError(f"support case failed: {detail}")
441
+ try:
442
+ payload = json.loads(result.stdout or "{}")
443
+ except json.JSONDecodeError as exc:
444
+ raise QuotaManagementError("support case returned invalid JSON") from exc
445
+ case_id = payload.get("caseId")
446
+ if isinstance(case_id, str) and case_id.strip():
447
+ return case_id.strip()
448
+ return "opened"
449
+
450
+
451
+ def _attach_quota_result(
452
+ rows: list[dict[str, Any]],
453
+ target: OutsideQuotaTarget,
454
+ payload: dict[str, Any],
455
+ ) -> None:
456
+ for row in rows:
457
+ series = row.get("series_fit")
458
+ if not isinstance(series, dict):
459
+ continue
460
+ named = series.get("instance_type")
461
+ region = row.get("region")
462
+ if named != target.instance_type or region != target.region:
463
+ continue
464
+ row["quota_result"] = dict(payload)
465
+ detail = series.get("detail")
466
+ if isinstance(detail, str):
467
+ from maproom.analyze.series_lookup import OUTSIDE_QUOTA_LINE
468
+
469
+ series["detail"] = detail.replace(OUTSIDE_QUOTA_LINE, "").strip()
470
+
471
+
472
+ def _settings_for_post(settings: dict[str, Any]) -> dict[str, Any]:
473
+ from maproom.analyze.quota_client import resolve_quota_lookup_url
474
+
475
+ merged = dict(settings)
476
+ service = dict(merged.get("service") or {})
477
+ url = resolve_quota_lookup_url(settings)
478
+ if url and not str(service.get("quota_lookup_url") or "").strip():
479
+ service["quota_lookup_url"] = url
480
+ merged["service"] = service
481
+ return merged
@@ -0,0 +1,75 @@
1
+ """POST quota fields to FleetFit recommend, or replay a fixture in CI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import urllib.error
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from maproom.analyze.quota_lookup import require_quota_lookup_body, require_quota_lookup_response
12
+ from maproom.analyze.recommend_client import (
13
+ KIND_QUOTA,
14
+ RecommendError,
15
+ post_recommend_kind,
16
+ resolve_recommend_url,
17
+ unwrap_kind_section,
18
+ )
19
+
20
+
21
+ class QuotaLookupError(Exception):
22
+ """Quota name lookup request failed."""
23
+
24
+
25
+ def post_quota_lookup(body: dict, settings: dict) -> dict:
26
+ require_quota_lookup_body(body)
27
+ fixture = os.environ.get("MAPROOM_QUOTA_LOOKUP_FIXTURE", "").strip()
28
+ if fixture:
29
+ return _read_fixture(Path(fixture))
30
+ try:
31
+ section = post_recommend_kind(
32
+ body,
33
+ settings,
34
+ kind=KIND_QUOTA,
35
+ lookup_label="quota lookup",
36
+ restore_request_type=False,
37
+ )
38
+ except RecommendError as exc:
39
+ raise QuotaLookupError(str(exc)) from exc
40
+ except urllib.error.HTTPError as exc:
41
+ raise QuotaLookupError(f"quota lookup HTTP {exc.code}") from exc
42
+ except (urllib.error.URLError, TimeoutError, ValueError) as exc:
43
+ raise QuotaLookupError(str(exc)) from exc
44
+ return _checked(section)
45
+
46
+
47
+ def quota_destination(settings: dict[str, Any] | None) -> bool:
48
+ if os.environ.get("MAPROOM_QUOTA_LOOKUP_FIXTURE", "").strip():
49
+ return True
50
+ return resolve_quota_lookup_url(settings) is not None
51
+
52
+
53
+ def resolve_quota_lookup_url(settings: dict | None) -> str | None:
54
+ return resolve_recommend_url(settings)
55
+
56
+
57
+ def _read_fixture(path: Path) -> dict[str, Any]:
58
+ try:
59
+ payload = json.loads(path.read_text(encoding="utf-8"))
60
+ except (OSError, json.JSONDecodeError) as exc:
61
+ raise QuotaLookupError("quota lookup fixture could not be read") from exc
62
+ try:
63
+ section = unwrap_kind_section(
64
+ payload, kind=KIND_QUOTA, restore_request_type=False
65
+ )
66
+ except RecommendError as exc:
67
+ raise QuotaLookupError(str(exc)) from exc
68
+ return _checked(section)
69
+
70
+
71
+ def _checked(payload: object) -> dict[str, Any]:
72
+ try:
73
+ return require_quota_lookup_response(payload)
74
+ except ValueError as exc:
75
+ raise QuotaLookupError(str(exc)) from exc
@@ -0,0 +1,110 @@
1
+ """Closed quota_lookup body and response for product version 6."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any
7
+
8
+ REQUEST_TYPE = "quota_lookup"
9
+
10
+ BODY_KEYS: frozenset[str] = frozenset(
11
+ {
12
+ "request_type",
13
+ "provider",
14
+ "region",
15
+ "instance",
16
+ }
17
+ )
18
+
19
+ RESPONSE_KEYS: frozenset[str] = frozenset(
20
+ {
21
+ "quota_code",
22
+ "quota_name",
23
+ "required_vcpus",
24
+ }
25
+ )
26
+
27
+ _FORBIDDEN_KEYS = frozenset(
28
+ {
29
+ "instance_id",
30
+ "name",
31
+ "account_id",
32
+ "volume_id",
33
+ "arn",
34
+ "spot_instance_request_id",
35
+ "reservation_id",
36
+ }
37
+ )
38
+
39
+ _INSTANCE_ID_RE = re.compile(r"i-[0-9a-f]{8,}", re.IGNORECASE)
40
+ _VOLUME_ID_RE = re.compile(r"vol-[0-9a-f]{8,}", re.IGNORECASE)
41
+ _ACCOUNT_ID_RE = re.compile(r"(?<!\d)\d{12}(?!\d)")
42
+
43
+
44
+ def build_quota_lookup_body(*, region: str, instance: str) -> dict[str, Any]:
45
+ body = {
46
+ "request_type": REQUEST_TYPE,
47
+ "provider": "aws",
48
+ "region": region.strip(),
49
+ "instance": instance.strip(),
50
+ }
51
+ require_quota_lookup_body(body)
52
+ return body
53
+
54
+
55
+ def require_quota_lookup_body(body: object) -> dict[str, Any]:
56
+ if not isinstance(body, dict):
57
+ raise ValueError("quota lookup body must be an object")
58
+ keys = set(body)
59
+ if keys != BODY_KEYS:
60
+ raise ValueError("quota lookup body has unexpected keys")
61
+ _reject_id_shaped(body)
62
+ if body.get("request_type") != REQUEST_TYPE:
63
+ raise ValueError("request_type must be quota_lookup")
64
+ if body.get("provider") != "aws":
65
+ raise ValueError("provider must be aws")
66
+ for key in ("region", "instance"):
67
+ value = body.get(key)
68
+ if not isinstance(value, str) or not value.strip():
69
+ raise ValueError("quota lookup body has an empty field")
70
+ return body
71
+
72
+
73
+ def require_quota_lookup_response(payload: object) -> dict[str, Any]:
74
+ if not isinstance(payload, dict):
75
+ raise ValueError("quota lookup response must be an object")
76
+ if set(payload) != RESPONSE_KEYS:
77
+ raise ValueError("quota lookup response has unexpected keys")
78
+ code = payload.get("quota_code")
79
+ name = payload.get("quota_name")
80
+ vcpus = payload.get("required_vcpus")
81
+ if not isinstance(code, str) or not code.strip():
82
+ raise ValueError("quota_code must be a non-empty string")
83
+ if not isinstance(name, str) or not name.strip():
84
+ raise ValueError("quota_name must be a non-empty string")
85
+ if isinstance(vcpus, bool) or not isinstance(vcpus, (int, float)) or float(vcpus) <= 0:
86
+ raise ValueError("required_vcpus must be a positive number")
87
+ return {
88
+ "quota_code": code.strip(),
89
+ "quota_name": name.strip(),
90
+ "required_vcpus": float(vcpus),
91
+ }
92
+
93
+
94
+ def _reject_id_shaped(value: object, *, key: object = None) -> None:
95
+ if isinstance(key, str) and key.lower() in _FORBIDDEN_KEYS:
96
+ raise ValueError("quota lookup body contains a forbidden key")
97
+ if isinstance(value, dict):
98
+ for child_key, child in value.items():
99
+ _reject_id_shaped(child, key=child_key)
100
+ return
101
+ if isinstance(value, list):
102
+ for child in value:
103
+ _reject_id_shaped(child)
104
+ return
105
+ if isinstance(value, str):
106
+ if _INSTANCE_ID_RE.search(value) or _VOLUME_ID_RE.search(value) or _ACCOUNT_ID_RE.search(value):
107
+ raise ValueError("quota lookup body contains a forbidden id")
108
+ return
109
+ if isinstance(value, int) and not isinstance(value, bool) and 10**11 <= abs(value) < 10**12:
110
+ raise ValueError("quota lookup body contains a forbidden id")