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,173 @@
1
+ """Atomic Savings Plan snapshot persistence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import tempfile
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from maproom.inventory.accounts import (
13
+ CloudAccount,
14
+ drop_replaced_legacy_snapshot,
15
+ primary_snapshot_path,
16
+ retire_other_account_folders,
17
+ snapshot_files,
18
+ )
19
+ from maproom.paths import data_root, data_subdir, prepare_data_write, readable_data_file
20
+ from maproom.redaction import redact_tree
21
+ from maproom.saving_plans.model import SavingPlanError
22
+
23
+ DATA_DIR = "savings-plans"
24
+ LEGACY_DATA_DIR = "saving-plans"
25
+ _FILENAME = "inventory.json"
26
+
27
+
28
+ def _migrate_legacy_data_dir() -> None:
29
+ """Move an on-disk saving-plans tree into savings-plans once."""
30
+ prepare_data_write()
31
+ root = data_root()
32
+ legacy = root / LEGACY_DATA_DIR
33
+ if not legacy.is_dir():
34
+ return
35
+ current = root / DATA_DIR
36
+ current.mkdir(parents=True, exist_ok=True)
37
+ for child in list(legacy.iterdir()):
38
+ dest = current / child.name
39
+ if dest.exists():
40
+ continue
41
+ shutil.move(str(child), str(dest))
42
+ try:
43
+ legacy.rmdir()
44
+ except OSError:
45
+ pass
46
+
47
+
48
+ def inventory_root() -> Path:
49
+ _migrate_legacy_data_dir()
50
+ return data_subdir(DATA_DIR)
51
+
52
+
53
+ def inventory_path() -> Path:
54
+ """Legacy path, or the only account snapshot when that is the file on disk."""
55
+ return primary_snapshot_path(inventory_root(), _FILENAME)
56
+
57
+
58
+ def status_path() -> Path:
59
+ files = snapshot_files(inventory_root(), _FILENAME)
60
+ if len(files) == 1:
61
+ return files[0]
62
+ if len(files) > 1:
63
+ return inventory_root()
64
+ return inventory_root() / _FILENAME
65
+
66
+
67
+ def account_snapshot_path(account: CloudAccount) -> Path:
68
+ return inventory_root() / account.folder_name() / _FILENAME
69
+
70
+
71
+ def _atomic_write_json(path: Path, payload: dict[str, Any]) -> SavingPlanError | None:
72
+ try:
73
+ path.parent.mkdir(parents=True, exist_ok=True)
74
+ fd, tmp_name = tempfile.mkstemp(
75
+ dir=path.parent,
76
+ prefix=f".{path.stem}-",
77
+ suffix=".tmp",
78
+ )
79
+ tmp_path = Path(tmp_name)
80
+ try:
81
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
82
+ json.dump(redact_tree(payload), handle, indent=2)
83
+ handle.write("\n")
84
+ os.replace(tmp_path, path)
85
+ except OSError:
86
+ tmp_path.unlink(missing_ok=True)
87
+ raise
88
+ except OSError as exc:
89
+ return SavingPlanError(f"could not write savings plan snapshot at {path}: {exc}")
90
+ return None
91
+
92
+
93
+ def write_snapshot(payload: dict[str, Any]) -> SavingPlanError | None:
94
+ prepare_data_write()
95
+ return _atomic_write_json(inventory_path(), payload)
96
+
97
+
98
+ def write_account_snapshot(payload: dict[str, Any], account: CloudAccount) -> SavingPlanError | None:
99
+ prepare_data_write()
100
+ path = account_snapshot_path(account)
101
+ err = _atomic_write_json(path, payload)
102
+ if err is not None:
103
+ return err
104
+ retire_other_account_folders(inventory_root(), account, keep=path.parent.name)
105
+ drop_replaced_legacy_snapshot(
106
+ inventory_root(),
107
+ _FILENAME,
108
+ clouds={account.cloud},
109
+ sources={"aws_get", "cloud_get", "payer_file"},
110
+ cloud_of=lambda _record: "aws",
111
+ write_json=lambda legacy, body: _atomic_write_json(legacy, body),
112
+ )
113
+ return None
114
+
115
+
116
+ def read_snapshot() -> dict[str, Any] | None | SavingPlanError:
117
+ root = inventory_root()
118
+ paths = snapshot_files(root, _FILENAME)
119
+ has_account_snapshots = any(path.parent != root for path in paths)
120
+ legacy = readable_data_file(DATA_DIR, _FILENAME)
121
+ if legacy.is_file() and legacy not in paths and not has_account_snapshots:
122
+ paths.insert(0, legacy)
123
+ if not paths:
124
+ return None
125
+ loaded: list[dict[str, Any]] = []
126
+ for path in paths:
127
+ data = _read_one(path)
128
+ if isinstance(data, SavingPlanError):
129
+ return data
130
+ if data is not None:
131
+ loaded.append(data)
132
+ if not loaded:
133
+ return None
134
+ if len(loaded) == 1:
135
+ return loaded[0]
136
+ return _merge(loaded)
137
+
138
+
139
+ def _read_one(path: Path) -> dict[str, Any] | None | SavingPlanError:
140
+ if not path.is_file():
141
+ return None
142
+ try:
143
+ text = path.read_text(encoding="utf-8")
144
+ except OSError as exc:
145
+ return SavingPlanError(f"could not read savings plan snapshot at {path}: {exc}")
146
+ try:
147
+ data = json.loads(text)
148
+ except json.JSONDecodeError as exc:
149
+ return SavingPlanError(f"corrupt savings plan snapshot {path}: {exc}")
150
+ if not isinstance(data, dict):
151
+ return SavingPlanError(f"corrupt savings plan snapshot {path}: expected JSON object")
152
+ return data
153
+
154
+
155
+ def _merge(parts: list[dict[str, Any]]) -> dict[str, Any]:
156
+ records: list[Any] = []
157
+ for part in parts:
158
+ rows = part.get("records")
159
+ if isinstance(rows, list):
160
+ records.extend(rows)
161
+ loaded = [str(part.get("loaded_as_of") or "") for part in parts if part.get("loaded_as_of")]
162
+ sources = {str(part.get("source") or "") for part in parts}
163
+ regions = {str(part.get("region") or "") for part in parts if part.get("region")}
164
+ payload: dict[str, Any] = {
165
+ "schema_version": parts[0].get("schema_version"),
166
+ "loaded_as_of": min(loaded) if loaded else "",
167
+ "source": sources.pop() if len(sources) == 1 else "mixed",
168
+ "record_count": len(records),
169
+ "records": records,
170
+ }
171
+ if len(regions) == 1:
172
+ payload["region"] = regions.pop()
173
+ return payload
@@ -0,0 +1,108 @@
1
+ """Tier 0 secret egress AST gate for maproom-cli."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import ast
7
+ import re
8
+ import sys
9
+ from collections.abc import Sequence
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+
13
+ from maproom.exitcodes import RUNTIME, SUCCESS
14
+
15
+ _REPO_ROOT = Path(__file__).resolve().parents[1]
16
+ DEFAULT_SCAN_ROOTS = ("maproom", "scripts", "publication")
17
+ INSTALL_CALL = "install_redacting_sinks"
18
+ REQUIRED = (
19
+ "maproom/cli.py",
20
+ "scripts/check_secret_egress.py",
21
+ "scripts/check_price_file_freshness.py",
22
+ "maproom/reference_data/scripts/import_price_file.py",
23
+ "maproom/reference_data/scripts/import_instance_specs.py",
24
+ "maproom/reference_data/scripts/import_forbidden_terms.py",
25
+ "maproom/reference_data/scripts/import_safe_moves.py",
26
+ "scripts/policy_pytest_suite.py",
27
+ "scripts/run_policy_pytest.py",
28
+ "scripts/sync_cli_fixtures.py",
29
+ "publication/export_tree.py",
30
+ "publication/validate.py",
31
+ "publication/check_installed.py",
32
+ "publication/write_provenance.py",
33
+ )
34
+ LOG_ATTRS = frozenset({"debug", "info", "warning", "error", "critical", "exception", "log"})
35
+ FORBIDDEN = (
36
+ (re.compile(r"password\s*=", re.I), "password= in egress call"),
37
+ (re.compile(r"\bclient_secret\b", re.I), "client_secret in egress call"),
38
+ (re.compile(r"\bAWS_SECRET_ACCESS_KEY\b"), "AWS_SECRET_ACCESS_KEY in egress call"),
39
+ (re.compile(r"AKIA[0-9A-Z]{16}"), "AWS access key id in egress call"),
40
+ )
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class EgressViolation:
45
+ path: Path
46
+ lineno: int
47
+ reason: str
48
+ snippet: str
49
+
50
+
51
+ def scan_source(path: Path, source: str, repo_root: Path | None = None) -> list[EgressViolation]:
52
+ try:
53
+ tree = ast.parse(source, filename=str(path))
54
+ except SyntaxError as exc:
55
+ return [EgressViolation(path, exc.lineno or 1, f"syntax error: {exc.msg}", "")]
56
+ out: list[EgressViolation] = []
57
+ for node in ast.walk(tree):
58
+ if not isinstance(node, ast.Call):
59
+ continue
60
+ func = node.func
61
+ is_log = isinstance(func, ast.Attribute) and func.attr in LOG_ATTRS
62
+ is_print = isinstance(func, ast.Name) and func.id == "print"
63
+ if not is_log and not is_print:
64
+ continue
65
+ fragment = ast.get_source_segment(source, node) or ""
66
+ for pattern, reason in FORBIDDEN:
67
+ if pattern.search(fragment):
68
+ out.append(EgressViolation(path, node.lineno, reason, fragment.splitlines()[0].strip()))
69
+ break
70
+ rel = path.resolve().relative_to((repo_root or _REPO_ROOT).resolve()).as_posix()
71
+ if rel in REQUIRED and INSTALL_CALL not in source:
72
+ out.append(EgressViolation(path, 1, f"entry point missing {INSTALL_CALL}()", ""))
73
+ return out
74
+
75
+
76
+ def scan_tree(root: Path, repo_root: Path | None = None) -> list[EgressViolation]:
77
+ violations: list[EgressViolation] = []
78
+ for path in sorted(root.rglob("*.py")):
79
+ try:
80
+ source = path.read_text(encoding="utf-8")
81
+ except OSError:
82
+ continue
83
+ violations.extend(scan_source(path, source, repo_root))
84
+ return violations
85
+
86
+
87
+ def scan_repo_roots(repo_root: Path, relative_roots: Sequence[str] = DEFAULT_SCAN_ROOTS) -> list[EgressViolation]:
88
+ violations: list[EgressViolation] = []
89
+ for rel in relative_roots:
90
+ violations.extend(scan_tree(repo_root / rel, repo_root))
91
+ return violations
92
+
93
+
94
+ def format_violations(violations: list[EgressViolation]) -> list[str]:
95
+ return [f"{v.path.as_posix()}:{v.lineno}: {v.reason}" for v in violations]
96
+
97
+
98
+ def main(argv: list[str] | None = None) -> int:
99
+ from maproom.redaction import install_redacting_sinks
100
+
101
+ install_redacting_sinks()
102
+ violations = scan_repo_roots(_REPO_ROOT)
103
+ if not violations:
104
+ print("check_secret_egress: OK")
105
+ return SUCCESS
106
+ for line in format_violations(violations):
107
+ print(line, file=sys.stderr)
108
+ return RUNTIME
@@ -0,0 +1,60 @@
1
+ """Per-install anonymous UUID for Analyze traffic and remote purge by id."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import uuid
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from maproom.settings.model import load_effective_settings
11
+ from maproom.settings.write import SettingsWriteError, persist_settings
12
+
13
+ ANONYMOUS_ID_KEY = "anonymous_id"
14
+ LEGACY_SERVICE_INSTALL_ID_KEY = "service_install_id"
15
+
16
+ _UUID_RE = re.compile(
17
+ r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
18
+ )
19
+
20
+
21
+ def is_valid_install_id(value: str) -> bool:
22
+ return _UUID_RE.fullmatch(value.strip()) is not None
23
+
24
+
25
+ def read_anonymous_id(settings: dict[str, Any]) -> str | None:
26
+ for key in (ANONYMOUS_ID_KEY, LEGACY_SERVICE_INSTALL_ID_KEY):
27
+ raw = settings.get(key)
28
+ if isinstance(raw, str) and is_valid_install_id(raw):
29
+ return raw.strip()
30
+ return None
31
+
32
+
33
+ def ensure_anonymous_id(path: Path) -> tuple[str, SettingsWriteError | None]:
34
+ """Return this install's anonymous id, creating and persisting a UUID when missing."""
35
+ settings, _ = load_effective_settings(path)
36
+ existing = read_anonymous_id(settings)
37
+ if existing:
38
+ if settings.get(ANONYMOUS_ID_KEY) != existing:
39
+ err = persist_settings(
40
+ path,
41
+ {ANONYMOUS_ID_KEY: existing, LEGACY_SERVICE_INSTALL_ID_KEY: None},
42
+ )
43
+ if err is not None:
44
+ return existing, err
45
+ elif LEGACY_SERVICE_INSTALL_ID_KEY in settings:
46
+ err = persist_settings(path, {LEGACY_SERVICE_INSTALL_ID_KEY: None})
47
+ if err is not None:
48
+ return existing, err
49
+ return existing, None
50
+ anonymous_id = str(uuid.uuid4())
51
+ err = persist_settings(path, {ANONYMOUS_ID_KEY: anonymous_id})
52
+ if err is not None:
53
+ return anonymous_id, err
54
+ return anonymous_id, None
55
+
56
+
57
+ # Compatibility names used before NEXT-16.
58
+ SERVICE_INSTALL_ID_KEY = ANONYMOUS_ID_KEY
59
+ read_service_install_id = read_anonymous_id
60
+ ensure_service_install_id = ensure_anonymous_id
@@ -0,0 +1 @@
1
+ """Settings show and bootstrap for maproom CLI."""
@@ -0,0 +1,73 @@
1
+ """Default settings keys from USER_JOURNEY.md section 8."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ DEFAULT_ENGINE_SETTINGS: dict[str, Any] = {
8
+ "min_savings_usd_month": 5,
9
+ "cpu_headroom_pct": 70,
10
+ "consolidation_p95_pct": 50,
11
+ "max_recommendations": 3,
12
+ "max_conditional": 3,
13
+ "min_days_since_change": 7,
14
+ }
15
+
16
+ DEFAULT_SERVICE_SETTINGS: dict[str, Any] = {}
17
+
18
+ DEFAULT_SETTINGS: dict[str, Any] = {
19
+ "product_version": 1,
20
+ "cloud_read_consent": False,
21
+ "service_upload_consent": False,
22
+ "quota_telemetry": False,
23
+ "quota_headroom_pct": 10,
24
+ "denial_suppress_days": 90,
25
+ "desired_cpu_p99": 66,
26
+ "desired_memory_p99": 66,
27
+ "desired_network_headroom_pct": 50,
28
+ "desired_disk_headroom_pct": 50,
29
+ "cache_max_age_hours": 1,
30
+ "cloud_authorize_protocol_hostname_port": "",
31
+ "cloud_analyze_protocol_hostname_port": "",
32
+ "engine": dict(DEFAULT_ENGINE_SETTINGS),
33
+ "service": dict(DEFAULT_SERVICE_SETTINGS),
34
+ }
35
+
36
+ # Overlay keys persisted only when grant or snooze is active (not in init template values).
37
+ FLEETFIT_POLICY_OVERLAY_KEYS: tuple[str, ...] = (
38
+ "fleetfit_policy_id",
39
+ "fleetfit_policy_url",
40
+ "fleetfit_policy_granted_at",
41
+ )
42
+
43
+ CONSENT_OVERLAY_KEYS: tuple[str, ...] = (
44
+ "cloud_read_consent_approved_text",
45
+ "cloud_read_consent_approved_at",
46
+ "cloud_read_consent_snoozed_until",
47
+ "service_upload_consent_approved_text",
48
+ "service_upload_consent_approved_at",
49
+ "service_upload_consent_declined_at",
50
+ "anonymous_id",
51
+ "service_install_id",
52
+ *FLEETFIT_POLICY_OVERLAY_KEYS,
53
+ )
54
+
55
+ SETTINGS_INIT_ONLY_KEYS: frozenset[str] = frozenset(
56
+ {
57
+ "quota_telemetry",
58
+ "quota_headroom_pct",
59
+ "denial_suppress_days",
60
+ }
61
+ )
62
+
63
+
64
+ def settings_init_only_keys_csv() -> str:
65
+ return ", ".join(sorted(SETTINGS_INIT_ONLY_KEYS))
66
+
67
+
68
+ DEFAULTS_MESSAGE = (
69
+ "No settings file yet. Showing built-in defaults. "
70
+ "Run maproom settings init to create it. "
71
+ "Use maproom settings set KEY VALUE for supported keys (see maproom settings set --help). "
72
+ f"Edit {settings_init_only_keys_csv()} in the settings file directly."
73
+ )
@@ -0,0 +1,143 @@
1
+ """Bootstrap settings.toml with documented defaults."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ import tempfile
8
+ from pathlib import Path
9
+
10
+ from datetime import datetime, timezone
11
+
12
+ from maproom.exitcodes import RUNTIME, SUCCESS
13
+ from maproom.output.json_envelope import build_document, command_metadata, print_json
14
+ from maproom.paths import settings_file
15
+ from maproom.settings.defaults import DEFAULT_SETTINGS, settings_init_only_keys_csv
16
+ from maproom.settings.product_versions import product_version_init_level_comment
17
+
18
+
19
+ def _format_toml(settings: dict[str, object]) -> str:
20
+ lines = [
21
+ "product_version = 1 # try-first recommendation level (1-8); higher unlocks more complexity",
22
+ "# 1 Local, safe moves",
23
+ "# 2 Remote, downsize and upsize",
24
+ "# 3 Remote, Spot-to-Spot",
25
+ "# 4 Remote, Cross-family Recommendations",
26
+ "# 5 Unused reservations",
27
+ "# 6 Quota management",
28
+ "# 7 Quota outcome feedback",
29
+ product_version_init_level_comment(8),
30
+ "",
31
+ "# Local recommendations -- engine thresholds apply only on this machine",
32
+ "desired_cpu_p99 = 66 # size + utilization: max projected CPU p99 after migration",
33
+ "desired_memory_p99 = 66 # utilization: max projected memory p99 after migration",
34
+ "desired_network_headroom_pct = 50 # utilization: network IOPS and throughput ceiling as % of published capacity",
35
+ "desired_disk_headroom_pct = 50 # utilization: disk IOPS and throughput ceiling as % of published capacity",
36
+ "",
37
+ "# Cloud account reads -- aws and az on this machine",
38
+ "cloud_read_consent = false # read-only provider calls",
39
+ "# cloud_read_consent_approved_text = ... # exact prompt text while consent is granted",
40
+ "# cloud_read_consent_approved_at = ... # UTC timestamp while consent is granted",
41
+ "# cloud_read_consent_snoozed_until = ... # UTC timestamp during an active snooze",
42
+ "",
43
+ "# Cloud recommendations -- FleetFit hosts; paths are fixed in code",
44
+ 'cloud_authorize_protocol_hostname_port = "" # token host, for example https://fleetfit-gate-dev.internal:443; no path; empty is not called',
45
+ 'cloud_analyze_protocol_hostname_port = "" # analyze host, for example http://127.0.0.1:8080; no path; empty is not called',
46
+ "service_upload_consent = false # anonymous workload-summary uploads",
47
+ "",
48
+ "# Other",
49
+ "quota_telemetry = false # when true, analyze reads plain JSON herd quota outcomes from quotas/herd_quota_outcomes.json; edit in file, not via settings set",
50
+ "quota_headroom_pct = 10 # pad added when computing a batched quota request value; edit in file, not via settings set",
51
+ "denial_suppress_days = 90 # how long a denied quota suppresses re-recommendation; edit in file, not via settings set",
52
+ "",
53
+ "cache_max_age_hours = 1 # reuse cached instances, reservations, quotas, and savings plans younger than this many hours; 0 always refreshes",
54
+ "",
55
+ "[engine]",
56
+ "min_savings_usd_month = 5 # minimum monthly savings for easy-move candidates",
57
+ "cpu_headroom_pct = 70 # reject when projected CPU p95 exceeds this",
58
+ "consolidation_p95_pct = 50 # conditional when projected p95 exceeds this",
59
+ "max_recommendations = 3 # surfaced easy-move candidates",
60
+ "max_conditional = 3 # surfaced conditional candidates",
61
+ "min_days_since_change = 7 # hold downsizing after instance-type change",
62
+ ]
63
+ assert set(DEFAULT_SETTINGS.keys()) == {
64
+ "product_version",
65
+ "cloud_read_consent",
66
+ "service_upload_consent",
67
+ "quota_telemetry",
68
+ "quota_headroom_pct",
69
+ "denial_suppress_days",
70
+ "desired_cpu_p99",
71
+ "desired_memory_p99",
72
+ "desired_network_headroom_pct",
73
+ "desired_disk_headroom_pct",
74
+ "cache_max_age_hours",
75
+ "cloud_authorize_protocol_hostname_port",
76
+ "cloud_analyze_protocol_hostname_port",
77
+ "engine",
78
+ "service",
79
+ }
80
+ return "\n".join(lines) + "\n"
81
+
82
+
83
+ def run_settings_init(*, as_json: bool = False) -> int:
84
+ started = datetime.now(timezone.utc)
85
+ path = settings_file()
86
+ if path.is_file():
87
+ if as_json:
88
+ print_json(
89
+ build_document(
90
+ schema_type="settings_init",
91
+ schema_id="maproom.settings_init",
92
+ metadata=command_metadata("settings init", started_at=started),
93
+ payload={"path": str(path), "created": False},
94
+ )
95
+ )
96
+ return SUCCESS
97
+ print(
98
+ f"Settings file already exists: {path}. Nothing was changed. "
99
+ "Run maproom settings to see the values. "
100
+ "Use maproom settings set KEY VALUE for supported keys (see maproom settings set --help). "
101
+ f"Edit {settings_init_only_keys_csv()} in the settings file directly."
102
+ )
103
+ return SUCCESS
104
+
105
+ content = _format_toml(DEFAULT_SETTINGS)
106
+ try:
107
+ path.parent.mkdir(parents=True, exist_ok=True)
108
+ fd, tmp_name = tempfile.mkstemp(
109
+ dir=path.parent,
110
+ prefix=".settings-",
111
+ suffix=".tmp",
112
+ )
113
+ tmp_path = Path(tmp_name)
114
+ try:
115
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
116
+ handle.write(content)
117
+ os.replace(tmp_path, path)
118
+ from maproom.service.install_id import ensure_anonymous_id
119
+
120
+ ensure_anonymous_id(path)
121
+ except OSError:
122
+ tmp_path.unlink(missing_ok=True)
123
+ raise
124
+ except OSError as exc:
125
+ print(f"error: could not create settings file at {path}: {exc}", file=sys.stderr)
126
+ return RUNTIME
127
+
128
+ if as_json:
129
+ print_json(
130
+ build_document(
131
+ schema_type="settings_init",
132
+ schema_id="maproom.settings_init",
133
+ metadata=command_metadata("settings init", started_at=started),
134
+ payload={"path": str(path), "created": True},
135
+ )
136
+ )
137
+ return SUCCESS
138
+ print(f"Created settings file: {path}")
139
+ print(
140
+ "Use maproom settings set KEY VALUE for supported keys (see maproom settings set --help). "
141
+ f"Edit {settings_init_only_keys_csv()} in that file directly."
142
+ )
143
+ return SUCCESS
@@ -0,0 +1,105 @@
1
+ """Load effective settings from disk or defaults."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from datetime import datetime, timedelta, timezone
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from maproom.settings.defaults import (
11
+ CONSENT_OVERLAY_KEYS,
12
+ DEFAULT_ENGINE_SETTINGS,
13
+ DEFAULT_SERVICE_SETTINGS,
14
+ DEFAULT_SETTINGS,
15
+ )
16
+ from maproom.settings.product_versions import (
17
+ MIN_PRODUCT_VERSION,
18
+ clamp_product_version,
19
+ )
20
+ from maproom.snapshot_time import parse_loaded_as_of
21
+
22
+ _DEFAULT_CACHE_MAX_AGE_HOURS = 1
23
+
24
+
25
+ def cache_max_age_hours(path: Path | None = None) -> int:
26
+ """Hours a cached cloud snapshot may be reused. 0 always refreshes. Default is 1."""
27
+ from maproom.paths import settings_file
28
+
29
+ settings, _ = load_effective_settings(path or settings_file())
30
+ raw = settings.get("cache_max_age_hours", 1)
31
+ if isinstance(raw, bool) or not isinstance(raw, int) or raw < 0:
32
+ return _DEFAULT_CACHE_MAX_AGE_HOURS
33
+ return raw
34
+
35
+
36
+ def snapshot_is_stale(
37
+ loaded_as_of: str | None,
38
+ max_age_hours: int,
39
+ *,
40
+ now: datetime | None = None,
41
+ ) -> bool:
42
+ """True when a snapshot is too old to reuse. 0 hours never reuses."""
43
+ if max_age_hours <= 0:
44
+ return True
45
+ parsed = parse_loaded_as_of(loaded_as_of)
46
+ if parsed is None:
47
+ return False
48
+ current = now or datetime.now(timezone.utc)
49
+ return (current - parsed) >= timedelta(hours=max_age_hours)
50
+
51
+
52
+ def product_version(path: Path | None = None) -> int:
53
+ """Recommendation complexity level from settings, 1 through 8. Default is 1."""
54
+ from maproom.paths import settings_file
55
+
56
+ settings, _ = load_effective_settings(path or settings_file())
57
+ return clamp_product_version(settings.get("product_version", MIN_PRODUCT_VERSION))
58
+
59
+
60
+ def load_effective_settings(path: Path) -> tuple[dict[str, Any], bool]:
61
+ """Return effective settings and whether defaults are in use."""
62
+ if not path.is_file():
63
+ return dict(DEFAULT_SETTINGS), True
64
+ raw = tomllib.loads(path.read_text(encoding="utf-8"))
65
+ effective = dict(DEFAULT_SETTINGS)
66
+ for key in DEFAULT_SETTINGS:
67
+ if key in raw:
68
+ effective[key] = raw[key]
69
+ effective["product_version"] = clamp_product_version(effective.get("product_version"))
70
+ engine_raw = raw.get("engine")
71
+ if isinstance(engine_raw, dict):
72
+ effective["engine"] = {**DEFAULT_ENGINE_SETTINGS, **engine_raw}
73
+ service_raw = raw.get("service")
74
+ if isinstance(service_raw, dict):
75
+ effective["service"] = {**DEFAULT_SERVICE_SETTINGS, **service_raw}
76
+ for key in CONSENT_OVERLAY_KEYS:
77
+ if key in raw:
78
+ effective[key] = raw[key]
79
+ return effective, False
80
+
81
+
82
+ def load_consent_state(path: Path) -> dict[str, Any]:
83
+ """Return consent-related fields from effective settings."""
84
+ settings, _ = load_effective_settings(path)
85
+ state: dict[str, Any] = {"cloud_read_consent": bool(settings.get("cloud_read_consent"))}
86
+ for key in CONSENT_OVERLAY_KEYS:
87
+ if key in settings:
88
+ state[key] = settings[key]
89
+ return state
90
+
91
+
92
+ def load_service_upload_state(path: Path) -> dict[str, Any]:
93
+ """Return service-upload consent fields from effective settings."""
94
+ settings, _ = load_effective_settings(path)
95
+ state: dict[str, Any] = {
96
+ "service_upload_consent": bool(settings.get("service_upload_consent")),
97
+ }
98
+ for key in (
99
+ "service_upload_consent_approved_text",
100
+ "service_upload_consent_approved_at",
101
+ "service_upload_consent_declined_at",
102
+ ):
103
+ if key in settings:
104
+ state[key] = settings[key]
105
+ return state