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
maproom/consent/stdin.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Detect whether stdin can answer an interactive consent prompt."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def stdin_allows_prompt(*, stdin_is_tty: bool | None = None) -> bool:
|
|
9
|
+
"""Return False when consent must not call input() (pipe, closed, Windows NUL, …)."""
|
|
10
|
+
if stdin_is_tty is not None:
|
|
11
|
+
return bool(stdin_is_tty)
|
|
12
|
+
if not sys.stdin.isatty():
|
|
13
|
+
return False
|
|
14
|
+
if _on_windows() and not _windows_console_stdin():
|
|
15
|
+
return False
|
|
16
|
+
return True
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _on_windows() -> bool:
|
|
20
|
+
return sys.platform == "win32"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _windows_console_stdin() -> bool:
|
|
24
|
+
"""On Windows, NUL and similar char devices report isatty() True but are not consoles."""
|
|
25
|
+
try:
|
|
26
|
+
import msvcrt
|
|
27
|
+
|
|
28
|
+
handle = msvcrt.get_osfhandle(sys.stdin.fileno())
|
|
29
|
+
except (OSError, ValueError, ImportError):
|
|
30
|
+
return True
|
|
31
|
+
if handle in (-1, -2):
|
|
32
|
+
return False
|
|
33
|
+
try:
|
|
34
|
+
import ctypes
|
|
35
|
+
from ctypes import wintypes
|
|
36
|
+
|
|
37
|
+
kernel32 = ctypes.windll.kernel32
|
|
38
|
+
mode = wintypes.DWORD()
|
|
39
|
+
if kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
|
|
40
|
+
return True
|
|
41
|
+
if kernel32.GetLastError() == 6: # ERROR_INVALID_HANDLE
|
|
42
|
+
return False
|
|
43
|
+
except (AttributeError, OSError, ValueError):
|
|
44
|
+
return True
|
|
45
|
+
return True
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Consent storage availability detection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from maproom.paths import settings_file
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _parent_creatable(path: Path) -> bool:
|
|
12
|
+
existing = path
|
|
13
|
+
while not existing.exists() and existing != existing.parent:
|
|
14
|
+
existing = existing.parent
|
|
15
|
+
if not existing.exists():
|
|
16
|
+
return False
|
|
17
|
+
return os.access(existing, os.W_OK)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def consent_storage_available(*, settings_path: Path | None = None) -> bool:
|
|
21
|
+
"""Return True when consent can be read and persisted to the settings path."""
|
|
22
|
+
path = settings_path or settings_file()
|
|
23
|
+
parent = path.parent
|
|
24
|
+
return parent.exists() or _parent_creatable(parent)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""One-time tokens for registered cloud writes.
|
|
2
|
+
|
|
3
|
+
``Runner.run`` rejects ``access: write`` APIs unless the caller presents a
|
|
4
|
+
token minted here. Minting happens only after a person has approved the exact
|
|
5
|
+
write. Tokens are single-use and process-local.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import secrets
|
|
11
|
+
|
|
12
|
+
_issued: set[tuple[str, str]] = set()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def issue_cloud_write_token(api_id: str) -> str:
|
|
16
|
+
"""Mint a single-use token for one registered write API."""
|
|
17
|
+
token = secrets.token_hex(16)
|
|
18
|
+
_issued.add((api_id, token))
|
|
19
|
+
return token
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def consume_cloud_write_token(api_id: str, token: str | None) -> bool:
|
|
23
|
+
if not token:
|
|
24
|
+
return False
|
|
25
|
+
key = (api_id, token)
|
|
26
|
+
if key not in _issued:
|
|
27
|
+
return False
|
|
28
|
+
_issued.discard(key)
|
|
29
|
+
return True
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Output contract helpers (schema validation and additive diff)."""
|
|
2
|
+
|
|
3
|
+
from maproom.contracts.schema_diff import BreakingChange, diff_schemas
|
|
4
|
+
from maproom.contracts.validate import validate_stdout_json
|
|
5
|
+
|
|
6
|
+
__all__ = ["BreakingChange", "diff_schemas", "validate_stdout_json"]
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Additive-only JSON Schema diff vs the released copy."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class BreakingChange:
|
|
11
|
+
path: str
|
|
12
|
+
message: str
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def diff_schemas(released: dict[str, Any], working: dict[str, Any]) -> list[BreakingChange]:
|
|
16
|
+
"""Return breaking changes when ``working`` is not additive over ``released``."""
|
|
17
|
+
changes: list[BreakingChange] = []
|
|
18
|
+
_diff_defs(released.get("$defs", {}), working.get("$defs", {}), changes)
|
|
19
|
+
_diff_schema_nodes(released, working, "$", changes)
|
|
20
|
+
return changes
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _diff_defs(
|
|
24
|
+
released: dict[str, Any],
|
|
25
|
+
working: dict[str, Any],
|
|
26
|
+
changes: list[BreakingChange],
|
|
27
|
+
) -> None:
|
|
28
|
+
for name, released_node in released.items():
|
|
29
|
+
path = f"$defs.{name}"
|
|
30
|
+
if name not in working:
|
|
31
|
+
changes.append(BreakingChange(path, f"removed schema def {name}"))
|
|
32
|
+
continue
|
|
33
|
+
_diff_schema_nodes(released_node, working[name], path, changes)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _diff_schema_nodes(
|
|
37
|
+
released: dict[str, Any],
|
|
38
|
+
working: dict[str, Any],
|
|
39
|
+
path: str,
|
|
40
|
+
changes: list[BreakingChange],
|
|
41
|
+
) -> None:
|
|
42
|
+
if not isinstance(released, dict) or not isinstance(working, dict):
|
|
43
|
+
return
|
|
44
|
+
|
|
45
|
+
released_type = released.get("type")
|
|
46
|
+
working_type = working.get("type")
|
|
47
|
+
if released_type is not None and working_type is not None and released_type != working_type:
|
|
48
|
+
changes.append(
|
|
49
|
+
BreakingChange(path, f"type changed from {released_type!r} to {working_type!r}")
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
released_props = released.get("properties")
|
|
53
|
+
working_props = working.get("properties")
|
|
54
|
+
if isinstance(released_props, dict) and isinstance(working_props, dict):
|
|
55
|
+
for key, released_prop in released_props.items():
|
|
56
|
+
prop_path = f"{path}.properties.{key}"
|
|
57
|
+
if key not in working_props:
|
|
58
|
+
changes.append(BreakingChange(prop_path, f"removed property {key!r}"))
|
|
59
|
+
continue
|
|
60
|
+
_diff_schema_nodes(released_prop, working_props[key], prop_path, changes)
|
|
61
|
+
for key, working_prop in working_props.items():
|
|
62
|
+
if key not in released_props:
|
|
63
|
+
_diff_schema_nodes({}, working_prop, f"{path}.properties.{key}", changes)
|
|
64
|
+
|
|
65
|
+
released_required = released.get("required")
|
|
66
|
+
working_required = working.get("required")
|
|
67
|
+
if isinstance(released_required, list) and isinstance(working_required, list):
|
|
68
|
+
for key in working_required:
|
|
69
|
+
if key not in released_required:
|
|
70
|
+
changes.append(
|
|
71
|
+
BreakingChange(
|
|
72
|
+
f"{path}.required",
|
|
73
|
+
f"field {key!r} newly required",
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
released_enum = released.get("enum")
|
|
78
|
+
working_enum = working.get("enum")
|
|
79
|
+
if isinstance(released_enum, list) and isinstance(working_enum, list):
|
|
80
|
+
removed = [value for value in released_enum if value not in working_enum]
|
|
81
|
+
if removed:
|
|
82
|
+
changes.append(
|
|
83
|
+
BreakingChange(
|
|
84
|
+
path,
|
|
85
|
+
f"removed enum values: {removed!r}",
|
|
86
|
+
)
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
released_const = released.get("const")
|
|
90
|
+
working_const = working.get("const")
|
|
91
|
+
if released_const is not None and working_const is not None and released_const != working_const:
|
|
92
|
+
changes.append(
|
|
93
|
+
BreakingChange(path, f"const changed from {released_const!r} to {working_const!r}")
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
if released.get("additionalProperties") is False and working.get("additionalProperties") is True:
|
|
97
|
+
changes.append(
|
|
98
|
+
BreakingChange(path, "additionalProperties relaxed from false to true")
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
for keyword in ("items", "contains", "not"):
|
|
102
|
+
if keyword in released or keyword in working:
|
|
103
|
+
_diff_schema_nodes(
|
|
104
|
+
released.get(keyword, {}),
|
|
105
|
+
working.get(keyword, {}),
|
|
106
|
+
f"{path}.{keyword}",
|
|
107
|
+
changes,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
for index, (released_branch, working_branch) in enumerate(
|
|
111
|
+
zip(released.get("oneOf", []), working.get("oneOf", []))
|
|
112
|
+
):
|
|
113
|
+
_diff_schema_nodes(released_branch, working_branch, f"{path}.oneOf[{index}]", changes)
|
|
114
|
+
|
|
115
|
+
if isinstance(released.get("oneOf"), list) and isinstance(working.get("oneOf"), list):
|
|
116
|
+
if len(working["oneOf"]) < len(released["oneOf"]):
|
|
117
|
+
changes.append(
|
|
118
|
+
BreakingChange(path, "removed oneOf branch")
|
|
119
|
+
)
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Validate maproom --json stdout against the working output schema."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from functools import lru_cache
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from maproom.exitcodes import (
|
|
11
|
+
released_plan_schema_path,
|
|
12
|
+
released_schema_path,
|
|
13
|
+
working_plan_schema_path,
|
|
14
|
+
working_schema_path,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _jsonschema():
|
|
19
|
+
"""jsonschema is a test dependency. The CLI does not validate its own stdout."""
|
|
20
|
+
import jsonschema
|
|
21
|
+
|
|
22
|
+
return jsonschema
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _schema_cache_key(path: Path) -> str:
|
|
26
|
+
return str(path.resolve())
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@lru_cache(maxsize=32)
|
|
30
|
+
def _load_schema_cached(key: str) -> dict[str, Any]:
|
|
31
|
+
path = Path(key)
|
|
32
|
+
if not path.is_file():
|
|
33
|
+
raise FileNotFoundError(f"schema not found: {path}")
|
|
34
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _load_schema(path) -> dict[str, Any]:
|
|
38
|
+
return _load_schema_cached(_schema_cache_key(Path(path)))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@lru_cache(maxsize=8)
|
|
42
|
+
def _command_schema_registry_cached(key: str):
|
|
43
|
+
"""Registry of command schemas next to an output schema file."""
|
|
44
|
+
from referencing import Registry, Resource
|
|
45
|
+
|
|
46
|
+
schema_path = Path(key)
|
|
47
|
+
commands_dir = schema_path.parent / "commands"
|
|
48
|
+
registry = Registry()
|
|
49
|
+
if not commands_dir.is_dir():
|
|
50
|
+
return registry
|
|
51
|
+
for command_path in sorted(commands_dir.glob("*.schema.json")):
|
|
52
|
+
contents = json.loads(command_path.read_text(encoding="utf-8"))
|
|
53
|
+
schema_id = contents.get("$id")
|
|
54
|
+
if isinstance(schema_id, str) and schema_id:
|
|
55
|
+
registry = registry.with_resource(schema_id, Resource.from_contents(contents))
|
|
56
|
+
return registry
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def command_schema_registry(anchor: Path | None = None):
|
|
60
|
+
"""Registry of command schemas next to an output schema file.
|
|
61
|
+
|
|
62
|
+
The umbrella ``$ref``s each command by ``$id`` (``maproom.analyze`` and
|
|
63
|
+
the rest). Those ids are not file URLs, so validation loads
|
|
64
|
+
``commands/*.schema.json`` beside ``anchor``.
|
|
65
|
+
"""
|
|
66
|
+
schema_path = anchor or working_schema_path()
|
|
67
|
+
return _command_schema_registry_cached(_schema_cache_key(Path(schema_path)))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _validate_document(
|
|
71
|
+
doc: Any,
|
|
72
|
+
schema: dict[str, Any],
|
|
73
|
+
*,
|
|
74
|
+
anchor: Path | None = None,
|
|
75
|
+
) -> None:
|
|
76
|
+
validator_cls = _jsonschema().validators.validator_for(schema)
|
|
77
|
+
validator_cls.check_schema(schema)
|
|
78
|
+
registry_anchor = anchor or working_schema_path()
|
|
79
|
+
validator_cls(schema, registry=command_schema_registry(registry_anchor)).validate(doc)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def validate_stdout_json(text: str) -> dict[str, Any]:
|
|
83
|
+
"""Parse stdout and validate against ``contracts/output/maproom_output.v1.schema.json``."""
|
|
84
|
+
stripped = text.strip()
|
|
85
|
+
if not stripped:
|
|
86
|
+
raise ValueError("empty stdout")
|
|
87
|
+
doc, end = json.JSONDecoder().raw_decode(stripped)
|
|
88
|
+
trailing = stripped[end:].strip()
|
|
89
|
+
if trailing:
|
|
90
|
+
raise ValueError(f"trailing stdout after JSON document: {trailing!r}")
|
|
91
|
+
path = working_schema_path()
|
|
92
|
+
_validate_document(doc, _load_schema(path), anchor=path)
|
|
93
|
+
return doc
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def validate_against_schema(doc: dict[str, Any], schema: dict[str, Any]) -> None:
|
|
97
|
+
_validate_document(doc, schema)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def load_working_schema() -> dict[str, Any]:
|
|
101
|
+
return _load_schema(working_schema_path())
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def load_released_schema() -> dict[str, Any]:
|
|
105
|
+
return _load_schema(released_schema_path())
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def load_working_plan_schema() -> dict[str, Any]:
|
|
109
|
+
return _load_schema(working_plan_schema_path())
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def load_released_plan_schema() -> dict[str, Any]:
|
|
113
|
+
return _load_schema(released_plan_schema_path())
|
maproom/data/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Local platform data directory commands."""
|
maproom/data/clear.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Delete all files and folders under the platform data root."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from maproom.exitcodes import RUNTIME, SUCCESS, USAGE
|
|
10
|
+
from maproom.paths import data_root
|
|
11
|
+
from maproom.plan.tty import PromptClosed, confirm_yes_no
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _safe_data_root() -> Path:
|
|
15
|
+
root = data_root()
|
|
16
|
+
if root.name != "maproom":
|
|
17
|
+
raise OSError(f"refusing to clear unexpected data root: {root}")
|
|
18
|
+
return root
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def clear_local_data(*, force: bool = False, stdin_is_tty: bool | None = None) -> int:
|
|
22
|
+
"""Remove everything under ``data_root()``; does not touch settings."""
|
|
23
|
+
try:
|
|
24
|
+
root = _safe_data_root()
|
|
25
|
+
except OSError as exc:
|
|
26
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
27
|
+
return RUNTIME
|
|
28
|
+
|
|
29
|
+
if not root.exists():
|
|
30
|
+
print(f"No local data at {root}")
|
|
31
|
+
return SUCCESS
|
|
32
|
+
|
|
33
|
+
entries = list(root.iterdir())
|
|
34
|
+
if not entries:
|
|
35
|
+
print(f"Local data directory is already empty: {root}")
|
|
36
|
+
return SUCCESS
|
|
37
|
+
|
|
38
|
+
is_tty = stdin_is_tty if stdin_is_tty is not None else sys.stdin.isatty()
|
|
39
|
+
if not force:
|
|
40
|
+
if not is_tty:
|
|
41
|
+
print(
|
|
42
|
+
"error: maproom data clear needs a confirmation",
|
|
43
|
+
file=sys.stderr,
|
|
44
|
+
)
|
|
45
|
+
print("hint: maproom data clear --force", file=sys.stderr)
|
|
46
|
+
return USAGE
|
|
47
|
+
print(f"Local data root: {root}")
|
|
48
|
+
print(
|
|
49
|
+
"Will remove instance snapshots, quota/reservation/savings-plan "
|
|
50
|
+
"inventories, plans, analyze reads, analyze grades, and request "
|
|
51
|
+
"ledger entries."
|
|
52
|
+
)
|
|
53
|
+
prompt = "Delete all local maproom data"
|
|
54
|
+
try:
|
|
55
|
+
confirmed = confirm_yes_no(prompt, default_no=True)
|
|
56
|
+
except PromptClosed as exc:
|
|
57
|
+
print(f"error: {exc.message}", file=sys.stderr)
|
|
58
|
+
return USAGE
|
|
59
|
+
if not confirmed:
|
|
60
|
+
print(f"Nothing was deleted. Local data is still at {root}.")
|
|
61
|
+
return SUCCESS
|
|
62
|
+
|
|
63
|
+
removed_paths: list[str] = []
|
|
64
|
+
for path in entries:
|
|
65
|
+
if path.is_dir():
|
|
66
|
+
shutil.rmtree(path)
|
|
67
|
+
else:
|
|
68
|
+
path.unlink()
|
|
69
|
+
removed_paths.append(str(path))
|
|
70
|
+
|
|
71
|
+
noun = "item" if len(removed_paths) == 1 else "items"
|
|
72
|
+
print(f"Removed {len(removed_paths)} {noun} under {root}:")
|
|
73
|
+
for path in removed_paths:
|
|
74
|
+
print(f" {path}")
|
|
75
|
+
print("Settings and consent are kept.")
|
|
76
|
+
return SUCCESS
|
maproom/data/commands.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""CLI handlers for ``maproom data``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from maproom.consent.stdin import stdin_allows_prompt
|
|
7
|
+
from maproom.data.clear import clear_local_data
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def cmd_data_clear(args: argparse.Namespace) -> int:
|
|
11
|
+
return clear_local_data(
|
|
12
|
+
force=bool(getattr(args, "force", False)),
|
|
13
|
+
stdin_is_tty=stdin_allows_prompt(),
|
|
14
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Doctor preflight checks for maproom CLI."""
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Fast local heuristics for whether the AWS CLI may have credentials."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import configparser
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from maproom.aws_region import resolve_aws_profile_name
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _home_dir() -> Path | None:
|
|
15
|
+
raw = os.environ.get("HOME") or os.environ.get("USERPROFILE")
|
|
16
|
+
if not raw:
|
|
17
|
+
return None
|
|
18
|
+
return Path(raw)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _credentials_path() -> Path | None:
|
|
22
|
+
explicit = os.environ.get("AWS_SHARED_CREDENTIALS_FILE")
|
|
23
|
+
if explicit:
|
|
24
|
+
return Path(explicit)
|
|
25
|
+
home = _home_dir()
|
|
26
|
+
if home is None:
|
|
27
|
+
return None
|
|
28
|
+
return home / ".aws" / "credentials"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _config_path() -> Path | None:
|
|
32
|
+
explicit = os.environ.get("AWS_CONFIG_FILE")
|
|
33
|
+
if explicit:
|
|
34
|
+
return Path(explicit)
|
|
35
|
+
home = _home_dir()
|
|
36
|
+
if home is None:
|
|
37
|
+
return None
|
|
38
|
+
return home / ".aws" / "config"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _profile_section(parser: configparser.ConfigParser, profile: str) -> str | None:
|
|
42
|
+
if profile == "default" and parser.has_section("default"):
|
|
43
|
+
return "default"
|
|
44
|
+
named = f"profile {profile}"
|
|
45
|
+
if parser.has_section(named):
|
|
46
|
+
return named
|
|
47
|
+
if profile == "default" and parser.has_section("profile default"):
|
|
48
|
+
return "profile default"
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _ini_profile_has_keys(path: Path, profile: str, keys: tuple[str, ...]) -> bool:
|
|
53
|
+
if not path.is_file():
|
|
54
|
+
return False
|
|
55
|
+
parser = configparser.ConfigParser()
|
|
56
|
+
parser.read(path, encoding="utf-8")
|
|
57
|
+
section = _profile_section(parser, profile)
|
|
58
|
+
if section is None:
|
|
59
|
+
return False
|
|
60
|
+
block = parser[section]
|
|
61
|
+
return any((block.get(key) or "").strip() for key in keys)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _login_cache_has_live_session() -> bool:
|
|
65
|
+
home = _home_dir()
|
|
66
|
+
if home is None:
|
|
67
|
+
return False
|
|
68
|
+
cache_dir = home / ".aws" / "login" / "cache"
|
|
69
|
+
if not cache_dir.is_dir():
|
|
70
|
+
return False
|
|
71
|
+
now = datetime.now(timezone.utc)
|
|
72
|
+
for path in cache_dir.glob("*.json"):
|
|
73
|
+
try:
|
|
74
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
75
|
+
except (OSError, json.JSONDecodeError):
|
|
76
|
+
continue
|
|
77
|
+
access = payload.get("accessToken")
|
|
78
|
+
if not isinstance(access, dict):
|
|
79
|
+
continue
|
|
80
|
+
if not (access.get("accessKeyId") or "").strip():
|
|
81
|
+
continue
|
|
82
|
+
expires = access.get("expiresAt")
|
|
83
|
+
if not isinstance(expires, str):
|
|
84
|
+
return True
|
|
85
|
+
text = expires.strip()
|
|
86
|
+
if text.endswith("Z"):
|
|
87
|
+
text = f"{text[:-1]}+00:00"
|
|
88
|
+
try:
|
|
89
|
+
expiry = datetime.fromisoformat(text)
|
|
90
|
+
except ValueError:
|
|
91
|
+
return True
|
|
92
|
+
if expiry.tzinfo is None:
|
|
93
|
+
expiry = expiry.replace(tzinfo=timezone.utc)
|
|
94
|
+
if expiry > now:
|
|
95
|
+
return True
|
|
96
|
+
return False
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _sso_cache_has_live_token() -> bool:
|
|
100
|
+
home = _home_dir()
|
|
101
|
+
if home is None:
|
|
102
|
+
return False
|
|
103
|
+
cache_dir = home / ".aws" / "sso" / "cache"
|
|
104
|
+
if not cache_dir.is_dir():
|
|
105
|
+
return False
|
|
106
|
+
now = datetime.now(timezone.utc)
|
|
107
|
+
for path in cache_dir.glob("*.json"):
|
|
108
|
+
try:
|
|
109
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
110
|
+
except (OSError, json.JSONDecodeError):
|
|
111
|
+
continue
|
|
112
|
+
token = (payload.get("accessToken") or "").strip()
|
|
113
|
+
if not token:
|
|
114
|
+
continue
|
|
115
|
+
expires = payload.get("expiresAt")
|
|
116
|
+
if not isinstance(expires, str):
|
|
117
|
+
return True
|
|
118
|
+
text = expires.strip()
|
|
119
|
+
if text.endswith("Z"):
|
|
120
|
+
text = f"{text[:-1]}+00:00"
|
|
121
|
+
try:
|
|
122
|
+
expiry = datetime.fromisoformat(text)
|
|
123
|
+
except ValueError:
|
|
124
|
+
return True
|
|
125
|
+
if expiry.tzinfo is None:
|
|
126
|
+
expiry = expiry.replace(tzinfo=timezone.utc)
|
|
127
|
+
if expiry > now:
|
|
128
|
+
return True
|
|
129
|
+
return False
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _source_profile_has_keys(
|
|
133
|
+
parser: configparser.ConfigParser,
|
|
134
|
+
creds_path: Path | None,
|
|
135
|
+
source_profile: str,
|
|
136
|
+
*,
|
|
137
|
+
visited: frozenset[str],
|
|
138
|
+
) -> bool:
|
|
139
|
+
if source_profile in visited:
|
|
140
|
+
return False
|
|
141
|
+
next_visited = visited | {source_profile}
|
|
142
|
+
if creds_path is not None and _ini_profile_has_keys(
|
|
143
|
+
creds_path, source_profile, ("aws_access_key_id", "aws_session_token")
|
|
144
|
+
):
|
|
145
|
+
return True
|
|
146
|
+
config_path = _config_path()
|
|
147
|
+
if config_path is None or not config_path.is_file():
|
|
148
|
+
return False
|
|
149
|
+
section = _profile_section(parser, source_profile)
|
|
150
|
+
if section is None:
|
|
151
|
+
return False
|
|
152
|
+
block = parser[section]
|
|
153
|
+
if (block.get("credential_process") or "").strip():
|
|
154
|
+
return True
|
|
155
|
+
if block.get("sso_session") or block.get("sso_start_url"):
|
|
156
|
+
return _sso_cache_has_live_token()
|
|
157
|
+
if (block.get("login_session") or "").strip():
|
|
158
|
+
return True
|
|
159
|
+
if _login_cache_has_live_session():
|
|
160
|
+
return True
|
|
161
|
+
nested_source = (block.get("source_profile") or "").strip()
|
|
162
|
+
if nested_source:
|
|
163
|
+
return _source_profile_has_keys(
|
|
164
|
+
parser, creds_path, nested_source, visited=next_visited
|
|
165
|
+
)
|
|
166
|
+
role_arn = (block.get("role_arn") or "").strip()
|
|
167
|
+
return bool(role_arn)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def aws_likely_has_credentials() -> bool:
|
|
171
|
+
"""Return False when no local AWS credential source is configured."""
|
|
172
|
+
env = os.environ
|
|
173
|
+
if (env.get("CLOUD_CLI_AWS") or "").strip() or (env.get("MAPROOM_AWS_CLI") or "").strip():
|
|
174
|
+
return True
|
|
175
|
+
if (env.get("AWS_ACCESS_KEY_ID") or "").strip() and (
|
|
176
|
+
env.get("AWS_SECRET_ACCESS_KEY") or ""
|
|
177
|
+
).strip():
|
|
178
|
+
return True
|
|
179
|
+
if (env.get("AWS_SESSION_TOKEN") or "").strip() and (
|
|
180
|
+
env.get("AWS_ACCESS_KEY_ID") or ""
|
|
181
|
+
).strip():
|
|
182
|
+
return True
|
|
183
|
+
token_file = (env.get("AWS_WEB_IDENTITY_TOKEN_FILE") or "").strip()
|
|
184
|
+
if token_file and Path(token_file).expanduser().is_file():
|
|
185
|
+
return True
|
|
186
|
+
if (env.get("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI") or "").strip():
|
|
187
|
+
return True
|
|
188
|
+
if (env.get("AWS_CONTAINER_CREDENTIALS_FULL_URI") or "").strip():
|
|
189
|
+
return True
|
|
190
|
+
|
|
191
|
+
profile = resolve_aws_profile_name()
|
|
192
|
+
creds_path = _credentials_path()
|
|
193
|
+
if creds_path is not None and _ini_profile_has_keys(
|
|
194
|
+
creds_path, profile, ("aws_access_key_id", "aws_session_token")
|
|
195
|
+
):
|
|
196
|
+
return True
|
|
197
|
+
|
|
198
|
+
config_path = _config_path()
|
|
199
|
+
if config_path is None or not config_path.is_file():
|
|
200
|
+
return False
|
|
201
|
+
parser = configparser.ConfigParser()
|
|
202
|
+
parser.read(config_path, encoding="utf-8")
|
|
203
|
+
section = _profile_section(parser, profile)
|
|
204
|
+
if section is None:
|
|
205
|
+
return False
|
|
206
|
+
block = parser[section]
|
|
207
|
+
if (block.get("credential_process") or "").strip():
|
|
208
|
+
return True
|
|
209
|
+
if block.get("sso_session") or block.get("sso_start_url"):
|
|
210
|
+
return _sso_cache_has_live_token()
|
|
211
|
+
if (block.get("login_session") or "").strip():
|
|
212
|
+
return True
|
|
213
|
+
if _login_cache_has_live_session():
|
|
214
|
+
return True
|
|
215
|
+
role_arn = (block.get("role_arn") or "").strip()
|
|
216
|
+
if role_arn:
|
|
217
|
+
source = (block.get("source_profile") or "").strip()
|
|
218
|
+
if source:
|
|
219
|
+
return _source_profile_has_keys(
|
|
220
|
+
parser, creds_path, source, visited=frozenset({profile})
|
|
221
|
+
)
|
|
222
|
+
return True
|
|
223
|
+
token_path = (block.get("web_identity_token_file") or "").strip()
|
|
224
|
+
if token_path and Path(token_path).expanduser().is_file():
|
|
225
|
+
return True
|
|
226
|
+
return False
|