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,392 @@
|
|
|
1
|
+
"""Product version 3: consented Spot-to-Spot lookup (try-first for Spot rows)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from decimal import Decimal
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from maproom.analyze.workset import WorkItem
|
|
13
|
+
from maproom.consent import require_service_upload_consent
|
|
14
|
+
from maproom.paths import settings_read_file
|
|
15
|
+
from maproom.redaction import redact_text
|
|
16
|
+
from maproom.analyze.fleetfit_policy import fleetfit_policy_accept_hint
|
|
17
|
+
from maproom.settings.model import load_effective_settings
|
|
18
|
+
|
|
19
|
+
_VOLUME_ID = re.compile(r"vol-[0-9a-fA-F]+")
|
|
20
|
+
_ID_KEYS = frozenset({"instance_id", "instance_name", "account_id", "volume_id"})
|
|
21
|
+
|
|
22
|
+
INCOMPLETE_LINE = "The Spot description was incomplete."
|
|
23
|
+
DECLINED_LINE = "The Spot lookup was declined."
|
|
24
|
+
MISSING_POLICY_LINE = (
|
|
25
|
+
"The Spot lookup was not sent: the FleetFit handling policy is not accepted. "
|
|
26
|
+
+ fleetfit_policy_accept_hint()
|
|
27
|
+
)
|
|
28
|
+
NOT_ASKED_LINE = "The Spot lookup was not asked."
|
|
29
|
+
NOT_SENT_LINE = "The Spot lookup was not sent."
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class SpotRun:
|
|
34
|
+
"""Consent and destination for one version-2 analyze, decided once."""
|
|
35
|
+
|
|
36
|
+
upload_allowed: bool
|
|
37
|
+
destination: bool
|
|
38
|
+
settings: dict[str, Any]
|
|
39
|
+
upload_reason: str | None = None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def is_spot_instance(item: WorkItem) -> bool:
|
|
43
|
+
return item.cloud == "aws" and item.lifecycle.strip().lower() == "spot"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def spot_destination(settings: dict[str, Any] | None) -> bool:
|
|
47
|
+
"""True when the Spot lookup URL resolves or the fixture is set."""
|
|
48
|
+
from maproom.analyze.spot_client import resolve_spot_lookup_url
|
|
49
|
+
|
|
50
|
+
if os.environ.get("MAPROOM_SPOT_FIXTURE", "").strip():
|
|
51
|
+
return True
|
|
52
|
+
return resolve_spot_lookup_url(settings) is not None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def prepare_spot_run(
|
|
56
|
+
items: list[WorkItem],
|
|
57
|
+
args: Any,
|
|
58
|
+
*,
|
|
59
|
+
as_json: bool,
|
|
60
|
+
) -> SpotRun:
|
|
61
|
+
"""Ask for upload consent only when some Spot description is complete enough to send."""
|
|
62
|
+
settings, _ = load_effective_settings(settings_read_file())
|
|
63
|
+
ready = any(_description_ready(item) for item in items)
|
|
64
|
+
if not ready:
|
|
65
|
+
return SpotRun(False, False, settings)
|
|
66
|
+
gate = require_service_upload_consent(
|
|
67
|
+
consent_fleetfit_recommendations=bool(
|
|
68
|
+
getattr(args, "consent_fleetfit_recommendations", False)
|
|
69
|
+
),
|
|
70
|
+
quiet=as_json,
|
|
71
|
+
)
|
|
72
|
+
allowed = bool(gate.upload_allowed) and gate.exit_code == 0
|
|
73
|
+
if allowed:
|
|
74
|
+
settings, _ = load_effective_settings(settings_read_file())
|
|
75
|
+
return SpotRun(
|
|
76
|
+
upload_allowed=allowed,
|
|
77
|
+
destination=spot_destination(settings),
|
|
78
|
+
settings=settings,
|
|
79
|
+
upload_reason=gate.reason_code,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def apply_spot_lookup(
|
|
84
|
+
item: WorkItem,
|
|
85
|
+
assessment: Any,
|
|
86
|
+
*,
|
|
87
|
+
run: SpotRun,
|
|
88
|
+
block_devices: dict[str, list[dict[str, Any]]],
|
|
89
|
+
as_json: bool,
|
|
90
|
+
run_banners: Any | None = None,
|
|
91
|
+
recommend_envelope: dict[str, Any] | None = None,
|
|
92
|
+
attach_only: bool = False,
|
|
93
|
+
) -> None:
|
|
94
|
+
"""Attach the Spot result to the version-1 row. On-demand and Azure are ignored."""
|
|
95
|
+
if not is_spot_instance(item):
|
|
96
|
+
if not attach_only:
|
|
97
|
+
block_devices.pop(item.instance_id, None)
|
|
98
|
+
return
|
|
99
|
+
mappings = list(block_devices.get(item.instance_id, []))
|
|
100
|
+
note = _public_note(_immovable_note(mappings))
|
|
101
|
+
if attach_only:
|
|
102
|
+
block_devices.pop(item.instance_id, None)
|
|
103
|
+
del mappings
|
|
104
|
+
if attach_only:
|
|
105
|
+
extra, payload = _spot_outcome_from_envelope(
|
|
106
|
+
item,
|
|
107
|
+
recommend_envelope,
|
|
108
|
+
note=note,
|
|
109
|
+
as_json=as_json,
|
|
110
|
+
)
|
|
111
|
+
else:
|
|
112
|
+
extra, payload = _spot_outcome(item, run=run, note=note, as_json=as_json)
|
|
113
|
+
if extra:
|
|
114
|
+
if (
|
|
115
|
+
run_banners is not None
|
|
116
|
+
and payload is not None
|
|
117
|
+
and payload.get("status") == "missing_policy"
|
|
118
|
+
):
|
|
119
|
+
run_banners.spot_missing_policy = True
|
|
120
|
+
else:
|
|
121
|
+
assessment.text = f"{assessment.text}\n{extra}" if assessment.text else extra
|
|
122
|
+
if payload is None:
|
|
123
|
+
return
|
|
124
|
+
if assessment.recommendation is not None:
|
|
125
|
+
assessment.recommendation["spot_lookup"] = payload
|
|
126
|
+
elif assessment.examined is not None:
|
|
127
|
+
assessment.examined["spot_lookup"] = payload
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _description_ready(item: WorkItem) -> bool:
|
|
131
|
+
if not is_spot_instance(item):
|
|
132
|
+
return False
|
|
133
|
+
return bool(
|
|
134
|
+
item.region.strip()
|
|
135
|
+
and item.availability_zone.strip()
|
|
136
|
+
and item.instance_type.strip()
|
|
137
|
+
and item.platform.strip()
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _spot_outcome(
|
|
142
|
+
item: WorkItem,
|
|
143
|
+
*,
|
|
144
|
+
run: SpotRun,
|
|
145
|
+
note: str,
|
|
146
|
+
as_json: bool,
|
|
147
|
+
) -> tuple[str, dict[str, Any] | None]:
|
|
148
|
+
operating_system = item.platform.strip()
|
|
149
|
+
local_az = item.availability_zone.strip()
|
|
150
|
+
if not item.region.strip() or not item.instance_type.strip() or not local_az or not operating_system:
|
|
151
|
+
return INCOMPLETE_LINE, _payload(
|
|
152
|
+
status="incomplete",
|
|
153
|
+
pool=None,
|
|
154
|
+
availability_zone=local_az,
|
|
155
|
+
immovable_volumes=note,
|
|
156
|
+
)
|
|
157
|
+
if not run.upload_allowed:
|
|
158
|
+
if run.upload_reason == "upload_required":
|
|
159
|
+
return NOT_ASKED_LINE, _payload(
|
|
160
|
+
status="not_asked",
|
|
161
|
+
pool=None,
|
|
162
|
+
availability_zone=local_az,
|
|
163
|
+
immovable_volumes=note,
|
|
164
|
+
)
|
|
165
|
+
if run.upload_reason == "upload_missing_policy":
|
|
166
|
+
return MISSING_POLICY_LINE, _payload(
|
|
167
|
+
status="missing_policy",
|
|
168
|
+
pool=None,
|
|
169
|
+
availability_zone=local_az,
|
|
170
|
+
immovable_volumes=note,
|
|
171
|
+
)
|
|
172
|
+
return DECLINED_LINE, _payload(
|
|
173
|
+
status="declined",
|
|
174
|
+
pool=None,
|
|
175
|
+
availability_zone=local_az,
|
|
176
|
+
immovable_volumes=note,
|
|
177
|
+
)
|
|
178
|
+
if not run.destination:
|
|
179
|
+
return NOT_SENT_LINE, _payload(
|
|
180
|
+
status="not_sent",
|
|
181
|
+
pool=None,
|
|
182
|
+
availability_zone=local_az,
|
|
183
|
+
immovable_volumes=note,
|
|
184
|
+
)
|
|
185
|
+
from maproom.analyze.spot_client import SpotLookupError, post_spot_lookup
|
|
186
|
+
from maproom.analyze.spot_lookup import build_spot_body, format_spot_result
|
|
187
|
+
|
|
188
|
+
catalog_az = item.availability_zone_id.strip() or local_az
|
|
189
|
+
body = build_spot_body(
|
|
190
|
+
provider=item.cloud,
|
|
191
|
+
region=item.region,
|
|
192
|
+
az=catalog_az,
|
|
193
|
+
instance=item.instance_type,
|
|
194
|
+
os=operating_system,
|
|
195
|
+
)
|
|
196
|
+
try:
|
|
197
|
+
response = post_spot_lookup(body, _settings_for_post(run.settings))
|
|
198
|
+
except SpotLookupError as exc:
|
|
199
|
+
warning = f"warning: Spot lookup failed: {redact_text(str(exc))}"
|
|
200
|
+
if as_json:
|
|
201
|
+
print(warning, file=sys.stderr)
|
|
202
|
+
return warning, _payload(
|
|
203
|
+
status="error",
|
|
204
|
+
pool=None,
|
|
205
|
+
availability_zone=local_az,
|
|
206
|
+
immovable_volumes=note,
|
|
207
|
+
)
|
|
208
|
+
if response is None:
|
|
209
|
+
return "", None
|
|
210
|
+
if not isinstance(response, dict):
|
|
211
|
+
warning = "warning: Spot lookup failed: unexpected payload"
|
|
212
|
+
if as_json:
|
|
213
|
+
print(warning, file=sys.stderr)
|
|
214
|
+
return warning, _payload(
|
|
215
|
+
status="error",
|
|
216
|
+
pool=None,
|
|
217
|
+
availability_zone=local_az,
|
|
218
|
+
immovable_volumes=note,
|
|
219
|
+
)
|
|
220
|
+
line = _public_note(str(format_spot_result(response, immovable_note=note)))
|
|
221
|
+
return line, _payload_from_response(
|
|
222
|
+
response,
|
|
223
|
+
availability_zone=local_az,
|
|
224
|
+
immovable_volumes=note,
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _spot_outcome_from_envelope(
|
|
229
|
+
item: WorkItem,
|
|
230
|
+
envelope: dict[str, Any] | None,
|
|
231
|
+
*,
|
|
232
|
+
note: str,
|
|
233
|
+
as_json: bool,
|
|
234
|
+
) -> tuple[str, dict[str, Any] | None]:
|
|
235
|
+
if envelope is None:
|
|
236
|
+
return "", None
|
|
237
|
+
local_az = item.availability_zone.strip()
|
|
238
|
+
from maproom.analyze.recommend_client import KIND_SPOT, RecommendError, unwrap_kind_section
|
|
239
|
+
from maproom.analyze.spot_lookup import format_spot_result
|
|
240
|
+
|
|
241
|
+
try:
|
|
242
|
+
response = unwrap_kind_section(envelope, kind=KIND_SPOT)
|
|
243
|
+
except RecommendError as exc:
|
|
244
|
+
warning = f"warning: Spot lookup failed: {redact_text(str(exc))}"
|
|
245
|
+
if as_json:
|
|
246
|
+
print(warning, file=sys.stderr)
|
|
247
|
+
return warning, _payload(
|
|
248
|
+
status="error",
|
|
249
|
+
pool=None,
|
|
250
|
+
availability_zone=local_az,
|
|
251
|
+
immovable_volumes=note,
|
|
252
|
+
)
|
|
253
|
+
line = _public_note(str(format_spot_result(response, immovable_note=note)))
|
|
254
|
+
return line, _payload_from_response(
|
|
255
|
+
response,
|
|
256
|
+
availability_zone=local_az,
|
|
257
|
+
immovable_volumes=note,
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _settings_for_post(settings: dict[str, Any]) -> dict[str, Any]:
|
|
262
|
+
"""Pass the resolved recommend URL through (env, [service], or the analyze setting)."""
|
|
263
|
+
from maproom.analyze.recommend_client import resolve_recommend_url
|
|
264
|
+
|
|
265
|
+
merged = dict(settings)
|
|
266
|
+
service = dict(merged.get("service") or {})
|
|
267
|
+
url = resolve_recommend_url(settings)
|
|
268
|
+
if url and not str(service.get("recommend_url") or "").strip():
|
|
269
|
+
service["recommend_url"] = url
|
|
270
|
+
merged["service"] = service
|
|
271
|
+
return merged
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _immovable_note(mappings: list[dict[str, Any]]) -> str:
|
|
275
|
+
from maproom.analyze.spot_lookup import volumes_that_cannot_move
|
|
276
|
+
|
|
277
|
+
note = volumes_that_cannot_move(mappings)
|
|
278
|
+
return note if isinstance(note, str) else ""
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _public_note(note: str) -> str:
|
|
282
|
+
return _VOLUME_ID.sub("", note).strip()
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _payload(
|
|
286
|
+
*,
|
|
287
|
+
status: str,
|
|
288
|
+
pool: str | None,
|
|
289
|
+
availability_zone: str,
|
|
290
|
+
immovable_volumes: str,
|
|
291
|
+
interrupt_risk: str | None = None,
|
|
292
|
+
region_prices: dict[str, str] | None = None,
|
|
293
|
+
cpu_performance_rank: dict[str, Any] | None = None,
|
|
294
|
+
recommendations: list[dict[str, str]] | None = None,
|
|
295
|
+
) -> dict[str, Any]:
|
|
296
|
+
payload = {
|
|
297
|
+
"status": status,
|
|
298
|
+
"pool": pool if pool else None,
|
|
299
|
+
"interrupt_risk": interrupt_risk,
|
|
300
|
+
"availability_zone": availability_zone,
|
|
301
|
+
"region_prices": region_prices,
|
|
302
|
+
"immovable_volumes": immovable_volumes or "",
|
|
303
|
+
"cpu_performance_rank": cpu_performance_rank,
|
|
304
|
+
}
|
|
305
|
+
if recommendations is not None:
|
|
306
|
+
payload["recommendations"] = recommendations
|
|
307
|
+
return payload
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _payload_from_response(
|
|
311
|
+
response: dict[str, Any],
|
|
312
|
+
*,
|
|
313
|
+
availability_zone: str,
|
|
314
|
+
immovable_volumes: str,
|
|
315
|
+
) -> dict[str, Any]:
|
|
316
|
+
response_az = response.get("availability_zone")
|
|
317
|
+
az = response_az.strip() if isinstance(response_az, str) and response_az.strip() else availability_zone
|
|
318
|
+
response_pool = response.get("pool")
|
|
319
|
+
named_pool = response_pool.strip() if isinstance(response_pool, str) and response_pool.strip() else ""
|
|
320
|
+
risk = response.get("interrupt_risk")
|
|
321
|
+
return _payload(
|
|
322
|
+
status="returned",
|
|
323
|
+
pool=named_pool or None,
|
|
324
|
+
availability_zone=az,
|
|
325
|
+
immovable_volumes=immovable_volumes,
|
|
326
|
+
interrupt_risk=risk.strip() if isinstance(risk, str) and risk.strip() else None,
|
|
327
|
+
region_prices=_region_prices(response.get("region_prices")),
|
|
328
|
+
cpu_performance_rank=_rank(response.get("cpu_performance_rank")),
|
|
329
|
+
recommendations=_recommendations(response.get("recommendations")),
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _recommendations(value: Any) -> list[dict[str, str]] | None:
|
|
334
|
+
if not isinstance(value, list):
|
|
335
|
+
return None
|
|
336
|
+
rows: list[dict[str, str]] = []
|
|
337
|
+
for item in value:
|
|
338
|
+
if not isinstance(item, dict):
|
|
339
|
+
continue
|
|
340
|
+
az = item.get("az")
|
|
341
|
+
hourly = item.get("hourly")
|
|
342
|
+
if not isinstance(az, str) or not isinstance(hourly, str):
|
|
343
|
+
continue
|
|
344
|
+
if not az.strip() or _VOLUME_ID.search(az) or _VOLUME_ID.search(hourly):
|
|
345
|
+
continue
|
|
346
|
+
rows.append({"az": az.strip(), "hourly": hourly.strip()})
|
|
347
|
+
return rows
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _region_prices(value: Any) -> dict[str, str] | None:
|
|
351
|
+
if not isinstance(value, dict):
|
|
352
|
+
return None
|
|
353
|
+
prices: dict[str, str] = {}
|
|
354
|
+
for key, raw in value.items():
|
|
355
|
+
if not isinstance(key, str) or key in _ID_KEYS:
|
|
356
|
+
continue
|
|
357
|
+
text = _decimal_string(raw)
|
|
358
|
+
if text is None or _VOLUME_ID.search(text):
|
|
359
|
+
continue
|
|
360
|
+
prices[key] = text
|
|
361
|
+
return prices
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _decimal_string(value: Any) -> str | None:
|
|
365
|
+
if isinstance(value, str):
|
|
366
|
+
return value
|
|
367
|
+
if isinstance(value, bool) or value is None:
|
|
368
|
+
return None
|
|
369
|
+
if isinstance(value, (int, Decimal)):
|
|
370
|
+
return format(Decimal(value), "f")
|
|
371
|
+
if isinstance(value, float):
|
|
372
|
+
return format(Decimal(str(value)), "f")
|
|
373
|
+
return None
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _rank(value: Any) -> dict[str, Any] | None:
|
|
377
|
+
if not isinstance(value, dict):
|
|
378
|
+
return None
|
|
379
|
+
cleaned: dict[str, Any] = {}
|
|
380
|
+
for key, raw in value.items():
|
|
381
|
+
if key in _ID_KEYS:
|
|
382
|
+
continue
|
|
383
|
+
if isinstance(raw, dict):
|
|
384
|
+
nested = _rank(raw)
|
|
385
|
+
if nested is not None:
|
|
386
|
+
cleaned[key] = nested
|
|
387
|
+
continue
|
|
388
|
+
if isinstance(raw, str) and _VOLUME_ID.search(raw):
|
|
389
|
+
continue
|
|
390
|
+
cleaned[key] = raw
|
|
391
|
+
return cleaned
|
|
392
|
+
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""POST spot fields to FleetFit recommend, or replay a fixture in CI.
|
|
2
|
+
|
|
3
|
+
The response section is returned with request_type restored for local checkers.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import urllib.error
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from maproom.analyze.recommend_client import (
|
|
15
|
+
KIND_SPOT,
|
|
16
|
+
RecommendError,
|
|
17
|
+
post_recommend_kind,
|
|
18
|
+
resolve_recommend_url,
|
|
19
|
+
unwrap_kind_section,
|
|
20
|
+
)
|
|
21
|
+
from maproom.analyze.spot_lookup import _require_closed_spot_body
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class SpotLookupError(Exception):
|
|
25
|
+
"""Spot lookup request failed."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def post_spot_lookup(body: dict, settings: dict) -> dict:
|
|
29
|
+
"""Send a closed spot_lookup body, or raise before any fixture read or POST."""
|
|
30
|
+
_require_closed_spot_body(body)
|
|
31
|
+
fixture = os.environ.get("MAPROOM_SPOT_FIXTURE", "").strip()
|
|
32
|
+
if fixture:
|
|
33
|
+
return _read_fixture(Path(fixture))
|
|
34
|
+
from maproom.analyze.recommend_batch import recommend_staging_only
|
|
35
|
+
|
|
36
|
+
try:
|
|
37
|
+
result = post_recommend_kind(
|
|
38
|
+
body, settings, kind=KIND_SPOT, lookup_label="spot lookup"
|
|
39
|
+
)
|
|
40
|
+
if recommend_staging_only() and result is None:
|
|
41
|
+
return None # type: ignore[return-value]
|
|
42
|
+
return result
|
|
43
|
+
except RecommendError as exc:
|
|
44
|
+
raise SpotLookupError(str(exc)) from exc
|
|
45
|
+
except urllib.error.HTTPError as exc:
|
|
46
|
+
raise SpotLookupError(f"spot lookup HTTP {exc.code}") from exc
|
|
47
|
+
except urllib.error.URLError as exc:
|
|
48
|
+
detail = exc.reason if isinstance(exc.reason, str) else str(exc)
|
|
49
|
+
raise SpotLookupError(detail) from exc
|
|
50
|
+
except (TimeoutError, ValueError) as exc:
|
|
51
|
+
raise SpotLookupError(str(exc)) from exc
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def resolve_spot_lookup_url(settings: dict | None) -> str | None:
|
|
55
|
+
"""Recommend URL (same for every lookup kind)."""
|
|
56
|
+
return resolve_recommend_url(settings)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _read_fixture(path: Path) -> dict[str, Any]:
|
|
60
|
+
try:
|
|
61
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
62
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
63
|
+
raise SpotLookupError("spot lookup fixture could not be read") from exc
|
|
64
|
+
try:
|
|
65
|
+
section = unwrap_kind_section(payload, kind=KIND_SPOT)
|
|
66
|
+
except RecommendError as exc:
|
|
67
|
+
raise SpotLookupError(str(exc)) from exc
|
|
68
|
+
return _require_spot_response(section)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _require_spot_response(payload: object) -> dict[str, Any]:
|
|
72
|
+
if not isinstance(payload, dict) or payload.get("request_type") != "spot_lookup":
|
|
73
|
+
raise SpotLookupError("spot lookup response must be a spot_lookup object")
|
|
74
|
+
return payload
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Spot-to-Spot lookup body and the line printed from a fleetfit response.
|
|
2
|
+
|
|
3
|
+
The body is the instance description without ids. Fleetfit answers it.
|
|
4
|
+
This module does not rank candidates and does not read the local price or spec tables.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
SPOT_BODY_KEYS: tuple[str, ...] = (
|
|
13
|
+
"request_type",
|
|
14
|
+
"provider",
|
|
15
|
+
"region",
|
|
16
|
+
"az",
|
|
17
|
+
"instance",
|
|
18
|
+
"os",
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
_FORBIDDEN_KEYS = frozenset(
|
|
22
|
+
{
|
|
23
|
+
"instance_id",
|
|
24
|
+
"name",
|
|
25
|
+
"account_id",
|
|
26
|
+
"volume_id",
|
|
27
|
+
"arn",
|
|
28
|
+
"spot_instance_request_id",
|
|
29
|
+
"reservation_id",
|
|
30
|
+
}
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
_INSTANCE_ID_RE = re.compile(r"i-[0-9a-f]{8,}", re.IGNORECASE)
|
|
34
|
+
_VOLUME_ID_RE = re.compile(r"vol-[0-9a-f]{8,}", re.IGNORECASE)
|
|
35
|
+
_ACCOUNT_ID_RE = re.compile(r"(?<!\d)\d{12}(?!\d)")
|
|
36
|
+
|
|
37
|
+
_NO_POOL_LINE = "No cheaper Spot pool was returned."
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_spot_body(
|
|
41
|
+
*,
|
|
42
|
+
provider: str,
|
|
43
|
+
region: str,
|
|
44
|
+
az: str,
|
|
45
|
+
instance: str,
|
|
46
|
+
os: str,
|
|
47
|
+
) -> dict[str, Any]:
|
|
48
|
+
"""Return the fleetfit spot_lookup body, or raise ValueError when it is not closed."""
|
|
49
|
+
body = {
|
|
50
|
+
"request_type": "spot_lookup",
|
|
51
|
+
"provider": provider,
|
|
52
|
+
"region": region,
|
|
53
|
+
"az": az,
|
|
54
|
+
"instance": instance,
|
|
55
|
+
"os": os,
|
|
56
|
+
}
|
|
57
|
+
_require_closed_spot_body(body)
|
|
58
|
+
return body
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def volumes_that_cannot_move(block_device_mappings: list) -> str:
|
|
62
|
+
"""Count instance-store mappings. EBS mappings can move and are not named."""
|
|
63
|
+
immovable = 0
|
|
64
|
+
for mapping in block_device_mappings:
|
|
65
|
+
ebs = mapping.get("Ebs") if isinstance(mapping, dict) else None
|
|
66
|
+
if not isinstance(ebs, dict):
|
|
67
|
+
immovable += 1
|
|
68
|
+
if immovable == 0:
|
|
69
|
+
return ""
|
|
70
|
+
kind = "volume" if immovable == 1 else "volumes"
|
|
71
|
+
return f"{immovable} instance-store {kind} cannot move with the instance."
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def format_spot_result(response: dict, *, immovable_note: str) -> str:
|
|
75
|
+
"""One line for the returned pool, or a line that no cheaper pool was returned."""
|
|
76
|
+
if not isinstance(response, dict):
|
|
77
|
+
raise ValueError("spot lookup response must be an object")
|
|
78
|
+
cleaned = _drop_forbidden(response)
|
|
79
|
+
note = _scrub_ids(immovable_note.strip()) if isinstance(immovable_note, str) else ""
|
|
80
|
+
recommendations = cleaned.get("recommendations") if isinstance(cleaned, dict) else None
|
|
81
|
+
if isinstance(recommendations, list):
|
|
82
|
+
line = _recommendation_line(recommendations)
|
|
83
|
+
elif not isinstance(cleaned, dict) or cleaned.get("pool") is None:
|
|
84
|
+
line = _NO_POOL_LINE
|
|
85
|
+
else:
|
|
86
|
+
line = _spot_line(cleaned)
|
|
87
|
+
if note:
|
|
88
|
+
line = f"{line} {note}"
|
|
89
|
+
return _scrub_ids(line)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _require_closed_spot_body(body: dict[str, Any]) -> None:
|
|
93
|
+
if not isinstance(body, dict):
|
|
94
|
+
raise ValueError("spot lookup body must be an object")
|
|
95
|
+
keys = set(body)
|
|
96
|
+
expected = set(SPOT_BODY_KEYS)
|
|
97
|
+
if keys - expected:
|
|
98
|
+
raise ValueError("spot lookup body has an extra key")
|
|
99
|
+
if expected - keys:
|
|
100
|
+
raise ValueError("spot lookup body is missing a key")
|
|
101
|
+
_reject_id_shaped(body)
|
|
102
|
+
if body.get("request_type") != "spot_lookup":
|
|
103
|
+
raise ValueError("request_type must be spot_lookup")
|
|
104
|
+
if body.get("provider") != "aws":
|
|
105
|
+
raise ValueError("provider must be aws")
|
|
106
|
+
for key in ("region", "az", "instance", "os"):
|
|
107
|
+
value = body.get(key)
|
|
108
|
+
if not isinstance(value, str) or value.strip() == "":
|
|
109
|
+
raise ValueError("spot lookup body has an empty field")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _reject_id_shaped(value: object, *, key: object = None) -> None:
|
|
113
|
+
if isinstance(key, str) and key.lower() in _FORBIDDEN_KEYS:
|
|
114
|
+
raise ValueError("spot lookup body contains a forbidden key")
|
|
115
|
+
if isinstance(value, dict):
|
|
116
|
+
for child_key, child in value.items():
|
|
117
|
+
_reject_id_shaped(child, key=child_key)
|
|
118
|
+
return
|
|
119
|
+
if isinstance(value, list):
|
|
120
|
+
for child in value:
|
|
121
|
+
_reject_id_shaped(child)
|
|
122
|
+
return
|
|
123
|
+
if isinstance(value, str):
|
|
124
|
+
if _INSTANCE_ID_RE.search(value) or _VOLUME_ID_RE.search(value) or _ACCOUNT_ID_RE.search(value):
|
|
125
|
+
raise ValueError("spot lookup body contains a forbidden id")
|
|
126
|
+
return
|
|
127
|
+
if isinstance(value, int) and not isinstance(value, bool) and 10**11 <= abs(value) < 10**12:
|
|
128
|
+
raise ValueError("spot lookup body contains a forbidden id")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _drop_forbidden(value: object) -> object:
|
|
132
|
+
if isinstance(value, dict):
|
|
133
|
+
return {
|
|
134
|
+
child_key: _drop_forbidden(child)
|
|
135
|
+
for child_key, child in value.items()
|
|
136
|
+
if not (isinstance(child_key, str) and child_key.lower() in _FORBIDDEN_KEYS)
|
|
137
|
+
}
|
|
138
|
+
if isinstance(value, list):
|
|
139
|
+
return [_drop_forbidden(child) for child in value]
|
|
140
|
+
return value
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _recommendation_line(rows: list) -> str:
|
|
144
|
+
parts: list[str] = []
|
|
145
|
+
for row in rows:
|
|
146
|
+
if not isinstance(row, dict):
|
|
147
|
+
continue
|
|
148
|
+
az = _scrub_ids(_as_text(row.get("az")))
|
|
149
|
+
hourly = _scrub_ids(_as_text(row.get("hourly")))
|
|
150
|
+
if az and hourly:
|
|
151
|
+
parts.append(f"{az} at {hourly}")
|
|
152
|
+
if not parts:
|
|
153
|
+
return _NO_POOL_LINE
|
|
154
|
+
return "cheaper Spot zones " + "; ".join(parts)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _spot_line(cleaned: dict[str, Any]) -> str:
|
|
158
|
+
rank = _rank_phrase(cleaned.get("cpu_performance_rank"))
|
|
159
|
+
parts = [
|
|
160
|
+
f"pool {_scrub_ids(_as_text(cleaned.get('pool')))}",
|
|
161
|
+
f"interrupt risk {_scrub_ids(_as_text(cleaned.get('interrupt_risk')))}",
|
|
162
|
+
f"availability zone {_scrub_ids(_as_text(cleaned.get('availability_zone')))}",
|
|
163
|
+
]
|
|
164
|
+
if rank:
|
|
165
|
+
parts.append(rank)
|
|
166
|
+
parts.append(_price_phrase(cleaned.get("region_prices")))
|
|
167
|
+
return " ".join(part.strip() for part in parts if part.strip())
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _rank_phrase(rank: object) -> str:
|
|
171
|
+
if not isinstance(rank, dict):
|
|
172
|
+
return ""
|
|
173
|
+
direction = rank.get("direction")
|
|
174
|
+
if direction is not None and direction != "higher_is_faster":
|
|
175
|
+
raise ValueError("cpu_performance_rank.direction must be higher_is_faster")
|
|
176
|
+
current = rank.get("current")
|
|
177
|
+
targeted = rank.get("targeted")
|
|
178
|
+
if current is None and targeted is None:
|
|
179
|
+
return ""
|
|
180
|
+
phrase = (
|
|
181
|
+
f"CPU performance rank {_scrub_ids(_as_text(current))} -> {_scrub_ids(_as_text(targeted))}"
|
|
182
|
+
)
|
|
183
|
+
if direction == "higher_is_faster":
|
|
184
|
+
phrase += " higher_is_faster"
|
|
185
|
+
return phrase
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _price_phrase(prices: object) -> str:
|
|
189
|
+
current = ""
|
|
190
|
+
targeted = ""
|
|
191
|
+
if isinstance(prices, dict):
|
|
192
|
+
current = _scrub_ids(_as_text(prices.get("current_hourly")))
|
|
193
|
+
targeted = _scrub_ids(_as_text(prices.get("targeted_hourly")))
|
|
194
|
+
return f"region prices {current} -> {targeted}".strip()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _as_text(value: object) -> str:
|
|
198
|
+
if isinstance(value, str):
|
|
199
|
+
return value
|
|
200
|
+
if isinstance(value, bool):
|
|
201
|
+
return ""
|
|
202
|
+
if isinstance(value, int):
|
|
203
|
+
return str(value)
|
|
204
|
+
if isinstance(value, float):
|
|
205
|
+
return format(value, "f")
|
|
206
|
+
return ""
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _scrub_ids(text: str) -> str:
|
|
210
|
+
scrubbed = _INSTANCE_ID_RE.sub("", text)
|
|
211
|
+
scrubbed = _VOLUME_ID_RE.sub("", scrubbed)
|
|
212
|
+
scrubbed = _ACCOUNT_ID_RE.sub("", scrubbed)
|
|
213
|
+
return " ".join(scrubbed.split())
|