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/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """maproom package (parsers + product UX). Runtime CLI calls go through cliio.runner."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ def _installed_version() -> str:
6
+ for dist_name in ("maproom", "maproom-cli"):
7
+ try:
8
+ return version(dist_name)
9
+ except PackageNotFoundError:
10
+ continue
11
+ return "0.0.0-dev"
12
+
13
+
14
+ __version__ = _installed_version()
maproom/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ """python -m maproom"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from maproom.cli import main
8
+
9
+ if __name__ == "__main__":
10
+ raise SystemExit(main())
@@ -0,0 +1 @@
1
+ """Analyze journey helpers (workload profile, utilization reads)."""
@@ -0,0 +1,45 @@
1
+ """Family-prefix heuristics for GPU, Inferentia, Trainium, and similar accelerator lines."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ _ACCEL_FAMILY_PREFIXES = frozenset(
8
+ {
9
+ "dl1",
10
+ "f1",
11
+ "g3",
12
+ "g4",
13
+ "g5",
14
+ "g6",
15
+ "gr6",
16
+ "hpc6",
17
+ "hpc7",
18
+ "inf1",
19
+ "inf2",
20
+ "p2",
21
+ "p3",
22
+ "p4",
23
+ "p5",
24
+ "p5e",
25
+ "trn1",
26
+ "trn2",
27
+ "vt1",
28
+ }
29
+ )
30
+
31
+ _ACCEL_FAMILY_RE = re.compile(
32
+ r"^(g\d|gr\d|p\d|inf|trn|dl|vt|f\d|hpc)",
33
+ re.IGNORECASE,
34
+ )
35
+
36
+
37
+ def instance_type_has_accelerator_family(instance_type: str) -> bool:
38
+ """True when the type family is a GPU, Inferentia, Trainium, or similar accelerator line."""
39
+ name = (instance_type or "").strip().lower()
40
+ if not name or "." not in name:
41
+ return False
42
+ family, _, _ = name.partition(".")
43
+ if _ACCEL_FAMILY_RE.match(family):
44
+ return True
45
+ return family in _ACCEL_FAMILY_PREFIXES
@@ -0,0 +1,260 @@
1
+ """Azure Activity Log reads for the analyze operator-context phase."""
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.analyze.account_cloudtrail import (
10
+ LaunchAttemptCounts,
11
+ SpotHistoryCounts,
12
+ context_trail_window,
13
+ )
14
+ from maproom.analyze.utilization import _iso_z
15
+ from maproom.inventory.account_identity import AccountIdentityError, resolve_azure_account
16
+
17
+ _EVENT_VM_WRITE = "microsoft.compute/virtualmachines/write"
18
+ _EVENT_SPOT_EVICT = "evictspotvm"
19
+ # az monitor activity-log list returns at most --max-events rows per call and has no
20
+ # CLI continuation token; keep requesting older slices until a short page or start.
21
+ _ACTIVITY_LOG_PAGE_SIZE = 500
22
+
23
+
24
+ def build_azure_activity_log_argv(
25
+ *,
26
+ start: Any,
27
+ end: Any,
28
+ max_events: int = _ACTIVITY_LOG_PAGE_SIZE,
29
+ ) -> list[str]:
30
+ return [
31
+ "monitor",
32
+ "activity-log",
33
+ "list",
34
+ "--start-time",
35
+ _iso_z(start),
36
+ "--end-time",
37
+ _iso_z(end),
38
+ "--max-events",
39
+ str(max_events),
40
+ "--output",
41
+ "json",
42
+ ]
43
+
44
+
45
+ def _operation_name(entry: dict[str, Any]) -> str:
46
+ operation = entry.get("operationName")
47
+ if isinstance(operation, dict):
48
+ return str(operation.get("value") or "").strip().lower()
49
+ if isinstance(operation, str):
50
+ return operation.strip().lower()
51
+ return ""
52
+
53
+
54
+ def _status_value(entry: dict[str, Any]) -> str:
55
+ status = entry.get("status")
56
+ if isinstance(status, dict):
57
+ return str(status.get("value") or "").strip().lower()
58
+ if isinstance(status, str):
59
+ return status.strip().lower()
60
+ return ""
61
+
62
+
63
+ def _substatus_code(entry: dict[str, Any]) -> str | None:
64
+ sub = entry.get("subStatus")
65
+ if isinstance(sub, dict):
66
+ code = sub.get("value") or sub.get("code")
67
+ if isinstance(code, str) and code.strip():
68
+ return code.strip()
69
+ props = entry.get("properties")
70
+ if isinstance(props, dict):
71
+ message = props.get("statusMessage")
72
+ if isinstance(message, str) and message.strip():
73
+ return message.strip()[:120]
74
+ return None
75
+
76
+
77
+ def _region_from_resource_id(resource_id: str) -> str | None:
78
+ parts = resource_id.strip().lower().split("/")
79
+ try:
80
+ index = parts.index("locations")
81
+ return parts[index + 1]
82
+ except (ValueError, IndexError):
83
+ return None
84
+
85
+
86
+ def _region_from_event(entry: dict[str, Any]) -> str | None:
87
+ for key in ("resourceLocation", "location", "ResourceLocation"):
88
+ value = entry.get(key)
89
+ if isinstance(value, str) and value.strip():
90
+ return value.strip().lower()
91
+ resource_id = str(entry.get("resourceId") or "").strip()
92
+ if resource_id:
93
+ return _region_from_resource_id(resource_id)
94
+ return None
95
+
96
+
97
+ def _parse_event_timestamp(entry: dict[str, Any]) -> datetime | None:
98
+ for key in ("eventTimestamp", "submissionTimestamp"):
99
+ raw = entry.get(key)
100
+ if not isinstance(raw, str) or not raw.strip():
101
+ continue
102
+ text = raw.strip().replace("Z", "+00:00")
103
+ try:
104
+ return datetime.fromisoformat(text)
105
+ except ValueError:
106
+ continue
107
+ return None
108
+
109
+
110
+ def _parsed_request_body(props: dict[str, Any]) -> dict[str, Any]:
111
+ raw = props.get("requestbody") or props.get("requestBody")
112
+ if isinstance(raw, dict):
113
+ return raw
114
+ if isinstance(raw, str) and raw.strip():
115
+ try:
116
+ loaded = json.loads(raw)
117
+ except json.JSONDecodeError:
118
+ return {}
119
+ return loaded if isinstance(loaded, dict) else {}
120
+ return {}
121
+
122
+
123
+ def _vm_size_from_body(body: dict[str, Any]) -> str | None:
124
+ hardware = body.get("hardwareProfile")
125
+ if isinstance(hardware, dict):
126
+ size = hardware.get("vmSize")
127
+ if isinstance(size, str) and size.strip():
128
+ return size.strip()
129
+ return None
130
+
131
+
132
+ def _is_spot_body(body: dict[str, Any]) -> bool:
133
+ priority = str(body.get("priority") or "").strip().lower()
134
+ if priority == "spot":
135
+ return True
136
+ billing = body.get("billingProfile")
137
+ if isinstance(billing, dict):
138
+ spot = billing.get("spotOptions") or billing.get("maxPrice")
139
+ if spot is not None:
140
+ return True
141
+ return False
142
+
143
+
144
+ def _activity_items(stdout_json: Any) -> list[dict[str, Any]]:
145
+ if isinstance(stdout_json, list):
146
+ return [item for item in stdout_json if isinstance(item, dict)]
147
+ if isinstance(stdout_json, dict):
148
+ value = stdout_json.get("value")
149
+ if isinstance(value, list):
150
+ return [item for item in value if isinstance(item, dict)]
151
+ return []
152
+
153
+
154
+ def _runner_response(result: Any) -> dict[str, Any]:
155
+ raw = (getattr(result, "stdout", "") or "").strip()
156
+ parsed: Any = []
157
+ if raw:
158
+ try:
159
+ parsed = json.loads(raw)
160
+ except json.JSONDecodeError:
161
+ parsed = []
162
+ return {
163
+ "exit_code": int(getattr(result, "exit_code", 1)),
164
+ "stderr": (getattr(result, "stderr", "") or ""),
165
+ "stdout_json": parsed,
166
+ }
167
+
168
+
169
+ def collect_account_azure_activity(
170
+ runner: Any,
171
+ regions: set[str],
172
+ *,
173
+ now: Any = None,
174
+ ) -> tuple[SpotHistoryCounts, LaunchAttemptCounts]:
175
+ """Read VM writes and Spot evictions for the last 30 days in scoped regions."""
176
+ wanted = {name.strip().lower() for name in regions if str(name).strip()}
177
+ start, end = context_trail_window(now)
178
+ spot = SpotHistoryCounts()
179
+ launches = LaunchAttemptCounts()
180
+ if not wanted:
181
+ return spot, launches
182
+ try:
183
+ resolve_azure_account(runner)
184
+ except AccountIdentityError:
185
+ return spot, launches
186
+
187
+ from maproom.analyze.local_reads import run_cached_analyze_read, window_cache_suffix
188
+
189
+ page_end = end
190
+ slice_index = 0
191
+ while page_end > start:
192
+ argv = build_azure_activity_log_argv(start=start, end=page_end)
193
+ result = run_cached_analyze_read(
194
+ runner,
195
+ "azure",
196
+ argv,
197
+ api_id="azure_monitor_activity_log_list",
198
+ region="global",
199
+ suffix=window_cache_suffix(
200
+ start=start,
201
+ end=page_end,
202
+ granularity="account_context",
203
+ token=str(slice_index),
204
+ label="activity",
205
+ ),
206
+ record=False,
207
+ now=now,
208
+ )
209
+ response = _runner_response(result)
210
+ if response["exit_code"] != 0:
211
+ break
212
+
213
+ entries = _activity_items(response["stdout_json"])
214
+ for entry in entries:
215
+ region = _region_from_event(entry)
216
+ if not region or region not in wanted:
217
+ continue
218
+ operation = _operation_name(entry)
219
+ if _EVENT_SPOT_EVICT in operation:
220
+ props = (
221
+ entry.get("properties") if isinstance(entry.get("properties"), dict) else {}
222
+ )
223
+ body = _parsed_request_body(props)
224
+ vm_size = _vm_size_from_body(body)
225
+ if not vm_size:
226
+ continue
227
+ key = (region, vm_size)
228
+ spot.terminations[key] += 1
229
+ continue
230
+ if _EVENT_VM_WRITE not in operation:
231
+ continue
232
+ props = entry.get("properties") if isinstance(entry.get("properties"), dict) else {}
233
+ body = _parsed_request_body(props)
234
+ vm_size = _vm_size_from_body(body)
235
+ if not vm_size:
236
+ continue
237
+ purchase = "spot" if _is_spot_body(body) else "on_demand"
238
+ status = _status_value(entry)
239
+ if status == "succeeded":
240
+ launches.launched[(region, vm_size, purchase)] += 1
241
+ if purchase == "spot":
242
+ spot.launches[(region, vm_size)] += 1
243
+ elif status == "failed":
244
+ error = _substatus_code(entry) or "Failed"
245
+ launches.failed[(region, vm_size, purchase, error)] += 1
246
+
247
+ if len(entries) < _ACTIVITY_LOG_PAGE_SIZE:
248
+ break
249
+ timestamps = [_parse_event_timestamp(entry) for entry in entries]
250
+ timestamps = [value for value in timestamps if value is not None]
251
+ if not timestamps:
252
+ break
253
+ oldest = min(timestamps)
254
+ if oldest.tzinfo is None:
255
+ oldest = oldest.replace(tzinfo=timezone.utc)
256
+ page_end = oldest - timedelta(microseconds=1)
257
+ slice_index += 1
258
+ if page_end <= start:
259
+ break
260
+ return spot, launches
@@ -0,0 +1,177 @@
1
+ """Azure quota increase requests for the operator-context phase."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+ from urllib.parse import parse_qs, urlparse
8
+
9
+ from maproom.analyze.account_cloudtrail import context_trail_window
10
+ from maproom.analyze.account_quota_requests import QuotaRequestCounts
11
+ from maproom.inventory.account_identity import AccountIdentityError, resolve_azure_account
12
+ from maproom.quotas.quota_request_sync import _parse_quota_timestamp
13
+
14
+ _COMPUTE_PROVIDER = "Microsoft.Compute"
15
+
16
+
17
+ def build_azure_quota_request_list_argv(*, scope: str, skip_token: str | None = None) -> list[str]:
18
+ argv = [
19
+ "quota",
20
+ "request",
21
+ "list",
22
+ "--scope",
23
+ scope,
24
+ "--output",
25
+ "json",
26
+ ]
27
+ if skip_token:
28
+ argv.extend(["--skiptoken", skip_token])
29
+ return argv
30
+
31
+
32
+ def _context_status_bucket(item: dict[str, Any]) -> str | None:
33
+ props = item.get("properties") if isinstance(item.get("properties"), dict) else {}
34
+ state = str(props.get("provisioningState") or props.get("provisioningstate") or "").strip()
35
+ lowered = state.lower()
36
+ if lowered in {"notstarted", "created"}:
37
+ return "requested"
38
+ if lowered in {"pending", "inprogress", "accepted"}:
39
+ return "pending"
40
+ if lowered in {"succeeded", "completed"}:
41
+ return "approved"
42
+ if lowered in {"failed", "cancelled", "canceled", "denied"}:
43
+ return "denied"
44
+ return None
45
+
46
+
47
+ def _quota_code(item: dict[str, Any]) -> str | None:
48
+ props = item.get("properties") if isinstance(item.get("properties"), dict) else {}
49
+ resource = props.get("resourceName")
50
+ if not isinstance(resource, str) or not resource.strip():
51
+ nested = props.get("resourceProperties")
52
+ if isinstance(nested, dict):
53
+ resource = nested.get("name")
54
+ if isinstance(resource, str) and resource.strip():
55
+ return resource.strip()
56
+ return None
57
+
58
+
59
+ def _skiptoken_from_next_link(link: str) -> str | None:
60
+ query = parse_qs(urlparse(link).query)
61
+ for key in ("$skiptoken", "skiptoken"):
62
+ values = query.get(key)
63
+ if values:
64
+ token = str(values[0]).strip()
65
+ if token:
66
+ return token
67
+ return None
68
+
69
+
70
+ def _item_timestamp(item: dict[str, Any]) -> Any:
71
+ props = item.get("properties") if isinstance(item.get("properties"), dict) else {}
72
+ for key in ("createdTime", "submitTime", "requestSubmitTime"):
73
+ if key in props:
74
+ return props.get(key)
75
+ return None
76
+
77
+
78
+ def _include_history_item(item: dict[str, Any], *, window_start: Any) -> bool:
79
+ bucket = _context_status_bucket(item)
80
+ if bucket is None:
81
+ return False
82
+ if bucket in {"requested", "pending"}:
83
+ return True
84
+ created = _parse_quota_timestamp(_item_timestamp(item))
85
+ if created is None:
86
+ return False
87
+ return created >= window_start
88
+
89
+
90
+ def _list_items(stdout_json: Any) -> tuple[list[dict[str, Any]], str | None]:
91
+ if isinstance(stdout_json, dict):
92
+ items = stdout_json.get("value")
93
+ next_link = stdout_json.get("nextLink")
94
+ if isinstance(next_link, str) and next_link.strip():
95
+ token = _skiptoken_from_next_link(next_link.strip())
96
+ else:
97
+ token = None
98
+ elif isinstance(stdout_json, list):
99
+ items = stdout_json
100
+ token = None
101
+ else:
102
+ return [], None
103
+ if not isinstance(items, list):
104
+ return [], None
105
+ return [row for row in items if isinstance(row, dict)], token
106
+
107
+
108
+ def _runner_response(result: Any) -> dict[str, Any]:
109
+ raw = (getattr(result, "stdout", "") or "").strip()
110
+ parsed: Any = {}
111
+ if raw:
112
+ try:
113
+ parsed = json.loads(raw)
114
+ except json.JSONDecodeError:
115
+ parsed = {}
116
+ return {
117
+ "exit_code": int(getattr(result, "exit_code", 1)),
118
+ "stderr": (getattr(result, "stderr", "") or ""),
119
+ "stdout_json": parsed,
120
+ }
121
+
122
+
123
+ def collect_account_azure_quota_requests(
124
+ runner: Any,
125
+ regions: set[str],
126
+ *,
127
+ now: Any = None,
128
+ ) -> QuotaRequestCounts:
129
+ """Read compute quota request history per region for the last 30 days plus open requests."""
130
+ window_start, window_end = context_trail_window(now)
131
+ counts = QuotaRequestCounts()
132
+ try:
133
+ subscription = resolve_azure_account(runner).account_id
134
+ except AccountIdentityError:
135
+ return counts
136
+
137
+ from maproom.analyze.local_reads import run_cached_analyze_read, window_cache_suffix
138
+
139
+ for region in sorted(name.strip().lower() for name in regions if str(name).strip()):
140
+ scope = (
141
+ f"/subscriptions/{subscription}/providers/{_COMPUTE_PROVIDER}/locations/{region}"
142
+ )
143
+ skip_token: str | None = None
144
+ while True:
145
+ argv = build_azure_quota_request_list_argv(scope=scope, skip_token=skip_token)
146
+ result = run_cached_analyze_read(
147
+ runner,
148
+ "azure",
149
+ argv,
150
+ api_id="azure_quota_request_list",
151
+ region=region,
152
+ suffix=window_cache_suffix(
153
+ start=window_start.date().isoformat(),
154
+ end=window_end.date().isoformat(),
155
+ granularity="account_context",
156
+ label="quota_requests",
157
+ token=skip_token or "first",
158
+ ),
159
+ record=False,
160
+ now=now,
161
+ )
162
+ response = _runner_response(result)
163
+ if response["exit_code"] != 0:
164
+ break
165
+ items, skip_token = _list_items(response["stdout_json"])
166
+ for requested in items:
167
+ if not _include_history_item(requested, window_start=window_start):
168
+ continue
169
+ quota_code = _quota_code(requested)
170
+ bucket = _context_status_bucket(requested)
171
+ if not quota_code or bucket is None:
172
+ continue
173
+ key = (region, quota_code, bucket)
174
+ counts.counts[key] += 1
175
+ if not skip_token:
176
+ break
177
+ return counts