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,99 @@
|
|
|
1
|
+
"""POST account operator context to FleetFit."""
|
|
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.context_lookup import ContextBodyError, require_context_response
|
|
12
|
+
from maproom.analyze.fleetfit_endpoints import CONTEXT_PATH, analyze_url
|
|
13
|
+
from maproom.analyze.lookup_http import LookupRedirectError, post_lookup_json
|
|
14
|
+
from maproom.analyze.fleetfit_endpoints import resolve_tokens_url
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ContextLookupError(Exception):
|
|
18
|
+
"""Operator context request failed."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def context_destination(settings: dict[str, Any] | None) -> bool:
|
|
22
|
+
if os.environ.get("MAPROOM_CONTEXT_FIXTURE", "").strip():
|
|
23
|
+
return True
|
|
24
|
+
if isinstance(settings, dict):
|
|
25
|
+
service = settings.get("service")
|
|
26
|
+
if isinstance(service, dict):
|
|
27
|
+
raw = service.get("context_url")
|
|
28
|
+
if isinstance(raw, str) and raw.strip():
|
|
29
|
+
return True
|
|
30
|
+
return resolve_context_url(settings) is not None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def resolve_context_url(settings: dict[str, Any] | None) -> str | None:
|
|
34
|
+
if isinstance(settings, dict):
|
|
35
|
+
service = settings.get("service")
|
|
36
|
+
if isinstance(service, dict):
|
|
37
|
+
raw = service.get("context_url")
|
|
38
|
+
if isinstance(raw, str) and raw.strip():
|
|
39
|
+
return raw.strip()
|
|
40
|
+
return analyze_url(settings, CONTEXT_PATH)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def post_operator_context(body: dict[str, Any], settings: dict[str, Any]) -> str:
|
|
44
|
+
from maproom.analyze.context_lookup import _require_closed_context_body
|
|
45
|
+
|
|
46
|
+
_require_closed_context_body(body)
|
|
47
|
+
fixture = os.environ.get("MAPROOM_CONTEXT_FIXTURE", "").strip()
|
|
48
|
+
if fixture:
|
|
49
|
+
return _read_fixture(Path(fixture))
|
|
50
|
+
url = resolve_context_url(settings)
|
|
51
|
+
if not url:
|
|
52
|
+
raise ContextLookupError("context URL is not configured")
|
|
53
|
+
tokens_url = resolve_tokens_url(settings)
|
|
54
|
+
if not tokens_url:
|
|
55
|
+
raise ContextLookupError("authorize URL is not configured")
|
|
56
|
+
from maproom.analyze.token_client import TokenFetchError, take_token
|
|
57
|
+
from maproom.paths import prepare_settings_write
|
|
58
|
+
from maproom.service.install_id import ensure_anonymous_id
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
guid = take_token(tokens_url)
|
|
62
|
+
except TokenFetchError as exc:
|
|
63
|
+
raise ContextLookupError(str(exc)) from exc
|
|
64
|
+
install_id, write_err = ensure_anonymous_id(prepare_settings_write())
|
|
65
|
+
if write_err is not None:
|
|
66
|
+
raise ContextLookupError(write_err.message)
|
|
67
|
+
try:
|
|
68
|
+
payload = post_lookup_json(
|
|
69
|
+
url,
|
|
70
|
+
dict(body),
|
|
71
|
+
lookup_label="operator context",
|
|
72
|
+
authorization=f"Bearer {guid}",
|
|
73
|
+
settings=settings,
|
|
74
|
+
anonymous_id=install_id,
|
|
75
|
+
)
|
|
76
|
+
except LookupRedirectError as exc:
|
|
77
|
+
raise ContextLookupError(str(exc)) from exc
|
|
78
|
+
except urllib.error.HTTPError as exc:
|
|
79
|
+
raise ContextLookupError(f"operator context HTTP {exc.code}") from exc
|
|
80
|
+
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
|
81
|
+
raise ContextLookupError(str(exc)) from exc
|
|
82
|
+
try:
|
|
83
|
+
return require_context_response(payload)
|
|
84
|
+
except ContextBodyError as exc:
|
|
85
|
+
raise ContextLookupError(str(exc)) from exc
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _read_fixture(path: Path) -> str:
|
|
89
|
+
try:
|
|
90
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
91
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
92
|
+
raise ContextLookupError("context fixture could not be read") from exc
|
|
93
|
+
if not isinstance(payload, dict):
|
|
94
|
+
raise ContextLookupError("context fixture must be a JSON object")
|
|
95
|
+
try:
|
|
96
|
+
return require_context_response(payload)
|
|
97
|
+
except ContextBodyError as exc:
|
|
98
|
+
raise ContextLookupError(str(exc)) from exc
|
|
99
|
+
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Closed operator-context body for POST /v1/context."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from maproom.analyze.account_cloudtrail import (
|
|
8
|
+
LaunchAttemptCounts,
|
|
9
|
+
SpotHistoryCounts,
|
|
10
|
+
assert_no_identity_values,
|
|
11
|
+
launch_attempt_rows,
|
|
12
|
+
spot_history_rows,
|
|
13
|
+
)
|
|
14
|
+
from maproom.analyze.account_quota_requests import QuotaRequestCounts, quota_request_rows
|
|
15
|
+
from maproom.analyze.safe_moves import aws_size_flexible, normalize_platform
|
|
16
|
+
|
|
17
|
+
_IDENTITY_KEYS = frozenset(
|
|
18
|
+
{
|
|
19
|
+
"account_id",
|
|
20
|
+
"account",
|
|
21
|
+
"arn",
|
|
22
|
+
"instance_id",
|
|
23
|
+
"reservation_id",
|
|
24
|
+
"subscription_id",
|
|
25
|
+
"request_id",
|
|
26
|
+
"private_ip",
|
|
27
|
+
"public_ip",
|
|
28
|
+
"user_identity",
|
|
29
|
+
"user_name",
|
|
30
|
+
"principal_id",
|
|
31
|
+
}
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ContextBodyError(ValueError):
|
|
36
|
+
"""Operator context body broke the closed contract."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def build_reservations_section(records: tuple[dict[str, Any], ...] | list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
40
|
+
rows: list[dict[str, Any]] = []
|
|
41
|
+
for record in records:
|
|
42
|
+
if not isinstance(record, dict):
|
|
43
|
+
continue
|
|
44
|
+
region = str(record.get("region") or "").strip().lower()
|
|
45
|
+
platform = normalize_platform(str(record.get("platform") or ""))
|
|
46
|
+
if not region or not platform:
|
|
47
|
+
continue
|
|
48
|
+
flexible = aws_size_flexible(record)
|
|
49
|
+
family = str(record.get("instance_family") or "").strip()
|
|
50
|
+
exact = str(record.get("instance_type") or "").strip()
|
|
51
|
+
fraction = record.get("utilization_fraction")
|
|
52
|
+
util: float | None = None
|
|
53
|
+
if isinstance(fraction, (int, float)) and not isinstance(fraction, bool):
|
|
54
|
+
util = max(0.0, min(float(fraction), 1.0))
|
|
55
|
+
row: dict[str, Any] = {
|
|
56
|
+
"region": region,
|
|
57
|
+
"platform": platform,
|
|
58
|
+
"size_flexible": flexible,
|
|
59
|
+
}
|
|
60
|
+
if flexible and family:
|
|
61
|
+
row["family"] = family
|
|
62
|
+
elif exact:
|
|
63
|
+
row["instance_type"] = exact
|
|
64
|
+
else:
|
|
65
|
+
continue
|
|
66
|
+
if util is not None:
|
|
67
|
+
row["utilization_fraction"] = util
|
|
68
|
+
rows.append(row)
|
|
69
|
+
return sorted(rows, key=lambda item: (item["region"], item.get("instance_type") or item.get("family", "")))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def build_operator_context_body(
|
|
73
|
+
*,
|
|
74
|
+
product_version: int,
|
|
75
|
+
spot: SpotHistoryCounts | None = None,
|
|
76
|
+
launches: LaunchAttemptCounts | None = None,
|
|
77
|
+
reservation_records: tuple[dict[str, Any], ...] | list[dict[str, Any]] | None = None,
|
|
78
|
+
quota_requests: QuotaRequestCounts | None = None,
|
|
79
|
+
provider: str = "aws",
|
|
80
|
+
) -> dict[str, Any]:
|
|
81
|
+
body: dict[str, Any] = {"provider": provider.strip().lower() or "aws", "sections": {}}
|
|
82
|
+
sections: dict[str, Any] = {}
|
|
83
|
+
if product_version >= 3 and spot is not None:
|
|
84
|
+
rows = spot_history_rows(spot)
|
|
85
|
+
if rows:
|
|
86
|
+
sections["spot_history"] = rows
|
|
87
|
+
if product_version >= 4 and launches is not None:
|
|
88
|
+
rows = launch_attempt_rows(launches)
|
|
89
|
+
if rows:
|
|
90
|
+
sections["launch_attempts"] = rows
|
|
91
|
+
if product_version >= 5 and reservation_records is not None:
|
|
92
|
+
rows = build_reservations_section(reservation_records)
|
|
93
|
+
if rows:
|
|
94
|
+
sections["reservations"] = rows
|
|
95
|
+
if product_version >= 6 and quota_requests is not None:
|
|
96
|
+
rows = quota_request_rows(quota_requests)
|
|
97
|
+
if rows:
|
|
98
|
+
sections["quota_requests"] = rows
|
|
99
|
+
body["sections"] = sections
|
|
100
|
+
_require_closed_context_body(body)
|
|
101
|
+
return body
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _require_closed_context_body(body: dict[str, Any]) -> None:
|
|
105
|
+
if not isinstance(body, dict):
|
|
106
|
+
raise ContextBodyError("context body must be an object")
|
|
107
|
+
provider = body.get("provider")
|
|
108
|
+
if not isinstance(provider, str) or not provider.strip():
|
|
109
|
+
raise ContextBodyError("context body needs provider")
|
|
110
|
+
sections = body.get("sections")
|
|
111
|
+
if not isinstance(sections, dict):
|
|
112
|
+
raise ContextBodyError("context body needs sections object")
|
|
113
|
+
for key in sections:
|
|
114
|
+
lowered = str(key).lower()
|
|
115
|
+
if lowered in _IDENTITY_KEYS:
|
|
116
|
+
raise ContextBodyError(f"forbidden key in context body: {key}")
|
|
117
|
+
_walk_forbidden_keys(body)
|
|
118
|
+
try:
|
|
119
|
+
assert_no_identity_values(body)
|
|
120
|
+
except ValueError as exc:
|
|
121
|
+
raise ContextBodyError(str(exc)) from exc
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _walk_forbidden_keys(value: Any, *, path: str = "") -> None:
|
|
125
|
+
if isinstance(value, dict):
|
|
126
|
+
for key, child in value.items():
|
|
127
|
+
if str(key).lower() in _IDENTITY_KEYS:
|
|
128
|
+
raise ContextBodyError(f"forbidden key {key} at {path or 'root'}")
|
|
129
|
+
_walk_forbidden_keys(child, path=f"{path}.{key}" if path else str(key))
|
|
130
|
+
elif isinstance(value, list):
|
|
131
|
+
for index, child in enumerate(value):
|
|
132
|
+
_walk_forbidden_keys(child, path=f"{path}[{index}]")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def require_context_response(payload: dict[str, Any]) -> str:
|
|
136
|
+
context_id = payload.get("context_id")
|
|
137
|
+
if not isinstance(context_id, str) or not context_id.strip():
|
|
138
|
+
raise ContextBodyError("context response missing context_id")
|
|
139
|
+
text = context_id.strip()
|
|
140
|
+
if len(text) > 128:
|
|
141
|
+
raise ContextBodyError("context_id is too long")
|
|
142
|
+
return text
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
"""Product version 4: reservation read, cover POST, and local reorder."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from maproom.analyze.catalog import SpecRow
|
|
10
|
+
from maproom.analyze.cover_client import CoverLookupError, post_cover_lookup
|
|
11
|
+
from maproom.analyze.recommend_client import recommend_destination
|
|
12
|
+
from maproom.analyze.cover_lookup import (
|
|
13
|
+
CHECKED_NONE,
|
|
14
|
+
DECLINED_LINE,
|
|
15
|
+
CoverCandidate,
|
|
16
|
+
INCOMPLETE_LINE,
|
|
17
|
+
NOT_SENT_LINE,
|
|
18
|
+
build_cover_body,
|
|
19
|
+
choose_candidate,
|
|
20
|
+
idle_coverage_warning,
|
|
21
|
+
parse_type_parts,
|
|
22
|
+
replace_unchecked_coverage,
|
|
23
|
+
scrub_buy_recommendation,
|
|
24
|
+
)
|
|
25
|
+
from maproom.analyze.reservation_read import read_analyze_reservation_records
|
|
26
|
+
from maproom.snapshot_time import as_of_date_label
|
|
27
|
+
from maproom.analyze.workset import WorkItem
|
|
28
|
+
from maproom.redaction import redact_text
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class CoverRun:
|
|
33
|
+
upload_allowed: bool
|
|
34
|
+
destination: bool
|
|
35
|
+
settings: dict[str, Any]
|
|
36
|
+
records: tuple[dict[str, Any], ...]
|
|
37
|
+
read_ok: bool
|
|
38
|
+
loaded_as_of: str | None = None
|
|
39
|
+
inventory_stale: bool = False
|
|
40
|
+
used_snapshot: bool = False
|
|
41
|
+
inventory_refresh_failed: bool = False
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class CoverSession:
|
|
46
|
+
coverage_checked: bool = False
|
|
47
|
+
preference: dict[str, Any] | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def prepare_cover_run(
|
|
51
|
+
items: list[WorkItem],
|
|
52
|
+
args: Any,
|
|
53
|
+
*,
|
|
54
|
+
as_json: bool,
|
|
55
|
+
runner: Any,
|
|
56
|
+
enabled: bool,
|
|
57
|
+
service_run: Any,
|
|
58
|
+
) -> CoverRun | None:
|
|
59
|
+
if not enabled:
|
|
60
|
+
return None
|
|
61
|
+
aws_regions = {
|
|
62
|
+
item.region.strip()
|
|
63
|
+
for item in items
|
|
64
|
+
if item.cloud == "aws" and item.region.strip()
|
|
65
|
+
}
|
|
66
|
+
azure_regions = {
|
|
67
|
+
item.region.strip()
|
|
68
|
+
for item in items
|
|
69
|
+
if item.cloud == "azure" and item.region.strip()
|
|
70
|
+
}
|
|
71
|
+
reservation_read = read_analyze_reservation_records(
|
|
72
|
+
runner,
|
|
73
|
+
aws_regions,
|
|
74
|
+
azure_regions=azure_regions,
|
|
75
|
+
as_json=as_json,
|
|
76
|
+
)
|
|
77
|
+
return CoverRun(
|
|
78
|
+
upload_allowed=service_run.upload_allowed,
|
|
79
|
+
destination=recommend_destination(service_run.settings),
|
|
80
|
+
settings=service_run.settings,
|
|
81
|
+
records=reservation_read.records,
|
|
82
|
+
read_ok=reservation_read.read_ok,
|
|
83
|
+
loaded_as_of=reservation_read.loaded_as_of,
|
|
84
|
+
inventory_stale=reservation_read.inventory_stale,
|
|
85
|
+
used_snapshot=reservation_read.used_snapshot,
|
|
86
|
+
inventory_refresh_failed=reservation_read.inventory_refresh_failed,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def stale_inventory_notice(run: CoverRun) -> str | None:
|
|
91
|
+
if not run.inventory_stale or not run.loaded_as_of:
|
|
92
|
+
return None
|
|
93
|
+
as_of = as_of_date_label(run.loaded_as_of)
|
|
94
|
+
if run.inventory_refresh_failed:
|
|
95
|
+
if run.used_snapshot:
|
|
96
|
+
return (
|
|
97
|
+
f"Reservation inventory on disk is stale (loaded {as_of}); coverage used that "
|
|
98
|
+
"snapshot because refresh could not complete. Re-run maproom inventory get to refresh."
|
|
99
|
+
)
|
|
100
|
+
return (
|
|
101
|
+
f"Reservation inventory on disk is stale (loaded {as_of}); refresh could not complete. "
|
|
102
|
+
"Re-run maproom inventory get to refresh."
|
|
103
|
+
)
|
|
104
|
+
if run.used_snapshot:
|
|
105
|
+
return (
|
|
106
|
+
f"Reservation inventory on disk is stale (loaded {as_of}); coverage used that "
|
|
107
|
+
"snapshot. Re-run maproom inventory get to refresh."
|
|
108
|
+
)
|
|
109
|
+
return (
|
|
110
|
+
f"Reservation inventory on disk is stale (loaded {as_of}); not every account "
|
|
111
|
+
"partition is fresh. Re-run maproom inventory get to refresh."
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def mark_checked_empty_coverage(assessments: list[Any]) -> None:
|
|
116
|
+
from maproom.analyze.safe_move import UNCHECKED_COVERAGE
|
|
117
|
+
from maproom.analyze.size_lookup import text_has_same_family_size_move
|
|
118
|
+
|
|
119
|
+
for assessment in assessments:
|
|
120
|
+
if not isinstance(assessment.text, str) or UNCHECKED_COVERAGE not in assessment.text:
|
|
121
|
+
continue
|
|
122
|
+
if text_has_same_family_size_move(assessment.text):
|
|
123
|
+
assessment.text = replace_unchecked_coverage(assessment.text, "")
|
|
124
|
+
else:
|
|
125
|
+
assessment.text = replace_unchecked_coverage(assessment.text, CHECKED_NONE)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def apply_reservation_reorder(
|
|
129
|
+
item: WorkItem,
|
|
130
|
+
assessment: Any,
|
|
131
|
+
*,
|
|
132
|
+
run: CoverRun | None,
|
|
133
|
+
specs: dict[tuple[str, str], SpecRow],
|
|
134
|
+
session: CoverSession,
|
|
135
|
+
as_json: bool,
|
|
136
|
+
) -> None:
|
|
137
|
+
if run is None or item.cloud != "aws":
|
|
138
|
+
return
|
|
139
|
+
if not run.read_ok:
|
|
140
|
+
return
|
|
141
|
+
if not run.upload_allowed:
|
|
142
|
+
line = DECLINED_LINE
|
|
143
|
+
assessment.text = _append_line(assessment.text, line)
|
|
144
|
+
return
|
|
145
|
+
if not run.destination:
|
|
146
|
+
line = NOT_SENT_LINE
|
|
147
|
+
assessment.text = _append_line(assessment.text, line)
|
|
148
|
+
return
|
|
149
|
+
|
|
150
|
+
v1_type = _v1_candidate(assessment)
|
|
151
|
+
v3_type = _v3_candidate(assessment)
|
|
152
|
+
candidates_types: list[tuple[str, str]] = []
|
|
153
|
+
if v1_type:
|
|
154
|
+
candidates_types.append((v1_type, "v1"))
|
|
155
|
+
if v3_type and v3_type != v1_type:
|
|
156
|
+
candidates_types.append((v3_type, "v3"))
|
|
157
|
+
if not candidates_types:
|
|
158
|
+
return
|
|
159
|
+
|
|
160
|
+
posted: list[CoverCandidate] = []
|
|
161
|
+
for instance_type, source in candidates_types:
|
|
162
|
+
if not item.region.strip() or parse_type_parts(instance_type) is None:
|
|
163
|
+
assessment.text = _append_line(assessment.text, INCOMPLETE_LINE)
|
|
164
|
+
return
|
|
165
|
+
body = build_cover_body(
|
|
166
|
+
region=item.region.strip(),
|
|
167
|
+
instance=instance_type,
|
|
168
|
+
records=list(run.records),
|
|
169
|
+
)
|
|
170
|
+
try:
|
|
171
|
+
response = post_cover_lookup(body, _settings_for_post(run.settings))
|
|
172
|
+
except (CoverLookupError, ValueError) as exc:
|
|
173
|
+
warning = f"warning: Reservation cover lookup failed: {redact_text(str(exc))}"
|
|
174
|
+
if as_json:
|
|
175
|
+
print(warning, file=sys.stderr)
|
|
176
|
+
assessment.text = _append_line(assessment.text, warning)
|
|
177
|
+
return
|
|
178
|
+
posted.append(CoverCandidate(instance_type=instance_type, source=source, response=response))
|
|
179
|
+
|
|
180
|
+
chosen = choose_candidate(posted)
|
|
181
|
+
if chosen is None:
|
|
182
|
+
return
|
|
183
|
+
|
|
184
|
+
session.coverage_checked = True
|
|
185
|
+
v1_response = next((entry.response for entry in posted if entry.source == "v1"), None)
|
|
186
|
+
current = specs.get((item.cloud, item.instance_type))
|
|
187
|
+
current_family = current.family if current is not None else ""
|
|
188
|
+
warning = idle_coverage_warning(
|
|
189
|
+
v1_type=v1_type,
|
|
190
|
+
v1_response=v1_response,
|
|
191
|
+
chosen=chosen,
|
|
192
|
+
current_family=current_family,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
if chosen.response.get("covered_by_unused_reservation") or chosen.response.get(
|
|
196
|
+
"cheaper_on_demand_only"
|
|
197
|
+
):
|
|
198
|
+
_apply_chosen_type(assessment, chosen.instance_type, specs, item)
|
|
199
|
+
coverage_line = _coverage_line(chosen)
|
|
200
|
+
else:
|
|
201
|
+
from maproom.analyze.size_lookup import text_has_same_family_size_move
|
|
202
|
+
|
|
203
|
+
coverage_line = (
|
|
204
|
+
""
|
|
205
|
+
if text_has_same_family_size_move(str(assessment.text or ""))
|
|
206
|
+
else CHECKED_NONE
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
assessment.text = replace_unchecked_coverage(assessment.text, coverage_line)
|
|
210
|
+
if warning:
|
|
211
|
+
assessment.text = _append_line(assessment.text, warning)
|
|
212
|
+
scrub_buy_recommendation(assessment.text)
|
|
213
|
+
|
|
214
|
+
session.preference = {
|
|
215
|
+
"status": "returned",
|
|
216
|
+
"chosen_instance_type": chosen.instance_type,
|
|
217
|
+
"candidates": [
|
|
218
|
+
{
|
|
219
|
+
"instance_type": entry.instance_type,
|
|
220
|
+
"source": entry.source,
|
|
221
|
+
"covered_by_unused_reservation": bool(
|
|
222
|
+
entry.response.get("covered_by_unused_reservation")
|
|
223
|
+
),
|
|
224
|
+
"size_flexibility_covers": bool(entry.response.get("size_flexibility_covers")),
|
|
225
|
+
"cheaper_on_demand_only": bool(entry.response.get("cheaper_on_demand_only")),
|
|
226
|
+
}
|
|
227
|
+
for entry in posted
|
|
228
|
+
],
|
|
229
|
+
"idle_warning": warning is not None,
|
|
230
|
+
}
|
|
231
|
+
if assessment.recommendation is not None:
|
|
232
|
+
assessment.recommendation["reservation_cover"] = {
|
|
233
|
+
"status": "returned",
|
|
234
|
+
"chosen_instance_type": chosen.instance_type,
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _coverage_line(chosen: CoverCandidate) -> str:
|
|
239
|
+
if chosen.response.get("covered_by_unused_reservation"):
|
|
240
|
+
return "Reservation coverage was checked; an unused reservation covers the chosen type."
|
|
241
|
+
if chosen.response.get("cheaper_on_demand_only"):
|
|
242
|
+
return "Reservation coverage was checked; the chosen type is only cheaper on demand."
|
|
243
|
+
return CHECKED_NONE
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _apply_chosen_type(
|
|
247
|
+
assessment: Any,
|
|
248
|
+
instance_type: str,
|
|
249
|
+
specs: dict[tuple[str, str], SpecRow],
|
|
250
|
+
item: WorkItem,
|
|
251
|
+
) -> None:
|
|
252
|
+
recommendation = assessment.recommendation
|
|
253
|
+
if recommendation is None:
|
|
254
|
+
return
|
|
255
|
+
alternatives = recommendation.get("recommended_alternatives")
|
|
256
|
+
if not isinstance(alternatives, list) or not alternatives:
|
|
257
|
+
return
|
|
258
|
+
alternative = alternatives[0]
|
|
259
|
+
if not isinstance(alternative, dict):
|
|
260
|
+
return
|
|
261
|
+
alternative["instance_type"] = instance_type
|
|
262
|
+
target = specs.get((item.cloud, instance_type))
|
|
263
|
+
current = specs.get((item.cloud, item.instance_type))
|
|
264
|
+
if target is None or current is None:
|
|
265
|
+
return
|
|
266
|
+
justification = alternative.get("justification")
|
|
267
|
+
if isinstance(justification, dict):
|
|
268
|
+
block = justification.get("fleetfit_recommended_safe_move")
|
|
269
|
+
if isinstance(block, dict):
|
|
270
|
+
cpu = block.get("cpu_performance_rank")
|
|
271
|
+
if isinstance(cpu, dict):
|
|
272
|
+
cpu["targeted"] = _decimal_str(target.cpu_performance_rank)
|
|
273
|
+
price = block.get("effective_price")
|
|
274
|
+
if isinstance(price, dict):
|
|
275
|
+
from maproom.analyze.catalog import load_us_east_1_hourly
|
|
276
|
+
|
|
277
|
+
prices = load_us_east_1_hourly()
|
|
278
|
+
targeted = prices.get(instance_type)
|
|
279
|
+
if targeted is not None:
|
|
280
|
+
price["targeted"] = _decimal_str(targeted)
|
|
281
|
+
lines = assessment.text.splitlines()
|
|
282
|
+
if lines:
|
|
283
|
+
label_prefix = lines[0].split("->", 1)[0].strip()
|
|
284
|
+
lines[0] = f"{label_prefix} -> {instance_type}"
|
|
285
|
+
assessment.text = "\n".join(lines)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _decimal_str(value: object) -> str | None:
|
|
289
|
+
from decimal import Decimal
|
|
290
|
+
|
|
291
|
+
if value is None:
|
|
292
|
+
return None
|
|
293
|
+
if isinstance(value, Decimal):
|
|
294
|
+
return format(value, "f")
|
|
295
|
+
return str(value)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _v1_candidate(assessment: Any) -> str | None:
|
|
299
|
+
recommendation = assessment.recommendation
|
|
300
|
+
if not isinstance(recommendation, dict):
|
|
301
|
+
return None
|
|
302
|
+
alternatives = recommendation.get("recommended_alternatives")
|
|
303
|
+
if not isinstance(alternatives, list) or not alternatives:
|
|
304
|
+
return None
|
|
305
|
+
first = alternatives[0]
|
|
306
|
+
if not isinstance(first, dict):
|
|
307
|
+
return None
|
|
308
|
+
instance_type = first.get("instance_type")
|
|
309
|
+
return instance_type.strip() if isinstance(instance_type, str) and instance_type.strip() else None
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _v3_candidate(assessment: Any) -> str | None:
|
|
313
|
+
for holder in (assessment.recommendation, assessment.examined):
|
|
314
|
+
if not isinstance(holder, dict):
|
|
315
|
+
continue
|
|
316
|
+
size_lookup = holder.get("size_lookup")
|
|
317
|
+
if not isinstance(size_lookup, dict):
|
|
318
|
+
continue
|
|
319
|
+
if size_lookup.get("status") != "returned":
|
|
320
|
+
continue
|
|
321
|
+
instance_type = size_lookup.get("instance_type")
|
|
322
|
+
if isinstance(instance_type, str) and instance_type.strip():
|
|
323
|
+
return instance_type.strip()
|
|
324
|
+
return None
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _append_line(text: str, line: str) -> str:
|
|
328
|
+
if not line:
|
|
329
|
+
return text
|
|
330
|
+
if not text:
|
|
331
|
+
return line
|
|
332
|
+
return f"{text}\n{line}"
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _settings_for_post(settings: dict[str, Any]) -> dict[str, Any]:
|
|
336
|
+
from maproom.analyze.cover_client import resolve_cover_lookup_url
|
|
337
|
+
|
|
338
|
+
merged = dict(settings)
|
|
339
|
+
service = dict(merged.get("service") or {})
|
|
340
|
+
url = resolve_cover_lookup_url(settings)
|
|
341
|
+
if url and not str(service.get("reservation_cover_url") or "").strip():
|
|
342
|
+
service["reservation_cover_url"] = url
|
|
343
|
+
merged["service"] = service
|
|
344
|
+
return merged
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""POST cover 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.cover_lookup import _require_closed_cover_body, require_cover_response
|
|
12
|
+
from maproom.analyze.recommend_client import (
|
|
13
|
+
KIND_COVER,
|
|
14
|
+
RecommendError,
|
|
15
|
+
post_recommend_kind,
|
|
16
|
+
resolve_recommend_url,
|
|
17
|
+
unwrap_kind_section,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CoverLookupError(Exception):
|
|
22
|
+
"""Cover lookup request failed."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def post_cover_lookup(body: dict, settings: dict) -> dict:
|
|
26
|
+
_require_closed_cover_body(body)
|
|
27
|
+
fixture = os.environ.get("MAPROOM_COVER_FIXTURE", "").strip()
|
|
28
|
+
if fixture:
|
|
29
|
+
return _read_fixture(Path(fixture))
|
|
30
|
+
try:
|
|
31
|
+
section = post_recommend_kind(
|
|
32
|
+
body, settings, kind=KIND_COVER, lookup_label="reservation cover lookup"
|
|
33
|
+
)
|
|
34
|
+
except RecommendError as exc:
|
|
35
|
+
raise CoverLookupError(str(exc)) from exc
|
|
36
|
+
except urllib.error.HTTPError as exc:
|
|
37
|
+
raise CoverLookupError(f"cover lookup HTTP {exc.code}") from exc
|
|
38
|
+
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
|
39
|
+
raise CoverLookupError(str(exc)) from exc
|
|
40
|
+
try:
|
|
41
|
+
return require_cover_response(section)
|
|
42
|
+
except ValueError as exc:
|
|
43
|
+
raise CoverLookupError(str(exc)) from exc
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def resolve_cover_lookup_url(settings: dict | None) -> str | None:
|
|
47
|
+
return resolve_recommend_url(settings)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _read_fixture(path: Path) -> dict[str, Any]:
|
|
51
|
+
try:
|
|
52
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
53
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
54
|
+
raise CoverLookupError("cover lookup fixture could not be read") from exc
|
|
55
|
+
try:
|
|
56
|
+
section = unwrap_kind_section(payload, kind=KIND_COVER)
|
|
57
|
+
except RecommendError as exc:
|
|
58
|
+
raise CoverLookupError(str(exc)) from exc
|
|
59
|
+
return require_cover_response(section)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def cover_destination(settings: dict[str, Any] | None) -> bool:
|
|
63
|
+
if os.environ.get("MAPROOM_COVER_FIXTURE", "").strip():
|
|
64
|
+
return True
|
|
65
|
+
return resolve_cover_lookup_url(settings) is not None
|