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,129 @@
|
|
|
1
|
+
"""TTY-aware ANSI styling for human CLI output."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
ANSI_RESET = "\033[0m"
|
|
10
|
+
_RESET = ANSI_RESET
|
|
11
|
+
_STATUS_COLORS = {
|
|
12
|
+
"PASS": "\033[1;38;5;82m",
|
|
13
|
+
"FAIL": "\033[1;91m",
|
|
14
|
+
"WARN": "\033[1;93m",
|
|
15
|
+
"SKIPPED": "\033[90m",
|
|
16
|
+
"OPTIONAL": "\033[90m",
|
|
17
|
+
}
|
|
18
|
+
# Subtle inline-code block: light grey background, default dark text.
|
|
19
|
+
ANSI_COMMAND = "\033[48;5;254m\033[30m"
|
|
20
|
+
# Command args: hyphens and dotted names (file.txt); exclude a lone period before
|
|
21
|
+
# whitespace or end-of-line so sentence punctuation does not extend the span.
|
|
22
|
+
_CLI_ARG = r"[\w-]+(?:\.[\w-]+)*"
|
|
23
|
+
_CLI_COMMAND_RE = re.compile(
|
|
24
|
+
rf"(?P<cmd>"
|
|
25
|
+
rf"maproom(?:\s+(?!\s){_CLI_ARG})+"
|
|
26
|
+
r"|pipx upgrade maproom"
|
|
27
|
+
r"|aws login"
|
|
28
|
+
r"|az login"
|
|
29
|
+
r")"
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
_VT_PREPARED = False
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _enable_windows_vt_on_handle(std_handle_id: int) -> bool:
|
|
36
|
+
if os.name != "nt":
|
|
37
|
+
return True
|
|
38
|
+
try:
|
|
39
|
+
import ctypes
|
|
40
|
+
from ctypes import wintypes
|
|
41
|
+
|
|
42
|
+
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
43
|
+
handle = kernel32.GetStdHandle(std_handle_id)
|
|
44
|
+
mode = wintypes.DWORD()
|
|
45
|
+
if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
|
|
46
|
+
return False
|
|
47
|
+
enable_vt = 0x0004
|
|
48
|
+
return bool(kernel32.SetConsoleMode(handle, mode.value | enable_vt))
|
|
49
|
+
except (AttributeError, OSError, ValueError):
|
|
50
|
+
return False
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def prepare_ansi_stdout() -> bool:
|
|
54
|
+
"""Enable ANSI processing on Windows consoles; no-op elsewhere."""
|
|
55
|
+
global _VT_PREPARED
|
|
56
|
+
if _VT_PREPARED:
|
|
57
|
+
return True
|
|
58
|
+
if os.name != "nt":
|
|
59
|
+
_VT_PREPARED = True
|
|
60
|
+
return True
|
|
61
|
+
ok = _enable_windows_vt_on_handle(-11)
|
|
62
|
+
_VT_PREPARED = True
|
|
63
|
+
return ok
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def ansi_color_enabled(
|
|
67
|
+
*,
|
|
68
|
+
stdout_is_tty: bool | None = None,
|
|
69
|
+
force_color: bool = False,
|
|
70
|
+
no_color: bool = False,
|
|
71
|
+
as_json: bool = False,
|
|
72
|
+
) -> bool:
|
|
73
|
+
"""Return whether ANSI color may be applied to stdout."""
|
|
74
|
+
if no_color:
|
|
75
|
+
return False
|
|
76
|
+
if os.environ.get("NO_COLOR") is not None:
|
|
77
|
+
return False
|
|
78
|
+
if force_color:
|
|
79
|
+
prepare_ansi_stdout()
|
|
80
|
+
return True
|
|
81
|
+
if as_json:
|
|
82
|
+
return False
|
|
83
|
+
if os.environ.get("TERM", "").lower() == "dumb":
|
|
84
|
+
return False
|
|
85
|
+
is_tty = sys.stdout.isatty() if stdout_is_tty is None else stdout_is_tty
|
|
86
|
+
if not is_tty:
|
|
87
|
+
return False
|
|
88
|
+
return prepare_ansi_stdout()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def colorize_status_word(label: str, enabled: bool) -> str:
|
|
92
|
+
"""Wrap a PASS/FAIL/WARN/SKIPPED label with ANSI color when enabled."""
|
|
93
|
+
if not enabled:
|
|
94
|
+
return label
|
|
95
|
+
prefix = _STATUS_COLORS.get(label)
|
|
96
|
+
if prefix is None:
|
|
97
|
+
return label
|
|
98
|
+
return f"{prefix}{label}{_RESET}"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def colorize_success_text(text: str, enabled: bool) -> str:
|
|
102
|
+
"""Use the same green styling as PASS for arbitrary success copy."""
|
|
103
|
+
if not enabled:
|
|
104
|
+
return text
|
|
105
|
+
prefix = _STATUS_COLORS.get("PASS")
|
|
106
|
+
if prefix is None:
|
|
107
|
+
return text
|
|
108
|
+
return f"{prefix}{text}{_RESET}"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def colorize_muted(text: str, enabled: bool) -> str:
|
|
112
|
+
"""Dim grey for secondary metadata lines on interactive doctor output."""
|
|
113
|
+
if not enabled:
|
|
114
|
+
return text
|
|
115
|
+
prefix = _STATUS_COLORS.get("SKIPPED")
|
|
116
|
+
if prefix is None:
|
|
117
|
+
return text
|
|
118
|
+
return f"{prefix}{text}{_RESET}"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def highlight_cli_commands(text: str, enabled: bool) -> str:
|
|
122
|
+
"""Emphasize ``maproom …`` and related CLI snippets on TTY output."""
|
|
123
|
+
if not enabled or not text:
|
|
124
|
+
return text
|
|
125
|
+
|
|
126
|
+
def _replace(match: re.Match[str]) -> str:
|
|
127
|
+
return f"{ANSI_COMMAND}{match.group('cmd')}{_RESET}"
|
|
128
|
+
|
|
129
|
+
return _CLI_COMMAND_RE.sub(_replace, text)
|
maproom/parsers.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""Parsers over AWS and Azure CLI JSON responses."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from maproom.errors import (
|
|
8
|
+
AccessDeniedError,
|
|
9
|
+
NotFoundError,
|
|
10
|
+
NotLoggedInError,
|
|
11
|
+
ShapeValidationError,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _stderr_lower(response: dict[str, Any]) -> str:
|
|
16
|
+
return str(response.get("stderr") or "").lower()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def parse_sts_identity(
|
|
20
|
+
response: dict[str, Any],
|
|
21
|
+
*,
|
|
22
|
+
api_id: str = "aws_sts_get_caller_identity",
|
|
23
|
+
cli_version: str | None = None,
|
|
24
|
+
) -> dict[str, str]:
|
|
25
|
+
"""Parse get-caller-identity fixture/response into Account/Arn/UserId."""
|
|
26
|
+
exit_code = int(response.get("exit_code", 0))
|
|
27
|
+
if exit_code in (253, 255) or "unable to locate credentials" in _stderr_lower(
|
|
28
|
+
response
|
|
29
|
+
):
|
|
30
|
+
raise NotLoggedInError(
|
|
31
|
+
"not logged in to AWS CLI",
|
|
32
|
+
api_id=api_id,
|
|
33
|
+
cli_version=cli_version,
|
|
34
|
+
)
|
|
35
|
+
if exit_code != 0:
|
|
36
|
+
raise AccessDeniedError(
|
|
37
|
+
"sts get-caller-identity failed",
|
|
38
|
+
api_id=api_id,
|
|
39
|
+
cli_version=cli_version,
|
|
40
|
+
)
|
|
41
|
+
payload = response.get("stdout_json") or {}
|
|
42
|
+
for key in ("Account", "Arn", "UserId"):
|
|
43
|
+
if key not in payload:
|
|
44
|
+
raise ShapeValidationError(
|
|
45
|
+
f"missing required field {key}",
|
|
46
|
+
api_id=api_id,
|
|
47
|
+
cli_version=cli_version,
|
|
48
|
+
path=f"$.{key}",
|
|
49
|
+
)
|
|
50
|
+
return {
|
|
51
|
+
"Account": str(payload["Account"]),
|
|
52
|
+
"Arn": str(payload["Arn"]),
|
|
53
|
+
"UserId": str(payload["UserId"]),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def aws_principal_display_name(arn: str) -> str:
|
|
58
|
+
"""Human label for the logged-in IAM user or role from a get-caller-identity ARN."""
|
|
59
|
+
text = arn.strip()
|
|
60
|
+
if not text.startswith("arn:"):
|
|
61
|
+
return text
|
|
62
|
+
parts = text.split(":", 5)
|
|
63
|
+
if len(parts) < 6:
|
|
64
|
+
return text
|
|
65
|
+
resource = parts[5]
|
|
66
|
+
if resource.startswith("assumed-role/"):
|
|
67
|
+
segments = resource.split("/")
|
|
68
|
+
if len(segments) >= 2 and segments[1]:
|
|
69
|
+
return segments[1]
|
|
70
|
+
for prefix in ("user/", "role/"):
|
|
71
|
+
if resource.startswith(prefix):
|
|
72
|
+
name = resource[len(prefix) :]
|
|
73
|
+
if name:
|
|
74
|
+
return name
|
|
75
|
+
if "/" in resource:
|
|
76
|
+
return resource.split("/", 1)[1]
|
|
77
|
+
return resource
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def azure_account_identity_display(payload: dict[str, Any]) -> str:
|
|
81
|
+
"""Human label for the signed-in Azure user or service principal."""
|
|
82
|
+
user = payload.get("user")
|
|
83
|
+
if isinstance(user, dict):
|
|
84
|
+
name = user.get("name")
|
|
85
|
+
if isinstance(name, str) and name.strip():
|
|
86
|
+
return name.strip()
|
|
87
|
+
subscription = payload.get("name")
|
|
88
|
+
if isinstance(subscription, str) and subscription.strip():
|
|
89
|
+
return subscription.strip()
|
|
90
|
+
return "Azure account"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def parse_ec2_describe_instances(
|
|
94
|
+
response: dict[str, Any],
|
|
95
|
+
*,
|
|
96
|
+
api_id: str = "aws_ec2_describe_instances",
|
|
97
|
+
cli_version: str | None = None,
|
|
98
|
+
state_id: str | None = None,
|
|
99
|
+
) -> list[dict[str, Any]]:
|
|
100
|
+
"""Parse describe-instances; map error exits to typed Journey errors."""
|
|
101
|
+
exit_code = int(response.get("exit_code", 0))
|
|
102
|
+
err = _stderr_lower(response)
|
|
103
|
+
if exit_code in (253, 255) and "credential" in err:
|
|
104
|
+
raise NotLoggedInError(
|
|
105
|
+
"not logged in to AWS CLI",
|
|
106
|
+
api_id=api_id,
|
|
107
|
+
cli_version=cli_version,
|
|
108
|
+
)
|
|
109
|
+
if exit_code != 0:
|
|
110
|
+
if "unauthorizedoperation" in err or "accessdenied" in err or "not authorized" in err:
|
|
111
|
+
raise AccessDeniedError(
|
|
112
|
+
"ec2:DescribeInstances denied",
|
|
113
|
+
api_id=api_id,
|
|
114
|
+
cli_version=cli_version,
|
|
115
|
+
)
|
|
116
|
+
if "invalidinstanceid" in err or "notfound" in err:
|
|
117
|
+
raise NotFoundError(
|
|
118
|
+
"instance not found",
|
|
119
|
+
api_id=api_id,
|
|
120
|
+
cli_version=cli_version,
|
|
121
|
+
)
|
|
122
|
+
raise AccessDeniedError(
|
|
123
|
+
f"ec2 describe-instances failed (exit {exit_code})",
|
|
124
|
+
api_id=api_id,
|
|
125
|
+
cli_version=cli_version,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
payload = response.get("stdout_json") or {}
|
|
129
|
+
if "Reservations" not in payload:
|
|
130
|
+
raise ShapeValidationError(
|
|
131
|
+
"missing required field Reservations",
|
|
132
|
+
api_id=api_id,
|
|
133
|
+
cli_version=cli_version,
|
|
134
|
+
path="$.Reservations",
|
|
135
|
+
)
|
|
136
|
+
instances: list[dict[str, Any]] = []
|
|
137
|
+
for reservation in payload.get("Reservations") or []:
|
|
138
|
+
for inst in reservation.get("Instances") or []:
|
|
139
|
+
instances.append(inst)
|
|
140
|
+
|
|
141
|
+
if state_id == "empty_filter":
|
|
142
|
+
return instances
|
|
143
|
+
if state_id in ("running", "stopped") and not instances:
|
|
144
|
+
raise NotFoundError(
|
|
145
|
+
"no instances in describe-instances result",
|
|
146
|
+
api_id=api_id,
|
|
147
|
+
cli_version=cli_version,
|
|
148
|
+
)
|
|
149
|
+
return instances
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def parse_cloudwatch_get_metric_data(
|
|
153
|
+
response: dict[str, Any],
|
|
154
|
+
*,
|
|
155
|
+
api_id: str = "aws_cloudwatch_get_metric_data",
|
|
156
|
+
cli_version: str | None = None,
|
|
157
|
+
) -> list[dict[str, Any]]:
|
|
158
|
+
"""Parse get-metric-data; return MetricDataResults rows (may be empty)."""
|
|
159
|
+
exit_code = int(response.get("exit_code", 0))
|
|
160
|
+
err = _stderr_lower(response)
|
|
161
|
+
if exit_code in (253, 255) and "credential" in err:
|
|
162
|
+
raise NotLoggedInError(
|
|
163
|
+
"not logged in to AWS CLI",
|
|
164
|
+
api_id=api_id,
|
|
165
|
+
cli_version=cli_version,
|
|
166
|
+
)
|
|
167
|
+
if exit_code != 0:
|
|
168
|
+
if "unauthorizedoperation" in err or "accessdenied" in err or "not authorized" in err:
|
|
169
|
+
raise AccessDeniedError(
|
|
170
|
+
"cloudwatch:GetMetricData denied",
|
|
171
|
+
api_id=api_id,
|
|
172
|
+
cli_version=cli_version,
|
|
173
|
+
)
|
|
174
|
+
raise AccessDeniedError(
|
|
175
|
+
f"cloudwatch get-metric-data failed (exit {exit_code})",
|
|
176
|
+
api_id=api_id,
|
|
177
|
+
cli_version=cli_version,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
payload = response.get("stdout_json") or {}
|
|
181
|
+
results = payload.get("MetricDataResults")
|
|
182
|
+
if results is None:
|
|
183
|
+
raise ShapeValidationError(
|
|
184
|
+
"missing required field MetricDataResults",
|
|
185
|
+
api_id=api_id,
|
|
186
|
+
cli_version=cli_version,
|
|
187
|
+
path="$.MetricDataResults",
|
|
188
|
+
)
|
|
189
|
+
return list(results)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def parse_cloudtrail_lookup_events(
|
|
193
|
+
response: dict[str, Any],
|
|
194
|
+
*,
|
|
195
|
+
api_id: str = "aws_cloudtrail_lookup_events",
|
|
196
|
+
cli_version: str | None = None,
|
|
197
|
+
) -> tuple[list[dict[str, Any]], str | None]:
|
|
198
|
+
"""Parse lookup-events; return events and optional NextToken."""
|
|
199
|
+
exit_code = int(response.get("exit_code", 0))
|
|
200
|
+
err = _stderr_lower(response)
|
|
201
|
+
if exit_code in (253, 255) and "credential" in err:
|
|
202
|
+
raise NotLoggedInError(
|
|
203
|
+
"not logged in to AWS CLI",
|
|
204
|
+
api_id=api_id,
|
|
205
|
+
cli_version=cli_version,
|
|
206
|
+
)
|
|
207
|
+
if exit_code != 0:
|
|
208
|
+
if "unauthorizedoperation" in err or "accessdenied" in err or "not authorized" in err:
|
|
209
|
+
raise AccessDeniedError(
|
|
210
|
+
"cloudtrail:LookupEvents denied",
|
|
211
|
+
api_id=api_id,
|
|
212
|
+
cli_version=cli_version,
|
|
213
|
+
)
|
|
214
|
+
raise AccessDeniedError(
|
|
215
|
+
f"cloudtrail lookup-events failed (exit {exit_code})",
|
|
216
|
+
api_id=api_id,
|
|
217
|
+
cli_version=cli_version,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
payload = response.get("stdout_json") or {}
|
|
221
|
+
events = payload.get("Events")
|
|
222
|
+
if events is None:
|
|
223
|
+
raise ShapeValidationError(
|
|
224
|
+
"missing required field Events",
|
|
225
|
+
api_id=api_id,
|
|
226
|
+
cli_version=cli_version,
|
|
227
|
+
path="$.Events",
|
|
228
|
+
)
|
|
229
|
+
next_token = payload.get("NextToken")
|
|
230
|
+
token_out = str(next_token) if next_token else None
|
|
231
|
+
return list(events), token_out
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def parse_config_resource_config_history(
|
|
235
|
+
response: dict[str, Any],
|
|
236
|
+
*,
|
|
237
|
+
api_id: str = "aws_config_get_resource_config_history",
|
|
238
|
+
cli_version: str | None = None,
|
|
239
|
+
) -> list[dict[str, Any]]:
|
|
240
|
+
"""Parse get-resource-config-history configuration items."""
|
|
241
|
+
exit_code = int(response.get("exit_code", 0))
|
|
242
|
+
err = _stderr_lower(response)
|
|
243
|
+
if exit_code in (253, 255) and "credential" in err:
|
|
244
|
+
raise NotLoggedInError(
|
|
245
|
+
"not logged in to AWS CLI",
|
|
246
|
+
api_id=api_id,
|
|
247
|
+
cli_version=cli_version,
|
|
248
|
+
)
|
|
249
|
+
if exit_code != 0:
|
|
250
|
+
lowered = err
|
|
251
|
+
if "noavailableconfigurationrecorderexception" in lowered:
|
|
252
|
+
raise AccessDeniedError(
|
|
253
|
+
"aws config recorder not enabled",
|
|
254
|
+
api_id=api_id,
|
|
255
|
+
cli_version=cli_version,
|
|
256
|
+
)
|
|
257
|
+
if "resourcenotdiscoveredexception" in lowered:
|
|
258
|
+
raise AccessDeniedError(
|
|
259
|
+
"aws config resource not discovered",
|
|
260
|
+
api_id=api_id,
|
|
261
|
+
cli_version=cli_version,
|
|
262
|
+
)
|
|
263
|
+
if "unauthorizedoperation" in lowered or "accessdenied" in lowered or "not authorized" in lowered:
|
|
264
|
+
raise AccessDeniedError(
|
|
265
|
+
"config:GetResourceConfigHistory denied",
|
|
266
|
+
api_id=api_id,
|
|
267
|
+
cli_version=cli_version,
|
|
268
|
+
)
|
|
269
|
+
raise AccessDeniedError(
|
|
270
|
+
f"config get-resource-config-history failed (exit {exit_code})",
|
|
271
|
+
api_id=api_id,
|
|
272
|
+
cli_version=cli_version,
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
payload = response.get("stdout_json") or {}
|
|
276
|
+
items = payload.get("configurationItems")
|
|
277
|
+
if items is None:
|
|
278
|
+
raise ShapeValidationError(
|
|
279
|
+
"missing required field configurationItems",
|
|
280
|
+
api_id=api_id,
|
|
281
|
+
cli_version=cli_version,
|
|
282
|
+
path="$.configurationItems",
|
|
283
|
+
)
|
|
284
|
+
return list(items)
|
maproom/paths.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Platform settings and data path resolution."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
DATA_SUBDIRS = ("reservations", "savings-plans", "quotas", "plans", "instances", "request_ledger")
|
|
11
|
+
|
|
12
|
+
DIR_NAME = "maproom"
|
|
13
|
+
# Pre-rename directory. Read when the Maproom directory is absent. Writes stay on DIR_NAME.
|
|
14
|
+
LEGACY_DIR_NAME = "repot"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def settings_dir() -> Path:
|
|
18
|
+
"""Return the Maproom config directory for this platform."""
|
|
19
|
+
config_home = os.environ.get("XDG_CONFIG_HOME")
|
|
20
|
+
if config_home:
|
|
21
|
+
return (Path(config_home) / DIR_NAME).resolve()
|
|
22
|
+
if sys.platform == "win32":
|
|
23
|
+
base = os.environ.get("APPDATA")
|
|
24
|
+
if base:
|
|
25
|
+
return (Path(base) / DIR_NAME).resolve()
|
|
26
|
+
return (Path.home() / "AppData" / "Roaming" / DIR_NAME).resolve()
|
|
27
|
+
return (Path.home() / ".config" / DIR_NAME).resolve()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def settings_file() -> Path:
|
|
31
|
+
"""Canonical settings path. Writes use this path."""
|
|
32
|
+
return settings_dir() / "settings.toml"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def settings_read_file() -> Path:
|
|
36
|
+
"""Settings file to read. Uses a pre-rename file when the Maproom file is absent."""
|
|
37
|
+
current = settings_file()
|
|
38
|
+
if current.is_file():
|
|
39
|
+
return current
|
|
40
|
+
legacy = settings_dir().with_name(LEGACY_DIR_NAME) / "settings.toml"
|
|
41
|
+
if legacy.is_file():
|
|
42
|
+
return legacy
|
|
43
|
+
return current
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def prepare_settings_write() -> Path:
|
|
47
|
+
"""Copy a pre-rename settings file into the Maproom path, then return that path."""
|
|
48
|
+
current = settings_file()
|
|
49
|
+
if current.exists():
|
|
50
|
+
return current
|
|
51
|
+
legacy = settings_dir().with_name(LEGACY_DIR_NAME) / "settings.toml"
|
|
52
|
+
if legacy.is_file():
|
|
53
|
+
current.parent.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
shutil.copy2(legacy, current)
|
|
55
|
+
return current
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def data_root() -> Path:
|
|
59
|
+
"""Return the Maproom data root (reservations/, quotas/, etc.)."""
|
|
60
|
+
data_home = os.environ.get("XDG_DATA_HOME")
|
|
61
|
+
if data_home:
|
|
62
|
+
return (Path(data_home) / DIR_NAME).resolve()
|
|
63
|
+
if sys.platform == "win32":
|
|
64
|
+
base = os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA")
|
|
65
|
+
if base:
|
|
66
|
+
return (Path(base) / DIR_NAME).resolve()
|
|
67
|
+
return (Path.home() / "AppData" / "Local" / DIR_NAME).resolve()
|
|
68
|
+
return (Path.home() / ".local" / "share" / DIR_NAME).resolve()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def data_subdir(name: str) -> Path:
|
|
72
|
+
return data_root() / name
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def readable_data_dir(name: str) -> Path:
|
|
76
|
+
"""Data subdirectory to read. Falls back to the pre-rename directory."""
|
|
77
|
+
current = data_subdir(name)
|
|
78
|
+
if current.exists():
|
|
79
|
+
return current
|
|
80
|
+
legacy = data_root().with_name(LEGACY_DIR_NAME) / name
|
|
81
|
+
if legacy.exists():
|
|
82
|
+
return legacy
|
|
83
|
+
return current
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def readable_data_file(*parts: str) -> Path:
|
|
87
|
+
"""Data file to read. Falls back to the same relative path under the pre-rename root."""
|
|
88
|
+
current = data_root().joinpath(*parts)
|
|
89
|
+
if current.exists():
|
|
90
|
+
return current
|
|
91
|
+
legacy = data_root().with_name(LEGACY_DIR_NAME).joinpath(*parts)
|
|
92
|
+
if legacy.exists():
|
|
93
|
+
return legacy
|
|
94
|
+
return current
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def prepare_data_write() -> Path:
|
|
98
|
+
"""Copy a pre-rename data directory into the Maproom path, then return that path."""
|
|
99
|
+
current = data_root()
|
|
100
|
+
if current.exists():
|
|
101
|
+
return current
|
|
102
|
+
legacy = current.with_name(LEGACY_DIR_NAME)
|
|
103
|
+
if legacy.is_dir():
|
|
104
|
+
shutil.copytree(legacy, current)
|
|
105
|
+
return current
|
maproom/plan/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Local plan store, analyze selection, and export."""
|
maproom/plan/accept.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Deterministic --accept candidate selection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from maproom.plan.errors import PlanError
|
|
8
|
+
from maproom.plan.migration_options import candidate_qualifies, parse_accept_values
|
|
9
|
+
|
|
10
|
+
_CONFIDENCE_RANK = {"HIGH": 3, "MEDIUM": 2, "LOW": 1}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _iter_candidates(doc: dict[str, Any]) -> list[dict[str, Any]]:
|
|
14
|
+
candidates: list[dict[str, Any]] = []
|
|
15
|
+
for item in doc.get("recommendations") or []:
|
|
16
|
+
candidates.append(dict(item))
|
|
17
|
+
for item in doc.get("conditional_moves") or []:
|
|
18
|
+
candidates.append(dict(item))
|
|
19
|
+
return candidates
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _price_key(candidate: dict[str, Any]) -> float:
|
|
23
|
+
raw = candidate.get("price_per_month_usd")
|
|
24
|
+
try:
|
|
25
|
+
return float(raw)
|
|
26
|
+
except (TypeError, ValueError):
|
|
27
|
+
return float("inf")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _confidence_key(candidate: dict[str, Any]) -> int:
|
|
31
|
+
value = str(candidate.get("confidence") or "LOW").upper()
|
|
32
|
+
return _CONFIDENCE_RANK.get(value, 0)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def select_accept_candidate(
|
|
36
|
+
doc: dict[str, Any],
|
|
37
|
+
accept_values: list[str],
|
|
38
|
+
) -> dict[str, Any] | PlanError:
|
|
39
|
+
parsed = parse_accept_values(accept_values)
|
|
40
|
+
if isinstance(parsed, PlanError):
|
|
41
|
+
return parsed
|
|
42
|
+
qualifiers = [
|
|
43
|
+
candidate
|
|
44
|
+
for candidate in _iter_candidates(doc)
|
|
45
|
+
if candidate_qualifies(
|
|
46
|
+
list(candidate.get("migration_options") or []),
|
|
47
|
+
parsed,
|
|
48
|
+
)
|
|
49
|
+
]
|
|
50
|
+
if not qualifiers:
|
|
51
|
+
return PlanError("no recommendation qualifies for the supplied --accept values")
|
|
52
|
+
qualifiers.sort(
|
|
53
|
+
key=lambda c: (
|
|
54
|
+
_price_key(c),
|
|
55
|
+
-_confidence_key(c),
|
|
56
|
+
str(c.get("candidate_id") or ""),
|
|
57
|
+
)
|
|
58
|
+
)
|
|
59
|
+
return qualifiers[0]
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Copy analyze recommendation context onto plan items (NEXT-1 W7)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from decimal import Decimal
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from maproom.pricing import PriceTable, load_price_table
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _usd_amount_str(value: Decimal) -> str:
|
|
12
|
+
rounded = value.quantize(Decimal("0.001"))
|
|
13
|
+
integral = rounded.to_integral_value()
|
|
14
|
+
if rounded == integral:
|
|
15
|
+
return str(int(integral))
|
|
16
|
+
text = format(rounded.normalize(), "f")
|
|
17
|
+
if "." in text:
|
|
18
|
+
text = text.rstrip("0").rstrip(".")
|
|
19
|
+
return text
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def build_rejected_summary(
|
|
23
|
+
doc: dict[str, Any],
|
|
24
|
+
*,
|
|
25
|
+
region: str,
|
|
26
|
+
prices: PriceTable | None = None,
|
|
27
|
+
) -> dict[str, Any] | None:
|
|
28
|
+
by_reason = dict(doc.get("rejected_by_reason") or {})
|
|
29
|
+
rejected_total = doc.get("rejected_total")
|
|
30
|
+
if rejected_total is None and not by_reason:
|
|
31
|
+
return None
|
|
32
|
+
total = int(rejected_total if rejected_total is not None else sum(by_reason.values()))
|
|
33
|
+
table = prices or load_price_table()
|
|
34
|
+
top: list[dict[str, Any]] = []
|
|
35
|
+
for entry in (doc.get("rejected") or [])[:5]:
|
|
36
|
+
instance_type = str(entry.get("instance_type") or "")
|
|
37
|
+
monthly = table.monthly(instance_type, region) if instance_type else None
|
|
38
|
+
price_str = _usd_amount_str(monthly) if monthly is not None else "0"
|
|
39
|
+
top.append(
|
|
40
|
+
{
|
|
41
|
+
"instance_type": instance_type,
|
|
42
|
+
"reason": str(entry.get("reason") or entry.get("reason_code") or ""),
|
|
43
|
+
"price_per_month_usd": price_str,
|
|
44
|
+
}
|
|
45
|
+
)
|
|
46
|
+
return {
|
|
47
|
+
"rejected_total": total,
|
|
48
|
+
"by_reason": by_reason,
|
|
49
|
+
"top": top,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def analysis_fields_from_document(
|
|
54
|
+
doc: dict[str, Any],
|
|
55
|
+
*,
|
|
56
|
+
region: str,
|
|
57
|
+
prices: PriceTable | None = None,
|
|
58
|
+
) -> dict[str, Any]:
|
|
59
|
+
"""Optional additive plan-item fields from a recommendation document."""
|
|
60
|
+
fields: dict[str, Any] = {}
|
|
61
|
+
if doc.get("provider_recommendation") is not None:
|
|
62
|
+
fields["provider_recommendation"] = doc.get("provider_recommendation")
|
|
63
|
+
gap = doc.get("provider_gap")
|
|
64
|
+
if isinstance(gap, dict) and gap:
|
|
65
|
+
fields["provider_gap"] = dict(gap)
|
|
66
|
+
rejected_summary = build_rejected_summary(doc, region=region, prices=prices)
|
|
67
|
+
if rejected_summary is not None:
|
|
68
|
+
fields["rejected_summary"] = rejected_summary
|
|
69
|
+
engine = doc.get("engine")
|
|
70
|
+
if isinstance(engine, dict) and engine:
|
|
71
|
+
fields["engine"] = dict(engine)
|
|
72
|
+
pricing_data_as_of = doc.get("pricing_data_as_of")
|
|
73
|
+
if pricing_data_as_of:
|
|
74
|
+
fields["pricing_data_as_of"] = str(pricing_data_as_of)
|
|
75
|
+
spec_source = doc.get("spec_source")
|
|
76
|
+
if spec_source in {"provider", "fixture", "shipped"}:
|
|
77
|
+
fields["spec_source"] = spec_source
|
|
78
|
+
return fields
|