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,264 @@
1
+ """Shared human and JSON inventory fetch outcomes (doctor, get, analyze)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ _RESERVATIONS_READ_PROGRESS = "Reading AWS EC2 Reserved Instances..."
8
+ _SAVING_PLANS_READ_PROGRESS = "Reading AWS Savings Plans..."
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class QuotasCloudSummary:
13
+ cloud: str
14
+ record_count: int
15
+ region: str
16
+ include_general_line: bool
17
+
18
+
19
+ def reservations_fetch_progress_line() -> str:
20
+ return _RESERVATIONS_READ_PROGRESS
21
+
22
+
23
+ def saving_plans_fetch_progress_line() -> str:
24
+ return _SAVING_PLANS_READ_PROGRESS
25
+
26
+
27
+ def quotas_fetch_progress_line_for(cloud: str) -> str:
28
+ if cloud == "azure":
29
+ return "Reading Azure VM quotas..."
30
+ return "Reading AWS EC2 quotas..."
31
+
32
+
33
+ def quotas_fetch_progress_lines(clouds: frozenset[str]) -> tuple[str, ...]:
34
+ order = ("aws", "azure")
35
+ return tuple(
36
+ quotas_fetch_progress_line_for(cloud)
37
+ for cloud in order
38
+ if cloud in clouds
39
+ )
40
+
41
+
42
+ def quotas_fetch_progress_line(region: str | None = None) -> str:
43
+ return quotas_fetch_progress_line_for("aws")
44
+
45
+
46
+ _AWS_GENERAL_LINE = (
47
+ "We've downloaded the general AWS EC2 quotas that cover on-demand and "
48
+ "Spot instance launches."
49
+ )
50
+ _AZURE_GENERAL_LINE = (
51
+ "We've downloaded the general Azure VM quotas that cover on-demand and "
52
+ "low-priority (Spot-style) launches."
53
+ )
54
+
55
+
56
+ def _specific_limits_line(summary: QuotasCloudSummary) -> str:
57
+ limit_word = "limit" if summary.record_count == 1 else "limits"
58
+ if summary.cloud == "azure":
59
+ special = "dedicated hosts and per-VM-family caps"
60
+ else:
61
+ special = "Dedicated Hosts"
62
+ if summary.cloud == "azure":
63
+ return (
64
+ f"We've also downloaded {summary.record_count} specific Azure VM "
65
+ f"{limit_word} from {summary.region} that cover special types like "
66
+ f"{special}."
67
+ )
68
+ return (
69
+ f"We've also downloaded {summary.record_count} specific AWS EC2 "
70
+ f"{limit_word} from {summary.region} that cover special types like "
71
+ f"{special}."
72
+ )
73
+
74
+
75
+ def quotas_get_human_lines(
76
+ *,
77
+ path: str,
78
+ cloud_summaries: tuple[QuotasCloudSummary, ...],
79
+ total_record_count: int = 0,
80
+ loaded_as_of: str = "",
81
+ ) -> tuple[str, ...]:
82
+ lines: list[str] = []
83
+ blocks: list[tuple[str, ...]] = []
84
+ for summary in cloud_summaries:
85
+ block: list[str] = []
86
+ if summary.include_general_line:
87
+ if summary.cloud == "azure":
88
+ block.append(_AZURE_GENERAL_LINE)
89
+ else:
90
+ block.append(_AWS_GENERAL_LINE)
91
+ if summary.record_count > 0:
92
+ block.append(_specific_limits_line(summary))
93
+ if block:
94
+ blocks.append(tuple(block))
95
+ if not blocks and total_record_count == 0:
96
+ checked = f" (checked at {loaded_as_of})" if loaded_as_of else ""
97
+ return (
98
+ "No EC2 quotas returned (read succeeded).",
99
+ f"Saved an empty quota snapshot to {path}{checked}.",
100
+ "",
101
+ )
102
+ for index, block in enumerate(blocks):
103
+ if index:
104
+ lines.append("")
105
+ lines.extend(block)
106
+ if total_record_count:
107
+ unit = "record" if total_record_count == 1 else "records"
108
+ lines.append("")
109
+ lines.append(f"Saved {total_record_count} quota {unit}.")
110
+ lines.append("")
111
+ lines.append(f"Quotas file: {path}")
112
+ lines.append("")
113
+ return tuple(lines)
114
+
115
+
116
+ def reservations_pool_summary_line(
117
+ *,
118
+ pool_record_count: int,
119
+ pool_account_count: int,
120
+ ) -> str:
121
+ unit = "record" if pool_record_count == 1 else "records"
122
+ account_unit = "account" if pool_account_count == 1 else "accounts"
123
+ return (
124
+ f"Coverage pool: {pool_record_count} reservation {unit} across "
125
+ f"{pool_account_count} {account_unit}."
126
+ )
127
+
128
+
129
+ def reservations_get_human_lines(
130
+ *,
131
+ record_count: int,
132
+ path: str,
133
+ loaded_as_of: str,
134
+ region: str = "us-east-1",
135
+ records: tuple[dict, ...] | list[dict] = (),
136
+ account_record_count: int | None = None,
137
+ pool_record_count: int | None = None,
138
+ pool_account_count: int | None = None,
139
+ ) -> tuple[str, ...]:
140
+ account_count = (
141
+ record_count if account_record_count is None else account_record_count
142
+ )
143
+ if account_count == 0 and record_count == 0:
144
+ lines = [
145
+ f"No EC2 Reserved Instances in {region} (read succeeded).",
146
+ (
147
+ "Saved an empty inventory snapshot to "
148
+ f"{path} (checked at {loaded_as_of})."
149
+ ),
150
+ ]
151
+ if pool_account_count and pool_account_count > 0:
152
+ lines.append(
153
+ reservations_pool_summary_line(
154
+ pool_record_count=int(pool_record_count or 0),
155
+ pool_account_count=pool_account_count,
156
+ )
157
+ )
158
+ return tuple(lines)
159
+ rows = [r for r in records if isinstance(r, dict)]
160
+ # Prefer rows for this fetch region when the account file holds multiple regions.
161
+ region_rows = [
162
+ row
163
+ for row in rows
164
+ if str(row.get("region") or "").strip() == region
165
+ ] or rows
166
+ display_count = len(region_rows) if region_rows else account_count
167
+ instances = sum(int(row.get("quantity") or 0) for row in region_rows)
168
+ by_state: dict[str, int] = {}
169
+ for row in region_rows:
170
+ state = str(row.get("state") or "unknown")
171
+ by_state[state] = by_state.get(state, 0) + 1
172
+ state_bits = ", ".join(f"{count} {state}" for state, count in sorted(by_state.items()))
173
+ unit = "record" if display_count == 1 else "records"
174
+ account_unit = "record" if account_count == 1 else "records"
175
+ lines: list[str] = [
176
+ (
177
+ f"Saved {account_count} reservation {account_unit} for this account to "
178
+ f"{path} (checked at {loaded_as_of})."
179
+ ),
180
+ (
181
+ f"EC2 reservations in {region}: {display_count} {unit} "
182
+ f"({instances} instance{'s' if instances != 1 else ''}; {state_bits})."
183
+ ),
184
+ ]
185
+ detail_limit = 8
186
+ for row in region_rows[:detail_limit]:
187
+ itype = str(row.get("instance_type") or "unknown")
188
+ qty = int(row.get("quantity") or 0)
189
+ state = str(row.get("state") or "unknown")
190
+ lines.append(f" {itype} x {qty} {state}")
191
+ if len(region_rows) > detail_limit:
192
+ lines.append(f" ... and {len(region_rows) - detail_limit} more")
193
+ if pool_account_count is not None and pool_record_count is not None:
194
+ lines.append(
195
+ reservations_pool_summary_line(
196
+ pool_record_count=pool_record_count,
197
+ pool_account_count=pool_account_count,
198
+ )
199
+ )
200
+ lines.append("")
201
+ return tuple(lines)
202
+
203
+
204
+ def reservations_get_summary_message(
205
+ record_count: int,
206
+ *,
207
+ region: str | None = None,
208
+ pool_record_count: int | None = None,
209
+ pool_account_count: int | None = None,
210
+ ) -> str:
211
+ where = f" in {region}" if region else ""
212
+ if record_count == 0:
213
+ base = f"No EC2 Reserved Instances{where} found (read succeeded)."
214
+ else:
215
+ unit = "record" if record_count == 1 else "records"
216
+ base = f"Saved {record_count} reservation {unit}{where} (read succeeded)."
217
+ if pool_account_count is not None and pool_record_count is not None:
218
+ return (
219
+ f"{base} "
220
+ + reservations_pool_summary_line(
221
+ pool_record_count=pool_record_count,
222
+ pool_account_count=pool_account_count,
223
+ )
224
+ )
225
+ return base
226
+
227
+
228
+ def saving_plans_get_human_lines(
229
+ *,
230
+ record_count: int,
231
+ path: str,
232
+ loaded_as_of: str,
233
+ ) -> tuple[str, ...]:
234
+ if record_count == 0:
235
+ return (
236
+ "No Savings Plans in this account (read succeeded).",
237
+ (
238
+ "Saved an empty inventory snapshot to "
239
+ f"{path} (checked at {loaded_as_of})."
240
+ ),
241
+ )
242
+ unit = "plan" if record_count == 1 else "plans"
243
+ return (
244
+ (
245
+ f"Saved {record_count} Savings {unit} to {path} "
246
+ f"(checked at {loaded_as_of})."
247
+ ),
248
+ "Includes every Savings Plan in this account (every state the API returned).",
249
+ )
250
+
251
+
252
+ def saving_plans_get_summary_message(record_count: int) -> str:
253
+ if record_count == 0:
254
+ return "No Savings Plans found (read succeeded)."
255
+ unit = "plan" if record_count == 1 else "plans"
256
+ return f"Saved {record_count} Savings {unit} (read succeeded)."
257
+
258
+
259
+ def quotas_get_summary_message(record_count: int) -> str:
260
+ if record_count == 0:
261
+ return "No quota rows returned; saved empty snapshot."
262
+ return f"Downloaded {record_count} quota rows (read succeeded)."
263
+
264
+
@@ -0,0 +1,37 @@
1
+ """Refresh on-disk reservation inventory during analyze."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from typing import Any
7
+
8
+ from maproom.inventory.accounts import AccountIdentityError
9
+ from maproom.reservations.model import ReservationError
10
+
11
+
12
+ def refresh_reservations_inventory(
13
+ runner: Any,
14
+ *,
15
+ as_json: bool = False,
16
+ aws_region: str | None = None,
17
+ ) -> bool:
18
+ """Run the same AWS reservation fetch as ``maproom inventory get`` reservations."""
19
+ import maproom.reservations.commands as reservation_cmd
20
+
21
+ from maproom.inventory.messages import reservations_fetch_progress_line
22
+ from maproom.reservations.model import build_snapshot
23
+
24
+ if not as_json:
25
+ print(reservations_fetch_progress_line(), file=sys.stderr, flush=True)
26
+ try:
27
+ account = reservation_cmd.resolve_aws_account(runner)
28
+ records, region = reservation_cmd.aws.fetch_aws_inventory(runner, region=aws_region)
29
+ except (AccountIdentityError, ReservationError):
30
+ return False
31
+ snapshot = build_snapshot(records, source="aws_get", region=region)
32
+ snapshot["cloud"] = account.cloud
33
+ snapshot["account_id"] = account.account_id
34
+ if account.alias:
35
+ snapshot["account_alias"] = account.alias
36
+ err = reservation_cmd.store.write_account_snapshot(snapshot, account)
37
+ return err is None
@@ -0,0 +1,28 @@
1
+ """Mock account files selected by environment variables."""
2
+
3
+ from maproom.mock_environment.load import (
4
+ ENV_ENVIRONMENT,
5
+ ENV_INSTANCES,
6
+ ENV_QUOTAS,
7
+ ENV_RESERVATIONS,
8
+ ENV_SAVINGS_PLANS,
9
+ MockAccount,
10
+ MockEnvironmentError,
11
+ MockInstance,
12
+ load_mock_account,
13
+ )
14
+ from maproom.mock_environment.runner import MockEnvironmentRunner, command_runner
15
+
16
+ __all__ = [
17
+ "ENV_ENVIRONMENT",
18
+ "ENV_INSTANCES",
19
+ "ENV_QUOTAS",
20
+ "ENV_RESERVATIONS",
21
+ "ENV_SAVINGS_PLANS",
22
+ "MockAccount",
23
+ "MockEnvironmentError",
24
+ "MockEnvironmentRunner",
25
+ "MockInstance",
26
+ "command_runner",
27
+ "load_mock_account",
28
+ ]
@@ -0,0 +1,241 @@
1
+ """Load a mock account from five JSON file paths."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ ENV_ENVIRONMENT = "MAPROOM_MOCK_ENVIRONMENT"
12
+ ENV_INSTANCES = "MAPROOM_MOCK_INSTANCES"
13
+ ENV_RESERVATIONS = "MAPROOM_MOCK_RESERVATIONS"
14
+ ENV_QUOTAS = "MAPROOM_MOCK_QUOTAS"
15
+ ENV_SAVINGS_PLANS = "MAPROOM_MOCK_SAVINGS_PLANS"
16
+
17
+ _LEVEL_FIELDS: dict[int, tuple[str, ...]] = {
18
+ 1: ("instance_type",),
19
+ 2: ("az", "lifecycle"),
20
+ 3: ("cpu_percent",),
21
+ 4: (),
22
+ 5: ("memory_percent", "disk", "network"),
23
+ 6: (),
24
+ }
25
+ _LIFECYCLES = frozenset({"spot", "on-demand"})
26
+ _NUMBER_FIELDS = frozenset(
27
+ {"cpu_percent", "memory_percent", "disk", "network", "credit_balance"}
28
+ )
29
+
30
+
31
+ class MockEnvironmentError(Exception):
32
+ """A mock file is missing, unreadable, or does not match its product level."""
33
+
34
+ def __init__(self, message: str) -> None:
35
+ self.message = message
36
+ super().__init__(message)
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class MockInstance:
41
+ """One instance. Fields past the product level stay empty."""
42
+
43
+ id: str
44
+ instance_type: str
45
+ az: str = ""
46
+ az_id: str = ""
47
+ lifecycle: str = ""
48
+ cpu_percent: float | None = None
49
+ memory_percent: float | None = None
50
+ disk: float | None = None
51
+ network: float | None = None
52
+ credit_balance: float | None = None
53
+ ena_support: bool = False
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class MockAccount:
58
+ """The composed mock account."""
59
+
60
+ cloud: str
61
+ region: str
62
+ product_level: int
63
+ instances: tuple[MockInstance, ...]
64
+ reservations: tuple[dict[str, Any], ...]
65
+ quotas: tuple[dict[str, Any], ...]
66
+ savings_plans: tuple[dict[str, Any], ...]
67
+ offered_instance_types: tuple[str, ...] = ()
68
+
69
+
70
+ def load_mock_account() -> MockAccount | None:
71
+ """Read the mock account, or None when ``MAPROOM_MOCK_ENVIRONMENT`` is unset.
72
+
73
+ A set path that cannot be read raises ``MockEnvironmentError``. Omitted
74
+ list variables are empty lists.
75
+ """
76
+ environment_path = _optional_env(ENV_ENVIRONMENT)
77
+ if environment_path is None:
78
+ return None
79
+ environment = _read_object(environment_path, "mock environment")
80
+ cloud = str(environment.get("cloud") or "").strip()
81
+ region = str(environment.get("region") or "").strip()
82
+ if cloud not in {"aws", "azure"}:
83
+ raise MockEnvironmentError("mock environment cloud must be aws or azure")
84
+ if not region:
85
+ raise MockEnvironmentError("mock environment region is required")
86
+ product_level = _product_level(environment.get("product_level"))
87
+ return MockAccount(
88
+ cloud=cloud,
89
+ region=region,
90
+ product_level=product_level,
91
+ instances=tuple(
92
+ _instances(_read_list(ENV_INSTANCES, "instances", "mock instances"), product_level)
93
+ ),
94
+ reservations=tuple(_read_list(ENV_RESERVATIONS, "reservations", "mock reservations")),
95
+ quotas=tuple(_read_list(ENV_QUOTAS, "quotas", "mock quotas")),
96
+ savings_plans=tuple(
97
+ _read_list(ENV_SAVINGS_PLANS, "savings_plans", "mock savings plans")
98
+ ),
99
+ offered_instance_types=_offered_types(environment.get("offered_instance_types")),
100
+ )
101
+
102
+
103
+ def _optional_env(name: str) -> str | None:
104
+ raw = os.environ.get(name)
105
+ if raw is None:
106
+ return None
107
+ text = raw.strip()
108
+ if not text:
109
+ return None
110
+ return text
111
+
112
+
113
+ def _read_object(path_text: str, label: str) -> dict[str, Any]:
114
+ payload = _read_json(path_text, label)
115
+ if not isinstance(payload, dict):
116
+ raise MockEnvironmentError(f"{label} file must be a JSON object")
117
+ return payload
118
+
119
+
120
+ def _read_list(env_name: str, key: str, label: str) -> list[dict[str, Any]]:
121
+ path_text = _optional_env(env_name)
122
+ if path_text is None:
123
+ return []
124
+ payload = _read_object(path_text, label)
125
+ rows = payload.get(key)
126
+ if rows is None:
127
+ return []
128
+ if not isinstance(rows, list):
129
+ raise MockEnvironmentError(f"{label} {key} must be a list")
130
+ collected: list[dict[str, Any]] = []
131
+ for row in rows:
132
+ if not isinstance(row, dict):
133
+ raise MockEnvironmentError(f"{label} {key} entries must be objects")
134
+ collected.append(row)
135
+ return collected
136
+
137
+
138
+ def _read_json(path_text: str, label: str) -> Any:
139
+ path = Path(path_text)
140
+ try:
141
+ text = path.read_text(encoding="utf-8")
142
+ except OSError as exc:
143
+ raise MockEnvironmentError(f"{label} file could not be read: {path_text}") from exc
144
+ try:
145
+ return json.loads(text)
146
+ except json.JSONDecodeError as exc:
147
+ raise MockEnvironmentError(f"{label} file is not valid JSON: {path_text}") from exc
148
+
149
+
150
+ def _offered_types(raw: object) -> tuple[str, ...]:
151
+ if raw is None:
152
+ return ()
153
+ if not isinstance(raw, list):
154
+ raise MockEnvironmentError("offered_instance_types must be a list of names")
155
+ names: list[str] = []
156
+ for item in raw:
157
+ if not isinstance(item, str) or not item.strip():
158
+ raise MockEnvironmentError("offered_instance_types must be a list of names")
159
+ names.append(item.strip())
160
+ return tuple(names)
161
+
162
+
163
+ def _product_level(raw: object) -> int:
164
+ if isinstance(raw, bool) or not isinstance(raw, int) or raw < 1 or raw > 6:
165
+ raise MockEnvironmentError("mock environment product_level must be an integer from 1 to 6")
166
+ return raw
167
+
168
+
169
+ def _instances(rows: list[dict[str, Any]], product_level: int) -> list[MockInstance]:
170
+ required = _required_fields(product_level)
171
+ instances: list[MockInstance] = []
172
+ for row in rows:
173
+ instance_id = str(row.get("id") or "").strip()
174
+ if not instance_id:
175
+ raise MockEnvironmentError("mock instance id is required")
176
+ missing = [name for name in required if name != "id" and not _present(row, name)]
177
+ if missing:
178
+ names = ", ".join(missing)
179
+ raise MockEnvironmentError(
180
+ f"mock instance {instance_id} is missing {names} for product level {product_level}"
181
+ )
182
+ lifecycle = str(row.get("lifecycle") or "").strip()
183
+ if lifecycle and lifecycle not in _LIFECYCLES:
184
+ raise MockEnvironmentError(
185
+ f"mock instance {instance_id} lifecycle must be spot or on-demand"
186
+ )
187
+ if "lifecycle" in required and not lifecycle:
188
+ raise MockEnvironmentError(
189
+ f"mock instance {instance_id} is missing lifecycle for product level {product_level}"
190
+ )
191
+ instances.append(
192
+ MockInstance(
193
+ id=instance_id,
194
+ instance_type=str(row.get("instance_type") or "").strip(),
195
+ az=str(row.get("az") or "").strip(),
196
+ az_id=str(row.get("az_id") or "").strip(),
197
+ lifecycle=lifecycle,
198
+ cpu_percent=_optional_number(row, "cpu_percent", instance_id),
199
+ memory_percent=_optional_number(row, "memory_percent", instance_id),
200
+ disk=_optional_number(row, "disk", instance_id),
201
+ network=_optional_number(row, "network", instance_id),
202
+ credit_balance=_optional_number(row, "credit_balance", instance_id),
203
+ ena_support=_ena_support(row, instance_id),
204
+ )
205
+ )
206
+ return instances
207
+
208
+
209
+ def _required_fields(product_level: int) -> tuple[str, ...]:
210
+ names: list[str] = ["id"]
211
+ for level in range(1, product_level + 1):
212
+ names.extend(_LEVEL_FIELDS[level])
213
+ return tuple(names)
214
+
215
+
216
+ def _present(row: dict[str, Any], name: str) -> bool:
217
+ if name not in row or row[name] is None:
218
+ return False
219
+ if name in _NUMBER_FIELDS:
220
+ return _is_number(row[name])
221
+ return bool(str(row[name]).strip())
222
+
223
+
224
+ def _optional_number(row: dict[str, Any], name: str, instance_id: str) -> float | None:
225
+ if name not in row or row[name] is None:
226
+ return None
227
+ if not _is_number(row[name]):
228
+ raise MockEnvironmentError(f"mock instance {instance_id} {name} must be a number")
229
+ return float(row[name])
230
+
231
+
232
+ def _is_number(value: object) -> bool:
233
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
234
+
235
+
236
+ def _ena_support(row: dict[str, Any], instance_id: str) -> bool:
237
+ if "ena" not in row or row["ena"] is None:
238
+ return False
239
+ if not isinstance(row["ena"], bool):
240
+ raise MockEnvironmentError(f"mock instance {instance_id} ena must be true or false")
241
+ return row["ena"]