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,217 @@
|
|
|
1
|
+
"""Resolved FleetFit URLs: the two protocol-hostname-port settings, their paths, and reporting."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from typing import Any
|
|
7
|
+
from urllib.parse import urlsplit, urlparse
|
|
8
|
+
|
|
9
|
+
AUTHORIZE_SETTING = "cloud_authorize_protocol_hostname_port"
|
|
10
|
+
ANALYZE_SETTING = "cloud_analyze_protocol_hostname_port"
|
|
11
|
+
PROTOCOL_HOSTNAME_PORT_SETTINGS: tuple[str, ...] = (AUTHORIZE_SETTING, ANALYZE_SETTING)
|
|
12
|
+
|
|
13
|
+
AUTHORIZE_ENV = "MAPROOM_CLOUD_AUTHORIZE_PROTOCOL_HOSTNAME_PORT"
|
|
14
|
+
ANALYZE_ENV = "MAPROOM_CLOUD_ANALYZE_PROTOCOL_HOSTNAME_PORT"
|
|
15
|
+
_SETTING_ENV: dict[str, str] = {
|
|
16
|
+
AUTHORIZE_SETTING: AUTHORIZE_ENV,
|
|
17
|
+
ANALYZE_SETTING: ANALYZE_ENV,
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
TOKENS_PATH = "/v1/tokens"
|
|
21
|
+
RECOMMEND_PATH = "/v1/recommend"
|
|
22
|
+
CONTEXT_PATH = "/v1/context"
|
|
23
|
+
|
|
24
|
+
_FIXTURE_ENV: dict[str, str] = {
|
|
25
|
+
"recommend": "MAPROOM_RECOMMEND_FIXTURE",
|
|
26
|
+
"spot_lookup": "MAPROOM_SPOT_FIXTURE",
|
|
27
|
+
"size_lookup": "MAPROOM_SIZE_FIXTURE",
|
|
28
|
+
"reservation_cover": "MAPROOM_COVER_FIXTURE",
|
|
29
|
+
"safe_moves": "MAPROOM_SAFE_MOVES_FIXTURE",
|
|
30
|
+
"series_lookup": "MAPROOM_SERIES_FIXTURE",
|
|
31
|
+
"quota_lookup": "MAPROOM_QUOTA_LOOKUP_FIXTURE",
|
|
32
|
+
"instance_price": "MAPROOM_INSTANCE_PRICE_FIXTURE",
|
|
33
|
+
"operator_context": "MAPROOM_CONTEXT_FIXTURE",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ProtocolHostnamePortError(ValueError):
|
|
38
|
+
"""The value is not scheme://host[:port] with nothing after it."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def normalize_protocol_hostname_port(value: str) -> str:
|
|
42
|
+
"""Return the value when it is empty or http(s)://host[:port]. Raise otherwise.
|
|
43
|
+
|
|
44
|
+
A slash after the host:port, a path, a query, a fragment, or a user name is
|
|
45
|
+
refused. The paths are fixed in this module and are never part of the setting.
|
|
46
|
+
"""
|
|
47
|
+
text = value.strip()
|
|
48
|
+
if not text:
|
|
49
|
+
return ""
|
|
50
|
+
if any(ch.isspace() for ch in text) or "\\" in text:
|
|
51
|
+
raise ProtocolHostnamePortError("must not contain spaces or backslashes")
|
|
52
|
+
scheme, separator, rest = text.partition("://")
|
|
53
|
+
if not separator or scheme.lower() not in ("http", "https"):
|
|
54
|
+
raise ProtocolHostnamePortError("must start with http:// or https://")
|
|
55
|
+
if "/" in rest:
|
|
56
|
+
raise ProtocolHostnamePortError(
|
|
57
|
+
"must not contain a path; give protocol, hostname, and port only"
|
|
58
|
+
)
|
|
59
|
+
if "?" in rest or "#" in rest:
|
|
60
|
+
raise ProtocolHostnamePortError("must not contain a query or fragment")
|
|
61
|
+
if "@" in rest:
|
|
62
|
+
raise ProtocolHostnamePortError("must not contain a user name or password")
|
|
63
|
+
try:
|
|
64
|
+
parts = urlsplit(text)
|
|
65
|
+
port = parts.port
|
|
66
|
+
except ValueError as exc:
|
|
67
|
+
raise ProtocolHostnamePortError("has an invalid host or port") from exc
|
|
68
|
+
if not parts.hostname:
|
|
69
|
+
raise ProtocolHostnamePortError("must name a host")
|
|
70
|
+
if rest.endswith(":") or port == 0:
|
|
71
|
+
raise ProtocolHostnamePortError("has an invalid port")
|
|
72
|
+
return f"{scheme.lower()}://{rest}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _protocol_hostname_port(settings: dict[str, Any] | None, key: str) -> str | None:
|
|
76
|
+
"""Env, then the settings key. A value with a path is treated as unset."""
|
|
77
|
+
candidates: list[object] = [os.environ.get(_SETTING_ENV[key], "")]
|
|
78
|
+
if isinstance(settings, dict):
|
|
79
|
+
candidates.append(settings.get(key))
|
|
80
|
+
for raw in candidates:
|
|
81
|
+
if not isinstance(raw, str) or not raw.strip():
|
|
82
|
+
continue
|
|
83
|
+
try:
|
|
84
|
+
return normalize_protocol_hostname_port(raw) or None
|
|
85
|
+
except ProtocolHostnamePortError:
|
|
86
|
+
return None
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def authorize_protocol_hostname_port(settings: dict[str, Any] | None) -> str | None:
|
|
91
|
+
return _protocol_hostname_port(settings, AUTHORIZE_SETTING)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def analyze_protocol_hostname_port(settings: dict[str, Any] | None) -> str | None:
|
|
95
|
+
return _protocol_hostname_port(settings, ANALYZE_SETTING)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
_EXPLICIT_LOOKUP_ENV_VARS: tuple[str, ...] = ("MAPROOM_RECOMMEND_URL",)
|
|
99
|
+
|
|
100
|
+
_EXPLICIT_LOOKUP_SERVICE_KEYS: tuple[str, ...] = (
|
|
101
|
+
"recommend_url",
|
|
102
|
+
"recommendation_url",
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _hostname_from_url(url: str) -> str | None:
|
|
107
|
+
host = urlparse(url.strip()).hostname
|
|
108
|
+
return host.lower() if host else None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def is_fleetfit_ai_default_host(hostname: str) -> bool:
|
|
112
|
+
"""True for hosts on the published fleetfit.ai fleet."""
|
|
113
|
+
host = hostname.lower().rstrip(".")
|
|
114
|
+
return host == "fleetfit.ai" or host.endswith(".fleetfit.ai")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def operator_override_hostnames(settings: dict[str, Any] | None) -> frozenset[str]:
|
|
118
|
+
"""Hosts the operator chose through env, settings, or per-lookup URL overrides."""
|
|
119
|
+
hosts: set[str] = set()
|
|
120
|
+
for base in (
|
|
121
|
+
authorize_protocol_hostname_port(settings),
|
|
122
|
+
analyze_protocol_hostname_port(settings),
|
|
123
|
+
):
|
|
124
|
+
if base:
|
|
125
|
+
name = _hostname_from_url(base)
|
|
126
|
+
if name:
|
|
127
|
+
hosts.add(name)
|
|
128
|
+
for env_name in _EXPLICIT_LOOKUP_ENV_VARS:
|
|
129
|
+
raw = os.environ.get(env_name, "").strip()
|
|
130
|
+
if raw:
|
|
131
|
+
name = _hostname_from_url(raw)
|
|
132
|
+
if name:
|
|
133
|
+
hosts.add(name)
|
|
134
|
+
if isinstance(settings, dict):
|
|
135
|
+
service = settings.get("service")
|
|
136
|
+
if isinstance(service, dict):
|
|
137
|
+
for key in _EXPLICIT_LOOKUP_SERVICE_KEYS:
|
|
138
|
+
raw = service.get(key)
|
|
139
|
+
if isinstance(raw, str) and raw.strip():
|
|
140
|
+
name = _hostname_from_url(raw)
|
|
141
|
+
if name:
|
|
142
|
+
hosts.add(name)
|
|
143
|
+
return frozenset(hosts)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def fleetfit_request_uses_operator_override(
|
|
147
|
+
url: str,
|
|
148
|
+
settings: dict[str, Any] | None = None,
|
|
149
|
+
) -> bool:
|
|
150
|
+
"""Override mode for operator-configured hosts; default mode for fleetfit.ai."""
|
|
151
|
+
host = _hostname_from_url(url)
|
|
152
|
+
if not host:
|
|
153
|
+
return False
|
|
154
|
+
if is_fleetfit_ai_default_host(host):
|
|
155
|
+
return False
|
|
156
|
+
return host in operator_override_hostnames(settings)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def authorize_url(settings: dict[str, Any] | None, path: str) -> str | None:
|
|
160
|
+
base = authorize_protocol_hostname_port(settings)
|
|
161
|
+
return f"{base}{path}" if base else None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def analyze_url(settings: dict[str, Any] | None, path: str) -> str | None:
|
|
165
|
+
base = analyze_protocol_hostname_port(settings)
|
|
166
|
+
return f"{base}{path}" if base else None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def resolve_tokens_url(settings: dict[str, Any] | None) -> str | None:
|
|
170
|
+
"""{authorize}/v1/tokens, or None when the authorize side is not configured."""
|
|
171
|
+
return authorize_url(settings, TOKENS_PATH)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _fixture_active(name: str) -> bool:
|
|
175
|
+
env_name = _FIXTURE_ENV.get(name)
|
|
176
|
+
return bool(env_name and os.environ.get(env_name, "").strip())
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def configured_fleetfit_endpoints(
|
|
180
|
+
settings: dict[str, Any] | None,
|
|
181
|
+
*,
|
|
182
|
+
product_version: int,
|
|
183
|
+
) -> dict[str, str]:
|
|
184
|
+
"""POST recommend URL for product versions 1 through 6.
|
|
185
|
+
|
|
186
|
+
Product versions 1 through 6 do not POST a workload summary; the
|
|
187
|
+
analyses recommendation URL is omitted from identity and settings reporting.
|
|
188
|
+
Field groups shared on the recommend body are selected by product_version
|
|
189
|
+
and CLI flags, not by distinct POST paths.
|
|
190
|
+
"""
|
|
191
|
+
from maproom.analyze.context_client import resolve_context_url
|
|
192
|
+
from maproom.analyze.recommend_client import resolve_recommend_url
|
|
193
|
+
|
|
194
|
+
del product_version # kinds/fields vary; the URL does not
|
|
195
|
+
found: dict[str, str] = {}
|
|
196
|
+
url = resolve_recommend_url(settings)
|
|
197
|
+
if url:
|
|
198
|
+
found["recommend"] = url
|
|
199
|
+
elif _fixture_active("recommend") or any(
|
|
200
|
+
_fixture_active(name)
|
|
201
|
+
for name in (
|
|
202
|
+
"spot_lookup",
|
|
203
|
+
"size_lookup",
|
|
204
|
+
"reservation_cover",
|
|
205
|
+
"safe_moves",
|
|
206
|
+
"series_lookup",
|
|
207
|
+
"quota_lookup",
|
|
208
|
+
"instance_price",
|
|
209
|
+
)
|
|
210
|
+
):
|
|
211
|
+
found["recommend"] = "fixture:recommend"
|
|
212
|
+
context_url = resolve_context_url(settings)
|
|
213
|
+
if context_url:
|
|
214
|
+
found["context"] = context_url
|
|
215
|
+
elif _fixture_active("operator_context"):
|
|
216
|
+
found["context"] = "fixture:operator_context"
|
|
217
|
+
return found
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Stored FleetFit handling policy id and POST body attachment."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from maproom.settings.defaults import FLEETFIT_POLICY_OVERLAY_KEYS
|
|
10
|
+
from maproom.settings.model import load_effective_settings
|
|
11
|
+
from maproom.settings.write import SettingsWriteError, persist_settings
|
|
12
|
+
|
|
13
|
+
FLEETFIT_POLICY_ID_KEY = "fleetfit_policy_id"
|
|
14
|
+
FLEETFIT_POLICY_ACCEPT_CMD = "maproom privacy fleetfit --accept"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def fleetfit_policy_accept_hint() -> str:
|
|
18
|
+
return f"Run {FLEETFIT_POLICY_ACCEPT_CMD} to record acceptance."
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class FleetFitPolicyRequiredError(Exception):
|
|
22
|
+
"""A FleetFit POST needs a stored handling policy id."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def stored_fleetfit_policy_id(settings: dict[str, Any]) -> str | None:
|
|
26
|
+
raw = settings.get(FLEETFIT_POLICY_ID_KEY)
|
|
27
|
+
if isinstance(raw, str) and raw.strip():
|
|
28
|
+
return raw.strip()
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def load_stored_fleetfit_policy(path: Path) -> str | None:
|
|
33
|
+
settings, _ = load_effective_settings(path)
|
|
34
|
+
return stored_fleetfit_policy_id(settings)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def with_fleetfit_policy_id(body: dict[str, Any], settings: dict[str, Any]) -> dict[str, Any]:
|
|
38
|
+
policy_id = stored_fleetfit_policy_id(settings)
|
|
39
|
+
if not policy_id:
|
|
40
|
+
raise FleetFitPolicyRequiredError(
|
|
41
|
+
"FleetFit handling policy is not accepted; "
|
|
42
|
+
f"run {FLEETFIT_POLICY_ACCEPT_CMD}"
|
|
43
|
+
)
|
|
44
|
+
merged = dict(body)
|
|
45
|
+
merged[FLEETFIT_POLICY_ID_KEY] = policy_id
|
|
46
|
+
return merged
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def persist_fleetfit_policy_grant(
|
|
50
|
+
path: Path,
|
|
51
|
+
*,
|
|
52
|
+
policy_id: str,
|
|
53
|
+
policy_url: str,
|
|
54
|
+
granted_at: str | None = None,
|
|
55
|
+
) -> SettingsWriteError | None:
|
|
56
|
+
moment = granted_at or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
57
|
+
updates: dict[str, Any] = {
|
|
58
|
+
"fleetfit_policy_id": policy_id,
|
|
59
|
+
"fleetfit_policy_url": policy_url,
|
|
60
|
+
"fleetfit_policy_granted_at": moment,
|
|
61
|
+
}
|
|
62
|
+
return persist_settings(path, updates)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def fleetfit_policy_overlay_in_settings(settings: dict[str, Any]) -> bool:
|
|
66
|
+
return any(key in settings and settings[key] for key in FLEETFIT_POLICY_OVERLAY_KEYS)
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Product version 1: consented instance price lookup for safe-move pricing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from decimal import Decimal, InvalidOperation
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from maproom.analyze.instance_price_client import (
|
|
10
|
+
InstancePriceError,
|
|
11
|
+
instance_price_destination,
|
|
12
|
+
post_instance_price,
|
|
13
|
+
)
|
|
14
|
+
from maproom.analyze.instance_price_lookup import build_instance_price_body
|
|
15
|
+
from maproom.analyze.safe_move import PRICE_ASSUMPTION, UNCHECKED_COVERAGE, passes_price_bar
|
|
16
|
+
from maproom.analyze.workset import WorkItem
|
|
17
|
+
from maproom.consent import require_service_upload_consent
|
|
18
|
+
from maproom.paths import settings_read_file
|
|
19
|
+
from maproom.settings.model import load_effective_settings
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class InstancePriceRun:
|
|
24
|
+
upload_allowed: bool
|
|
25
|
+
destination: bool
|
|
26
|
+
settings: dict[str, Any]
|
|
27
|
+
upload_reason: str | None = None
|
|
28
|
+
consent_fleetfit: bool = False
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _platform_for_item(item: WorkItem) -> str:
|
|
32
|
+
if item.platform.strip():
|
|
33
|
+
return item.platform.strip()
|
|
34
|
+
return "Linux/UNIX" if item.cloud == "aws" else "Linux"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def prepare_instance_price_run(
|
|
38
|
+
items: list[WorkItem],
|
|
39
|
+
args: Any,
|
|
40
|
+
*,
|
|
41
|
+
as_json: bool,
|
|
42
|
+
) -> InstancePriceRun:
|
|
43
|
+
settings, _ = load_effective_settings(settings_read_file())
|
|
44
|
+
destination = instance_price_destination(settings)
|
|
45
|
+
consent_fleetfit = bool(
|
|
46
|
+
getattr(args, "consent_fleetfit_recommendations", False)
|
|
47
|
+
)
|
|
48
|
+
if not destination:
|
|
49
|
+
return InstancePriceRun(False, False, settings, consent_fleetfit=consent_fleetfit)
|
|
50
|
+
ready = any(item.instance_type.strip() and item.region.strip() for item in items)
|
|
51
|
+
if not ready:
|
|
52
|
+
return InstancePriceRun(False, destination, settings, consent_fleetfit=consent_fleetfit)
|
|
53
|
+
return InstancePriceRun(False, destination, settings, consent_fleetfit=consent_fleetfit)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _fetch_price(item: WorkItem, instance_type: str, settings: dict[str, Any]) -> Decimal | None:
|
|
57
|
+
from maproom.settings.model import product_version
|
|
58
|
+
|
|
59
|
+
if product_version() < 2:
|
|
60
|
+
return None
|
|
61
|
+
body = build_instance_price_body(
|
|
62
|
+
instance_type=instance_type,
|
|
63
|
+
region=item.region,
|
|
64
|
+
platform=_platform_for_item(item),
|
|
65
|
+
)
|
|
66
|
+
try:
|
|
67
|
+
return post_instance_price(body, settings)
|
|
68
|
+
except InstancePriceError:
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def apply_instance_price_lookup(
|
|
73
|
+
item: WorkItem,
|
|
74
|
+
assessment: Any,
|
|
75
|
+
*,
|
|
76
|
+
run: InstancePriceRun,
|
|
77
|
+
specs: dict[tuple[str, str], Any],
|
|
78
|
+
) -> None:
|
|
79
|
+
from maproom.analyze.safe_analyze import _identity
|
|
80
|
+
|
|
81
|
+
if assessment.recommendation is None:
|
|
82
|
+
return
|
|
83
|
+
alternatives = assessment.recommendation.get("recommended_alternatives")
|
|
84
|
+
if not alternatives:
|
|
85
|
+
return
|
|
86
|
+
if not run.destination:
|
|
87
|
+
return
|
|
88
|
+
if not run.upload_allowed:
|
|
89
|
+
gate = require_service_upload_consent(
|
|
90
|
+
consent_fleetfit_recommendations=run.consent_fleetfit,
|
|
91
|
+
quiet=True,
|
|
92
|
+
)
|
|
93
|
+
if not (gate.upload_allowed and gate.exit_code == 0):
|
|
94
|
+
return
|
|
95
|
+
if _reprice_catalog_moves(item, assessment, alternatives, run):
|
|
96
|
+
return
|
|
97
|
+
alternative = alternatives[0]
|
|
98
|
+
target_type = alternative.get("instance_type")
|
|
99
|
+
current_type = item.instance_type
|
|
100
|
+
if not isinstance(target_type, str) or not target_type.strip():
|
|
101
|
+
return
|
|
102
|
+
current_row = specs.get((item.cloud, current_type))
|
|
103
|
+
target_row = specs.get((item.cloud, target_type))
|
|
104
|
+
if current_row is None or target_row is None:
|
|
105
|
+
return
|
|
106
|
+
current_price = _fetch_price(item, current_type, run.settings)
|
|
107
|
+
target_price = _fetch_price(item, target_type, run.settings)
|
|
108
|
+
if current_price is None or target_price is None:
|
|
109
|
+
return
|
|
110
|
+
if not passes_price_bar(current_row, target_row, current_price, target_price):
|
|
111
|
+
assessment.recommendation = None
|
|
112
|
+
assessment.examined = {
|
|
113
|
+
**_identity(item),
|
|
114
|
+
"outcome": "no_recommendation",
|
|
115
|
+
}
|
|
116
|
+
assessment.text = "\n".join(
|
|
117
|
+
[f"{item.label()}: no completely safe type.", UNCHECKED_COVERAGE]
|
|
118
|
+
)
|
|
119
|
+
assessment.scored = True
|
|
120
|
+
return
|
|
121
|
+
|
|
122
|
+
move = alternative.get("justification", {}).get("fleetfit_recommended_safe_move", {})
|
|
123
|
+
effective = move.get("effective_price")
|
|
124
|
+
if isinstance(effective, dict):
|
|
125
|
+
effective["current"] = format(current_price, "f")
|
|
126
|
+
effective["targeted"] = format(target_price, "f")
|
|
127
|
+
effective.pop("assumption", None)
|
|
128
|
+
column = "us-east-1 Linux" if item.cloud == "aws" else "eastus Linux"
|
|
129
|
+
lines = [line for line in assessment.text.split("\n") if PRICE_ASSUMPTION not in line]
|
|
130
|
+
for index, line in enumerate(lines):
|
|
131
|
+
if " price USD " in line and "/hour" in line:
|
|
132
|
+
lines[index] = f"{column} price USD {format(target_price, 'f')}/hour."
|
|
133
|
+
break
|
|
134
|
+
assessment.text = "\n".join(lines)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _catalog_block(alternative: dict[str, Any]) -> dict[str, Any] | None:
|
|
138
|
+
move = alternative.get("justification", {}).get("fleetfit_recommended_safe_move", {})
|
|
139
|
+
summary = move.get("source_target_summary") if isinstance(move, dict) else None
|
|
140
|
+
if isinstance(summary, dict):
|
|
141
|
+
return move
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _reprice_catalog_moves(
|
|
146
|
+
item: WorkItem,
|
|
147
|
+
assessment: Any,
|
|
148
|
+
alternatives: list[dict[str, Any]],
|
|
149
|
+
run: InstancePriceRun,
|
|
150
|
+
) -> bool:
|
|
151
|
+
"""Refresh shipped catalog prices and list the survivors by live savings.
|
|
152
|
+
|
|
153
|
+
Returns True when these alternatives came from safe-moves-v1.json.
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
from maproom.analyze.safe_analyze import _identity
|
|
157
|
+
from maproom.analyze.safe_moves_catalog import format_summary
|
|
158
|
+
|
|
159
|
+
if not any(_catalog_block(alternative) for alternative in alternatives):
|
|
160
|
+
return False
|
|
161
|
+
current_price = _fetch_price(item, item.instance_type, run.settings)
|
|
162
|
+
if current_price is None:
|
|
163
|
+
return True
|
|
164
|
+
kept: list[dict[str, Any]] = []
|
|
165
|
+
for alternative in alternatives:
|
|
166
|
+
move = _catalog_block(alternative)
|
|
167
|
+
target_type = alternative.get("instance_type")
|
|
168
|
+
if move is None or not isinstance(target_type, str):
|
|
169
|
+
continue
|
|
170
|
+
target_price = _fetch_price(item, target_type, run.settings)
|
|
171
|
+
if target_price is None:
|
|
172
|
+
kept.append(alternative)
|
|
173
|
+
continue
|
|
174
|
+
if target_price > current_price:
|
|
175
|
+
continue
|
|
176
|
+
effective = move.get("effective_price")
|
|
177
|
+
if isinstance(effective, dict):
|
|
178
|
+
effective["current"] = format(current_price, "f")
|
|
179
|
+
effective["targeted"] = format(target_price, "f")
|
|
180
|
+
effective.pop("assumption", None)
|
|
181
|
+
kept.append(alternative)
|
|
182
|
+
if not kept:
|
|
183
|
+
assessment.recommendation = None
|
|
184
|
+
assessment.examined = {**_identity(item), "outcome": "no_recommendation"}
|
|
185
|
+
assessment.text = "\n".join(
|
|
186
|
+
[f"{item.label()}: no completely safe type.", UNCHECKED_COVERAGE]
|
|
187
|
+
)
|
|
188
|
+
assessment.scored = True
|
|
189
|
+
return True
|
|
190
|
+
|
|
191
|
+
def _savings(alternative: dict[str, Any]) -> Decimal:
|
|
192
|
+
move = _catalog_block(alternative) or {}
|
|
193
|
+
effective = move.get("effective_price") or {}
|
|
194
|
+
try:
|
|
195
|
+
return Decimal(str(effective.get("current"))) - Decimal(str(effective.get("targeted")))
|
|
196
|
+
except (InvalidOperation, TypeError):
|
|
197
|
+
return Decimal(0)
|
|
198
|
+
|
|
199
|
+
kept.sort(key=lambda alternative: (-_savings(alternative), str(alternative.get("instance_type"))))
|
|
200
|
+
for rank, alternative in enumerate(kept, start=1):
|
|
201
|
+
alternative["rank"] = rank
|
|
202
|
+
assessment.recommendation["recommended_alternatives"] = kept
|
|
203
|
+
lines: list[str] = []
|
|
204
|
+
for alternative in kept:
|
|
205
|
+
move = _catalog_block(alternative) or {}
|
|
206
|
+
summary = move.get("source_target_summary") or {}
|
|
207
|
+
lines.append(
|
|
208
|
+
f"{item.label()} -> {alternative.get('instance_type')} "
|
|
209
|
+
f"(saves USD {format(_savings(alternative), 'f')}/hour)"
|
|
210
|
+
)
|
|
211
|
+
if isinstance(summary, dict):
|
|
212
|
+
lines.append(format_summary(summary))
|
|
213
|
+
kept_lines = [
|
|
214
|
+
line
|
|
215
|
+
for line in assessment.text.split("\n")
|
|
216
|
+
if "Compute Optimizer" in line or line == "Provider grade was not read."
|
|
217
|
+
]
|
|
218
|
+
lines.extend(kept_lines)
|
|
219
|
+
lines.append(UNCHECKED_COVERAGE)
|
|
220
|
+
assessment.text = "\n".join(lines)
|
|
221
|
+
return True
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""POST a closed instance price body to fleetfit-analyze, or replay a fixture in CI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.request
|
|
9
|
+
from decimal import Decimal
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
13
|
+
|
|
14
|
+
from maproom.analyze.instance_price_lookup import (
|
|
15
|
+
InstancePriceBodyError,
|
|
16
|
+
parse_instance_price_response,
|
|
17
|
+
require_instance_price_body,
|
|
18
|
+
)
|
|
19
|
+
from maproom.analyze.lookup_http import lookup_network_error_message
|
|
20
|
+
from maproom.redaction import redact_tree
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class InstancePriceError(Exception):
|
|
24
|
+
"""Instance price lookup request failed."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def post_instance_price(body: dict[str, str], settings: dict[str, Any]) -> Decimal:
|
|
28
|
+
require_instance_price_body(body)
|
|
29
|
+
fixture = os.environ.get("MAPROOM_INSTANCE_PRICE_FIXTURE", "").strip()
|
|
30
|
+
if fixture:
|
|
31
|
+
return _read_fixture(Path(fixture), body)
|
|
32
|
+
url = _lookup_url(settings)
|
|
33
|
+
if not url:
|
|
34
|
+
raise InstancePriceError("instance price URL is not configured")
|
|
35
|
+
payload = _post_json(url, body, settings)
|
|
36
|
+
try:
|
|
37
|
+
return parse_instance_price_response(payload)
|
|
38
|
+
except InstancePriceBodyError as exc:
|
|
39
|
+
raise InstancePriceError(str(exc)) from exc
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def instance_price_destination(settings: dict[str, Any] | None) -> bool:
|
|
43
|
+
if os.environ.get("MAPROOM_INSTANCE_PRICE_FIXTURE", "").strip():
|
|
44
|
+
return True
|
|
45
|
+
return resolve_instance_price_url(settings) is not None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def resolve_instance_price_url(settings: dict[str, Any] | None) -> str | None:
|
|
49
|
+
from maproom.analyze.recommend_client import resolve_recommend_url
|
|
50
|
+
|
|
51
|
+
return resolve_recommend_url(settings)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _lookup_url(settings: dict[str, Any] | None) -> str | None:
|
|
55
|
+
return resolve_instance_price_url(settings)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _fixture_key(body: dict[str, str]) -> str:
|
|
59
|
+
return "|".join(body[key] for key in ("instance_type", "region", "platform"))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _read_fixture(path: Path, body: dict[str, str]) -> Decimal:
|
|
63
|
+
try:
|
|
64
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
65
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
66
|
+
raise InstancePriceError("instance price fixture could not be read") from exc
|
|
67
|
+
if isinstance(payload, dict) and "hourly" in payload:
|
|
68
|
+
return parse_instance_price_response(payload)
|
|
69
|
+
if not isinstance(payload, dict):
|
|
70
|
+
raise InstancePriceError("instance price fixture must be a JSON object")
|
|
71
|
+
prices = payload.get("prices")
|
|
72
|
+
if not isinstance(prices, dict):
|
|
73
|
+
raise InstancePriceError("instance price fixture must include prices or hourly")
|
|
74
|
+
key = _fixture_key(body)
|
|
75
|
+
entry = prices.get(key)
|
|
76
|
+
if entry is None:
|
|
77
|
+
raise InstancePriceError(f"instance price fixture has no entry for {key}")
|
|
78
|
+
if isinstance(entry, str):
|
|
79
|
+
return parse_instance_price_response({"hourly": entry})
|
|
80
|
+
if isinstance(entry, dict):
|
|
81
|
+
return parse_instance_price_response(entry)
|
|
82
|
+
raise InstancePriceError("instance price fixture entry must be a string or object")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _post_json(url: str, body: dict[str, str], settings: dict[str, Any]) -> dict[str, Any]:
|
|
86
|
+
from maproom.analyze.recommend_client import (
|
|
87
|
+
KIND_PRICE,
|
|
88
|
+
RecommendError,
|
|
89
|
+
post_recommend_kind,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
legacy_body = {
|
|
93
|
+
"provider": "aws",
|
|
94
|
+
"region": body["region"],
|
|
95
|
+
"instance": body["instance_type"],
|
|
96
|
+
"platform": body["platform"],
|
|
97
|
+
}
|
|
98
|
+
del url
|
|
99
|
+
try:
|
|
100
|
+
return post_recommend_kind(
|
|
101
|
+
legacy_body,
|
|
102
|
+
settings,
|
|
103
|
+
kind=KIND_PRICE,
|
|
104
|
+
lookup_label="instance price lookup",
|
|
105
|
+
restore_request_type=False,
|
|
106
|
+
)
|
|
107
|
+
except RecommendError as exc:
|
|
108
|
+
raise InstancePriceError(str(exc)) from exc
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Closed instance price lookup body and response parsing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from decimal import Decimal, InvalidOperation
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
_BODY_KEYS = frozenset({"instance_type", "region", "platform"})
|
|
9
|
+
_FORBIDDEN = frozenset(
|
|
10
|
+
{
|
|
11
|
+
"instance_id",
|
|
12
|
+
"name",
|
|
13
|
+
"account_id",
|
|
14
|
+
"subscription_id",
|
|
15
|
+
"install_id",
|
|
16
|
+
"anonymous_id",
|
|
17
|
+
"arn",
|
|
18
|
+
}
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class InstancePriceBodyError(ValueError):
|
|
23
|
+
"""Instance price lookup body or response is not closed."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_instance_price_body(*, instance_type: str, region: str, platform: str) -> dict[str, str]:
|
|
27
|
+
body = {
|
|
28
|
+
"instance_type": instance_type.strip(),
|
|
29
|
+
"region": region.strip(),
|
|
30
|
+
"platform": platform.strip(),
|
|
31
|
+
}
|
|
32
|
+
require_instance_price_body(body)
|
|
33
|
+
return body
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def require_instance_price_body(body: object) -> dict[str, str]:
|
|
37
|
+
if not isinstance(body, dict):
|
|
38
|
+
raise InstancePriceBodyError("body must be a JSON object")
|
|
39
|
+
if set(body) != _BODY_KEYS:
|
|
40
|
+
raise InstancePriceBodyError("body keys must be instance_type, region, and platform only")
|
|
41
|
+
for key in _BODY_KEYS:
|
|
42
|
+
value = body.get(key)
|
|
43
|
+
if not isinstance(value, str) or not value.strip():
|
|
44
|
+
raise InstancePriceBodyError(f"{key} must be a non-empty string")
|
|
45
|
+
for forbidden in _FORBIDDEN:
|
|
46
|
+
if forbidden in body:
|
|
47
|
+
raise InstancePriceBodyError(f"{forbidden} must not appear in the body")
|
|
48
|
+
return {key: str(body[key]).strip() for key in _BODY_KEYS}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def parse_instance_price_response(payload: object) -> Decimal:
|
|
52
|
+
if not isinstance(payload, dict):
|
|
53
|
+
raise InstancePriceBodyError("response must be a JSON object")
|
|
54
|
+
hourly = payload.get("hourly")
|
|
55
|
+
if not isinstance(hourly, str) or not hourly.strip():
|
|
56
|
+
raise InstancePriceBodyError("hourly must be a non-empty string")
|
|
57
|
+
try:
|
|
58
|
+
return Decimal(hourly.strip())
|
|
59
|
+
except InvalidOperation as exc:
|
|
60
|
+
raise InstancePriceBodyError("hourly must be a decimal string") from exc
|