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.
Files changed (199) hide show
  1. maproom/__init__.py +14 -0
  2. maproom/__main__.py +10 -0
  3. maproom/analyze/__init__.py +1 -0
  4. maproom/analyze/accel_families.py +45 -0
  5. maproom/analyze/account_azure_activity.py +260 -0
  6. maproom/analyze/account_azure_quota_requests.py +177 -0
  7. maproom/analyze/account_cloudtrail.py +316 -0
  8. maproom/analyze/account_quota_requests.py +180 -0
  9. maproom/analyze/analyze_v1_orchestration.py +1194 -0
  10. maproom/analyze/catalog.py +353 -0
  11. maproom/analyze/change_detection.py +652 -0
  12. maproom/analyze/context_client.py +99 -0
  13. maproom/analyze/context_lookup.py +142 -0
  14. maproom/analyze/cover_analyze.py +344 -0
  15. maproom/analyze/cover_client.py +65 -0
  16. maproom/analyze/cover_lookup.py +242 -0
  17. maproom/analyze/engine.py +644 -0
  18. maproom/analyze/fleetfit_endpoints.py +217 -0
  19. maproom/analyze/fleetfit_policy.py +66 -0
  20. maproom/analyze/instance_price_analyze.py +221 -0
  21. maproom/analyze/instance_price_client.py +108 -0
  22. maproom/analyze/instance_price_lookup.py +60 -0
  23. maproom/analyze/local_reads.py +484 -0
  24. maproom/analyze/lookup_http.py +280 -0
  25. maproom/analyze/metric_format.py +20 -0
  26. maproom/analyze/migration_method.py +130 -0
  27. maproom/analyze/move_list.py +93 -0
  28. maproom/analyze/operator_context.py +156 -0
  29. maproom/analyze/performance_rank.py +97 -0
  30. maproom/analyze/primary_recommendation.py +422 -0
  31. maproom/analyze/provider_comparison.py +401 -0
  32. maproom/analyze/quota_analyze.py +481 -0
  33. maproom/analyze/quota_client.py +75 -0
  34. maproom/analyze/quota_lookup.py +110 -0
  35. maproom/analyze/quota_outcome_steer.py +105 -0
  36. maproom/analyze/recommend_batch.py +199 -0
  37. maproom/analyze/recommend_client.py +362 -0
  38. maproom/analyze/recommend_share.py +118 -0
  39. maproom/analyze/recommendation.py +591 -0
  40. maproom/analyze/reservation_pack.py +883 -0
  41. maproom/analyze/reservation_read.py +461 -0
  42. maproom/analyze/safe_analyze.py +1134 -0
  43. maproom/analyze/safe_move.py +195 -0
  44. maproom/analyze/safe_moves.py +571 -0
  45. maproom/analyze/safe_moves_catalog.py +127 -0
  46. maproom/analyze/safe_moves_client.py +70 -0
  47. maproom/analyze/series_analyze.py +491 -0
  48. maproom/analyze/series_client.py +106 -0
  49. maproom/analyze/series_lookup.py +663 -0
  50. maproom/analyze/shape.py +254 -0
  51. maproom/analyze/size_analyze.py +883 -0
  52. maproom/analyze/size_client.py +81 -0
  53. maproom/analyze/size_keep.py +409 -0
  54. maproom/analyze/size_lookup.py +368 -0
  55. maproom/analyze/specs.py +325 -0
  56. maproom/analyze/spot_analyze.py +392 -0
  57. maproom/analyze/spot_client.py +74 -0
  58. maproom/analyze/spot_lookup.py +213 -0
  59. maproom/analyze/token_client.py +97 -0
  60. maproom/analyze/utilization.py +190 -0
  61. maproom/analyze/workload.py +104 -0
  62. maproom/analyze/workset.py +762 -0
  63. maproom/aws_region.py +78 -0
  64. maproom/cache/__init__.py +1 -0
  65. maproom/cache/catalog.py +372 -0
  66. maproom/cache/commands.py +215 -0
  67. maproom/cache/instances.py +460 -0
  68. maproom/cli.py +2084 -0
  69. maproom/cli_argv.py +329 -0
  70. maproom/cli_floors.py +89 -0
  71. maproom/cliio/__init__.py +1 -0
  72. maproom/cliio/registry.py +377 -0
  73. maproom/cliio/runner.py +489 -0
  74. maproom/consent/__init__.py +33 -0
  75. maproom/consent/gate.py +238 -0
  76. maproom/consent/policy.py +20 -0
  77. maproom/consent/prompt.py +61 -0
  78. maproom/consent/service_upload_gate.py +318 -0
  79. maproom/consent/service_upload_prompt.py +62 -0
  80. maproom/consent/stdin.py +45 -0
  81. maproom/consent/storage.py +24 -0
  82. maproom/consent/write_token.py +29 -0
  83. maproom/contracts/__init__.py +6 -0
  84. maproom/contracts/schema_diff.py +119 -0
  85. maproom/contracts/validate.py +113 -0
  86. maproom/data/__init__.py +1 -0
  87. maproom/data/clear.py +76 -0
  88. maproom/data/commands.py +14 -0
  89. maproom/doctor/__init__.py +1 -0
  90. maproom/doctor/aws_session.py +226 -0
  91. maproom/doctor/checks.py +701 -0
  92. maproom/doctor/context.py +32 -0
  93. maproom/doctor/display.py +96 -0
  94. maproom/doctor/inventory_display.py +377 -0
  95. maproom/doctor/runner.py +1467 -0
  96. maproom/errors.py +43 -0
  97. maproom/exitcodes.py +70 -0
  98. maproom/inventory/__init__.py +1 -0
  99. maproom/inventory/account_identity.py +79 -0
  100. maproom/inventory/accounts.py +155 -0
  101. maproom/inventory/command.py +961 -0
  102. maproom/inventory/messages.py +264 -0
  103. maproom/inventory/reservations_refresh.py +37 -0
  104. maproom/mock_environment/__init__.py +28 -0
  105. maproom/mock_environment/load.py +241 -0
  106. maproom/mock_environment/runner.py +387 -0
  107. maproom/output/__init__.py +1 -0
  108. maproom/output/json_envelope.py +241 -0
  109. maproom/output/redact.py +11 -0
  110. maproom/output/terminal.py +129 -0
  111. maproom/parsers.py +284 -0
  112. maproom/paths.py +105 -0
  113. maproom/plan/__init__.py +1 -0
  114. maproom/plan/accept.py +59 -0
  115. maproom/plan/analysis_context.py +78 -0
  116. maproom/plan/analyze_selection.py +279 -0
  117. maproom/plan/commands.py +586 -0
  118. maproom/plan/current.py +59 -0
  119. maproom/plan/errors.py +10 -0
  120. maproom/plan/export.py +36 -0
  121. maproom/plan/formatting.py +91 -0
  122. maproom/plan/ids.py +13 -0
  123. maproom/plan/migration_options.py +75 -0
  124. maproom/plan/model.py +265 -0
  125. maproom/plan/names.py +24 -0
  126. maproom/plan/store.py +193 -0
  127. maproom/plan/tty.py +34 -0
  128. maproom/pricing/__init__.py +5 -0
  129. maproom/pricing/prices.py +119 -0
  130. maproom/privacy/__init__.py +6 -0
  131. maproom/privacy/commands.py +159 -0
  132. maproom/privacy/delete_uploads.py +204 -0
  133. maproom/privacy/fleetfit_policy.py +125 -0
  134. maproom/privacy/fleetfit_statement.py +104 -0
  135. maproom/privacy/format.py +76 -0
  136. maproom/privacy/manifests.py +342 -0
  137. maproom/privacy/statement.py +58 -0
  138. maproom/quotas/__init__.py +21 -0
  139. maproom/quotas/aws.py +204 -0
  140. maproom/quotas/azure.py +75 -0
  141. maproom/quotas/commands.py +240 -0
  142. maproom/quotas/family_coverage.py +122 -0
  143. maproom/quotas/fetch.py +124 -0
  144. maproom/quotas/load.py +41 -0
  145. maproom/quotas/model.py +178 -0
  146. maproom/quotas/outcome_ledger.py +245 -0
  147. maproom/quotas/quota_request_sync.py +221 -0
  148. maproom/quotas/show.py +73 -0
  149. maproom/quotas/status.py +206 -0
  150. maproom/quotas/store.py +161 -0
  151. maproom/redaction.py +157 -0
  152. maproom/reference_data/__init__.py +1 -0
  153. maproom/reference_data/aws/aws_prices.csv +25562 -0
  154. maproom/reference_data/aws/capabilities.csv +1346 -0
  155. maproom/reference_data/aws/instance_types.csv +1346 -0
  156. maproom/reference_data/azure/azure_prices.csv +1 -0
  157. maproom/reference_data/azure/vm_types.csv +1 -0
  158. maproom/reference_data/benchmarks/cpu-lscpu-v2-instances.json +27 -0
  159. maproom/reference_data/benchmarks/safe-moves-v1.json +328 -0
  160. maproom/reference_data/manifest.json +174 -0
  161. maproom/reference_data/manifest.py +69 -0
  162. maproom/reservations/__init__.py +17 -0
  163. maproom/reservations/aws.py +76 -0
  164. maproom/reservations/azure.py +36 -0
  165. maproom/reservations/commands.py +149 -0
  166. maproom/reservations/load.py +41 -0
  167. maproom/reservations/model.py +316 -0
  168. maproom/reservations/show.py +64 -0
  169. maproom/reservations/status.py +181 -0
  170. maproom/reservations/store.py +391 -0
  171. maproom/resources.py +54 -0
  172. maproom/root_help.py +251 -0
  173. maproom/saving_plans/__init__.py +15 -0
  174. maproom/saving_plans/aws.py +73 -0
  175. maproom/saving_plans/commands.py +122 -0
  176. maproom/saving_plans/load.py +41 -0
  177. maproom/saving_plans/model.py +101 -0
  178. maproom/saving_plans/show.py +64 -0
  179. maproom/saving_plans/status.py +118 -0
  180. maproom/saving_plans/store.py +173 -0
  181. maproom/secret_egress_gate.py +108 -0
  182. maproom/service/install_id.py +60 -0
  183. maproom/settings/__init__.py +1 -0
  184. maproom/settings/defaults.py +73 -0
  185. maproom/settings/init.py +143 -0
  186. maproom/settings/model.py +105 -0
  187. maproom/settings/product_version_change.py +343 -0
  188. maproom/settings/product_versions.py +68 -0
  189. maproom/settings/set.py +347 -0
  190. maproom/settings/show.py +227 -0
  191. maproom/settings/write.py +273 -0
  192. maproom/snapshot_time.py +27 -0
  193. maproom-0.2.0.dist-info/METADATA +263 -0
  194. maproom-0.2.0.dist-info/RECORD +199 -0
  195. maproom-0.2.0.dist-info/WHEEL +5 -0
  196. maproom-0.2.0.dist-info/entry_points.txt +2 -0
  197. maproom-0.2.0.dist-info/licenses/LICENSE +201 -0
  198. maproom-0.2.0.dist-info/licenses/NOTICE +72 -0
  199. maproom-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,70 @@
1
+ """POST safe_moves fields to FleetFit recommend, or replay a fixture in CI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import urllib.error
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from maproom.analyze.recommend_client import (
12
+ KIND_SAFE_MOVES,
13
+ RecommendError,
14
+ post_recommend_kind,
15
+ resolve_recommend_url,
16
+ unwrap_kind_section,
17
+ )
18
+ from maproom.analyze.safe_moves import _require_closed_body, require_safe_moves_response
19
+
20
+
21
+ class SafeMovesLookupError(Exception):
22
+ """Safe moves lookup request failed."""
23
+
24
+
25
+ def post_safe_moves(body: dict, settings: dict) -> dict | None:
26
+ _require_closed_body(body)
27
+ fixture = os.environ.get("MAPROOM_SAFE_MOVES_FIXTURE", "").strip()
28
+ if fixture:
29
+ return _read_fixture(Path(fixture))
30
+ from maproom.analyze.recommend_batch import recommend_staging_only
31
+
32
+ try:
33
+ payload = post_recommend_kind(
34
+ body, settings, kind=KIND_SAFE_MOVES, lookup_label="safe moves lookup"
35
+ )
36
+ if recommend_staging_only() and payload is None:
37
+ return None
38
+ return payload
39
+ except RecommendError as exc:
40
+ raise SafeMovesLookupError(str(exc)) from exc
41
+ except urllib.error.HTTPError as exc:
42
+ raise SafeMovesLookupError(f"safe moves HTTP {exc.code}") from exc
43
+ except (urllib.error.URLError, TimeoutError, ValueError) as exc:
44
+ raise SafeMovesLookupError(str(exc)) from exc
45
+
46
+
47
+ def resolve_safe_moves_lookup_url(settings: dict | None) -> str | None:
48
+ return resolve_recommend_url(settings)
49
+
50
+
51
+ def _read_fixture(path: Path) -> dict[str, Any]:
52
+ try:
53
+ payload = json.loads(path.read_text(encoding="utf-8"))
54
+ except (OSError, json.JSONDecodeError) as exc:
55
+ raise SafeMovesLookupError("safe moves fixture could not be read") from exc
56
+ try:
57
+ section = unwrap_kind_section(payload, kind=KIND_SAFE_MOVES)
58
+ except RecommendError as exc:
59
+ raise SafeMovesLookupError(str(exc)) from exc
60
+ try:
61
+ return require_safe_moves_response(section)
62
+ except ValueError as exc:
63
+ raise SafeMovesLookupError(str(exc)) from exc
64
+
65
+
66
+ def safe_moves_destination(settings: dict[str, Any] | None) -> bool:
67
+ """True when the recommend URL resolves or the fixture is set."""
68
+ if os.environ.get("MAPROOM_SAFE_MOVES_FIXTURE", "").strip():
69
+ return True
70
+ return resolve_safe_moves_lookup_url(settings) is not None
@@ -0,0 +1,491 @@
1
+ """Product version 4+: consented utilization / cross-family Analyze recommend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import sys
8
+ from dataclasses import dataclass
9
+ from datetime import datetime, timedelta, timezone
10
+ from typing import Any
11
+
12
+ from maproom.analyze.catalog import SpecRow, spec_architecture
13
+ from maproom.analyze.change_detection import (
14
+ _pairs_from_metric_row,
15
+ detect_instance_type_change,
16
+ trim_cpu_metric_row,
17
+ )
18
+ from maproom.analyze.series_lookup import (
19
+ DECLINED_DETAIL,
20
+ DECLINED_LINE,
21
+ INCOMPLETE_LINE,
22
+ MISSING_POLICY_LINE,
23
+ NOT_CONFIGURED_LINE,
24
+ NOT_IMPLEMENTED_LINE,
25
+ NOT_SENT_LINE,
26
+ SAMPLE_MINUTES,
27
+ WINDOW_DAYS,
28
+ SeriesJudgment,
29
+ SeriesNotImplementedError,
30
+ build_utilization_body,
31
+ judge_series_response,
32
+ shape_to_recommendation_shape,
33
+ summary_to_utilization_metrics,
34
+ )
35
+ from maproom.analyze.shape import ShapeConstraint, shape_in_effect
36
+ from maproom.analyze.size_analyze import _describe_instance, _runner_response
37
+ from maproom.analyze.utilization import (
38
+ _iso_z,
39
+ p99_from_values,
40
+ sum_aligned_rates,
41
+ )
42
+ from maproom.analyze.workset import WorkItem
43
+ from maproom.errors import AccessDeniedError, MaproomParseError
44
+ from maproom.parsers import parse_cloudwatch_get_metric_data
45
+ from maproom.paths import data_subdir
46
+ from maproom.redaction import redact_text
47
+
48
+ _PERIOD_SECONDS = SAMPLE_MINUTES * 60
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class SeriesRun:
53
+ upload_allowed: bool
54
+ destination: bool
55
+ settings: dict[str, Any]
56
+ shape: ShapeConstraint | None
57
+ upload_reason: str | None = None
58
+
59
+
60
+ def series_applies_to(item: WorkItem) -> bool:
61
+ return item.cloud == "aws" and bool(item.region.strip()) and bool(item.instance_type.strip())
62
+
63
+
64
+ def series_description_ready(item: WorkItem, specs: dict[tuple[str, str], SpecRow]) -> bool:
65
+ if not series_applies_to(item):
66
+ return False
67
+ row = specs.get((item.cloud, item.instance_type))
68
+ if row is None or not (row.quota_family or "").strip():
69
+ return False
70
+ return spec_architecture(row) is not None
71
+
72
+
73
+ def prepare_series_run_from_service(run: Any, shape: ShapeConstraint | None) -> SeriesRun:
74
+ return SeriesRun(
75
+ upload_allowed=bool(run.upload_allowed),
76
+ destination=bool(run.series_destination),
77
+ settings=run.settings,
78
+ shape=shape,
79
+ upload_reason=getattr(run, "upload_reason", None),
80
+ )
81
+
82
+
83
+ def apply_series_lookup(
84
+ item: WorkItem,
85
+ assessment: Any,
86
+ *,
87
+ run: SeriesRun,
88
+ runner: Any,
89
+ specs: dict[tuple[str, str], SpecRow],
90
+ as_json: bool,
91
+ now_utc: Any = None,
92
+ run_banners: Any | None = None,
93
+ recommend_envelope: dict[str, Any] | None = None,
94
+ attach_only: bool = False,
95
+ ) -> None:
96
+ if not series_applies_to(item):
97
+ return
98
+ response_override: dict[str, Any] | None = None
99
+ if attach_only and recommend_envelope is not None:
100
+ from maproom.analyze.series_lookup import SeriesNotImplementedError, require_series_response
101
+
102
+ cleaned = {
103
+ key: value
104
+ for key, value in recommend_envelope.items()
105
+ if key
106
+ not in {
107
+ "kinds",
108
+ "purchase_option",
109
+ "size",
110
+ "quota",
111
+ "spot",
112
+ "safe_moves",
113
+ "cover",
114
+ }
115
+ }
116
+ try:
117
+ response_override = require_series_response(cleaned)
118
+ except (ValueError, SeriesNotImplementedError):
119
+ response_override = None
120
+ extra, payload = _series_outcome(
121
+ item,
122
+ run=run,
123
+ runner=runner,
124
+ specs=specs,
125
+ as_json=as_json,
126
+ now_utc=now_utc,
127
+ response_override=response_override,
128
+ )
129
+ if extra:
130
+ if (
131
+ run_banners is not None
132
+ and payload is not None
133
+ and payload.get("status") == "missing_policy"
134
+ ):
135
+ run_banners.series_missing_policy = True
136
+ elif (
137
+ run_banners is not None
138
+ and payload is not None
139
+ and payload.get("status") == "declined"
140
+ and not run.upload_allowed
141
+ ):
142
+ run_banners.series_declined = True
143
+ elif (
144
+ run_banners is not None
145
+ and payload is not None
146
+ and payload.get("status") == "not_sent"
147
+ and not run.destination
148
+ ):
149
+ run_banners.series_not_configured = True
150
+ elif (
151
+ run_banners is not None
152
+ and payload is not None
153
+ and payload.get("status") == "not_implemented"
154
+ ):
155
+ run_banners.series_not_implemented = True
156
+ else:
157
+ assessment.text = f"{assessment.text}\n{extra}" if assessment.text else extra
158
+ if payload is None:
159
+ return
160
+ if assessment.recommendation is not None:
161
+ assessment.recommendation["utilization_metrics"] = payload
162
+ # Keep legacy key during OUTPUT_CONTRACT transition for old readers.
163
+ assessment.recommendation["series_fit"] = payload
164
+ elif assessment.examined is not None:
165
+ assessment.examined["utilization_metrics"] = payload
166
+ assessment.examined["series_fit"] = payload
167
+
168
+
169
+ def _series_outcome(
170
+ item: WorkItem,
171
+ *,
172
+ run: SeriesRun,
173
+ runner: Any,
174
+ specs: dict[tuple[str, str], SpecRow],
175
+ as_json: bool,
176
+ now_utc: Any,
177
+ response_override: dict[str, Any] | None = None,
178
+ ) -> tuple[str, dict[str, Any] | None]:
179
+ current = specs.get((item.cloud, item.instance_type))
180
+ architecture = spec_architecture(current) if current is not None else None
181
+ quota_family = (current.quota_family or "").strip() if current is not None else ""
182
+ if current is None or not architecture or not quota_family:
183
+ return INCOMPLETE_LINE, _payload(status="incomplete", detail=INCOMPLETE_LINE)
184
+ shape = shape_in_effect(run.shape)
185
+ if not run.upload_allowed:
186
+ if run.upload_reason == "upload_missing_policy":
187
+ return MISSING_POLICY_LINE, _payload(
188
+ status="missing_policy", detail=MISSING_POLICY_LINE
189
+ )
190
+ return DECLINED_LINE, _payload(status="declined", detail=DECLINED_DETAIL)
191
+ if not run.destination:
192
+ return (
193
+ NOT_CONFIGURED_LINE,
194
+ _payload(status="not_sent", detail=NOT_CONFIGURED_LINE),
195
+ )
196
+
197
+ summary, window_trimmed = _week_summary(item, runner=runner, now_utc=now_utc)
198
+ if summary is None:
199
+ return INCOMPLETE_LINE, _payload(status="incomplete", detail=INCOMPLETE_LINE)
200
+
201
+ from maproom.analyze.series_client import SeriesLookupError, post_series_lookup
202
+
203
+ del window_trimmed # client only uploads post-trim utilization for the current type
204
+ try:
205
+ is_spot = (item.lifecycle or "").strip().lower() == "spot"
206
+ az = (getattr(item, "availability_zone", None) or item.region or "").strip() or item.region.strip()
207
+ metrics = summary_to_utilization_metrics(summary)
208
+ has_memory = any(
209
+ isinstance(child, dict)
210
+ and child.get("name") == "memory"
211
+ and str(child.get("metric", "")).startswith("p99-")
212
+ for child in metrics
213
+ )
214
+ body = build_utilization_body(
215
+ instance_type=item.instance_type.strip(),
216
+ region=item.region.strip(),
217
+ az=az,
218
+ is_spot=is_spot,
219
+ utilization_metrics=metrics,
220
+ recommendation_shape=shape_to_recommendation_shape(
221
+ modify=shape.modify,
222
+ keep=shape.keep,
223
+ keep_region=True,
224
+ keep_az=True,
225
+ keep_is_spot=True,
226
+ settings=run.settings,
227
+ instance_type=item.instance_type.strip(),
228
+ has_memory_metric=has_memory,
229
+ ),
230
+ )
231
+ if response_override is not None:
232
+ response = response_override
233
+ else:
234
+ response = post_series_lookup(body, _settings_for_post(run.settings))
235
+ except SeriesNotImplementedError:
236
+ return (
237
+ NOT_IMPLEMENTED_LINE,
238
+ _payload(status="not_implemented", detail=NOT_IMPLEMENTED_LINE, omitted=True),
239
+ )
240
+ except (SeriesLookupError, ValueError) as exc:
241
+ warning = f"warning: Utilization lookup failed: {redact_text(str(exc))}"
242
+ if as_json:
243
+ print(warning, file=sys.stderr)
244
+ return warning, _payload(status="error", detail=warning)
245
+ if response is None:
246
+ return "", None
247
+
248
+ judgment = judge_series_response(
249
+ response,
250
+ current=current,
251
+ specs=specs,
252
+ modify=shape.modify,
253
+ keep=shape.keep,
254
+ )
255
+ hourly = response.get("latest_hourly")
256
+ return judgment.line, _payload_from_judgment(
257
+ judgment,
258
+ modify=shape.modify,
259
+ keep=shape.keep,
260
+ latest_hourly=hourly if isinstance(hourly, str) else None,
261
+ )
262
+
263
+
264
+ def _week_summary(
265
+ item: WorkItem,
266
+ *,
267
+ runner: Any,
268
+ now_utc: Any,
269
+ ) -> tuple[dict[str, Any] | None, bool]:
270
+ now = (now_utc or (lambda: datetime.now(timezone.utc)))()
271
+ end = now.astimezone(timezone.utc).replace(microsecond=0)
272
+ start = end - timedelta(days=WINDOW_DAYS)
273
+ metric_argv = _series_metric_argv(
274
+ item.instance_id,
275
+ start=start,
276
+ end=end,
277
+ ) + ["--region", item.region]
278
+ from maproom.analyze.local_reads import run_cached_analyze_read, window_cache_suffix
279
+
280
+ metric_result = run_cached_analyze_read(
281
+ runner,
282
+ "aws",
283
+ metric_argv,
284
+ api_id="aws_cloudwatch_get_metric_data",
285
+ region=item.region.strip(),
286
+ instance_id=item.instance_id,
287
+ suffix=window_cache_suffix(start=start, end=end, label="series"),
288
+ record=False,
289
+ now=now,
290
+ )
291
+ response = _runner_response(metric_result)
292
+ try:
293
+ rows = parse_cloudwatch_get_metric_data(
294
+ response,
295
+ cli_version=getattr(metric_result, "cli_version", None),
296
+ )
297
+ except (AccessDeniedError, MaproomParseError):
298
+ return None, False
299
+
300
+ by_id = {str(row.get("Id")): row for row in rows if isinstance(row, dict)}
301
+ cpu_metric_row = by_id.get("cpu")
302
+ inst = _describe_instance(item, runner)
303
+ change = detect_instance_type_change(
304
+ instance_id=item.instance_id,
305
+ region=item.region,
306
+ instance=inst,
307
+ window_start=start,
308
+ window_end=end,
309
+ cpu_metric_row=cpu_metric_row,
310
+ runner=runner,
311
+ local_only=False,
312
+ now=now,
313
+ )
314
+ window_trimmed = change.changed_at is not None
315
+ if window_trimmed:
316
+ for query_id, row in list(by_id.items()):
317
+ trimmed = trim_cpu_metric_row(row, change.changed_at)
318
+ if trimmed is not None:
319
+ by_id[query_id] = trimmed
320
+ summary = _summary_from_rows(by_id)
321
+ if summary is None:
322
+ return None, window_trimmed
323
+ return summary, window_trimmed
324
+
325
+
326
+ def _summary_from_rows(by_id: dict[str, dict[str, Any]]) -> dict[str, Any] | None:
327
+ cpu = [value for _, value in _pairs_from_metric_row(by_id.get("cpu") or {})]
328
+ cpu_p99 = p99_from_values(cpu)
329
+ if cpu_p99 is None:
330
+ return None
331
+
332
+ def _rate(*query_ids: str) -> list[float]:
333
+ return sum_aligned_rates(
334
+ [_pairs_from_metric_row(by_id.get(query_id) or {}) for query_id in query_ids],
335
+ period_seconds=_PERIOD_SECONDS,
336
+ )
337
+
338
+ memory = [value for _, value in _pairs_from_metric_row(by_id.get("memory") or {})]
339
+ network = _rate("net_in_bytes", "net_out_bytes")
340
+ network_iops = _rate("net_in_pkts", "net_out_pkts")
341
+ disk = _rate("ebs_read_bytes", "ebs_write_bytes")
342
+ disk_iops = _rate("ebs_read_ops", "ebs_write_ops")
343
+ credit_balance = [value for _, value in _pairs_from_metric_row(by_id.get("credit_balance") or {})]
344
+ credit_usage = [value for _, value in _pairs_from_metric_row(by_id.get("credit_usage") or {})]
345
+ return {
346
+ "cpu_p99": cpu_p99,
347
+ "cpu_max": round(max(cpu), 2),
348
+ "memory_p99": p99_from_values(memory),
349
+ "network_bytes_per_second_p99": p99_from_values(network),
350
+ "network_bytes_per_second_max": round(max(network), 2) if network else None,
351
+ "network_iops_p99": p99_from_values(network_iops),
352
+ "disk_bytes_per_second_p99": p99_from_values(disk),
353
+ "disk_bytes_per_second_max": round(max(disk), 2) if disk else None,
354
+ "disk_iops_p99": p99_from_values(disk_iops),
355
+ "credit_balance_min": round(min(credit_balance), 2) if credit_balance else None,
356
+ "credit_usage_p99": p99_from_values(credit_usage),
357
+ }
358
+
359
+
360
+ def _series_metric_argv(instance_id: str, *, start: datetime, end: datetime) -> list[str]:
361
+ dimensions = [{"Name": "InstanceId", "Value": instance_id}]
362
+
363
+ def _query(
364
+ query_id: str,
365
+ metric: str,
366
+ stat: str,
367
+ *,
368
+ namespace: str = "AWS/EC2",
369
+ ) -> dict[str, Any]:
370
+ return {
371
+ "Id": query_id,
372
+ "MetricStat": {
373
+ "Metric": {
374
+ "Namespace": namespace,
375
+ "MetricName": metric,
376
+ "Dimensions": dimensions,
377
+ },
378
+ "Period": _PERIOD_SECONDS,
379
+ "Stat": stat,
380
+ },
381
+ "ReturnData": True,
382
+ }
383
+
384
+ queries = [
385
+ _query("cpu", "CPUUtilization", "Average"),
386
+ _query("memory", "mem_used_percent", "Average", namespace="CWAgent"),
387
+ _query("ebs_read_bytes", "EBSReadBytes", "Sum"),
388
+ _query("ebs_write_bytes", "EBSWriteBytes", "Sum"),
389
+ _query("ebs_read_ops", "EBSReadOps", "Sum"),
390
+ _query("ebs_write_ops", "EBSWriteOps", "Sum"),
391
+ _query("net_in_bytes", "NetworkIn", "Sum"),
392
+ _query("net_out_bytes", "NetworkOut", "Sum"),
393
+ _query("net_in_pkts", "NetworkPacketsIn", "Sum"),
394
+ _query("net_out_pkts", "NetworkPacketsOut", "Sum"),
395
+ _query("credit_balance", "CPUCreditBalance", "Average"),
396
+ _query("credit_usage", "CPUCreditUsage", "Average"),
397
+ ]
398
+ return [
399
+ "cloudwatch",
400
+ "get-metric-data",
401
+ "--metric-data-queries",
402
+ json.dumps(queries, separators=(",", ":")),
403
+ "--start-time",
404
+ _iso_z(start),
405
+ "--end-time",
406
+ _iso_z(end),
407
+ "--output",
408
+ "json",
409
+ ]
410
+
411
+
412
+ def _load_saved_grade(instance_id: str) -> dict[str, Any] | None:
413
+ safe = re.sub(r"[^A-Za-z0-9_.-]+", "_", instance_id).strip("._") or "instance"
414
+ path = data_subdir("optimizer-grades") / f"{safe}.json"
415
+ if not path.is_file():
416
+ return None
417
+ try:
418
+ payload = json.loads(path.read_text(encoding="utf-8"))
419
+ except (OSError, json.JSONDecodeError):
420
+ return None
421
+ return payload if isinstance(payload, dict) else None
422
+
423
+
424
+ def _settings_for_post(settings: dict[str, Any]) -> dict[str, Any]:
425
+ from maproom.analyze.series_client import resolve_series_lookup_url
426
+
427
+ merged = dict(settings)
428
+ service = dict(merged.get("service") or {})
429
+ url = resolve_series_lookup_url(settings)
430
+ if url and not str(service.get("series_lookup_url") or "").strip():
431
+ service["series_lookup_url"] = url
432
+ merged["service"] = service
433
+ return merged
434
+
435
+
436
+ def _payload_from_judgment(
437
+ judgment: SeriesJudgment,
438
+ *,
439
+ modify: frozenset[str] | None = None,
440
+ keep: frozenset[str] | None = None,
441
+ latest_hourly: str | None = None,
442
+ ) -> dict[str, Any]:
443
+ payload = _payload(
444
+ status="returned",
445
+ passed=judgment.passed,
446
+ instance_type=judgment.instance_type,
447
+ projected_fit=judgment.projected_fit,
448
+ grade_gap_log=judgment.grade_gap_log,
449
+ credit_result=judgment.credit_result,
450
+ fits_while_bursting=judgment.fits_while_bursting,
451
+ quota_family=judgment.quota_family,
452
+ detail=judgment.line,
453
+ omitted=judgment.omitted,
454
+ )
455
+ if modify is not None or keep is not None:
456
+ payload["filters"] = {
457
+ "modify": sorted(modify or frozenset()),
458
+ "keep": sorted(keep or frozenset()),
459
+ }
460
+ if isinstance(latest_hourly, str) and latest_hourly.strip():
461
+ payload["latest_ondemand_hourly"] = latest_hourly.strip()
462
+ return payload
463
+
464
+
465
+ def _payload(
466
+ *,
467
+ status: str,
468
+ detail: str,
469
+ passed: bool = False,
470
+ instance_type: str | None = None,
471
+ projected_fit: str | None = None,
472
+ grade_gap_log: str | None = None,
473
+ credit_result: str | None = None,
474
+ fits_while_bursting: bool = False,
475
+ quota_family: str | None = None,
476
+ omitted: bool | None = None,
477
+ ) -> dict[str, Any]:
478
+ payload: dict[str, Any] = {
479
+ "status": status,
480
+ "passed": bool(passed),
481
+ "instance_type": instance_type,
482
+ "projected_fit": projected_fit,
483
+ "grade_gap_log": grade_gap_log,
484
+ "credit_result": credit_result,
485
+ "fits_while_bursting": bool(fits_while_bursting),
486
+ "quota_family": quota_family,
487
+ "detail": detail,
488
+ }
489
+ if omitted is not None:
490
+ payload["omitted"] = bool(omitted)
491
+ return payload
@@ -0,0 +1,106 @@
1
+ """POST utilization recommend body to FleetFit, or replay a fixture in CI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import urllib.error
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from maproom.analyze.lookup_http import LookupRedirectError, post_lookup_json
12
+ from maproom.analyze.recommend_client import (
13
+ RecommendError,
14
+ _RECOMMEND_SKIP_MESSAGE,
15
+ analyze_recommend_banners,
16
+ attach_run_context_id,
17
+ recommend_unreachable_proven,
18
+ resolve_recommend_url,
19
+ )
20
+ from maproom.analyze.series_lookup import (
21
+ SeriesNotImplementedError,
22
+ require_series_response,
23
+ require_utilization_body,
24
+ )
25
+
26
+
27
+ class SeriesLookupError(Exception):
28
+ """Utilization recommend request failed."""
29
+
30
+
31
+ def post_series_lookup(body: dict, settings: dict) -> dict:
32
+ """Post a closed utilization body (no kinds) to the recommend URL."""
33
+ require_utilization_body(body)
34
+ fixture = os.environ.get("MAPROOM_SERIES_FIXTURE", "").strip()
35
+ if fixture:
36
+ return _read_fixture(Path(fixture))
37
+ from maproom.analyze.recommend_batch import (
38
+ active_recommend_batch,
39
+ recommend_staging_only,
40
+ )
41
+
42
+ batch = active_recommend_batch()
43
+ if batch is not None:
44
+ batch.stage_utilization(body)
45
+ if recommend_staging_only():
46
+ return None # type: ignore[return-value]
47
+ batch._maybe_flush()
48
+ if batch._response is None:
49
+ batch.ensure_response()
50
+ return _checked(batch._response)
51
+ banners = analyze_recommend_banners()
52
+ if recommend_unreachable_proven(banners):
53
+ raise SeriesLookupError(_RECOMMEND_SKIP_MESSAGE)
54
+ url = resolve_recommend_url(settings)
55
+ if not url:
56
+ raise SeriesLookupError("recommend URL is not configured")
57
+ from maproom.paths import prepare_settings_write
58
+ from maproom.service.install_id import ensure_anonymous_id
59
+
60
+ install_id, write_err = ensure_anonymous_id(prepare_settings_write())
61
+ if write_err is not None:
62
+ raise SeriesLookupError(write_err.message)
63
+ try:
64
+ payload = post_lookup_json(
65
+ url,
66
+ attach_run_context_id(body),
67
+ lookup_label="utilization lookup",
68
+ settings=settings,
69
+ anonymous_id=install_id,
70
+ )
71
+ except LookupRedirectError as exc:
72
+ raise SeriesLookupError(str(exc)) from exc
73
+ except RecommendError as exc:
74
+ raise SeriesLookupError(str(exc)) from exc
75
+ except urllib.error.HTTPError as exc:
76
+ raise SeriesLookupError(f"utilization lookup HTTP {exc.code}") from exc
77
+ except (urllib.error.URLError, TimeoutError, ValueError) as exc:
78
+ raise SeriesLookupError(str(exc)) from exc
79
+ return _checked(payload)
80
+
81
+
82
+ def series_destination(settings: dict[str, Any] | None) -> bool:
83
+ if os.environ.get("MAPROOM_SERIES_FIXTURE", "").strip():
84
+ return True
85
+ return resolve_series_lookup_url(settings) is not None
86
+
87
+
88
+ def resolve_series_lookup_url(settings: dict | None) -> str | None:
89
+ return resolve_recommend_url(settings)
90
+
91
+
92
+ def _read_fixture(path: Path) -> dict[str, Any]:
93
+ try:
94
+ payload = json.loads(path.read_text(encoding="utf-8"))
95
+ except (OSError, json.JSONDecodeError) as exc:
96
+ raise SeriesLookupError("utilization lookup fixture could not be read") from exc
97
+ return _checked(payload)
98
+
99
+
100
+ def _checked(payload: object) -> dict[str, Any]:
101
+ try:
102
+ return require_series_response(payload)
103
+ except SeriesNotImplementedError:
104
+ raise
105
+ except ValueError as exc:
106
+ raise SeriesLookupError(str(exc)) from exc