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,883 @@
|
|
|
1
|
+
"""Product version 2: consented same-type size lookup (remote downsize and upsize)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import datetime, timedelta, timezone
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from maproom.analyze.catalog import SpecRow, spec_architecture
|
|
14
|
+
from maproom.analyze.fleetfit_policy import fleetfit_policy_accept_hint
|
|
15
|
+
from maproom.analyze.change_detection import (
|
|
16
|
+
_pairs_from_metric_row,
|
|
17
|
+
detect_instance_type_change,
|
|
18
|
+
)
|
|
19
|
+
from maproom.analyze.size_keep import (
|
|
20
|
+
evaluate_size_keep,
|
|
21
|
+
harvest_running_instance_facts,
|
|
22
|
+
instance_type_excluded_from_size_tryfirst,
|
|
23
|
+
target_modify_limits_from_spec,
|
|
24
|
+
)
|
|
25
|
+
from maproom.analyze.size_lookup import (
|
|
26
|
+
DECLINED_LINE,
|
|
27
|
+
INCOMPLETE_LINE,
|
|
28
|
+
NOT_SENT_LINE,
|
|
29
|
+
build_size_body,
|
|
30
|
+
downsize_on_cooldown,
|
|
31
|
+
format_size_downsize_hold,
|
|
32
|
+
format_size_result,
|
|
33
|
+
)
|
|
34
|
+
from maproom.analyze.spot_analyze import is_spot_instance
|
|
35
|
+
from maproom.analyze.utilization import (
|
|
36
|
+
METRIC_NAMES,
|
|
37
|
+
SAMPLE_PERIOD_MINUTES,
|
|
38
|
+
_iso_z,
|
|
39
|
+
build_size_metric_argv,
|
|
40
|
+
p99_from_values,
|
|
41
|
+
sum_aligned_rates,
|
|
42
|
+
utilization_window,
|
|
43
|
+
)
|
|
44
|
+
from maproom.analyze.metric_format import format_human_metric
|
|
45
|
+
from maproom.analyze.workset import WorkItem
|
|
46
|
+
from maproom.consent import require_service_upload_consent
|
|
47
|
+
from maproom.errors import AccessDeniedError, MaproomParseError
|
|
48
|
+
from maproom.parsers import parse_cloudwatch_get_metric_data, parse_ec2_describe_instances
|
|
49
|
+
from maproom.paths import settings_read_file
|
|
50
|
+
from maproom.redaction import redact_text
|
|
51
|
+
from maproom.settings.model import load_effective_settings
|
|
52
|
+
|
|
53
|
+
from maproom.analyze.spot_analyze import spot_destination
|
|
54
|
+
|
|
55
|
+
MISSING_POLICY_LINE = (
|
|
56
|
+
"The size lookup was not sent: the FleetFit handling policy is not accepted. "
|
|
57
|
+
+ fleetfit_policy_accept_hint()
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
_SIZE_CONN_PREFIX = "size lookup connection failed for "
|
|
61
|
+
_SIZE_RESOLVE_PREFIX = "size lookup host name did not resolve: "
|
|
62
|
+
_SIZE_METRIC_QUERY_COUNT = 10
|
|
63
|
+
_CLOUDWATCH_MAX_DATAPOINTS = 100_800
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def size_unreachable_banner(network_message: str) -> str:
|
|
67
|
+
"""One run-level line when the size host cannot be reached."""
|
|
68
|
+
if network_message.startswith(_SIZE_CONN_PREFIX):
|
|
69
|
+
host = network_message[len(_SIZE_CONN_PREFIX) :].strip()
|
|
70
|
+
return f"Could not reach {host}, so the size lookup did not run."
|
|
71
|
+
if network_message.startswith(_SIZE_RESOLVE_PREFIX):
|
|
72
|
+
host = network_message[len(_SIZE_RESOLVE_PREFIX) :].strip()
|
|
73
|
+
return f"Could not reach {host}, so the size lookup did not run."
|
|
74
|
+
return "Could not reach the size lookup host, so the size lookup did not run."
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _size_lookup_network_failure(message: str) -> bool:
|
|
78
|
+
return message.startswith(_SIZE_CONN_PREFIX) or message.startswith(
|
|
79
|
+
_SIZE_RESOLVE_PREFIX
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class SizeRun:
|
|
85
|
+
upload_allowed: bool
|
|
86
|
+
destination: bool
|
|
87
|
+
settings: dict[str, Any]
|
|
88
|
+
upload_reason: str | None = None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(frozen=True)
|
|
92
|
+
class ServiceUploadRun:
|
|
93
|
+
upload_allowed: bool
|
|
94
|
+
settings: dict[str, Any]
|
|
95
|
+
spot_destination: bool
|
|
96
|
+
size_destination: bool
|
|
97
|
+
cover_destination: bool
|
|
98
|
+
series_destination: bool = False
|
|
99
|
+
quota_destination: bool = False
|
|
100
|
+
upload_reason: str | None = None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def size_destination(settings: dict[str, Any] | None) -> bool:
|
|
104
|
+
"""True when the size lookup URL resolves or the fixture is set."""
|
|
105
|
+
from maproom.analyze.size_client import resolve_size_lookup_url
|
|
106
|
+
|
|
107
|
+
if os.environ.get("MAPROOM_SIZE_FIXTURE", "").strip():
|
|
108
|
+
return True
|
|
109
|
+
return resolve_size_lookup_url(settings) is not None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def size_applies_to(item: WorkItem) -> bool:
|
|
113
|
+
if item.cloud != "aws":
|
|
114
|
+
return False
|
|
115
|
+
if is_spot_instance(item):
|
|
116
|
+
return False
|
|
117
|
+
lifecycle = item.lifecycle.strip().lower()
|
|
118
|
+
if lifecycle not in ("", "standard"):
|
|
119
|
+
return False
|
|
120
|
+
return not instance_type_excluded_from_size_tryfirst(item.instance_type)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def size_description_ready(item: WorkItem, specs: dict[tuple[str, str], SpecRow]) -> bool:
|
|
124
|
+
if not size_applies_to(item):
|
|
125
|
+
return False
|
|
126
|
+
if not item.region.strip() or not item.instance_type.strip():
|
|
127
|
+
return False
|
|
128
|
+
row = specs.get((item.cloud, item.instance_type))
|
|
129
|
+
if row is None:
|
|
130
|
+
return False
|
|
131
|
+
if not (row.quota_family or "").strip():
|
|
132
|
+
return False
|
|
133
|
+
return spec_architecture(row) is not None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def prepare_service_upload_run(
|
|
137
|
+
items: list[WorkItem],
|
|
138
|
+
args: Any,
|
|
139
|
+
*,
|
|
140
|
+
as_json: bool,
|
|
141
|
+
spot_enabled: bool,
|
|
142
|
+
size_enabled: bool,
|
|
143
|
+
cover_enabled: bool = False,
|
|
144
|
+
series_enabled: bool = False,
|
|
145
|
+
quota_enabled: bool = False,
|
|
146
|
+
specs: dict[tuple[str, str], SpecRow],
|
|
147
|
+
) -> ServiceUploadRun:
|
|
148
|
+
from maproom.analyze.cover_client import cover_destination as _cover_destination
|
|
149
|
+
from maproom.analyze.quota_client import quota_destination as _quota_destination
|
|
150
|
+
from maproom.analyze.safe_moves_client import safe_moves_destination as _safe_moves_destination
|
|
151
|
+
from maproom.analyze.series_analyze import series_description_ready
|
|
152
|
+
from maproom.analyze.series_client import series_destination as _series_destination
|
|
153
|
+
|
|
154
|
+
settings, _ = load_effective_settings(settings_read_file())
|
|
155
|
+
if bool(getattr(args, "local_only", False)):
|
|
156
|
+
return ServiceUploadRun(
|
|
157
|
+
upload_allowed=False,
|
|
158
|
+
settings=settings,
|
|
159
|
+
spot_destination=spot_destination(settings),
|
|
160
|
+
size_destination=size_destination(settings),
|
|
161
|
+
cover_destination=_cover_destination(settings),
|
|
162
|
+
series_destination=_series_destination(settings),
|
|
163
|
+
quota_destination=_quota_destination(settings),
|
|
164
|
+
upload_reason="local_only",
|
|
165
|
+
)
|
|
166
|
+
spot_ready = spot_enabled and any(
|
|
167
|
+
_spot_description_ready(item) for item in items
|
|
168
|
+
)
|
|
169
|
+
size_ready = size_enabled and any(
|
|
170
|
+
size_description_ready(item, specs) for item in items
|
|
171
|
+
)
|
|
172
|
+
cover_ready = cover_enabled and _safe_moves_destination(settings) and any(
|
|
173
|
+
item.cloud in ("aws", "azure") for item in items
|
|
174
|
+
)
|
|
175
|
+
series_ready = series_enabled and any(
|
|
176
|
+
series_description_ready(item, specs) for item in items
|
|
177
|
+
)
|
|
178
|
+
quota_ready = quota_enabled and series_ready and _quota_destination(settings)
|
|
179
|
+
if not spot_ready and not size_ready and not cover_ready and not series_ready and not quota_ready:
|
|
180
|
+
return ServiceUploadRun(
|
|
181
|
+
False,
|
|
182
|
+
settings,
|
|
183
|
+
spot_destination(settings),
|
|
184
|
+
size_destination(settings),
|
|
185
|
+
_cover_destination(settings),
|
|
186
|
+
_series_destination(settings),
|
|
187
|
+
_quota_destination(settings),
|
|
188
|
+
)
|
|
189
|
+
gate = require_service_upload_consent(
|
|
190
|
+
consent_fleetfit_recommendations=bool(
|
|
191
|
+
getattr(args, "consent_fleetfit_recommendations", False)
|
|
192
|
+
),
|
|
193
|
+
quiet=as_json,
|
|
194
|
+
)
|
|
195
|
+
allowed = bool(gate.upload_allowed) and gate.exit_code == 0
|
|
196
|
+
if allowed:
|
|
197
|
+
settings, _ = load_effective_settings(settings_read_file())
|
|
198
|
+
return ServiceUploadRun(
|
|
199
|
+
upload_allowed=allowed,
|
|
200
|
+
settings=settings,
|
|
201
|
+
spot_destination=spot_destination(settings),
|
|
202
|
+
size_destination=size_destination(settings),
|
|
203
|
+
cover_destination=_cover_destination(settings),
|
|
204
|
+
series_destination=_series_destination(settings),
|
|
205
|
+
quota_destination=_quota_destination(settings),
|
|
206
|
+
upload_reason=gate.reason_code,
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def prepare_spot_run_from_service(run: ServiceUploadRun) -> Any:
|
|
211
|
+
from maproom.analyze.spot_analyze import SpotRun
|
|
212
|
+
|
|
213
|
+
return SpotRun(
|
|
214
|
+
run.upload_allowed,
|
|
215
|
+
run.spot_destination,
|
|
216
|
+
run.settings,
|
|
217
|
+
upload_reason=run.upload_reason,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def prepare_size_run_from_service(run: ServiceUploadRun) -> SizeRun:
|
|
222
|
+
return SizeRun(
|
|
223
|
+
run.upload_allowed,
|
|
224
|
+
run.size_destination,
|
|
225
|
+
run.settings,
|
|
226
|
+
upload_reason=run.upload_reason,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def apply_size_lookup(
|
|
231
|
+
item: WorkItem,
|
|
232
|
+
assessment: Any,
|
|
233
|
+
*,
|
|
234
|
+
run: SizeRun,
|
|
235
|
+
runner: Any,
|
|
236
|
+
specs: dict[tuple[str, str], SpecRow],
|
|
237
|
+
as_json: bool,
|
|
238
|
+
now_utc: Any = None,
|
|
239
|
+
run_banners: Any | None = None,
|
|
240
|
+
recommend_envelope: dict[str, Any] | None = None,
|
|
241
|
+
attach_only: bool = False,
|
|
242
|
+
) -> None:
|
|
243
|
+
if not size_applies_to(item):
|
|
244
|
+
return
|
|
245
|
+
response_override: dict[str, Any] | None = None
|
|
246
|
+
if attach_only and recommend_envelope is not None:
|
|
247
|
+
from maproom.analyze.recommend_client import KIND_SIZE, RecommendError, unwrap_kind_section
|
|
248
|
+
|
|
249
|
+
try:
|
|
250
|
+
response_override = unwrap_kind_section(
|
|
251
|
+
recommend_envelope,
|
|
252
|
+
kind=KIND_SIZE,
|
|
253
|
+
restore_request_type=False,
|
|
254
|
+
)
|
|
255
|
+
except RecommendError:
|
|
256
|
+
response_override = None
|
|
257
|
+
extra, payload = _size_outcome(
|
|
258
|
+
item,
|
|
259
|
+
run=run,
|
|
260
|
+
runner=runner,
|
|
261
|
+
specs=specs,
|
|
262
|
+
as_json=as_json,
|
|
263
|
+
now_utc=now_utc,
|
|
264
|
+
run_banners=run_banners,
|
|
265
|
+
response_override=response_override,
|
|
266
|
+
)
|
|
267
|
+
if extra:
|
|
268
|
+
if (
|
|
269
|
+
run_banners is not None
|
|
270
|
+
and payload is not None
|
|
271
|
+
and payload.get("status") == "missing_policy"
|
|
272
|
+
):
|
|
273
|
+
run_banners.size_missing_policy = True
|
|
274
|
+
else:
|
|
275
|
+
assessment.text = f"{assessment.text}\n{extra}" if assessment.text else extra
|
|
276
|
+
if payload is None:
|
|
277
|
+
return
|
|
278
|
+
row = assessment.examined if assessment.recommendation is None else assessment.recommendation
|
|
279
|
+
if assessment.recommendation is not None:
|
|
280
|
+
assessment.recommendation["size_lookup"] = payload
|
|
281
|
+
elif assessment.examined is not None:
|
|
282
|
+
assessment.examined["size_lookup"] = payload
|
|
283
|
+
if not extra and isinstance(payload, dict) and payload.get("omitted"):
|
|
284
|
+
from maproom.analyze.safe_analyze import (
|
|
285
|
+
NO_RECOMMENDATION_HEADLINE,
|
|
286
|
+
interactive_conclusion,
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
if interactive_conclusion(item, assessment.text).strip() == NO_RECOMMENDATION_HEADLINE:
|
|
290
|
+
assessment.text = ""
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _spot_description_ready(item: WorkItem) -> bool:
|
|
294
|
+
from maproom.analyze.spot_analyze import is_spot_instance as _is_spot
|
|
295
|
+
|
|
296
|
+
if not _is_spot(item):
|
|
297
|
+
return False
|
|
298
|
+
return bool(
|
|
299
|
+
item.region.strip()
|
|
300
|
+
and item.availability_zone.strip()
|
|
301
|
+
and item.instance_type.strip()
|
|
302
|
+
and item.platform.strip()
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _size_outcome(
|
|
307
|
+
item: WorkItem,
|
|
308
|
+
*,
|
|
309
|
+
run: SizeRun,
|
|
310
|
+
runner: Any,
|
|
311
|
+
specs: dict[tuple[str, str], SpecRow],
|
|
312
|
+
as_json: bool,
|
|
313
|
+
now_utc: Any,
|
|
314
|
+
run_banners: Any | None = None,
|
|
315
|
+
response_override: dict[str, Any] | None = None,
|
|
316
|
+
) -> tuple[str, dict[str, Any] | None]:
|
|
317
|
+
current = specs.get((item.cloud, item.instance_type))
|
|
318
|
+
if current is None or not item.region.strip() or not item.instance_type.strip():
|
|
319
|
+
return INCOMPLETE_LINE, _payload(status="incomplete", window_trimmed=False)
|
|
320
|
+
architecture = spec_architecture(current)
|
|
321
|
+
quota_family = (current.quota_family or "").strip()
|
|
322
|
+
if not architecture or not quota_family:
|
|
323
|
+
return INCOMPLETE_LINE, _payload(status="incomplete", window_trimmed=False)
|
|
324
|
+
if not run.upload_allowed:
|
|
325
|
+
if run.upload_reason == "upload_missing_policy":
|
|
326
|
+
return MISSING_POLICY_LINE, _payload(status="missing_policy", window_trimmed=False)
|
|
327
|
+
return DECLINED_LINE, _payload(status="declined", window_trimmed=False)
|
|
328
|
+
if not run.destination:
|
|
329
|
+
return NOT_SENT_LINE, _payload(status="not_sent", window_trimmed=False)
|
|
330
|
+
if run_banners is not None and (
|
|
331
|
+
run_banners.size_unreachable_line is not None
|
|
332
|
+
or run_banners.recommend_unreachable_line is not None
|
|
333
|
+
):
|
|
334
|
+
return "", _payload(status="error", window_trimmed=False)
|
|
335
|
+
|
|
336
|
+
readings, window_trimmed, sample_minutes, change, period_minutes = _trimmed_readings(
|
|
337
|
+
item, runner=runner, now_utc=now_utc
|
|
338
|
+
)
|
|
339
|
+
if readings.get("cpu") is None:
|
|
340
|
+
return INCOMPLETE_LINE, _payload(
|
|
341
|
+
status="incomplete",
|
|
342
|
+
window_trimmed=window_trimmed,
|
|
343
|
+
metric_readings=_metric_readings_for_payload(readings),
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
from maproom.analyze.size_client import SizeLookupError, post_size_lookup
|
|
347
|
+
desired = _desired_cpu_p99(run.settings)
|
|
348
|
+
if desired is None:
|
|
349
|
+
return INCOMPLETE_LINE, _payload(
|
|
350
|
+
status="incomplete",
|
|
351
|
+
window_trimmed=window_trimmed,
|
|
352
|
+
metric_readings=_metric_readings_for_payload(readings),
|
|
353
|
+
)
|
|
354
|
+
metric_snapshot = _metric_readings_for_payload(readings)
|
|
355
|
+
body = build_size_body(
|
|
356
|
+
region=item.region.strip(),
|
|
357
|
+
instance=item.instance_type.strip(),
|
|
358
|
+
architecture=architecture,
|
|
359
|
+
quota_family=quota_family,
|
|
360
|
+
sample_minutes=sample_minutes,
|
|
361
|
+
window_trimmed=window_trimmed,
|
|
362
|
+
desired_cpu_p99=desired,
|
|
363
|
+
readings=readings,
|
|
364
|
+
period_minutes=period_minutes,
|
|
365
|
+
)
|
|
366
|
+
try:
|
|
367
|
+
if response_override is not None:
|
|
368
|
+
response = response_override
|
|
369
|
+
else:
|
|
370
|
+
response = post_size_lookup(body, _settings_for_post(run.settings))
|
|
371
|
+
except SizeLookupError as exc:
|
|
372
|
+
message = str(exc)
|
|
373
|
+
if _size_lookup_network_failure(message):
|
|
374
|
+
if run_banners is not None:
|
|
375
|
+
if run_banners.size_unreachable_line is None:
|
|
376
|
+
run_banners.size_unreachable_line = size_unreachable_banner(message)
|
|
377
|
+
return "", _payload(
|
|
378
|
+
status="error",
|
|
379
|
+
window_trimmed=window_trimmed,
|
|
380
|
+
metric_readings=metric_snapshot,
|
|
381
|
+
)
|
|
382
|
+
warning = f"warning: Size lookup failed: {redact_text(message)}"
|
|
383
|
+
if as_json:
|
|
384
|
+
print(warning, file=sys.stderr)
|
|
385
|
+
return warning, _payload(
|
|
386
|
+
status="error",
|
|
387
|
+
window_trimmed=window_trimmed,
|
|
388
|
+
metric_readings=metric_snapshot,
|
|
389
|
+
)
|
|
390
|
+
if response is None:
|
|
391
|
+
return "", None
|
|
392
|
+
trim_suffix_at = change.changed_at if window_trimmed else None
|
|
393
|
+
now = (now_utc or (lambda: datetime.now(timezone.utc)))()
|
|
394
|
+
from maproom.analyze.engine import engine_settings_from_mapping
|
|
395
|
+
|
|
396
|
+
min_days = engine_settings_from_mapping(run.settings).min_days_since_change
|
|
397
|
+
cooldown_active = change.cooldown_active(now, min_days)
|
|
398
|
+
target_type_raw = response.get("recommended_instance_type")
|
|
399
|
+
target_type = target_type_raw.strip() if isinstance(target_type_raw, str) else ""
|
|
400
|
+
target = specs.get((item.cloud, target_type)) if target_type else None
|
|
401
|
+
if target is not None and downsize_on_cooldown(
|
|
402
|
+
current,
|
|
403
|
+
target,
|
|
404
|
+
cooldown_active=cooldown_active,
|
|
405
|
+
):
|
|
406
|
+
hold_until = change.cooldown_until(now, min_days)
|
|
407
|
+
if hold_until is None:
|
|
408
|
+
hold_until = now
|
|
409
|
+
hold_line = format_size_downsize_hold(
|
|
410
|
+
target_type=target_type,
|
|
411
|
+
min_days_since_change=min_days,
|
|
412
|
+
hold_until=hold_until,
|
|
413
|
+
)
|
|
414
|
+
return hold_line, _payload(
|
|
415
|
+
status="returned",
|
|
416
|
+
window_trimmed=window_trimmed,
|
|
417
|
+
instance_type=target_type,
|
|
418
|
+
explanation=hold_line,
|
|
419
|
+
omitted=True,
|
|
420
|
+
cpu_p99=readings.get("cpu"),
|
|
421
|
+
desired_cpu_p99=desired,
|
|
422
|
+
sample_minutes=sample_minutes,
|
|
423
|
+
metric_readings=metric_snapshot,
|
|
424
|
+
)
|
|
425
|
+
running_facts = harvest_running_instance_facts(_describe_instance(item, runner))
|
|
426
|
+
desired_memory = _desired_memory_p99(run.settings)
|
|
427
|
+
target_limits = None
|
|
428
|
+
keep_verdict = None
|
|
429
|
+
if target is not None and target_type:
|
|
430
|
+
target_limits = target_modify_limits_from_spec(target)
|
|
431
|
+
keep_verdict = evaluate_size_keep(
|
|
432
|
+
current=current,
|
|
433
|
+
target=target,
|
|
434
|
+
target_type=target_type,
|
|
435
|
+
readings=readings,
|
|
436
|
+
desired_memory_p99=desired_memory,
|
|
437
|
+
running=running_facts,
|
|
438
|
+
target_limits=target_limits,
|
|
439
|
+
require_modify_facts=True,
|
|
440
|
+
)
|
|
441
|
+
if keep_verdict.withhold:
|
|
442
|
+
return keep_verdict.withhold, _payload(
|
|
443
|
+
status="returned",
|
|
444
|
+
window_trimmed=window_trimmed,
|
|
445
|
+
instance_type=target_type,
|
|
446
|
+
explanation=keep_verdict.withhold,
|
|
447
|
+
omitted=True,
|
|
448
|
+
cpu_p99=readings.get("cpu"),
|
|
449
|
+
desired_cpu_p99=desired,
|
|
450
|
+
sample_minutes=sample_minutes,
|
|
451
|
+
metric_readings=metric_snapshot,
|
|
452
|
+
)
|
|
453
|
+
keep_extra = keep_verdict.extra_lines if keep_verdict is not None else ()
|
|
454
|
+
line = format_size_result(
|
|
455
|
+
response,
|
|
456
|
+
current=current,
|
|
457
|
+
specs=specs,
|
|
458
|
+
window_trimmed=bool(trim_suffix_at),
|
|
459
|
+
changed_at=trim_suffix_at,
|
|
460
|
+
cpu_p99=readings.get("cpu"),
|
|
461
|
+
desired_cpu_p99=desired,
|
|
462
|
+
extra_lines=keep_extra,
|
|
463
|
+
)
|
|
464
|
+
if line is None:
|
|
465
|
+
return "", _payload(
|
|
466
|
+
status="returned",
|
|
467
|
+
window_trimmed=window_trimmed,
|
|
468
|
+
instance_type=response.get("recommended_instance_type"),
|
|
469
|
+
explanation=response.get("explanation"),
|
|
470
|
+
omitted=True,
|
|
471
|
+
cpu_p99=readings.get("cpu"),
|
|
472
|
+
desired_cpu_p99=desired,
|
|
473
|
+
sample_minutes=sample_minutes,
|
|
474
|
+
metric_readings=metric_snapshot,
|
|
475
|
+
)
|
|
476
|
+
return line, _payload(
|
|
477
|
+
status="returned",
|
|
478
|
+
window_trimmed=window_trimmed,
|
|
479
|
+
instance_type=response.get("recommended_instance_type"),
|
|
480
|
+
explanation=response.get("explanation"),
|
|
481
|
+
omitted=False,
|
|
482
|
+
metric_readings=metric_snapshot,
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _trimmed_readings(
|
|
487
|
+
item: WorkItem,
|
|
488
|
+
*,
|
|
489
|
+
runner: Any,
|
|
490
|
+
now_utc: Any,
|
|
491
|
+
) -> tuple[dict[str, float | None], bool, int, Any, int]:
|
|
492
|
+
"""P99 readings after optional CloudTrail or Config trim, plus minutes in that window."""
|
|
493
|
+
from maproom.analyze.change_detection import InstanceTypeChange
|
|
494
|
+
|
|
495
|
+
now = (now_utc or (lambda: datetime.now(timezone.utc)))()
|
|
496
|
+
window_start, window_end = utilization_window(now)
|
|
497
|
+
empty: dict[str, float | None] = {name: None for name in METRIC_NAMES}
|
|
498
|
+
|
|
499
|
+
change = detect_instance_type_change(
|
|
500
|
+
instance_id=item.instance_id,
|
|
501
|
+
region=item.region,
|
|
502
|
+
instance={},
|
|
503
|
+
window_start=window_start,
|
|
504
|
+
window_end=window_end,
|
|
505
|
+
cpu_metric_row=None,
|
|
506
|
+
runner=runner,
|
|
507
|
+
local_only=False,
|
|
508
|
+
now=now,
|
|
509
|
+
allow_metric_fallbacks=False,
|
|
510
|
+
)
|
|
511
|
+
window_trimmed = change.detection_source in ("cloudtrail", "aws_config") and (
|
|
512
|
+
change.changed_at is not None
|
|
513
|
+
)
|
|
514
|
+
considered_start = window_start
|
|
515
|
+
if window_trimmed and change.changed_at is not None and change.changed_at > window_start:
|
|
516
|
+
considered_start = change.changed_at
|
|
517
|
+
|
|
518
|
+
period_minutes = SAMPLE_PERIOD_MINUTES
|
|
519
|
+
readings = empty
|
|
520
|
+
for candidate_minutes in (1, SAMPLE_PERIOD_MINUTES):
|
|
521
|
+
period_seconds = candidate_minutes * 60
|
|
522
|
+
by_id = _fetch_size_metric_rows(
|
|
523
|
+
item,
|
|
524
|
+
runner=runner,
|
|
525
|
+
start=considered_start,
|
|
526
|
+
end=window_end,
|
|
527
|
+
period_seconds=period_seconds,
|
|
528
|
+
now=now,
|
|
529
|
+
)
|
|
530
|
+
if by_id is None:
|
|
531
|
+
continue
|
|
532
|
+
trial = _readings_from_rows(by_id, period_seconds=period_seconds)
|
|
533
|
+
if trial.get("cpu") is not None:
|
|
534
|
+
readings = trial
|
|
535
|
+
period_minutes = candidate_minutes
|
|
536
|
+
break
|
|
537
|
+
return (
|
|
538
|
+
readings,
|
|
539
|
+
window_trimmed,
|
|
540
|
+
_sample_minutes(considered_start, window_end),
|
|
541
|
+
change,
|
|
542
|
+
period_minutes,
|
|
543
|
+
)
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _metric_fetch_chunk_span(period_seconds: int) -> timedelta:
|
|
547
|
+
span_seconds = int(_CLOUDWATCH_MAX_DATAPOINTS * period_seconds / _SIZE_METRIC_QUERY_COUNT)
|
|
548
|
+
return timedelta(seconds=max(span_seconds, period_seconds))
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _metric_fetch_chunks(
|
|
552
|
+
start: datetime,
|
|
553
|
+
end: datetime,
|
|
554
|
+
*,
|
|
555
|
+
period_seconds: int,
|
|
556
|
+
) -> list[tuple[datetime, datetime]]:
|
|
557
|
+
span = _metric_fetch_chunk_span(period_seconds)
|
|
558
|
+
chunks: list[tuple[datetime, datetime]] = []
|
|
559
|
+
cursor = start
|
|
560
|
+
while cursor < end:
|
|
561
|
+
chunk_end = min(cursor + span, end)
|
|
562
|
+
chunks.append((cursor, chunk_end))
|
|
563
|
+
if chunk_end >= end:
|
|
564
|
+
break
|
|
565
|
+
cursor = chunk_end
|
|
566
|
+
return chunks or [(start, end)]
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def _merge_size_metric_rows(
|
|
570
|
+
by_id: dict[str, dict[str, Any]],
|
|
571
|
+
part: dict[str, dict[str, Any]],
|
|
572
|
+
*,
|
|
573
|
+
period_seconds: int,
|
|
574
|
+
) -> dict[str, dict[str, Any]]:
|
|
575
|
+
merged = dict(by_id)
|
|
576
|
+
for query_id, row in part.items():
|
|
577
|
+
if query_id not in merged:
|
|
578
|
+
merged[query_id] = row
|
|
579
|
+
continue
|
|
580
|
+
pairs = _pairs_from_metric_row(merged[query_id]) + _pairs_from_metric_row(row)
|
|
581
|
+
pairs.sort(key=lambda item: item[0])
|
|
582
|
+
deduped: list[tuple[datetime, float]] = []
|
|
583
|
+
last_ts: datetime | None = None
|
|
584
|
+
for ts, value in pairs:
|
|
585
|
+
if last_ts is not None and ts == last_ts:
|
|
586
|
+
deduped[-1] = (ts, value)
|
|
587
|
+
else:
|
|
588
|
+
deduped.append((ts, value))
|
|
589
|
+
last_ts = ts
|
|
590
|
+
merged[query_id] = {
|
|
591
|
+
**row,
|
|
592
|
+
"Period": period_seconds,
|
|
593
|
+
"Timestamps": [_iso_z(t) for t, _ in deduped],
|
|
594
|
+
"Values": [v for _, v in deduped],
|
|
595
|
+
}
|
|
596
|
+
return merged
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def _fetch_size_metric_rows(
|
|
600
|
+
item: WorkItem,
|
|
601
|
+
*,
|
|
602
|
+
runner: Any,
|
|
603
|
+
start: datetime,
|
|
604
|
+
end: datetime,
|
|
605
|
+
period_seconds: int,
|
|
606
|
+
now: datetime,
|
|
607
|
+
) -> dict[str, dict[str, Any]] | None:
|
|
608
|
+
"""CloudWatch size fetches, chunked to stay under the GetMetricData datapoint cap."""
|
|
609
|
+
merged: dict[str, dict[str, Any]] = {}
|
|
610
|
+
for chunk_start, chunk_end in _metric_fetch_chunks(
|
|
611
|
+
start, end, period_seconds=period_seconds
|
|
612
|
+
):
|
|
613
|
+
part = _fetch_size_metric_rows_once(
|
|
614
|
+
item,
|
|
615
|
+
runner=runner,
|
|
616
|
+
start=chunk_start,
|
|
617
|
+
end=chunk_end,
|
|
618
|
+
period_seconds=period_seconds,
|
|
619
|
+
now=now,
|
|
620
|
+
)
|
|
621
|
+
if part is None:
|
|
622
|
+
return None
|
|
623
|
+
merged = _merge_size_metric_rows(merged, part, period_seconds=period_seconds)
|
|
624
|
+
return merged
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def _fetch_size_metric_rows_once(
|
|
628
|
+
item: WorkItem,
|
|
629
|
+
*,
|
|
630
|
+
runner: Any,
|
|
631
|
+
start: datetime,
|
|
632
|
+
end: datetime,
|
|
633
|
+
period_seconds: int,
|
|
634
|
+
now: datetime,
|
|
635
|
+
) -> dict[str, dict[str, Any]] | None:
|
|
636
|
+
"""One GetMetricData call for the same-type size-change readings."""
|
|
637
|
+
from maproom.analyze.local_reads import run_cached_analyze_read, window_cache_suffix
|
|
638
|
+
|
|
639
|
+
metric_argv = build_size_metric_argv(
|
|
640
|
+
item.instance_id,
|
|
641
|
+
start=start,
|
|
642
|
+
end=end,
|
|
643
|
+
period_seconds=period_seconds,
|
|
644
|
+
) + ["--region", item.region]
|
|
645
|
+
metric_result = run_cached_analyze_read(
|
|
646
|
+
runner,
|
|
647
|
+
"aws",
|
|
648
|
+
metric_argv,
|
|
649
|
+
api_id="aws_cloudwatch_get_metric_data",
|
|
650
|
+
region=item.region.strip(),
|
|
651
|
+
instance_id=item.instance_id,
|
|
652
|
+
suffix=window_cache_suffix(
|
|
653
|
+
start=start,
|
|
654
|
+
end=end,
|
|
655
|
+
label=f"size-p{period_seconds}",
|
|
656
|
+
),
|
|
657
|
+
record=False,
|
|
658
|
+
now=now,
|
|
659
|
+
)
|
|
660
|
+
response = _runner_response(metric_result)
|
|
661
|
+
try:
|
|
662
|
+
rows = parse_cloudwatch_get_metric_data(
|
|
663
|
+
response,
|
|
664
|
+
cli_version=getattr(metric_result, "cli_version", None),
|
|
665
|
+
)
|
|
666
|
+
except (AccessDeniedError, MaproomParseError):
|
|
667
|
+
return None
|
|
668
|
+
return {str(row.get("Id")): row for row in rows if isinstance(row, dict)}
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def _desired_memory_p99(settings: dict[str, Any]) -> float | None:
|
|
672
|
+
from maproom.settings.defaults import DEFAULT_SETTINGS
|
|
673
|
+
|
|
674
|
+
raw = settings.get("desired_memory_p99", DEFAULT_SETTINGS["desired_memory_p99"])
|
|
675
|
+
if isinstance(raw, bool) or not isinstance(raw, (int, float)):
|
|
676
|
+
return None
|
|
677
|
+
number = float(raw)
|
|
678
|
+
if not math.isfinite(number) or number <= 0:
|
|
679
|
+
return None
|
|
680
|
+
return number
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def _desired_cpu_p99(settings: dict[str, Any]) -> float | None:
|
|
684
|
+
"""The operator's CPU p99 target. Missing settings use the product default."""
|
|
685
|
+
from maproom.settings.defaults import DEFAULT_SETTINGS
|
|
686
|
+
|
|
687
|
+
raw = settings.get("desired_cpu_p99", DEFAULT_SETTINGS["desired_cpu_p99"])
|
|
688
|
+
if isinstance(raw, bool) or not isinstance(raw, (int, float)):
|
|
689
|
+
return None
|
|
690
|
+
number = float(raw)
|
|
691
|
+
if not math.isfinite(number) or number <= 0:
|
|
692
|
+
return None
|
|
693
|
+
return number
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def _sample_minutes(start: datetime, end: datetime) -> int:
|
|
697
|
+
minutes = int((end - start).total_seconds() // 60)
|
|
698
|
+
return minutes if minutes > 0 else 1
|
|
699
|
+
|
|
700
|
+
|
|
701
|
+
def _readings_from_rows(
|
|
702
|
+
by_id: dict[str, dict[str, Any]],
|
|
703
|
+
*,
|
|
704
|
+
period_seconds: int,
|
|
705
|
+
) -> dict[str, float | None]:
|
|
706
|
+
def _values(query_id: str) -> list[float]:
|
|
707
|
+
row = by_id.get(query_id) or {}
|
|
708
|
+
return [value for _, value in _pairs_from_metric_row(row)]
|
|
709
|
+
|
|
710
|
+
def _rate(*query_ids: str) -> list[float]:
|
|
711
|
+
return sum_aligned_rates(
|
|
712
|
+
[_pairs_from_metric_row(by_id.get(query_id) or {}) for query_id in query_ids],
|
|
713
|
+
period_seconds=period_seconds,
|
|
714
|
+
)
|
|
715
|
+
|
|
716
|
+
series = {
|
|
717
|
+
"cpu": _values("cpu"),
|
|
718
|
+
"memory": _values("memory"),
|
|
719
|
+
"disk_iops_per_second": _rate("ebs_read_ops", "ebs_write_ops"),
|
|
720
|
+
"disk_throughput_per_second": _rate("ebs_read_bytes", "ebs_write_bytes"),
|
|
721
|
+
"net_iops_per_second": _rate("net_in_pkts", "net_out_pkts"),
|
|
722
|
+
"net_throughput_per_second": _rate("net_in_bytes", "net_out_bytes"),
|
|
723
|
+
}
|
|
724
|
+
return {name: p99_from_values(values) for name, values in series.items()}
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def _describe_instance(item: WorkItem, runner: Any) -> dict[str, Any]:
|
|
728
|
+
from maproom.analyze.local_reads import run_cached_analyze_read
|
|
729
|
+
|
|
730
|
+
result = run_cached_analyze_read(
|
|
731
|
+
runner,
|
|
732
|
+
"aws",
|
|
733
|
+
[
|
|
734
|
+
"ec2",
|
|
735
|
+
"describe-instances",
|
|
736
|
+
"--instance-ids",
|
|
737
|
+
item.instance_id,
|
|
738
|
+
"--region",
|
|
739
|
+
item.region,
|
|
740
|
+
"--output",
|
|
741
|
+
"json",
|
|
742
|
+
],
|
|
743
|
+
api_id="aws_ec2_describe_instances",
|
|
744
|
+
region=item.region.strip(),
|
|
745
|
+
instance_id=item.instance_id,
|
|
746
|
+
record=False,
|
|
747
|
+
)
|
|
748
|
+
response = _runner_response(result)
|
|
749
|
+
try:
|
|
750
|
+
instances = parse_ec2_describe_instances(
|
|
751
|
+
response,
|
|
752
|
+
cli_version=getattr(result, "cli_version", None),
|
|
753
|
+
state_id=None,
|
|
754
|
+
)
|
|
755
|
+
except Exception:
|
|
756
|
+
return {}
|
|
757
|
+
return instances[0] if instances else {}
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def _runner_response(result: Any) -> dict[str, Any]:
|
|
761
|
+
if isinstance(result, dict):
|
|
762
|
+
return result
|
|
763
|
+
stdout = getattr(result, "stdout", "") or ""
|
|
764
|
+
payload: dict[str, Any] = {
|
|
765
|
+
"exit_code": getattr(result, "exit_code", 0),
|
|
766
|
+
"stdout_json": {},
|
|
767
|
+
"stderr": getattr(result, "stderr", ""),
|
|
768
|
+
}
|
|
769
|
+
if stdout.strip():
|
|
770
|
+
try:
|
|
771
|
+
payload["stdout_json"] = json.loads(stdout)
|
|
772
|
+
except json.JSONDecodeError:
|
|
773
|
+
payload["stdout_json"] = {"_raw_stdout": stdout}
|
|
774
|
+
return payload
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
def _settings_for_post(settings: dict[str, Any]) -> dict[str, Any]:
|
|
778
|
+
from maproom.analyze.recommend_client import resolve_recommend_url
|
|
779
|
+
|
|
780
|
+
merged = dict(settings)
|
|
781
|
+
service = dict(merged.get("service") or {})
|
|
782
|
+
url = resolve_recommend_url(settings)
|
|
783
|
+
if url and not str(service.get("recommend_url") or "").strip():
|
|
784
|
+
service["recommend_url"] = url
|
|
785
|
+
merged["service"] = service
|
|
786
|
+
return merged
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
def _metric_readings_for_payload(
|
|
790
|
+
readings: dict[str, float | None],
|
|
791
|
+
) -> dict[str, float]:
|
|
792
|
+
snapshot: dict[str, float] = {}
|
|
793
|
+
for name, value in readings.items():
|
|
794
|
+
if value is None or isinstance(value, bool):
|
|
795
|
+
continue
|
|
796
|
+
if isinstance(value, (int, float)) and math.isfinite(float(value)):
|
|
797
|
+
snapshot[name] = float(value)
|
|
798
|
+
return snapshot
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def _payload(
|
|
802
|
+
*,
|
|
803
|
+
status: str,
|
|
804
|
+
window_trimmed: bool,
|
|
805
|
+
instance_type: object = None,
|
|
806
|
+
explanation: object = None,
|
|
807
|
+
omitted: bool | None = None,
|
|
808
|
+
cpu_p99: object = None,
|
|
809
|
+
desired_cpu_p99: object = None,
|
|
810
|
+
sample_minutes: object = None,
|
|
811
|
+
metric_readings: dict[str, float] | None = None,
|
|
812
|
+
) -> dict[str, Any]:
|
|
813
|
+
payload: dict[str, Any] = {
|
|
814
|
+
"status": status,
|
|
815
|
+
"window_trimmed": bool(window_trimmed),
|
|
816
|
+
"instance_type": instance_type if isinstance(instance_type, str) else None,
|
|
817
|
+
"explanation": explanation if isinstance(explanation, str) else None,
|
|
818
|
+
}
|
|
819
|
+
if omitted is not None:
|
|
820
|
+
payload["omitted"] = bool(omitted)
|
|
821
|
+
if cpu_p99 is not None and not isinstance(cpu_p99, bool):
|
|
822
|
+
payload["cpu_p99"] = float(cpu_p99)
|
|
823
|
+
if desired_cpu_p99 is not None and not isinstance(desired_cpu_p99, bool):
|
|
824
|
+
payload["desired_cpu_p99"] = float(desired_cpu_p99)
|
|
825
|
+
if isinstance(sample_minutes, int) and sample_minutes > 0:
|
|
826
|
+
payload["sample_minutes"] = sample_minutes
|
|
827
|
+
if metric_readings:
|
|
828
|
+
payload["metric_readings"] = dict(metric_readings)
|
|
829
|
+
return payload
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
_METRIC_LABELS = {
|
|
833
|
+
"cpu": "CPU",
|
|
834
|
+
"memory": "memory",
|
|
835
|
+
"disk_iops_per_second": "disk IOPS",
|
|
836
|
+
"disk_throughput_per_second": "disk",
|
|
837
|
+
"net_iops_per_second": "net",
|
|
838
|
+
"net_throughput_per_second": "net",
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def _collected_metric_value(key: str, value: float) -> str:
|
|
843
|
+
text = format_human_metric(float(value))
|
|
844
|
+
if key == "cpu" or key == "memory":
|
|
845
|
+
return f"{text}%"
|
|
846
|
+
if key == "disk_iops_per_second":
|
|
847
|
+
return f"{text} IOPS"
|
|
848
|
+
if key == "disk_throughput_per_second" or key == "net_throughput_per_second":
|
|
849
|
+
return f"{text} B/s"
|
|
850
|
+
if key == "net_iops_per_second":
|
|
851
|
+
return f"{text} pps"
|
|
852
|
+
return text
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
def size_collected_metrics_summary(payload: dict[str, Any] | None) -> str | None:
|
|
856
|
+
if not isinstance(payload, dict):
|
|
857
|
+
return None
|
|
858
|
+
stored = payload.get("metric_readings")
|
|
859
|
+
if isinstance(stored, dict) and stored:
|
|
860
|
+
parts: list[str] = []
|
|
861
|
+
for key, label in _METRIC_LABELS.items():
|
|
862
|
+
value = stored.get(key)
|
|
863
|
+
if value is None:
|
|
864
|
+
continue
|
|
865
|
+
parts.append(f"{label} p99 {_collected_metric_value(key, float(value))}")
|
|
866
|
+
if parts:
|
|
867
|
+
return "Collected " + ", ".join(parts) + "."
|
|
868
|
+
return size_metrics_recap_line(payload)
|
|
869
|
+
|
|
870
|
+
|
|
871
|
+
def size_metrics_recap_line(payload: dict[str, Any] | None) -> str | None:
|
|
872
|
+
if not isinstance(payload, dict) or not payload.get("omitted"):
|
|
873
|
+
return None
|
|
874
|
+
cpu = payload.get("cpu_p99")
|
|
875
|
+
desired = payload.get("desired_cpu_p99")
|
|
876
|
+
minutes = payload.get("sample_minutes")
|
|
877
|
+
if cpu is None or desired is None or not isinstance(minutes, int):
|
|
878
|
+
return None
|
|
879
|
+
return (
|
|
880
|
+
f"Based on CPU p99 {format_human_metric(float(cpu))}, "
|
|
881
|
+
f"desired target {format_human_metric(float(desired))}, "
|
|
882
|
+
f"and a {minutes:,}-minute sample window."
|
|
883
|
+
)
|