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.
- maproom/__init__.py +14 -0
- maproom/__main__.py +10 -0
- maproom/analyze/__init__.py +1 -0
- maproom/analyze/accel_families.py +45 -0
- maproom/analyze/account_azure_activity.py +260 -0
- maproom/analyze/account_azure_quota_requests.py +177 -0
- maproom/analyze/account_cloudtrail.py +316 -0
- maproom/analyze/account_quota_requests.py +180 -0
- maproom/analyze/analyze_v1_orchestration.py +1194 -0
- maproom/analyze/catalog.py +353 -0
- maproom/analyze/change_detection.py +652 -0
- maproom/analyze/context_client.py +99 -0
- maproom/analyze/context_lookup.py +142 -0
- maproom/analyze/cover_analyze.py +344 -0
- maproom/analyze/cover_client.py +65 -0
- maproom/analyze/cover_lookup.py +242 -0
- maproom/analyze/engine.py +644 -0
- maproom/analyze/fleetfit_endpoints.py +217 -0
- maproom/analyze/fleetfit_policy.py +66 -0
- maproom/analyze/instance_price_analyze.py +221 -0
- maproom/analyze/instance_price_client.py +108 -0
- maproom/analyze/instance_price_lookup.py +60 -0
- maproom/analyze/local_reads.py +484 -0
- maproom/analyze/lookup_http.py +280 -0
- maproom/analyze/metric_format.py +20 -0
- maproom/analyze/migration_method.py +130 -0
- maproom/analyze/move_list.py +93 -0
- maproom/analyze/operator_context.py +156 -0
- maproom/analyze/performance_rank.py +97 -0
- maproom/analyze/primary_recommendation.py +422 -0
- maproom/analyze/provider_comparison.py +401 -0
- maproom/analyze/quota_analyze.py +481 -0
- maproom/analyze/quota_client.py +75 -0
- maproom/analyze/quota_lookup.py +110 -0
- maproom/analyze/quota_outcome_steer.py +105 -0
- maproom/analyze/recommend_batch.py +199 -0
- maproom/analyze/recommend_client.py +362 -0
- maproom/analyze/recommend_share.py +118 -0
- maproom/analyze/recommendation.py +591 -0
- maproom/analyze/reservation_pack.py +883 -0
- maproom/analyze/reservation_read.py +461 -0
- maproom/analyze/safe_analyze.py +1134 -0
- maproom/analyze/safe_move.py +195 -0
- maproom/analyze/safe_moves.py +571 -0
- maproom/analyze/safe_moves_catalog.py +127 -0
- maproom/analyze/safe_moves_client.py +70 -0
- maproom/analyze/series_analyze.py +491 -0
- maproom/analyze/series_client.py +106 -0
- maproom/analyze/series_lookup.py +663 -0
- maproom/analyze/shape.py +254 -0
- maproom/analyze/size_analyze.py +883 -0
- maproom/analyze/size_client.py +81 -0
- maproom/analyze/size_keep.py +409 -0
- maproom/analyze/size_lookup.py +368 -0
- maproom/analyze/specs.py +325 -0
- maproom/analyze/spot_analyze.py +392 -0
- maproom/analyze/spot_client.py +74 -0
- maproom/analyze/spot_lookup.py +213 -0
- maproom/analyze/token_client.py +97 -0
- maproom/analyze/utilization.py +190 -0
- maproom/analyze/workload.py +104 -0
- maproom/analyze/workset.py +762 -0
- maproom/aws_region.py +78 -0
- maproom/cache/__init__.py +1 -0
- maproom/cache/catalog.py +372 -0
- maproom/cache/commands.py +215 -0
- maproom/cache/instances.py +460 -0
- maproom/cli.py +2084 -0
- maproom/cli_argv.py +329 -0
- maproom/cli_floors.py +89 -0
- maproom/cliio/__init__.py +1 -0
- maproom/cliio/registry.py +377 -0
- maproom/cliio/runner.py +489 -0
- maproom/consent/__init__.py +33 -0
- maproom/consent/gate.py +238 -0
- maproom/consent/policy.py +20 -0
- maproom/consent/prompt.py +61 -0
- maproom/consent/service_upload_gate.py +318 -0
- maproom/consent/service_upload_prompt.py +62 -0
- maproom/consent/stdin.py +45 -0
- maproom/consent/storage.py +24 -0
- maproom/consent/write_token.py +29 -0
- maproom/contracts/__init__.py +6 -0
- maproom/contracts/schema_diff.py +119 -0
- maproom/contracts/validate.py +113 -0
- maproom/data/__init__.py +1 -0
- maproom/data/clear.py +76 -0
- maproom/data/commands.py +14 -0
- maproom/doctor/__init__.py +1 -0
- maproom/doctor/aws_session.py +226 -0
- maproom/doctor/checks.py +701 -0
- maproom/doctor/context.py +32 -0
- maproom/doctor/display.py +96 -0
- maproom/doctor/inventory_display.py +377 -0
- maproom/doctor/runner.py +1467 -0
- maproom/errors.py +43 -0
- maproom/exitcodes.py +70 -0
- maproom/inventory/__init__.py +1 -0
- maproom/inventory/account_identity.py +79 -0
- maproom/inventory/accounts.py +155 -0
- maproom/inventory/command.py +961 -0
- maproom/inventory/messages.py +264 -0
- maproom/inventory/reservations_refresh.py +37 -0
- maproom/mock_environment/__init__.py +28 -0
- maproom/mock_environment/load.py +241 -0
- maproom/mock_environment/runner.py +387 -0
- maproom/output/__init__.py +1 -0
- maproom/output/json_envelope.py +241 -0
- maproom/output/redact.py +11 -0
- maproom/output/terminal.py +129 -0
- maproom/parsers.py +284 -0
- maproom/paths.py +105 -0
- maproom/plan/__init__.py +1 -0
- maproom/plan/accept.py +59 -0
- maproom/plan/analysis_context.py +78 -0
- maproom/plan/analyze_selection.py +279 -0
- maproom/plan/commands.py +586 -0
- maproom/plan/current.py +59 -0
- maproom/plan/errors.py +10 -0
- maproom/plan/export.py +36 -0
- maproom/plan/formatting.py +91 -0
- maproom/plan/ids.py +13 -0
- maproom/plan/migration_options.py +75 -0
- maproom/plan/model.py +265 -0
- maproom/plan/names.py +24 -0
- maproom/plan/store.py +193 -0
- maproom/plan/tty.py +34 -0
- maproom/pricing/__init__.py +5 -0
- maproom/pricing/prices.py +119 -0
- maproom/privacy/__init__.py +6 -0
- maproom/privacy/commands.py +159 -0
- maproom/privacy/delete_uploads.py +204 -0
- maproom/privacy/fleetfit_policy.py +125 -0
- maproom/privacy/fleetfit_statement.py +104 -0
- maproom/privacy/format.py +76 -0
- maproom/privacy/manifests.py +342 -0
- maproom/privacy/statement.py +58 -0
- maproom/quotas/__init__.py +21 -0
- maproom/quotas/aws.py +204 -0
- maproom/quotas/azure.py +75 -0
- maproom/quotas/commands.py +240 -0
- maproom/quotas/family_coverage.py +122 -0
- maproom/quotas/fetch.py +124 -0
- maproom/quotas/load.py +41 -0
- maproom/quotas/model.py +178 -0
- maproom/quotas/outcome_ledger.py +245 -0
- maproom/quotas/quota_request_sync.py +221 -0
- maproom/quotas/show.py +73 -0
- maproom/quotas/status.py +206 -0
- maproom/quotas/store.py +161 -0
- maproom/redaction.py +157 -0
- maproom/reference_data/__init__.py +1 -0
- maproom/reference_data/aws/aws_prices.csv +25562 -0
- maproom/reference_data/aws/capabilities.csv +1346 -0
- maproom/reference_data/aws/instance_types.csv +1346 -0
- maproom/reference_data/azure/azure_prices.csv +1 -0
- maproom/reference_data/azure/vm_types.csv +1 -0
- maproom/reference_data/benchmarks/cpu-lscpu-v2-instances.json +27 -0
- maproom/reference_data/benchmarks/safe-moves-v1.json +328 -0
- maproom/reference_data/manifest.json +174 -0
- maproom/reference_data/manifest.py +69 -0
- maproom/reservations/__init__.py +17 -0
- maproom/reservations/aws.py +76 -0
- maproom/reservations/azure.py +36 -0
- maproom/reservations/commands.py +149 -0
- maproom/reservations/load.py +41 -0
- maproom/reservations/model.py +316 -0
- maproom/reservations/show.py +64 -0
- maproom/reservations/status.py +181 -0
- maproom/reservations/store.py +391 -0
- maproom/resources.py +54 -0
- maproom/root_help.py +251 -0
- maproom/saving_plans/__init__.py +15 -0
- maproom/saving_plans/aws.py +73 -0
- maproom/saving_plans/commands.py +122 -0
- maproom/saving_plans/load.py +41 -0
- maproom/saving_plans/model.py +101 -0
- maproom/saving_plans/show.py +64 -0
- maproom/saving_plans/status.py +118 -0
- maproom/saving_plans/store.py +173 -0
- maproom/secret_egress_gate.py +108 -0
- maproom/service/install_id.py +60 -0
- maproom/settings/__init__.py +1 -0
- maproom/settings/defaults.py +73 -0
- maproom/settings/init.py +143 -0
- maproom/settings/model.py +105 -0
- maproom/settings/product_version_change.py +343 -0
- maproom/settings/product_versions.py +68 -0
- maproom/settings/set.py +347 -0
- maproom/settings/show.py +227 -0
- maproom/settings/write.py +273 -0
- maproom/snapshot_time.py +27 -0
- maproom-0.2.0.dist-info/METADATA +263 -0
- maproom-0.2.0.dist-info/RECORD +199 -0
- maproom-0.2.0.dist-info/WHEEL +5 -0
- maproom-0.2.0.dist-info/entry_points.txt +2 -0
- maproom-0.2.0.dist-info/licenses/LICENSE +201 -0
- maproom-0.2.0.dist-info/licenses/NOTICE +72 -0
- maproom-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Sync terminal Service Quotas outcomes into the local steering ledger."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Iterator
|
|
10
|
+
|
|
11
|
+
from maproom.analyze.catalog import SpecRow
|
|
12
|
+
from maproom.paths import data_subdir
|
|
13
|
+
from maproom.quotas.outcome_ledger import record_quota_denial
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class QuotaOutcomeRecordingRequired(RuntimeError):
|
|
17
|
+
"""product_version 7+ cannot run quota lifecycle calls without recording."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
_QUOTA_RECORDING_MESSAGE = (
|
|
21
|
+
"product_version 7 and 8 need request recording for quota-outcome memory. "
|
|
22
|
+
"Run maproom settings set product_version 6 or lower, or allow recording "
|
|
23
|
+
"for Service Quotas lifecycle calls."
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def resolve_quota_service_record(product_version: int, *, record: bool) -> bool:
|
|
28
|
+
"""Return the record flag for Service Quotas lifecycle CLI calls."""
|
|
29
|
+
if product_version >= 7 and not record:
|
|
30
|
+
raise QuotaOutcomeRecordingRequired(_QUOTA_RECORDING_MESSAGE)
|
|
31
|
+
if product_version >= 7:
|
|
32
|
+
return True
|
|
33
|
+
return record
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _pending_root() -> Path:
|
|
37
|
+
return data_subdir("request_ledger") / "quota-requests" / "pending"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def record_quota_request_submitted(
|
|
41
|
+
*,
|
|
42
|
+
request_id: str,
|
|
43
|
+
cloud: str,
|
|
44
|
+
region: str,
|
|
45
|
+
quota_code: str,
|
|
46
|
+
desired_value: float,
|
|
47
|
+
instance_type: str | None = None,
|
|
48
|
+
quota_family: str | None = None,
|
|
49
|
+
) -> Path:
|
|
50
|
+
"""Remember a submitted increase so a later analyze run can poll its outcome."""
|
|
51
|
+
root = _pending_root()
|
|
52
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
53
|
+
safe_id = request_id.strip().replace("/", "_")
|
|
54
|
+
path = root / f"{safe_id}.json"
|
|
55
|
+
body: dict[str, Any] = {
|
|
56
|
+
"kind": "quota_request_pending",
|
|
57
|
+
"request_id": request_id.strip(),
|
|
58
|
+
"cloud": cloud.strip().lower(),
|
|
59
|
+
"region": region.strip().lower(),
|
|
60
|
+
"quota_code": quota_code.strip(),
|
|
61
|
+
"desired_value": float(desired_value),
|
|
62
|
+
"submitted_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
63
|
+
}
|
|
64
|
+
if instance_type:
|
|
65
|
+
body["instance_type"] = instance_type.strip()
|
|
66
|
+
if quota_family:
|
|
67
|
+
body["quota_family"] = quota_family.strip()
|
|
68
|
+
path.write_text(json.dumps(body, indent=2), encoding="utf-8")
|
|
69
|
+
return path
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _iter_pending_requests() -> Iterator[dict[str, Any]]:
|
|
73
|
+
root = _pending_root()
|
|
74
|
+
if not root.is_dir():
|
|
75
|
+
return
|
|
76
|
+
for path in sorted(root.glob("*.json")):
|
|
77
|
+
try:
|
|
78
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
79
|
+
except (OSError, json.JSONDecodeError):
|
|
80
|
+
continue
|
|
81
|
+
if isinstance(raw, dict):
|
|
82
|
+
yield raw
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _poll_requested_quota_change(
|
|
86
|
+
runner: Any,
|
|
87
|
+
*,
|
|
88
|
+
product_version: int,
|
|
89
|
+
request_id: str,
|
|
90
|
+
region: str,
|
|
91
|
+
) -> dict[str, Any] | None:
|
|
92
|
+
from maproom.quotas.aws import _parse_runner_json
|
|
93
|
+
|
|
94
|
+
record = resolve_quota_service_record(
|
|
95
|
+
product_version, record=(product_version >= 7)
|
|
96
|
+
)
|
|
97
|
+
result = runner.run(
|
|
98
|
+
"aws",
|
|
99
|
+
[
|
|
100
|
+
"service-quotas",
|
|
101
|
+
"get-requested-service-quota-change",
|
|
102
|
+
"--request-id",
|
|
103
|
+
request_id,
|
|
104
|
+
"--region",
|
|
105
|
+
region,
|
|
106
|
+
"--output",
|
|
107
|
+
"json",
|
|
108
|
+
],
|
|
109
|
+
record=record,
|
|
110
|
+
api_id="aws_service_quotas_get_requested_service_quota_change",
|
|
111
|
+
)
|
|
112
|
+
if result.exit_code != 0:
|
|
113
|
+
return None
|
|
114
|
+
try:
|
|
115
|
+
data = _parse_runner_json(
|
|
116
|
+
result,
|
|
117
|
+
f"aws service-quotas get-requested-service-quota-change ({region})",
|
|
118
|
+
)
|
|
119
|
+
except Exception:
|
|
120
|
+
return None
|
|
121
|
+
requested = data.get("RequestedQuota")
|
|
122
|
+
return requested if isinstance(requested, dict) else None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _is_terminal_quota_request(requested: dict[str, Any]) -> bool:
|
|
126
|
+
status = str(requested.get("Status") or "").strip().upper()
|
|
127
|
+
if status in {"", "PENDING", "IN_PROGRESS", "CASE_OPENED"}:
|
|
128
|
+
return False
|
|
129
|
+
return True
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _terminal_denied(requested: dict[str, Any]) -> bool:
|
|
133
|
+
status = str(requested.get("Status") or "").strip().upper()
|
|
134
|
+
if status == "DENIED":
|
|
135
|
+
return True
|
|
136
|
+
if status == "NOT_APPROVED":
|
|
137
|
+
return True
|
|
138
|
+
if status != "CASE_CLOSED":
|
|
139
|
+
return False
|
|
140
|
+
case_status = str(requested.get("CaseStatus") or "").strip().upper()
|
|
141
|
+
return case_status in {"DENIED", "NOT_APPROVED", "UNAPPROVED"}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def sync_terminal_quota_denials(
|
|
145
|
+
runner: Any,
|
|
146
|
+
*,
|
|
147
|
+
product_version: int,
|
|
148
|
+
specs: dict[tuple[str, str], SpecRow] | None = None,
|
|
149
|
+
) -> int:
|
|
150
|
+
"""Poll pending quota increases and persist terminal denials for steering."""
|
|
151
|
+
written = 0
|
|
152
|
+
if product_version < 7:
|
|
153
|
+
return written
|
|
154
|
+
specs = specs or {}
|
|
155
|
+
for pending in _iter_pending_requests():
|
|
156
|
+
request_id = str(pending.get("request_id") or "").strip()
|
|
157
|
+
region = str(pending.get("region") or "").strip()
|
|
158
|
+
cloud = str(pending.get("cloud") or "aws").strip().lower()
|
|
159
|
+
if not request_id or not region:
|
|
160
|
+
continue
|
|
161
|
+
requested = _poll_requested_quota_change(
|
|
162
|
+
runner,
|
|
163
|
+
product_version=product_version,
|
|
164
|
+
request_id=request_id,
|
|
165
|
+
region=region,
|
|
166
|
+
)
|
|
167
|
+
if requested is None or not _is_terminal_quota_request(requested):
|
|
168
|
+
continue
|
|
169
|
+
if _terminal_denied(requested):
|
|
170
|
+
quota_code = str(
|
|
171
|
+
pending.get("quota_code") or requested.get("QuotaCode") or ""
|
|
172
|
+
).strip()
|
|
173
|
+
desired_raw = pending.get("desired_value", requested.get("DesiredValue"))
|
|
174
|
+
try:
|
|
175
|
+
desired_value = float(desired_raw)
|
|
176
|
+
except (TypeError, ValueError):
|
|
177
|
+
desired_value = 0.0
|
|
178
|
+
instance_type = pending.get("instance_type")
|
|
179
|
+
type_name = instance_type.strip() if isinstance(instance_type, str) else None
|
|
180
|
+
quota_family = pending.get("quota_family")
|
|
181
|
+
family_name = quota_family.strip() if isinstance(quota_family, str) else None
|
|
182
|
+
if not family_name and type_name:
|
|
183
|
+
spec = specs.get((cloud, type_name))
|
|
184
|
+
if spec is not None and spec.quota_family:
|
|
185
|
+
family_name = spec.quota_family.strip()
|
|
186
|
+
denied_at = _parse_quota_timestamp(requested.get("Created"))
|
|
187
|
+
record_quota_denial(
|
|
188
|
+
cloud=cloud,
|
|
189
|
+
region=region,
|
|
190
|
+
quota_code=quota_code or family_name or "unknown",
|
|
191
|
+
requested_value=desired_value,
|
|
192
|
+
instance_type=type_name,
|
|
193
|
+
quota_family=family_name,
|
|
194
|
+
denied_at=denied_at,
|
|
195
|
+
)
|
|
196
|
+
written += 1
|
|
197
|
+
_remove_pending_request(request_id)
|
|
198
|
+
return written
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _parse_quota_timestamp(raw: object) -> datetime | None:
|
|
202
|
+
if not isinstance(raw, str) or not raw.strip():
|
|
203
|
+
return None
|
|
204
|
+
text = raw.strip()
|
|
205
|
+
if text.endswith("Z"):
|
|
206
|
+
text = text[:-1] + "+00:00"
|
|
207
|
+
try:
|
|
208
|
+
parsed = datetime.fromisoformat(text)
|
|
209
|
+
except ValueError:
|
|
210
|
+
return None
|
|
211
|
+
if parsed.tzinfo is None:
|
|
212
|
+
parsed = parsed.replace(tzinfo=timezone.utc)
|
|
213
|
+
return parsed.astimezone(timezone.utc)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _remove_pending_request(request_id: str) -> None:
|
|
217
|
+
root = _pending_root()
|
|
218
|
+
safe_id = request_id.strip().replace("/", "_")
|
|
219
|
+
path = root / f"{safe_id}.json"
|
|
220
|
+
if path.is_file():
|
|
221
|
+
path.unlink()
|
maproom/quotas/show.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Quota snapshot summary. The operator command is maproom inventory."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
from maproom.doctor.inventory_display import (
|
|
8
|
+
QUOTAS_GET_HINT,
|
|
9
|
+
quota_inventory_detail_lines,
|
|
10
|
+
quota_record_lines,
|
|
11
|
+
)
|
|
12
|
+
from maproom.exitcodes import RUNTIME, SUCCESS
|
|
13
|
+
from maproom.output.json_envelope import build_document, command_metadata, error_item, print_json
|
|
14
|
+
from maproom.quotas.model import count_launch_relevant_records
|
|
15
|
+
from maproom.quotas.status import doctor_quotas_message, read_quota_state
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def run_quotas_show(*, as_json: bool = False, show_all: bool = False) -> int:
|
|
19
|
+
state = read_quota_state()
|
|
20
|
+
if state.parse_error:
|
|
21
|
+
message = doctor_quotas_message(state)
|
|
22
|
+
if as_json:
|
|
23
|
+
print_json(
|
|
24
|
+
build_document(
|
|
25
|
+
schema_type="quotas",
|
|
26
|
+
schema_id="maproom.quotas",
|
|
27
|
+
metadata=command_metadata("quotas"),
|
|
28
|
+
errors=[error_item("runtime", message)],
|
|
29
|
+
warnings=[],
|
|
30
|
+
payload={
|
|
31
|
+
"snapshot_path": str(state.snapshot_path),
|
|
32
|
+
"exists": state.exists,
|
|
33
|
+
"loaded_as_of": state.loaded_as_of,
|
|
34
|
+
"record_count": state.record_count,
|
|
35
|
+
"launch_relevant_count": 0,
|
|
36
|
+
"is_stale": state.is_stale,
|
|
37
|
+
"records": [],
|
|
38
|
+
},
|
|
39
|
+
)
|
|
40
|
+
)
|
|
41
|
+
return RUNTIME
|
|
42
|
+
print(message)
|
|
43
|
+
return RUNTIME
|
|
44
|
+
if as_json:
|
|
45
|
+
launch_relevant = count_launch_relevant_records(state.records)
|
|
46
|
+
print_json(
|
|
47
|
+
build_document(
|
|
48
|
+
schema_type="quotas",
|
|
49
|
+
schema_id="maproom.quotas",
|
|
50
|
+
metadata=command_metadata("quotas"),
|
|
51
|
+
payload={
|
|
52
|
+
"snapshot_path": str(state.snapshot_path),
|
|
53
|
+
"exists": state.exists,
|
|
54
|
+
"loaded_as_of": state.loaded_as_of,
|
|
55
|
+
"record_count": state.record_count,
|
|
56
|
+
"launch_relevant_count": launch_relevant,
|
|
57
|
+
"is_stale": state.is_stale,
|
|
58
|
+
"records": list(state.records),
|
|
59
|
+
},
|
|
60
|
+
)
|
|
61
|
+
)
|
|
62
|
+
return SUCCESS
|
|
63
|
+
|
|
64
|
+
for line in quota_inventory_detail_lines(state):
|
|
65
|
+
print(line)
|
|
66
|
+
detail = quota_record_lines(state, show_all=show_all)
|
|
67
|
+
if detail:
|
|
68
|
+
print()
|
|
69
|
+
for line in detail:
|
|
70
|
+
print(line)
|
|
71
|
+
print()
|
|
72
|
+
print(QUOTAS_GET_HINT)
|
|
73
|
+
return SUCCESS
|
maproom/quotas/status.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""Quota snapshot read-side status, launchability, and TTY helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Literal
|
|
9
|
+
|
|
10
|
+
from maproom.paths import settings_read_file
|
|
11
|
+
from maproom.quotas import store
|
|
12
|
+
from maproom.quotas.model import EC2_STANDARD_QUOTA_CODE, QuotaError, count_launch_relevant_records
|
|
13
|
+
from maproom.settings.model import cache_max_age_hours, snapshot_is_stale
|
|
14
|
+
from maproom.snapshot_time import as_of_date_label
|
|
15
|
+
|
|
16
|
+
Launchability = Literal["unknown", "sufficient", "blocked"]
|
|
17
|
+
|
|
18
|
+
QUOTAS_INVENTORY_REMEDIATION = "Refresh with: maproom inventory get"
|
|
19
|
+
QUOTAS_INVENTORY_REMEDIATION_AWS_ONLY = "Refresh with: maproom inventory get"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class QuotaState:
|
|
24
|
+
snapshot_path: Path
|
|
25
|
+
exists: bool
|
|
26
|
+
loaded_as_of: str | None
|
|
27
|
+
record_count: int
|
|
28
|
+
is_stale: bool
|
|
29
|
+
cache_max_age_hours: int
|
|
30
|
+
parse_error: str | None = None
|
|
31
|
+
source: str | None = None
|
|
32
|
+
records: tuple[dict[str, Any], ...] = ()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def read_quota_state(
|
|
36
|
+
settings_path: Path | None = None,
|
|
37
|
+
*,
|
|
38
|
+
now_utc: datetime | None = None,
|
|
39
|
+
) -> QuotaState:
|
|
40
|
+
path = store.status_path()
|
|
41
|
+
settings_file_path = settings_path or settings_read_file()
|
|
42
|
+
max_age = cache_max_age_hours(settings_file_path)
|
|
43
|
+
|
|
44
|
+
data = store.read_snapshot()
|
|
45
|
+
if isinstance(data, QuotaError):
|
|
46
|
+
return QuotaState(
|
|
47
|
+
snapshot_path=path,
|
|
48
|
+
exists=True,
|
|
49
|
+
loaded_as_of=None,
|
|
50
|
+
record_count=0,
|
|
51
|
+
is_stale=False,
|
|
52
|
+
cache_max_age_hours=max_age,
|
|
53
|
+
parse_error=data.message,
|
|
54
|
+
)
|
|
55
|
+
if data is None:
|
|
56
|
+
return QuotaState(
|
|
57
|
+
snapshot_path=path,
|
|
58
|
+
exists=False,
|
|
59
|
+
loaded_as_of=None,
|
|
60
|
+
record_count=0,
|
|
61
|
+
is_stale=False,
|
|
62
|
+
cache_max_age_hours=max_age,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
loaded_as_of = str(data.get("loaded_as_of") or "")
|
|
66
|
+
records_raw = data.get("records") or []
|
|
67
|
+
records = tuple(r for r in records_raw if isinstance(r, dict))
|
|
68
|
+
record_count = int(
|
|
69
|
+
data.get("record_count") if data.get("record_count") is not None else len(records)
|
|
70
|
+
)
|
|
71
|
+
source = str(data.get("source") or "") or None
|
|
72
|
+
stale = snapshot_is_stale(loaded_as_of, max_age, now=now_utc)
|
|
73
|
+
return QuotaState(
|
|
74
|
+
snapshot_path=path,
|
|
75
|
+
exists=True,
|
|
76
|
+
loaded_as_of=loaded_as_of or None,
|
|
77
|
+
record_count=record_count,
|
|
78
|
+
is_stale=stale,
|
|
79
|
+
cache_max_age_hours=max_age,
|
|
80
|
+
source=source,
|
|
81
|
+
records=records,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def quota_headroom_missing(state: QuotaState) -> bool:
|
|
86
|
+
if state.parse_error:
|
|
87
|
+
return True
|
|
88
|
+
if not state.exists:
|
|
89
|
+
return True
|
|
90
|
+
if state.is_stale:
|
|
91
|
+
return True
|
|
92
|
+
return state.record_count == 0
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _find_standard_quota(state: QuotaState, region: str) -> dict[str, Any] | None:
|
|
96
|
+
for record in state.records:
|
|
97
|
+
if record.get("quota_code") == EC2_STANDARD_QUOTA_CODE and record.get("region") == region:
|
|
98
|
+
return record
|
|
99
|
+
for record in state.records:
|
|
100
|
+
if record.get("quota_code") == EC2_STANDARD_QUOTA_CODE:
|
|
101
|
+
return record
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def candidate_exceeds_standard_quota_headroom(
|
|
106
|
+
state: QuotaState,
|
|
107
|
+
*,
|
|
108
|
+
region: str,
|
|
109
|
+
headroom_pct: int,
|
|
110
|
+
additional_vcpus: int,
|
|
111
|
+
) -> bool:
|
|
112
|
+
"""True when launching additional_vcpus would exceed standard quota with headroom pad."""
|
|
113
|
+
if quota_headroom_missing(state) or additional_vcpus <= 0:
|
|
114
|
+
return False
|
|
115
|
+
record = _find_standard_quota(state, region)
|
|
116
|
+
if record is None:
|
|
117
|
+
return False
|
|
118
|
+
limit = float(record.get("value") or 0)
|
|
119
|
+
usage = float(record.get("usage") or 0)
|
|
120
|
+
if limit <= 0:
|
|
121
|
+
return False
|
|
122
|
+
headroom_units = limit * (headroom_pct / 100.0)
|
|
123
|
+
return usage + additional_vcpus + headroom_units > limit
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def quota_blocked_instance_types(
|
|
127
|
+
state: QuotaState | None,
|
|
128
|
+
*,
|
|
129
|
+
region: str,
|
|
130
|
+
headroom_pct: int,
|
|
131
|
+
offered_specs: dict[str, Any],
|
|
132
|
+
) -> set[str] | None:
|
|
133
|
+
"""Instance types that would exceed standard running-instances vCPU headroom."""
|
|
134
|
+
if state is None or quota_headroom_missing(state):
|
|
135
|
+
return None
|
|
136
|
+
blocked: set[str] = set()
|
|
137
|
+
for instance_type, spec in offered_specs.items():
|
|
138
|
+
vcpus = int(getattr(spec, "vcpus", 0) or 0)
|
|
139
|
+
if candidate_exceeds_standard_quota_headroom(
|
|
140
|
+
state,
|
|
141
|
+
region=region,
|
|
142
|
+
headroom_pct=headroom_pct,
|
|
143
|
+
additional_vcpus=vcpus,
|
|
144
|
+
):
|
|
145
|
+
blocked.add(instance_type)
|
|
146
|
+
return blocked
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def launchability_for_region(
|
|
150
|
+
state: QuotaState,
|
|
151
|
+
*,
|
|
152
|
+
region: str,
|
|
153
|
+
headroom_pct: int,
|
|
154
|
+
) -> Launchability:
|
|
155
|
+
if quota_headroom_missing(state):
|
|
156
|
+
return "unknown"
|
|
157
|
+
record = _find_standard_quota(state, region)
|
|
158
|
+
if record is None:
|
|
159
|
+
return "unknown"
|
|
160
|
+
limit = float(record.get("value") or 0)
|
|
161
|
+
usage = float(record.get("usage") or 0)
|
|
162
|
+
if limit <= 0:
|
|
163
|
+
return "unknown"
|
|
164
|
+
headroom_units = limit * (headroom_pct / 100.0)
|
|
165
|
+
if usage + headroom_units < limit:
|
|
166
|
+
return "sufficient"
|
|
167
|
+
if usage >= limit:
|
|
168
|
+
return "blocked"
|
|
169
|
+
return "sufficient"
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def quotas_tty_segment(state: QuotaState) -> str:
|
|
173
|
+
if not state.exists or state.parse_error:
|
|
174
|
+
return "quotas: not loaded"
|
|
175
|
+
as_of = as_of_date_label(state.loaded_as_of)
|
|
176
|
+
if state.is_stale:
|
|
177
|
+
return f"quotas: loaded (stale) (as of {as_of})"
|
|
178
|
+
if state.record_count == 0:
|
|
179
|
+
return f"quotas: none in snapshot (checked {as_of})"
|
|
180
|
+
return f"quotas: loaded (as of {as_of})"
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def stale_quota_warning(state: QuotaState) -> str | None:
|
|
184
|
+
if not state.exists or not state.is_stale or not state.loaded_as_of:
|
|
185
|
+
return None
|
|
186
|
+
as_of = as_of_date_label(state.loaded_as_of)
|
|
187
|
+
return (
|
|
188
|
+
f"Quota snapshot is stale (loaded {as_of}; reuse limit "
|
|
189
|
+
f"{state.cache_max_age_hours} hours). Re-run 'maproom inventory get'."
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def doctor_quotas_message(state: QuotaState) -> str:
|
|
194
|
+
path = str(state.snapshot_path)
|
|
195
|
+
if state.parse_error:
|
|
196
|
+
return f"{path}; could not read snapshot: {state.parse_error}"
|
|
197
|
+
if not state.exists:
|
|
198
|
+
return f"No quota snapshot file yet. Path: {path}"
|
|
199
|
+
parts = [path, f"loaded_as_of={state.loaded_as_of}"]
|
|
200
|
+
launch_count = count_launch_relevant_records(state.records)
|
|
201
|
+
if launch_count:
|
|
202
|
+
parts.append(f"launch_relevant_records={launch_count}")
|
|
203
|
+
warning = stale_quota_warning(state)
|
|
204
|
+
if warning:
|
|
205
|
+
parts.append(warning)
|
|
206
|
+
return "; ".join(parts)
|
maproom/quotas/store.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Atomic quota snapshot persistence."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from maproom.inventory.accounts import (
|
|
12
|
+
CloudAccount,
|
|
13
|
+
drop_replaced_legacy_snapshot,
|
|
14
|
+
primary_snapshot_path,
|
|
15
|
+
retire_other_account_folders,
|
|
16
|
+
snapshot_files,
|
|
17
|
+
)
|
|
18
|
+
from maproom.paths import data_subdir, prepare_data_write, readable_data_file
|
|
19
|
+
from maproom.quotas.model import QuotaError
|
|
20
|
+
from maproom.redaction import redact_tree
|
|
21
|
+
|
|
22
|
+
_FILENAME = "snapshot.json"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def snapshot_root() -> Path:
|
|
26
|
+
return data_subdir("quotas")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def snapshot_path() -> Path:
|
|
30
|
+
"""Legacy path, or the only account snapshot when that is the file on disk."""
|
|
31
|
+
return primary_snapshot_path(snapshot_root(), _FILENAME)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def status_path() -> Path:
|
|
35
|
+
"""File when one snapshot exists, otherwise the quotas directory."""
|
|
36
|
+
files = snapshot_files(snapshot_root(), _FILENAME)
|
|
37
|
+
if len(files) == 1:
|
|
38
|
+
return files[0]
|
|
39
|
+
if len(files) > 1:
|
|
40
|
+
return snapshot_root()
|
|
41
|
+
return snapshot_root() / _FILENAME
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def account_snapshot_path(account: CloudAccount) -> Path:
|
|
45
|
+
return snapshot_root() / account.folder_name() / _FILENAME
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def has_snapshot() -> bool:
|
|
49
|
+
root = snapshot_root()
|
|
50
|
+
if snapshot_files(root, _FILENAME):
|
|
51
|
+
return True
|
|
52
|
+
legacy = readable_data_file("quotas", _FILENAME)
|
|
53
|
+
return legacy.is_file()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _atomic_write_json(path: Path, payload: dict[str, Any]) -> QuotaError | None:
|
|
57
|
+
try:
|
|
58
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
59
|
+
fd, tmp_name = tempfile.mkstemp(
|
|
60
|
+
dir=path.parent,
|
|
61
|
+
prefix=f".{path.stem}-",
|
|
62
|
+
suffix=".tmp",
|
|
63
|
+
)
|
|
64
|
+
tmp_path = Path(tmp_name)
|
|
65
|
+
try:
|
|
66
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
67
|
+
json.dump(redact_tree(payload), handle, indent=2)
|
|
68
|
+
handle.write("\n")
|
|
69
|
+
os.replace(tmp_path, path)
|
|
70
|
+
except OSError:
|
|
71
|
+
tmp_path.unlink(missing_ok=True)
|
|
72
|
+
raise
|
|
73
|
+
except OSError as exc:
|
|
74
|
+
return QuotaError(f"could not write quota snapshot at {path}: {exc}")
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def write_snapshot(payload: dict[str, Any]) -> QuotaError | None:
|
|
79
|
+
prepare_data_write()
|
|
80
|
+
return _atomic_write_json(snapshot_root() / _FILENAME, payload)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def write_account_snapshot(payload: dict[str, Any], account: CloudAccount) -> QuotaError | None:
|
|
84
|
+
"""Save this account's snapshot and remove a previous folder name for the same account."""
|
|
85
|
+
prepare_data_write()
|
|
86
|
+
path = account_snapshot_path(account)
|
|
87
|
+
err = _atomic_write_json(path, payload)
|
|
88
|
+
if err is not None:
|
|
89
|
+
return err
|
|
90
|
+
retire_other_account_folders(snapshot_root(), account, keep=path.parent.name)
|
|
91
|
+
drop_replaced_legacy_snapshot(
|
|
92
|
+
snapshot_root(),
|
|
93
|
+
_FILENAME,
|
|
94
|
+
clouds={account.cloud},
|
|
95
|
+
sources={"cloud_get", "aws_get", "payer_file"},
|
|
96
|
+
cloud_of=_quota_cloud,
|
|
97
|
+
write_json=lambda legacy, body: _atomic_write_json(legacy, body),
|
|
98
|
+
)
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def read_snapshot() -> dict[str, Any] | None | QuotaError:
|
|
103
|
+
root = snapshot_root()
|
|
104
|
+
paths = snapshot_files(root, _FILENAME)
|
|
105
|
+
has_account_snapshots = any(path.parent != root for path in paths)
|
|
106
|
+
legacy = readable_data_file("quotas", _FILENAME)
|
|
107
|
+
if legacy.is_file() and legacy not in paths and not has_account_snapshots:
|
|
108
|
+
paths.insert(0, legacy)
|
|
109
|
+
if not paths:
|
|
110
|
+
return None
|
|
111
|
+
loaded: list[dict[str, Any]] = []
|
|
112
|
+
for path in paths:
|
|
113
|
+
data = _read_one(path)
|
|
114
|
+
if isinstance(data, QuotaError):
|
|
115
|
+
return data
|
|
116
|
+
if data is not None:
|
|
117
|
+
loaded.append(data)
|
|
118
|
+
if not loaded:
|
|
119
|
+
return None
|
|
120
|
+
if len(loaded) == 1:
|
|
121
|
+
return loaded[0]
|
|
122
|
+
return _merge(loaded)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _quota_cloud(record: dict[str, Any]) -> str:
|
|
126
|
+
if str(record.get("kind") or "") == "azure_compute_usage":
|
|
127
|
+
return "azure"
|
|
128
|
+
return "azure" if str(record.get("cloud") or "") == "azure" else "aws"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _read_one(path: Path) -> dict[str, Any] | None | QuotaError:
|
|
132
|
+
if not path.is_file():
|
|
133
|
+
return None
|
|
134
|
+
try:
|
|
135
|
+
text = path.read_text(encoding="utf-8")
|
|
136
|
+
except OSError as exc:
|
|
137
|
+
return QuotaError(f"could not read quota snapshot at {path}: {exc}")
|
|
138
|
+
try:
|
|
139
|
+
data = json.loads(text)
|
|
140
|
+
except json.JSONDecodeError as exc:
|
|
141
|
+
return QuotaError(f"corrupt quota snapshot {path}: {exc}")
|
|
142
|
+
if not isinstance(data, dict):
|
|
143
|
+
return QuotaError(f"corrupt quota snapshot {path}: expected JSON object")
|
|
144
|
+
return data
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _merge(parts: list[dict[str, Any]]) -> dict[str, Any]:
|
|
148
|
+
records: list[Any] = []
|
|
149
|
+
for part in parts:
|
|
150
|
+
rows = part.get("records")
|
|
151
|
+
if isinstance(rows, list):
|
|
152
|
+
records.extend(rows)
|
|
153
|
+
loaded = [str(part.get("loaded_as_of") or "") for part in parts if part.get("loaded_as_of")]
|
|
154
|
+
sources = {str(part.get("source") or "") for part in parts}
|
|
155
|
+
return {
|
|
156
|
+
"schema_version": parts[0].get("schema_version"),
|
|
157
|
+
"loaded_as_of": min(loaded) if loaded else "",
|
|
158
|
+
"source": sources.pop() if len(sources) == 1 else "mixed",
|
|
159
|
+
"record_count": len(records),
|
|
160
|
+
"records": records,
|
|
161
|
+
}
|