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,280 @@
|
|
|
1
|
+
"""Network error messages and shared POST opener for fleetfit lookup clients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import socket
|
|
7
|
+
import ssl
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.request
|
|
10
|
+
from typing import Any
|
|
11
|
+
from urllib.parse import urlparse
|
|
12
|
+
|
|
13
|
+
from maproom.analyze.fleetfit_endpoints import fleetfit_request_uses_operator_override
|
|
14
|
+
from maproom.redaction import redact_tree
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class LookupRedirectError(Exception):
|
|
18
|
+
"""The configured host redirected to another host."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
_UNAUTHORIZED_BODY_LIMIT = 65536
|
|
22
|
+
LOOKUP_JSON_BODY_LIMIT = 1_048_576
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def read_http_body_limited(response: object, limit: int) -> bytes:
|
|
26
|
+
"""Read up to ``limit`` bytes; refuse bodies larger than the cap."""
|
|
27
|
+
read = response.read # type: ignore[attr-defined]
|
|
28
|
+
try:
|
|
29
|
+
raw = read(limit + 1)
|
|
30
|
+
except TypeError:
|
|
31
|
+
raw = read()
|
|
32
|
+
if not isinstance(raw, (bytes, bytearray)):
|
|
33
|
+
raise TypeError("HTTP response read did not return bytes")
|
|
34
|
+
if len(raw) > limit:
|
|
35
|
+
raise ValueError(f"HTTP response body exceeds {limit} bytes")
|
|
36
|
+
return bytes(raw)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class LookupUnauthorizedError(urllib.error.HTTPError):
|
|
40
|
+
"""HTTP 401 with its JSON body read, so the caller can see the error code.
|
|
41
|
+
|
|
42
|
+
It is an HTTPError, so a caller that only reports the status keeps working.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(self, url: str, payload: dict[str, Any] | None) -> None:
|
|
46
|
+
super().__init__(url, 401, "Unauthorized", None, None) # type: ignore[arg-type]
|
|
47
|
+
self.payload: dict[str, Any] = payload if isinstance(payload, dict) else {}
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def error_code(self) -> str | None:
|
|
51
|
+
code = self.payload.get("error")
|
|
52
|
+
return code if isinstance(code, str) else None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _unauthorized_payload(exc: urllib.error.HTTPError) -> dict[str, Any] | None:
|
|
56
|
+
try:
|
|
57
|
+
raw = exc.read(_UNAUTHORIZED_BODY_LIMIT)
|
|
58
|
+
payload = json.loads(raw.decode("utf-8"))
|
|
59
|
+
except (OSError, ValueError, AttributeError):
|
|
60
|
+
return None
|
|
61
|
+
return payload if isinstance(payload, dict) else None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class NoRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
65
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def]
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class PostPreservingRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
70
|
+
"""Follow redirects while keeping the POST body and request headers."""
|
|
71
|
+
|
|
72
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def]
|
|
73
|
+
if code not in (301, 302, 303, 307, 308):
|
|
74
|
+
return None
|
|
75
|
+
redirected = urllib.request.Request(
|
|
76
|
+
newurl,
|
|
77
|
+
data=req.data,
|
|
78
|
+
headers=dict(req.header_items()),
|
|
79
|
+
origin_req_host=req.origin_req_host,
|
|
80
|
+
unverifiable=True,
|
|
81
|
+
)
|
|
82
|
+
redirected.get_method = lambda: req.get_method() # type: ignore[method-assign]
|
|
83
|
+
return redirected
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
_STRICT_OPENER: urllib.request.OpenerDirector | None = None
|
|
87
|
+
_OVERRIDE_OPENER: urllib.request.OpenerDirector | None = None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _strict_opener() -> urllib.request.OpenerDirector:
|
|
91
|
+
global _STRICT_OPENER
|
|
92
|
+
if _STRICT_OPENER is None:
|
|
93
|
+
_STRICT_OPENER = urllib.request.build_opener(NoRedirectHandler())
|
|
94
|
+
return _STRICT_OPENER
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _override_opener() -> urllib.request.OpenerDirector:
|
|
98
|
+
global _OVERRIDE_OPENER
|
|
99
|
+
if _OVERRIDE_OPENER is None:
|
|
100
|
+
context = ssl._create_unverified_context()
|
|
101
|
+
https = urllib.request.HTTPSHandler(context=context)
|
|
102
|
+
_OVERRIDE_OPENER = urllib.request.build_opener(
|
|
103
|
+
PostPreservingRedirectHandler(),
|
|
104
|
+
https,
|
|
105
|
+
)
|
|
106
|
+
return _OVERRIDE_OPENER
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def fleetfit_lookup_opener(
|
|
110
|
+
url: str = "",
|
|
111
|
+
settings: dict[str, Any] | None = None,
|
|
112
|
+
) -> urllib.request.OpenerDirector:
|
|
113
|
+
if url and fleetfit_request_uses_operator_override(url, settings):
|
|
114
|
+
return _override_opener()
|
|
115
|
+
return _strict_opener()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def post_lookup_json(
|
|
119
|
+
url: str,
|
|
120
|
+
body: dict[str, Any],
|
|
121
|
+
*,
|
|
122
|
+
lookup_label: str,
|
|
123
|
+
timeout: float = 30,
|
|
124
|
+
authorization: str | None = None,
|
|
125
|
+
settings: dict[str, Any] | None = None,
|
|
126
|
+
attach_fleetfit_policy: bool = True,
|
|
127
|
+
anonymous_id: str | None = None,
|
|
128
|
+
) -> dict[str, Any]:
|
|
129
|
+
"""POST JSON to the configured host; refuse redirects and off-host responses.
|
|
130
|
+
|
|
131
|
+
``authorization`` is sent as the Authorization header when given. HTTP 401
|
|
132
|
+
raises LookupUnauthorizedError carrying the JSON body.
|
|
133
|
+
"""
|
|
134
|
+
from maproom.analyze.fleetfit_policy import with_fleetfit_policy_id
|
|
135
|
+
|
|
136
|
+
operator_override = fleetfit_request_uses_operator_override(url, settings)
|
|
137
|
+
outbound = dict(body)
|
|
138
|
+
if attach_fleetfit_policy and settings is not None:
|
|
139
|
+
outbound = with_fleetfit_policy_id(outbound, settings)
|
|
140
|
+
if anonymous_id:
|
|
141
|
+
outbound["anonymous_id"] = anonymous_id
|
|
142
|
+
configured = urlparse(url)
|
|
143
|
+
configured_host = (configured.hostname or "").lower()
|
|
144
|
+
encoded = json.dumps(redact_tree(outbound)).encode("utf-8")
|
|
145
|
+
request = urllib.request.Request(
|
|
146
|
+
url,
|
|
147
|
+
data=encoded,
|
|
148
|
+
headers={"Content-Type": "application/json"},
|
|
149
|
+
method="POST",
|
|
150
|
+
)
|
|
151
|
+
if authorization:
|
|
152
|
+
if operator_override:
|
|
153
|
+
request.add_header("Authorization", authorization)
|
|
154
|
+
else:
|
|
155
|
+
request.add_unredirected_header("Authorization", authorization)
|
|
156
|
+
try:
|
|
157
|
+
with fleetfit_lookup_opener(url, settings).open(request, timeout=timeout) as response:
|
|
158
|
+
if not operator_override:
|
|
159
|
+
final = urlparse(response.geturl())
|
|
160
|
+
final_host = (final.hostname or "").lower()
|
|
161
|
+
if configured_host and final_host and final_host != configured_host:
|
|
162
|
+
raise LookupRedirectError(
|
|
163
|
+
f"{lookup_label} left the configured host"
|
|
164
|
+
)
|
|
165
|
+
if response.status and 300 <= response.status < 400:
|
|
166
|
+
raise LookupRedirectError(
|
|
167
|
+
f"{lookup_label} refused redirect response"
|
|
168
|
+
)
|
|
169
|
+
try:
|
|
170
|
+
raw = read_http_body_limited(response, LOOKUP_JSON_BODY_LIMIT)
|
|
171
|
+
except ValueError as exc:
|
|
172
|
+
raise ValueError(f"{lookup_label} response body too large") from exc
|
|
173
|
+
except LookupRedirectError:
|
|
174
|
+
raise
|
|
175
|
+
except urllib.error.HTTPError as exc:
|
|
176
|
+
if not operator_override and 300 <= exc.code < 400:
|
|
177
|
+
raise LookupRedirectError(
|
|
178
|
+
f"{lookup_label} refused redirect response"
|
|
179
|
+
) from exc
|
|
180
|
+
if exc.code == 401:
|
|
181
|
+
raise LookupUnauthorizedError(url, _unauthorized_payload(exc)) from exc
|
|
182
|
+
raise
|
|
183
|
+
except urllib.error.URLError as exc:
|
|
184
|
+
raise urllib.error.URLError(
|
|
185
|
+
lookup_network_error_message(
|
|
186
|
+
url,
|
|
187
|
+
exc,
|
|
188
|
+
lookup_label=lookup_label,
|
|
189
|
+
settings=settings,
|
|
190
|
+
)
|
|
191
|
+
) from exc
|
|
192
|
+
except TimeoutError as exc:
|
|
193
|
+
raise TimeoutError(
|
|
194
|
+
lookup_network_error_message(
|
|
195
|
+
url,
|
|
196
|
+
exc,
|
|
197
|
+
lookup_label=lookup_label,
|
|
198
|
+
settings=settings,
|
|
199
|
+
)
|
|
200
|
+
) from exc
|
|
201
|
+
try:
|
|
202
|
+
payload = json.loads(raw.decode("utf-8"))
|
|
203
|
+
except (UnicodeError, json.JSONDecodeError) as exc:
|
|
204
|
+
raise ValueError(f"{lookup_label} returned invalid JSON") from exc
|
|
205
|
+
if not isinstance(payload, dict):
|
|
206
|
+
raise ValueError(f"{lookup_label} response must be a JSON object")
|
|
207
|
+
return payload
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _host_from_url(url: str) -> str:
|
|
211
|
+
host = urlparse(url).hostname
|
|
212
|
+
return host if host else url
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _is_name_resolution_failure(reason: object) -> bool:
|
|
216
|
+
if isinstance(reason, socket.gaierror):
|
|
217
|
+
return True
|
|
218
|
+
if isinstance(reason, OSError):
|
|
219
|
+
errno = reason.errno
|
|
220
|
+
for code in (
|
|
221
|
+
getattr(socket, "EAI_NONAME", None),
|
|
222
|
+
getattr(socket, "EAI_AGAIN", None),
|
|
223
|
+
getattr(socket, "EAI_NODATA", None),
|
|
224
|
+
11001,
|
|
225
|
+
11002,
|
|
226
|
+
):
|
|
227
|
+
if code is not None and errno == code:
|
|
228
|
+
return True
|
|
229
|
+
return False
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _is_connection_failure(reason: object) -> bool:
|
|
233
|
+
if isinstance(reason, (ConnectionRefusedError, ConnectionResetError, BrokenPipeError)):
|
|
234
|
+
return True
|
|
235
|
+
if isinstance(reason, (TimeoutError, socket.timeout)):
|
|
236
|
+
return True
|
|
237
|
+
if isinstance(reason, OSError):
|
|
238
|
+
errno = reason.errno
|
|
239
|
+
for code in (
|
|
240
|
+
getattr(socket, "ECONNREFUSED", None),
|
|
241
|
+
getattr(socket, "ECONNRESET", None),
|
|
242
|
+
getattr(socket, "EHOSTUNREACH", None),
|
|
243
|
+
getattr(socket, "ENETUNREACH", None),
|
|
244
|
+
10061,
|
|
245
|
+
10065,
|
|
246
|
+
):
|
|
247
|
+
if code is not None and errno == code:
|
|
248
|
+
return True
|
|
249
|
+
return False
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _is_certificate_failure(reason: object) -> bool:
|
|
253
|
+
if isinstance(reason, ssl.SSLError):
|
|
254
|
+
return "CERTIFICATE_VERIFY_FAILED" in str(reason)
|
|
255
|
+
if isinstance(reason, urllib.error.URLError) and reason.reason is not None:
|
|
256
|
+
return _is_certificate_failure(reason.reason)
|
|
257
|
+
return "CERTIFICATE_VERIFY_FAILED" in str(reason)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def lookup_network_error_message(
|
|
261
|
+
url: str,
|
|
262
|
+
exc: BaseException,
|
|
263
|
+
*,
|
|
264
|
+
lookup_label: str,
|
|
265
|
+
settings: dict[str, Any] | None = None,
|
|
266
|
+
) -> str:
|
|
267
|
+
host = _host_from_url(url)
|
|
268
|
+
operator_override = fleetfit_request_uses_operator_override(url, settings)
|
|
269
|
+
if isinstance(exc, TimeoutError):
|
|
270
|
+
return f"{lookup_label} connection failed for {host}"
|
|
271
|
+
if isinstance(exc, urllib.error.URLError):
|
|
272
|
+
reason = exc.reason
|
|
273
|
+
if _is_name_resolution_failure(reason):
|
|
274
|
+
return f"{lookup_label} host name did not resolve: {host}"
|
|
275
|
+
if not operator_override and _is_certificate_failure(reason):
|
|
276
|
+
return f"{lookup_label} certificate verification failed for {host}"
|
|
277
|
+
if _is_connection_failure(reason):
|
|
278
|
+
return f"{lookup_label} connection failed for {host}"
|
|
279
|
+
return f"{lookup_label} connection failed for {host}"
|
|
280
|
+
return f"{lookup_label} connection failed for {host}"
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Human-readable metric values for operator-facing analyze output."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def format_human_metric(value: float) -> str:
|
|
9
|
+
"""Fixed decimals, thousands grouping, no scientific notation for typical magnitudes."""
|
|
10
|
+
if not math.isfinite(value):
|
|
11
|
+
return format(value, "f")
|
|
12
|
+
abs_value = abs(value)
|
|
13
|
+
if abs_value >= 1000:
|
|
14
|
+
rounded = round(value)
|
|
15
|
+
return f"{rounded:,}"
|
|
16
|
+
if abs_value >= 10:
|
|
17
|
+
text = f"{value:,.2f}".rstrip("0").rstrip(".")
|
|
18
|
+
return text if text else "0"
|
|
19
|
+
text = f"{value:.2f}".rstrip("0").rstrip(".")
|
|
20
|
+
return text if text else "0"
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""migration_method from instance attributes plus the spec table."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
METHOD_STOP = "stop-restart-on-new-type"
|
|
9
|
+
METHOD_OLD_AMI = "launch-old-ami"
|
|
10
|
+
METHOD_NEW_AMI = "new-instance-new-ami"
|
|
11
|
+
|
|
12
|
+
REASON_NVME = "the target needs NVMe boot and the current type does not"
|
|
13
|
+
REASON_HVM = "the instance is not HVM"
|
|
14
|
+
REASON_ENA = "ENA disabled"
|
|
15
|
+
REASON_ENA_UNREAD = "ENA was not read"
|
|
16
|
+
REASON_VIRT_UNREAD = "virtualization type was not read"
|
|
17
|
+
REASON_ROOT_UNREAD = "root device was not read"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class MigrationDecision:
|
|
22
|
+
method: str
|
|
23
|
+
reason: str | None = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
METHOD_JSON = {
|
|
27
|
+
METHOD_STOP: "stop_and_restart_on_new_type",
|
|
28
|
+
METHOD_OLD_AMI: "redeploy_same_ami",
|
|
29
|
+
METHOD_NEW_AMI: "redeploy_new_ami",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
REASON_JSON = {
|
|
33
|
+
REASON_NVME: "nvme_boot",
|
|
34
|
+
REASON_HVM: "not_hvm",
|
|
35
|
+
REASON_ENA: "ena_disabled",
|
|
36
|
+
REASON_ENA_UNREAD: "ena_not_read",
|
|
37
|
+
REASON_VIRT_UNREAD: "virtualization_not_read",
|
|
38
|
+
REASON_ROOT_UNREAD: "root_device_not_read",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def migration_method_human(decision: MigrationDecision) -> str:
|
|
43
|
+
if decision.method == METHOD_STOP:
|
|
44
|
+
line = "How to move: stop the instance, change the type, and start it."
|
|
45
|
+
elif decision.method == METHOD_OLD_AMI:
|
|
46
|
+
line = "How to move: launch a new instance from the existing image on the new type."
|
|
47
|
+
else:
|
|
48
|
+
line = "How to move: launch a new instance with a new image on the new type."
|
|
49
|
+
if decision.reason:
|
|
50
|
+
line = f"{line} ({decision.reason})"
|
|
51
|
+
return line
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def migration_json_codes(decision: MigrationDecision) -> tuple[str, str | None]:
|
|
55
|
+
"""JSON method and reason. Terminal strings stay on ``decision`` itself.
|
|
56
|
+
|
|
57
|
+
``migration_reason`` is null unless the method is ``redeploy_new_ami``.
|
|
58
|
+
"""
|
|
59
|
+
method = METHOD_JSON[decision.method]
|
|
60
|
+
if method != "redeploy_new_ami":
|
|
61
|
+
return method, None
|
|
62
|
+
if decision.reason is None:
|
|
63
|
+
return method, None
|
|
64
|
+
return method, REASON_JSON[decision.reason]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def decide_migration(
|
|
68
|
+
*,
|
|
69
|
+
current_nvme_boot: bool,
|
|
70
|
+
target_nvme_boot: bool,
|
|
71
|
+
target_ena_required: bool,
|
|
72
|
+
virtualization_type: str,
|
|
73
|
+
root_kind: str,
|
|
74
|
+
ena_enabled: bool | None,
|
|
75
|
+
ena_read_failed: bool = False,
|
|
76
|
+
) -> MigrationDecision:
|
|
77
|
+
"""Choose the method after a target has passed the safe-move boot bar.
|
|
78
|
+
|
|
79
|
+
The search drops a target that is not HVM, that needs ENA when ENA is off
|
|
80
|
+
or unread, or that uses NVMe when the current type does not. This function
|
|
81
|
+
labels the move that remains. An unread root device is a new AMI. An
|
|
82
|
+
instance-store root launches the existing image.
|
|
83
|
+
"""
|
|
84
|
+
if target_nvme_boot and not current_nvme_boot:
|
|
85
|
+
return MigrationDecision(METHOD_NEW_AMI, REASON_NVME)
|
|
86
|
+
|
|
87
|
+
virt = (virtualization_type or "").strip().lower()
|
|
88
|
+
if not virt:
|
|
89
|
+
return MigrationDecision(METHOD_NEW_AMI, REASON_VIRT_UNREAD)
|
|
90
|
+
if virt != "hvm":
|
|
91
|
+
return MigrationDecision(METHOD_NEW_AMI, REASON_HVM)
|
|
92
|
+
if target_ena_required and ena_read_failed:
|
|
93
|
+
return MigrationDecision(METHOD_NEW_AMI, REASON_ENA_UNREAD)
|
|
94
|
+
if target_ena_required and not ena_enabled:
|
|
95
|
+
return MigrationDecision(METHOD_NEW_AMI, REASON_ENA)
|
|
96
|
+
|
|
97
|
+
root = (root_kind or "").strip().lower().replace("_", "-")
|
|
98
|
+
if not root:
|
|
99
|
+
return MigrationDecision(METHOD_NEW_AMI, REASON_ROOT_UNREAD)
|
|
100
|
+
if root in {"instance-store", "instance store"}:
|
|
101
|
+
return MigrationDecision(METHOD_OLD_AMI)
|
|
102
|
+
if root == "ebs":
|
|
103
|
+
return MigrationDecision(METHOD_STOP)
|
|
104
|
+
return MigrationDecision(METHOD_NEW_AMI, REASON_HVM)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def azure_root_kind(vm: dict[str, Any]) -> str:
|
|
108
|
+
"""Ephemeral OS disk is the instance-store branch. A managed disk is the ebs branch."""
|
|
109
|
+
storage = vm.get("storageProfile") if isinstance(vm.get("storageProfile"), dict) else {}
|
|
110
|
+
os_disk = storage.get("osDisk") if isinstance(storage, dict) else {}
|
|
111
|
+
if isinstance(os_disk, dict) and os_disk.get("diffDiskSettings"):
|
|
112
|
+
return "instance-store"
|
|
113
|
+
return "ebs"
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def azure_primary_nic_id(vm: dict[str, Any]) -> str:
|
|
117
|
+
network = vm.get("networkProfile") if isinstance(vm.get("networkProfile"), dict) else {}
|
|
118
|
+
nics = network.get("networkInterfaces") if isinstance(network, dict) else None
|
|
119
|
+
if not isinstance(nics, list):
|
|
120
|
+
return ""
|
|
121
|
+
primary = ""
|
|
122
|
+
for nic in nics:
|
|
123
|
+
if not isinstance(nic, dict):
|
|
124
|
+
continue
|
|
125
|
+
nic_id = str(nic.get("id") or "").strip()
|
|
126
|
+
if nic.get("primary") is True and nic_id:
|
|
127
|
+
return nic_id
|
|
128
|
+
if nic_id and not primary:
|
|
129
|
+
primary = nic_id
|
|
130
|
+
return primary
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Optional MAPROOM_MOVE_LIST overrides for analyze candidate filtering.
|
|
2
|
+
|
|
3
|
+
Legacy JSONL rows use cpu, disk, and network (confirmed or unknown). A shipped
|
|
4
|
+
safe-moves-v1.json (schema version 2) lists targets by source in ``moves``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Mapping
|
|
12
|
+
|
|
13
|
+
MOVE_FIELDS = frozenset({"cloud", "source", "target", "cpu", "disk", "network"})
|
|
14
|
+
DIMENSIONS = ("cpu", "disk", "network")
|
|
15
|
+
STATUSES = frozenset({"confirmed", "unknown"})
|
|
16
|
+
CLOUDS = frozenset({"aws", "azure"})
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def move_target(row: object, source: str) -> str | None:
|
|
20
|
+
"""Return the target when this row is a published move from source."""
|
|
21
|
+
|
|
22
|
+
if not isinstance(row, Mapping):
|
|
23
|
+
return None
|
|
24
|
+
if set(row) != MOVE_FIELDS:
|
|
25
|
+
return None
|
|
26
|
+
if str(row.get("source") or "") != source:
|
|
27
|
+
return None
|
|
28
|
+
cloud = str(row.get("cloud") or "")
|
|
29
|
+
target = str(row.get("target") or "").strip()
|
|
30
|
+
if cloud not in CLOUDS or not target or target == source:
|
|
31
|
+
return None
|
|
32
|
+
for name in DIMENSIONS:
|
|
33
|
+
if row.get(name) not in STATUSES:
|
|
34
|
+
return None
|
|
35
|
+
if not any(row.get(name) == "confirmed" for name in DIMENSIONS):
|
|
36
|
+
return None
|
|
37
|
+
return target
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def require_move(row: Any) -> dict[str, str]:
|
|
41
|
+
"""Return one share move, or raise when the row is not that shape."""
|
|
42
|
+
|
|
43
|
+
if not isinstance(row, Mapping) or set(row) != MOVE_FIELDS:
|
|
44
|
+
raise ValueError("safe move row is not the closed key set")
|
|
45
|
+
cloud = str(row.get("cloud") or "")
|
|
46
|
+
source = str(row.get("source") or "").strip()
|
|
47
|
+
target = str(row.get("target") or "").strip()
|
|
48
|
+
if cloud not in CLOUDS or not source or not target or source == target:
|
|
49
|
+
raise ValueError("safe move row is missing cloud, source, or target")
|
|
50
|
+
cleaned = {"cloud": cloud, "source": source, "target": target}
|
|
51
|
+
for name in DIMENSIONS:
|
|
52
|
+
status = row.get(name)
|
|
53
|
+
if status not in STATUSES:
|
|
54
|
+
raise ValueError(f"safe move {name} must be confirmed or unknown")
|
|
55
|
+
cleaned[name] = str(status)
|
|
56
|
+
if not any(cleaned[name] == "confirmed" for name in DIMENSIONS):
|
|
57
|
+
raise ValueError("safe move has no confirmed dimension")
|
|
58
|
+
if move_target(cleaned, source) != target:
|
|
59
|
+
raise ValueError("safe move row is not a published move")
|
|
60
|
+
return cleaned
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def targets_for_source(path: Path, instance_type: str) -> set[str]:
|
|
64
|
+
"""Return target types for ``instance_type`` from a move-list path."""
|
|
65
|
+
|
|
66
|
+
source = instance_type.strip()
|
|
67
|
+
if not source:
|
|
68
|
+
return set()
|
|
69
|
+
if path.suffix.lower() == ".json":
|
|
70
|
+
document = json.loads(path.read_text(encoding="utf-8"))
|
|
71
|
+
if isinstance(document, dict) and document.get("schema_version") == 2:
|
|
72
|
+
moves = document.get("moves")
|
|
73
|
+
if not isinstance(moves, list):
|
|
74
|
+
return set()
|
|
75
|
+
targets: set[str] = set()
|
|
76
|
+
for row in moves:
|
|
77
|
+
if not isinstance(row, Mapping):
|
|
78
|
+
continue
|
|
79
|
+
if str(row.get("source") or "").strip() != source:
|
|
80
|
+
continue
|
|
81
|
+
target = str(row.get("target") or "").strip()
|
|
82
|
+
if target and target != source:
|
|
83
|
+
targets.add(target)
|
|
84
|
+
return targets
|
|
85
|
+
targets = set()
|
|
86
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
87
|
+
if not line.strip():
|
|
88
|
+
continue
|
|
89
|
+
row = json.loads(line)
|
|
90
|
+
target = move_target(row, source)
|
|
91
|
+
if target:
|
|
92
|
+
targets.add(target)
|
|
93
|
+
return targets
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""One anonymized account context before per-instance inspect."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from maproom.analyze.account_cloudtrail import (
|
|
9
|
+
LaunchAttemptCounts,
|
|
10
|
+
SpotHistoryCounts,
|
|
11
|
+
collect_account_cloudtrail,
|
|
12
|
+
)
|
|
13
|
+
from maproom.analyze.account_quota_requests import QuotaRequestCounts, collect_account_quota_requests
|
|
14
|
+
from maproom.analyze.context_client import ContextLookupError, context_destination, post_operator_context
|
|
15
|
+
from maproom.analyze.context_lookup import build_operator_context_body
|
|
16
|
+
from maproom.consent import require_service_upload_consent
|
|
17
|
+
from maproom.paths import settings_read_file
|
|
18
|
+
from maproom.settings.model import load_effective_settings, product_version as settings_product_version
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class OperatorContextRun:
|
|
23
|
+
upload_allowed: bool
|
|
24
|
+
destination: bool
|
|
25
|
+
settings: dict[str, Any]
|
|
26
|
+
context_id: str | None = None
|
|
27
|
+
attempted: bool = False
|
|
28
|
+
upload_reason: str | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def sections_enabled(product_version: int) -> bool:
|
|
32
|
+
return product_version >= 3
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def prepare_operator_context_run(
|
|
36
|
+
args: Any,
|
|
37
|
+
*,
|
|
38
|
+
as_json: bool,
|
|
39
|
+
cloud: str,
|
|
40
|
+
) -> OperatorContextRun | None:
|
|
41
|
+
version = settings_product_version()
|
|
42
|
+
if cloud not in ("aws", "azure") or version < 3:
|
|
43
|
+
return None
|
|
44
|
+
settings, _ = load_effective_settings(settings_read_file())
|
|
45
|
+
if bool(getattr(args, "local_only", False)):
|
|
46
|
+
return OperatorContextRun(
|
|
47
|
+
upload_allowed=False,
|
|
48
|
+
destination=context_destination(settings),
|
|
49
|
+
settings=settings,
|
|
50
|
+
upload_reason="local_only",
|
|
51
|
+
)
|
|
52
|
+
if not sections_enabled(version):
|
|
53
|
+
return OperatorContextRun(
|
|
54
|
+
upload_allowed=False,
|
|
55
|
+
destination=context_destination(settings),
|
|
56
|
+
settings=settings,
|
|
57
|
+
)
|
|
58
|
+
gate = require_service_upload_consent(
|
|
59
|
+
consent_fleetfit_recommendations=bool(
|
|
60
|
+
getattr(args, "consent_fleetfit_recommendations", False)
|
|
61
|
+
),
|
|
62
|
+
quiet=as_json,
|
|
63
|
+
)
|
|
64
|
+
allowed = bool(gate.upload_allowed) and gate.exit_code == 0
|
|
65
|
+
if allowed:
|
|
66
|
+
settings, _ = load_effective_settings(settings_read_file())
|
|
67
|
+
return OperatorContextRun(
|
|
68
|
+
upload_allowed=allowed,
|
|
69
|
+
destination=context_destination(settings),
|
|
70
|
+
settings=settings,
|
|
71
|
+
upload_reason=gate.reason_code,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _regions_from_items(items: list[Any], cloud: str) -> set[str]:
|
|
76
|
+
return {
|
|
77
|
+
str(item.region).strip().lower()
|
|
78
|
+
for item in items
|
|
79
|
+
if getattr(item, "cloud", "") == cloud and str(getattr(item, "region", "")).strip()
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def run_operator_context_phase(
|
|
84
|
+
ctx: Any,
|
|
85
|
+
*,
|
|
86
|
+
reservation_records: tuple[dict[str, Any], ...] | list[dict[str, Any]] | None = None,
|
|
87
|
+
) -> None:
|
|
88
|
+
run = getattr(ctx, "operator_context_run", None)
|
|
89
|
+
if run is None:
|
|
90
|
+
return
|
|
91
|
+
if not ctx.items:
|
|
92
|
+
return
|
|
93
|
+
version = settings_product_version()
|
|
94
|
+
if not sections_enabled(version):
|
|
95
|
+
return
|
|
96
|
+
if not run.upload_allowed or not run.destination:
|
|
97
|
+
return
|
|
98
|
+
cloud = str(getattr(ctx, "cloud", "aws") or "aws").strip().lower()
|
|
99
|
+
regions = _regions_from_items(ctx.items, cloud)
|
|
100
|
+
if not regions:
|
|
101
|
+
return
|
|
102
|
+
spot: SpotHistoryCounts | None = None
|
|
103
|
+
launches: LaunchAttemptCounts | None = None
|
|
104
|
+
quota_requests: QuotaRequestCounts | None = None
|
|
105
|
+
if version >= 3:
|
|
106
|
+
if cloud == "azure":
|
|
107
|
+
from maproom.analyze.account_azure_activity import collect_account_azure_activity
|
|
108
|
+
|
|
109
|
+
spot, launches = collect_account_azure_activity(
|
|
110
|
+
ctx.runner, regions, now=ctx.started_at
|
|
111
|
+
)
|
|
112
|
+
else:
|
|
113
|
+
spot, launches = collect_account_cloudtrail(ctx.runner, regions, now=ctx.started_at)
|
|
114
|
+
if version >= 6:
|
|
115
|
+
if cloud == "azure":
|
|
116
|
+
from maproom.analyze.account_azure_quota_requests import (
|
|
117
|
+
collect_account_azure_quota_requests,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
quota_requests = collect_account_azure_quota_requests(
|
|
121
|
+
ctx.runner, regions, now=ctx.started_at
|
|
122
|
+
)
|
|
123
|
+
else:
|
|
124
|
+
quota_requests = collect_account_quota_requests(
|
|
125
|
+
ctx.runner, regions, now=ctx.started_at
|
|
126
|
+
)
|
|
127
|
+
body = build_operator_context_body(
|
|
128
|
+
product_version=version,
|
|
129
|
+
spot=spot,
|
|
130
|
+
launches=launches,
|
|
131
|
+
reservation_records=reservation_records if version >= 5 else None,
|
|
132
|
+
quota_requests=quota_requests if version >= 6 else None,
|
|
133
|
+
provider=cloud,
|
|
134
|
+
)
|
|
135
|
+
if not body.get("sections"):
|
|
136
|
+
return
|
|
137
|
+
run.attempted = True
|
|
138
|
+
try:
|
|
139
|
+
run.context_id = post_operator_context(body, run.settings)
|
|
140
|
+
except ContextLookupError as exc:
|
|
141
|
+
_record_context_warning(ctx, str(exc))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _record_context_warning(ctx: Any, message: str) -> None:
|
|
145
|
+
if getattr(ctx, "operator_context_warned", False):
|
|
146
|
+
return
|
|
147
|
+
ctx.operator_context_warned = True
|
|
148
|
+
text = f"Operator context was not set: {message}"
|
|
149
|
+
if ctx.as_json:
|
|
150
|
+
from maproom.output.json_envelope import warning_item
|
|
151
|
+
|
|
152
|
+
ctx.warnings.append(warning_item("operator_context_failed", text))
|
|
153
|
+
else:
|
|
154
|
+
from maproom.analyze.workset import note_progress
|
|
155
|
+
|
|
156
|
+
note_progress(text)
|