hfim-cli 1.15.6__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 (288) hide show
  1. fim/__init__.py +42 -0
  2. fim/analysis/__init__.py +53 -0
  3. fim/analysis/burst_sdc.py +160 -0
  4. fim/analysis/classifier.py +924 -0
  5. fim/analysis/comparator.py +738 -0
  6. fim/analysis/consolidate.py +625 -0
  7. fim/analysis/csv_io.py +28 -0
  8. fim/analysis/ecc_quartet.py +167 -0
  9. fim/analysis/nvm_endurance_matrix.py +170 -0
  10. fim/analysis/observable_state.py +945 -0
  11. fim/analysis/reporter.py +712 -0
  12. fim/analysis/results_txt.py +229 -0
  13. fim/campaigns/__init__.py +28 -0
  14. fim/campaigns/base_campaign.py +5151 -0
  15. fim/campaigns/cache_campaign.py +233 -0
  16. fim/campaigns/campaign_view.py +135 -0
  17. fim/campaigns/csr_campaign.py +31 -0
  18. fim/campaigns/fault_plan.py +105 -0
  19. fim/campaigns/faultlist_builder.py +503 -0
  20. fim/campaigns/gem5_parallel_runner.py +210 -0
  21. fim/campaigns/golden_gate.py +158 -0
  22. fim/campaigns/injection_point_selector.py +473 -0
  23. fim/campaigns/memory_campaign.py +686 -0
  24. fim/campaigns/parallel_runner.py +510 -0
  25. fim/campaigns/register_campaign.py +617 -0
  26. fim/campaigns/serial_feeder.py +169 -0
  27. fim/cli.py +2652 -0
  28. fim/configs/benchmarks/bitcount.yaml +11 -0
  29. fim/configs/benchmarks/checksum.yaml +11 -0
  30. fim/configs/benchmarks/dotprod_f64.yaml +12 -0
  31. fim/configs/benchmarks/fibonacci.yaml +10 -0
  32. fim/configs/boards/board_spec_schema.yaml +216 -0
  33. fim/configs/boards/raspberry_pi_5.yaml +122 -0
  34. fim/configs/boards/xuantie_c906.yaml +127 -0
  35. fim/configs/boards/xuantie_c906_ruby_nvmain.yaml +85 -0
  36. fim/configs/dramsim3/DDR3_1Gb_x8_1333.ini +69 -0
  37. fim/configs/dramsim3/DDR3_4Gb_x16_1600.ini +67 -0
  38. fim/configs/dramsim3/DDR3_4Gb_x16_1866.ini +67 -0
  39. fim/configs/dramsim3/DDR3_4Gb_x4_1600.ini +67 -0
  40. fim/configs/dramsim3/DDR3_4Gb_x4_1866.ini +67 -0
  41. fim/configs/dramsim3/DDR3_4Gb_x8_1600.ini +67 -0
  42. fim/configs/dramsim3/DDR3_4Gb_x8_1866.ini +67 -0
  43. fim/configs/dramsim3/DDR3_8Gb_x16_1600.ini +67 -0
  44. fim/configs/dramsim3/DDR3_8Gb_x16_1866.ini +67 -0
  45. fim/configs/dramsim3/DDR3_8Gb_x4_1600.ini +67 -0
  46. fim/configs/dramsim3/DDR3_8Gb_x4_1866.ini +67 -0
  47. fim/configs/dramsim3/DDR3_8Gb_x8_1600.ini +67 -0
  48. fim/configs/dramsim3/DDR3_8Gb_x8_1866.ini +67 -0
  49. fim/configs/dramsim3/DDR4_4Gb_x16_1866.ini +67 -0
  50. fim/configs/dramsim3/DDR4_4Gb_x16_2133.ini +67 -0
  51. fim/configs/dramsim3/DDR4_4Gb_x16_2133_2.ini +67 -0
  52. fim/configs/dramsim3/DDR4_4Gb_x16_2400.ini +67 -0
  53. fim/configs/dramsim3/DDR4_4Gb_x16_2400_2.ini +67 -0
  54. fim/configs/dramsim3/DDR4_4Gb_x16_2666.ini +67 -0
  55. fim/configs/dramsim3/DDR4_4Gb_x16_2666_2.ini +67 -0
  56. fim/configs/dramsim3/DDR4_4Gb_x4_1866.ini +67 -0
  57. fim/configs/dramsim3/DDR4_4Gb_x4_2133.ini +67 -0
  58. fim/configs/dramsim3/DDR4_4Gb_x4_2133_2.ini +67 -0
  59. fim/configs/dramsim3/DDR4_4Gb_x4_2400.ini +67 -0
  60. fim/configs/dramsim3/DDR4_4Gb_x4_2400_2.ini +67 -0
  61. fim/configs/dramsim3/DDR4_4Gb_x4_2666.ini +67 -0
  62. fim/configs/dramsim3/DDR4_4Gb_x4_2666_2.ini +67 -0
  63. fim/configs/dramsim3/DDR4_4Gb_x8_1866.ini +67 -0
  64. fim/configs/dramsim3/DDR4_4Gb_x8_2133.ini +67 -0
  65. fim/configs/dramsim3/DDR4_4Gb_x8_2133_2.ini +67 -0
  66. fim/configs/dramsim3/DDR4_4Gb_x8_2400.ini +67 -0
  67. fim/configs/dramsim3/DDR4_4Gb_x8_2400_2.ini +67 -0
  68. fim/configs/dramsim3/DDR4_4Gb_x8_2666.ini +67 -0
  69. fim/configs/dramsim3/DDR4_4Gb_x8_2666_2.ini +67 -0
  70. fim/configs/dramsim3/DDR4_8Gb_x16_1866.ini +67 -0
  71. fim/configs/dramsim3/DDR4_8Gb_x16_2133.ini +67 -0
  72. fim/configs/dramsim3/DDR4_8Gb_x16_2133_2.ini +67 -0
  73. fim/configs/dramsim3/DDR4_8Gb_x16_2400.ini +67 -0
  74. fim/configs/dramsim3/DDR4_8Gb_x16_2400_2.ini +67 -0
  75. fim/configs/dramsim3/DDR4_8Gb_x16_2666.ini +67 -0
  76. fim/configs/dramsim3/DDR4_8Gb_x16_2666_2.ini +67 -0
  77. fim/configs/dramsim3/DDR4_8Gb_x16_2933.ini +67 -0
  78. fim/configs/dramsim3/DDR4_8Gb_x16_2933_2.ini +67 -0
  79. fim/configs/dramsim3/DDR4_8Gb_x16_3200.ini +67 -0
  80. fim/configs/dramsim3/DDR4_8Gb_x4_1866.ini +67 -0
  81. fim/configs/dramsim3/DDR4_8Gb_x4_2133.ini +67 -0
  82. fim/configs/dramsim3/DDR4_8Gb_x4_2133_2.ini +67 -0
  83. fim/configs/dramsim3/DDR4_8Gb_x4_2400.ini +67 -0
  84. fim/configs/dramsim3/DDR4_8Gb_x4_2400_2.ini +67 -0
  85. fim/configs/dramsim3/DDR4_8Gb_x4_2666.ini +67 -0
  86. fim/configs/dramsim3/DDR4_8Gb_x4_2666_2.ini +67 -0
  87. fim/configs/dramsim3/DDR4_8Gb_x4_2933.ini +67 -0
  88. fim/configs/dramsim3/DDR4_8Gb_x4_2933_2.ini +67 -0
  89. fim/configs/dramsim3/DDR4_8Gb_x4_3200.ini +67 -0
  90. fim/configs/dramsim3/DDR4_8Gb_x8_1866.ini +67 -0
  91. fim/configs/dramsim3/DDR4_8Gb_x8_2133.ini +67 -0
  92. fim/configs/dramsim3/DDR4_8Gb_x8_2133_2.ini +67 -0
  93. fim/configs/dramsim3/DDR4_8Gb_x8_2400.ini +77 -0
  94. fim/configs/dramsim3/DDR4_8Gb_x8_2400_2.ini +67 -0
  95. fim/configs/dramsim3/DDR4_8Gb_x8_2666.ini +67 -0
  96. fim/configs/dramsim3/DDR4_8Gb_x8_2666_2.ini +67 -0
  97. fim/configs/dramsim3/DDR4_8Gb_x8_2933.ini +67 -0
  98. fim/configs/dramsim3/DDR4_8Gb_x8_2933_2.ini +67 -0
  99. fim/configs/dramsim3/DDR4_8Gb_x8_3200.ini +67 -0
  100. fim/configs/ecc_policies/c906.yaml +26 -0
  101. fim/configs/matmul_aarch64.yaml +62 -0
  102. fim/configs/mcpat/c906.xml +481 -0
  103. fim/configs/mcpat/raspberry_pi_5.xml +405 -0
  104. fim/configs/mcpat/sTemplate.xml +444 -0
  105. fim/configs/mcpat/template.xml +405 -0
  106. fim/configs/mmult.yaml +140 -0
  107. fim/configs/mmult_memory_gem5.yaml +23 -0
  108. fim/configs/nvmain/2D_DRAM_example.config +249 -0
  109. fim/configs/nvmain/3D_DRAMCache_OffChipMemory_example.config +154 -0
  110. fim/configs/nvmain/3D_DRAMCache_example.config +275 -0
  111. fim/configs/nvmain/3D_DRAM_example.config +237 -0
  112. fim/configs/nvmain/3D_PredictorDRC_example.config +277 -0
  113. fim/configs/nvmain/3D_VariableDRC_example.config +278 -0
  114. fim/configs/nvmain/Hybrid_DRAM_channel.config +249 -0
  115. fim/configs/nvmain/Hybrid_NVM_channel.config +208 -0
  116. fim/configs/nvmain/Hybrid_NVM_channel_BitModel.config +208 -0
  117. fim/configs/nvmain/Hybrid_example.config +72 -0
  118. fim/configs/nvmain/Hybrid_example_BitModel.config +72 -0
  119. fim/configs/nvmain/PCM_ISSCC_2012_4GB.config +217 -0
  120. fim/configs/nvmain/PCM_ISSCC_2012_4GB_BitModel.config +217 -0
  121. fim/configs/nvmain/PCM_ISSCC_2012_4GB_BitModel_ECP.config +222 -0
  122. fim/configs/nvmain/PCM_ISSCC_2012_4GB_ByteModel.config +217 -0
  123. fim/configs/nvmain/PCM_ISSCC_2012_4GB_RowModel.config +217 -0
  124. fim/configs/nvmain/PCM_ISSCC_2012_4GB_WordModel.config +217 -0
  125. fim/configs/nvmain/PCM_MLC_estimated.config +233 -0
  126. fim/configs/nvmain/PCM_MLC_example.config +232 -0
  127. fim/configs/nvmain/PCM_MLC_example_BitModel.config +232 -0
  128. fim/configs/nvmain/PerfectMemory.config +229 -0
  129. fim/configs/nvmain/RRAM_ISSCC_2012_4GB.config +218 -0
  130. fim/configs/nvmain/STTRAM_Everspin_4GB.config +217 -0
  131. fim/configs/nvmain/STTRAM_Everspin_4GB_BitModel.config +217 -0
  132. fim/configs/nvmain/printtrace.config +145 -0
  133. fim/configs/nvmain/printtrace_bitflip.config +146 -0
  134. fim/configs/quicksort_dmr.yaml +225 -0
  135. fim/configs/rust_sort_array.yaml +28 -0
  136. fim/configs/rust_sort_bss.yaml +38 -0
  137. fim/configs/sum.yaml +149 -0
  138. fim/configs/template.yaml +418 -0
  139. fim/configs/toolchains.remote.json +14 -0
  140. fim/core/__init__.py +161 -0
  141. fim/core/artifacts/__init__.py +25 -0
  142. fim/core/artifacts/adapters/__init__.py +146 -0
  143. fim/core/artifacts/adapters/board.py +38 -0
  144. fim/core/artifacts/adapters/config.py +115 -0
  145. fim/core/artifacts/adapters/sdk.py +435 -0
  146. fim/core/artifacts/adapters/simulator.py +139 -0
  147. fim/core/artifacts/adapters/template.py +107 -0
  148. fim/core/artifacts/classification.py +95 -0
  149. fim/core/artifacts/hashing.py +265 -0
  150. fim/core/artifacts/inputs.py +179 -0
  151. fim/core/artifacts/records.py +238 -0
  152. fim/core/artifacts/retention.py +504 -0
  153. fim/core/artifacts/staleness.py +486 -0
  154. fim/core/artifacts/store.py +202 -0
  155. fim/core/artifacts/workspace.py +108 -0
  156. fim/core/checkpoint.py +338 -0
  157. fim/core/checkpoint_policy.py +171 -0
  158. fim/core/classifier_view.py +96 -0
  159. fim/core/clock_view.py +99 -0
  160. fim/core/configuration/__init__.py +13 -0
  161. fim/core/configuration/frozen.py +85 -0
  162. fim/core/configuration/groups.py +41 -0
  163. fim/core/configuration/includes.py +249 -0
  164. fim/core/configuration/lifecycle_rules.py +83 -0
  165. fim/core/configuration/reference.py +200 -0
  166. fim/core/configuration/reference_docs.py +344 -0
  167. fim/core/configuration/resolver.py +495 -0
  168. fim/core/configuration/run_context.py +51 -0
  169. fim/core/configuration/schema.py +784 -0
  170. fim/core/configuration/sources.py +121 -0
  171. fim/core/configuration/template_pins.py +79 -0
  172. fim/core/fault_models.py +261 -0
  173. fim/core/fim.py +452 -0
  174. fim/core/gdb_controller.py +2053 -0
  175. fim/core/gem5_controller.py +1226 -0
  176. fim/core/gem5_launch.py +489 -0
  177. fim/core/gem5_observable.py +202 -0
  178. fim/core/gem5_producers.py +684 -0
  179. fim/core/gem5_simulator.py +724 -0
  180. fim/core/golden_view.py +94 -0
  181. fim/core/hardware_cluster.py +236 -0
  182. fim/core/hardware_simulator.py +992 -0
  183. fim/core/hardware_spec.py +352 -0
  184. fim/core/hardware_station.py +374 -0
  185. fim/core/hardware_view.py +64 -0
  186. fim/core/hardware_window.py +102 -0
  187. fim/core/hook_view.py +52 -0
  188. fim/core/lifecycle.py +433 -0
  189. fim/core/machine_binding.py +317 -0
  190. fim/core/ovp_plan.py +419 -0
  191. fim/core/ovp_protocol.py +647 -0
  192. fim/core/ovp_simulator.py +1201 -0
  193. fim/core/ovp_view.py +99 -0
  194. fim/core/qemu_controller.py +1396 -0
  195. fim/core/qemu_launch.py +179 -0
  196. fim/core/qemu_simulator.py +329 -0
  197. fim/core/results_store.py +218 -0
  198. fim/core/results_view.py +94 -0
  199. fim/core/simulator_controller.py +298 -0
  200. fim/core/simulator_manifest.py +739 -0
  201. fim/core/station_host.py +277 -0
  202. fim/install/__init__.py +16 -0
  203. fim/install/ensure.py +182 -0
  204. fim/install/home.py +126 -0
  205. fim/install/index.py +122 -0
  206. fim/install/index.yaml +59 -0
  207. fim/install/prebuilt.py +120 -0
  208. fim/install/probes.py +182 -0
  209. fim/install/remote.py +165 -0
  210. fim/install/sdk.py +178 -0
  211. fim/install/setup.py +184 -0
  212. fim/install/simulators.py +323 -0
  213. fim/install/template.py +147 -0
  214. fim/install/uninstall.py +149 -0
  215. fim/provision/__init__.py +48 -0
  216. fim/provision/catalog.py +278 -0
  217. fim/provision/commands.py +1051 -0
  218. fim/provision/doctor.py +291 -0
  219. fim/provision/drain.py +117 -0
  220. fim/provision/forms/__init__.py +4 -0
  221. fim/provision/forms/docker.py +469 -0
  222. fim/provision/forms/fake.py +281 -0
  223. fim/provision/forms/native.py +438 -0
  224. fim/provision/fresh_layout.py +66 -0
  225. fim/provision/hostdeps.py +229 -0
  226. fim/provision/layout_units.py +148 -0
  227. fim/provision/lock.py +100 -0
  228. fim/provision/package.py +110 -0
  229. fim/provision/plan.py +356 -0
  230. fim/provision/privilege.py +259 -0
  231. fim/provision/probe.py +117 -0
  232. fim/provision/release.py +188 -0
  233. fim/provision/sdk.py +102 -0
  234. fim/provision/steps.py +324 -0
  235. fim/provision/switch.py +80 -0
  236. fim/provision/switch_recovery.py +165 -0
  237. fim/remote/__init__.py +15 -0
  238. fim/remote/access/__init__.py +203 -0
  239. fim/remote/access/credential.py +46 -0
  240. fim/remote/access/credentials/__init__.py +4 -0
  241. fim/remote/access/credentials/command.py +50 -0
  242. fim/remote/access/credentials/keychain.py +50 -0
  243. fim/remote/access/credentials/none.py +16 -0
  244. fim/remote/access/credentials/peer.py +25 -0
  245. fim/remote/access/credentials/token.py +50 -0
  246. fim/remote/access/spec.py +34 -0
  247. fim/remote/access/transport.py +66 -0
  248. fim/remote/access/transports/__init__.py +4 -0
  249. fim/remote/access/transports/command.py +222 -0
  250. fim/remote/access/transports/direct.py +39 -0
  251. fim/remote/access/transports/ssh_tunnel.py +74 -0
  252. fim/remote/api.py +245 -0
  253. fim/remote/commands.py +625 -0
  254. fim/remote/fetch.py +155 -0
  255. fim/remote/follow.py +157 -0
  256. fim/remote/journal.py +150 -0
  257. fim/remote/location.py +108 -0
  258. fim/remote/preflight.py +350 -0
  259. fim/remote/servers.py +159 -0
  260. fim/remote/snapshot.py +249 -0
  261. fim/remote/submit.py +302 -0
  262. fim/scripts/__init__.py +2 -0
  263. fim/scripts/generate_report.py +108 -0
  264. fim/scripts/run_campaign.py +1447 -0
  265. fim/scripts/run_ecc_quartet.py +94 -0
  266. fim/scripts/run_golden.py +2256 -0
  267. fim/scripts/verify_provenance.py +61 -0
  268. fim/utils/__init__.py +74 -0
  269. fim/utils/board.py +378 -0
  270. fim/utils/board_view.py +39 -0
  271. fim/utils/config.py +1714 -0
  272. fim/utils/coredump.py +28 -0
  273. fim/utils/elf_parser.py +1118 -0
  274. fim/utils/elf_provenance.py +140 -0
  275. fim/utils/injection_file_writer.py +309 -0
  276. fim/utils/logger.py +362 -0
  277. fim/utils/picker.py +195 -0
  278. fim/utils/prng.py +207 -0
  279. fim/utils/provenance.py +873 -0
  280. fim/utils/register_width.py +52 -0
  281. hfim_cli-1.15.6.data/data/share/hfim/gem5_to_mcpat.py +508 -0
  282. hfim_cli-1.15.6.dist-info/METADATA +131 -0
  283. hfim_cli-1.15.6.dist-info/RECORD +288 -0
  284. hfim_cli-1.15.6.dist-info/WHEEL +5 -0
  285. hfim_cli-1.15.6.dist-info/entry_points.txt +2 -0
  286. hfim_cli-1.15.6.dist-info/licenses/LICENSE +21 -0
  287. hfim_cli-1.15.6.dist-info/licenses/THIRD_PARTY_NOTICES +166 -0
  288. hfim_cli-1.15.6.dist-info/top_level.txt +1 -0
@@ -0,0 +1,229 @@
1
+ # SPDX-FileCopyrightText: 2026 HI-REST and the HFIM contributors
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The system packages a native Server needs to build its simulator, and the
5
+ one command that installs the missing ones on this distribution.
6
+
7
+ hfim never installs an OS package itself (the Admin Account installs
8
+ prerequisites). It names what is missing and prints the exact
9
+ command for the package manager of this host, so the refusal of `hfim
10
+ server install` and the doctor line can be pasted as they are.
11
+
12
+ SIM_BUILD is what `hfim sim install` with the native form needs to build
13
+ hfim-sim-qemu (its Dockerfile's build stage: the tools, and the libraries
14
+ QEMU's configure cannot do without), plus gdb-multiarch, which drives the
15
+ injections. FEEDER_BUILD is what pip needs to fill an account's Feeder Venv.
16
+ A library is checked with pkg-config, so it is checked only once pkg-config
17
+ is there.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ import shutil
24
+ import subprocess
25
+ from dataclasses import dataclass
26
+ from pathlib import Path
27
+ from typing import Callable, Dict, List, Optional, Tuple
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Dep:
32
+ name: str # what the message calls it
33
+ tool: Optional[str] = None # a program on PATH
34
+ pc: Optional[str] = None # a pkg-config module
35
+ packages: Tuple[Tuple[str, str], ...] = () # (family, package)
36
+
37
+ def package(self, family: str) -> Optional[str]:
38
+ return dict(self.packages).get(family)
39
+
40
+
41
+ def _pk(debian, fedora, arch, suse, alpine):
42
+ return tuple((f, p) for f, p in (("debian", debian), ("fedora", fedora), ("arch", arch),
43
+ ("suse", suse), ("alpine", alpine)) if p)
44
+
45
+
46
+ SIM_BUILD: Tuple[Dep, ...] = (
47
+ Dep("ninja", tool="ninja",
48
+ packages=_pk("ninja-build", "ninja-build", "ninja", "ninja", "samurai")),
49
+ Dep("meson", tool="meson",
50
+ packages=_pk("meson", "meson", "meson", "meson", "meson")),
51
+ Dep("pkg-config", tool="pkg-config",
52
+ packages=_pk("pkg-config", "pkgconf-pkg-config", "pkgconf", "pkg-config", "pkgconf")),
53
+ Dep("gdb-multiarch", tool="gdb-multiarch",
54
+ packages=_pk("gdb-multiarch", None, None, None, "gdb-multiarch")),
55
+ Dep("a C compiler (cc)", tool="cc",
56
+ packages=_pk("build-essential", "gcc", "base-devel", "gcc", "build-base")),
57
+ Dep("glib-2.0", pc="glib-2.0",
58
+ packages=_pk("libglib2.0-dev", "glib2-devel", "glib2", "glib2-devel", "glib-dev")),
59
+ Dep("pixman-1", pc="pixman-1",
60
+ packages=_pk("libpixman-1-dev", "pixman-devel", "pixman", "libpixman-1-0-devel",
61
+ "pixman-dev")),
62
+ Dep("zlib", pc="zlib",
63
+ packages=_pk("zlib1g-dev", "zlib-devel", "zlib", "zlib-devel", "zlib-dev")),
64
+ )
65
+
66
+ # What pip compiles in an account's Feeder Venv. pybullet has no wheel for a
67
+ # new Python, so it builds C++ against the interpreter's headers. An account
68
+ # needs them even on a Server with no simulator to build: without them the
69
+ # account content stops at pip, after the account's user was made.
70
+ FEEDER_BUILD: Tuple[Dep, ...] = (
71
+ Dep("Python headers", pc="python3",
72
+ packages=_pk("python3-dev", "python3-devel", "python", "python3-devel", "python3-dev")),
73
+ Dep("a C++ compiler (c++)", tool="c++",
74
+ packages=_pk("build-essential", "gcc-c++", "base-devel", "gcc-c++", "build-base")),
75
+ )
76
+
77
+ # family -> the install command, without the package names
78
+ INSTALLERS: Dict[str, str] = {
79
+ "debian": "apt install",
80
+ "fedora": "dnf install",
81
+ "arch": "pacman -S --needed",
82
+ "suse": "zypper install",
83
+ "alpine": "apk add",
84
+ }
85
+
86
+ _FAMILY_IDS = {
87
+ "debian": ("debian", "ubuntu", "raspbian", "linuxmint", "pop", "kali"),
88
+ "fedora": ("fedora", "rhel", "centos", "rocky", "almalinux", "ol", "amzn"),
89
+ "arch": ("arch", "manjaro", "endeavouros"),
90
+ "suse": ("opensuse", "opensuse-leap", "opensuse-tumbleweed", "sles", "suse"),
91
+ "alpine": ("alpine",),
92
+ }
93
+
94
+
95
+ def os_release(path: Path = Path("/etc/os-release")) -> Dict[str, str]:
96
+ out: Dict[str, str] = {}
97
+ try:
98
+ text = path.read_text()
99
+ except OSError:
100
+ return out
101
+ for line in text.splitlines():
102
+ key, sep, value = line.partition("=")
103
+ if sep:
104
+ out[key.strip()] = value.strip().strip('"').strip("'")
105
+ return out
106
+
107
+
108
+ def family(release: Dict[str, str]) -> Optional[str]:
109
+ """The package family of a host from its os-release ID and ID_LIKE."""
110
+ ids = [release.get("ID", "")] + release.get("ID_LIKE", "").split()
111
+ for ident in ids:
112
+ ident = ident.lower()
113
+ for fam, names in _FAMILY_IDS.items():
114
+ if ident in names or (fam == "suse" and ident.startswith("opensuse")):
115
+ return fam
116
+ return None
117
+
118
+
119
+ def _pc_exists(module: str) -> bool:
120
+ return subprocess.run(["pkg-config", "--exists", module],
121
+ capture_output=True).returncode == 0
122
+
123
+
124
+ def _missing(deps: Tuple[Dep, ...], which: Callable[[str], Optional[str]],
125
+ pc_exists: Callable[[str], bool]) -> List[Dep]:
126
+ """The dependencies this host lacks. Libraries count only when
127
+ pkg-config can be asked."""
128
+ missing = [d for d in deps if d.tool and not which(d.tool)]
129
+ if which("pkg-config"):
130
+ missing += [d for d in deps if d.pc and not pc_exists(d.pc)]
131
+ return missing
132
+
133
+
134
+ def missing_sim_build(which: Callable[[str], Optional[str]] = shutil.which,
135
+ pc_exists: Callable[[str], bool] = _pc_exists) -> List[Dep]:
136
+ """The simulator build dependencies this host lacks."""
137
+ return _missing(SIM_BUILD, which, pc_exists)
138
+
139
+
140
+ def missing_feeder_build(which: Callable[[str], Optional[str]] = shutil.which,
141
+ pc_exists: Callable[[str], bool] = _pc_exists) -> List[Dep]:
142
+ """What this host lacks to build an account's Feeder Venv."""
143
+ return _missing(FEEDER_BUILD, which, pc_exists)
144
+
145
+
146
+ def install_command(missing: List[Dep], release: Optional[Dict[str, str]] = None,
147
+ euid: Optional[int] = None) -> Optional[str]:
148
+ """`sudo apt install meson libpixman-1-dev ...` for this host, or None
149
+ when its distribution is unknown or a dependency has no package there."""
150
+ if not missing:
151
+ return None
152
+ fam = family(os_release() if release is None else release)
153
+ if fam is None:
154
+ return None
155
+ packages: List[str] = []
156
+ for d in missing:
157
+ p = d.package(fam)
158
+ if p is None:
159
+ return None
160
+ if p not in packages:
161
+ packages.append(p)
162
+ euid = os.geteuid() if euid is None and hasattr(os, "geteuid") else (euid or 0)
163
+ prefix = "" if euid == 0 else "sudo "
164
+ return f"{prefix}{INSTALLERS[fam]} {' '.join(packages)}"
165
+
166
+
167
+ def how_to_install(missing: List[Dep], command: Optional[str]) -> str:
168
+ """How to install `missing` here: the command for this host, else the
169
+ Debian one as an example."""
170
+ if command:
171
+ return f"install them with: {command}"
172
+ debian = [p for p in dict.fromkeys(d.package("debian") for d in missing) if p]
173
+ return ("install them with this distribution's package manager"
174
+ + (f"; on Debian or Ubuntu: sudo apt install {' '.join(debian)}" if debian else ""))
175
+
176
+
177
+ def describe(missing: List[Dep], command: Optional[str]) -> str:
178
+ """One line: what is missing, and how to install it here."""
179
+ return f"{', '.join(d.name for d in missing)} ({how_to_install(missing, command)})"
180
+
181
+
182
+ # -- the compilers of the simulator packages -----------------------------------
183
+ #
184
+ # A package declares the compiler it builds benchmarks with (manifest
185
+ # sdk.toolchains, one per arch). A campaign on a native Server takes it from
186
+ # the package's prefix bin/, else from PATH (fim/core/artifacts/adapters/
187
+ # sdk.py), so a host that lacks it fails at the first build. A package whose
188
+ # native install puts its compilers in its prefix says so
189
+ # (runtime.native.compilers: bundled); otherwise they are the host's.
190
+
191
+ def compiler_dep(compiler: str) -> Dep:
192
+ """A declared compiler as a Dep. Debian and Ubuntu package a GNU cross
193
+ compiler <triple>-gcc as gcc-<triple>; other families get the generic
194
+ line (describe)."""
195
+ triple = compiler[:-len("-gcc")] if compiler.endswith("-gcc") else None
196
+ return Dep(compiler, tool=compiler,
197
+ packages=(("debian", f"gcc-{triple}"),) if triple else ())
198
+
199
+
200
+ def declared_compilers(manifest: Dict) -> List[Tuple[str, str]]:
201
+ """(arch, compiler) of a package manifest's sdk.toolchains."""
202
+ toolchains = ((manifest or {}).get("sdk") or {}).get("toolchains") or {}
203
+ return [(str(a), str(c)) for a, c in toolchains.items() if c]
204
+
205
+
206
+ def bundles_compilers(manifest: Dict) -> bool:
207
+ native = (((manifest or {}).get("runtime") or {}).get("native") or {})
208
+ return str(native.get("compilers") or "").lower() == "bundled"
209
+
210
+
211
+ def missing_compilers(manifest: Dict, root: Optional[str] = None,
212
+ which: Callable[[str], Optional[str]] = shutil.which) -> List[Dep]:
213
+ """The compilers a native install of this package would build with and
214
+ this host lacks. `root` is the prefix of an installed version (its
215
+ registered runtime.native.root): there, or on PATH, as a build looks.
216
+ Without one the package is not installed yet, and a package that
217
+ bundles its compilers brings them with its install."""
218
+ missing: List[Dep] = []
219
+ for _, compiler in declared_compilers(manifest):
220
+ if any(d.name == compiler for d in missing):
221
+ continue
222
+ if root and os.access(Path(root) / "bin" / compiler, os.X_OK):
223
+ continue
224
+ if root is None and bundles_compilers(manifest):
225
+ continue
226
+ if which(compiler):
227
+ continue
228
+ missing.append(compiler_dep(compiler))
229
+ return missing
@@ -0,0 +1,148 @@
1
+ # SPDX-FileCopyrightText: 2026 HI-REST and the HFIM contributors
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Public systemd service aliases for a managed native Server.
5
+
6
+ Keep the installed template as the unit's identity. Both spellings then
7
+ select the same running instance, account-specific drop-ins and service PID.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import re
14
+ import subprocess
15
+ from pathlib import Path
16
+
17
+ from fim.provision import Refused
18
+ from fim.provision.lock import load_lock
19
+ from fim.provision.package import load_package
20
+
21
+ UNIT_DIR = "/etc/systemd/system"
22
+ RECORD = "/etc/hfim/layout-unit-aliases.json"
23
+ _UNIT = re.compile(r"fim-[a-zA-Z0-9_.-]+@?\.service\Z")
24
+ _EXTRA = (".d", ".wants", ".requires", ".upholds")
25
+
26
+
27
+ def _unit_dirs(privilege):
28
+ if privilege.root == Path("/"):
29
+ # Use the manager's actual search order, including runtime generators,
30
+ # local overrides, unit-control paths and the distribution's unit dir.
31
+ result = subprocess.run(["systemctl", "show", "--property=UnitPath", "--value"],
32
+ text=True, capture_output=True)
33
+ if result.returncode or not result.stdout.strip():
34
+ raise Refused("cannot read systemd's unit search path", fix="check the system manager")
35
+ paths = [Path(item) for item in result.stdout.split()]
36
+ else:
37
+ paths = [privilege.path(path) for path in
38
+ (UNIT_DIR, "/run/systemd/system", "/usr/local/lib/systemd/system",
39
+ "/usr/lib/systemd/system", "/lib/systemd/system")]
40
+ return {p.resolve() for p in paths if p.is_dir()}
41
+
42
+
43
+ def _check_names(unit_dirs, dest, name):
44
+ """Refuse foreign configurations that aliasing would shadow or activate."""
45
+ alias = "h" + name
46
+ template = "@" in name
47
+ # systemd also reads prefix drop-ins, e.g. foo-.service.d applies to
48
+ # foo-bar@ana.service. Adding an alias can activate those settings too.
49
+ stem = alias.removesuffix(".service")
50
+ prefix_dropins = {stem[:i + 1] + ".service.d" for i, char in enumerate(stem) if char == "-"}
51
+ for folder in unit_dirs:
52
+ for item in folder.iterdir():
53
+ if item == dest and item.is_symlink() and os.readlink(item) == name:
54
+ continue
55
+ entry = item.name
56
+ for suffix in _EXTRA:
57
+ if entry.endswith(suffix):
58
+ entry = entry[:-len(suffix)]
59
+ break
60
+ if (item.name in prefix_dropins or entry == alias
61
+ or (template and entry.startswith(alias.split("@")[0] + "@")
62
+ and entry.endswith(".service"))):
63
+ raise Refused(f"existing systemd configuration collides with {alias}: {item}")
64
+ if (template and item.name.startswith(name.split("@")[0] + "@")
65
+ and item.name.endswith(".service") and item.name != name):
66
+ raise Refused(f"instance-specific unit {item} needs an explicit alias")
67
+
68
+
69
+ def _save(privilege, owned, pending):
70
+ if owned or pending:
71
+ data = {"owned": sorted(owned), "reload_pending": pending}
72
+ privilege.write(RECORD, (json.dumps(data, sort_keys=True) + "\n").encode())
73
+ else:
74
+ privilege.remove(RECORD)
75
+
76
+
77
+ def sync_unit_aliases(privilege, *, rollback=False, dry_run=False, out=print, unit_names=None):
78
+ """Validate all destinations before changing one; call inside the machine lock."""
79
+ if privilege.path(RECORD).is_symlink():
80
+ raise Refused(f"unexpected symlink at {RECORD}")
81
+ raw = privilege.read(RECORD)
82
+ try:
83
+ data = json.loads(raw) if raw is not None else {}
84
+ owned = set(data.get("owned", []))
85
+ pending = data.get("reload_pending", False)
86
+ if any(not _UNIT.fullmatch(n) for n in owned) or not isinstance(pending, bool):
87
+ raise ValueError("invalid unit alias record")
88
+ except (TypeError, ValueError, AttributeError) as exc:
89
+ raise Refused(f"invalid {RECORD}: {exc}") from exc
90
+
91
+ if rollback:
92
+ names = owned.copy()
93
+ else:
94
+ if unit_names is None:
95
+ lock = load_lock(privilege)
96
+ if lock is None or lock.data.get("form") != "native":
97
+ return
98
+ package_dir = (lock.data.get("package") or {}).get("path")
99
+ if not package_dir or not Path(package_dir).is_absolute():
100
+ raise Refused("the native Server Lock has no absolute package checkout path")
101
+ package = load_package(privilege.path(package_dir))
102
+ unit_names = [p.name for p in package.units("native")]
103
+ names = {n for n in unit_names if _UNIT.fullmatch(n)}
104
+ if not names and not pending:
105
+ return
106
+
107
+ folder = privilege.path(UNIT_DIR).resolve()
108
+ search = _unit_dirs(privilege)
109
+ changes = []
110
+ for name in sorted(names):
111
+ alias = folder / ("h" + name)
112
+ present = alias.is_symlink() and os.readlink(alias) == name
113
+ if rollback:
114
+ if os.path.lexists(alias) and not present:
115
+ raise Refused(f"refusing to remove modified alias {alias}")
116
+ if present:
117
+ changes.append(name)
118
+ else:
119
+ _check_names(search, alias, name)
120
+ source = folder / name
121
+ if not os.path.lexists(source):
122
+ continue # The optional component has not been installed.
123
+ if source.is_symlink() or not source.is_file():
124
+ raise Refused(f"expected a regular installed unit at {source}")
125
+ if not present:
126
+ changes.append(name)
127
+ for name in changes:
128
+ action = "remove" if rollback else "add"
129
+ out(f"{action} service alias h{name} -> {name}")
130
+ if dry_run or not (changes or pending or (rollback and owned)):
131
+ return
132
+
133
+ # Journal the reload before touching aliases. A killed command can leave
134
+ # files correct while systemd still has its old view; retry must reload.
135
+ if not rollback:
136
+ owned.update(changes)
137
+ _save(privilege, owned, True)
138
+ for name in changes:
139
+ alias_path = UNIT_DIR + "/h" + name
140
+ if rollback:
141
+ privilege.remove(alias_path)
142
+ else:
143
+ privilege.create_link(alias_path, name)
144
+ result = privilege.run(["systemctl", "daemon-reload"])
145
+ if result.returncode:
146
+ raise Refused(f"systemd daemon-reload failed: {result.stderr.strip()}",
147
+ fix="correct the manager error and repeat the layout command")
148
+ _save(privilege, set() if rollback else owned, False)
fim/provision/lock.py ADDED
@@ -0,0 +1,100 @@
1
+ # SPDX-FileCopyrightText: 2026 HI-REST and the HFIM contributors
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The Server Lock (`/etc/hfim/server.lock`): what hfim installed on a Server.
5
+
6
+ JSON, written only by hfim, with a temporary file and a rename after every
7
+ Provisioning Step, so a command that stops resumes after
8
+ its last completed step. It holds no secret: file entries
9
+ are content hashes.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from typing import Dict, List, Optional
16
+
17
+ from fim.core.artifacts.hashing import hash_bytes
18
+ from fim.provision.plan import LOCK_PATH
19
+
20
+ LOCK_VERSION = 1
21
+
22
+
23
+ class ServerLock:
24
+ def __init__(self, data: Optional[Dict] = None):
25
+ d = dict(data or {})
26
+ d.setdefault("version", LOCK_VERSION)
27
+ d.setdefault("form", None)
28
+ d.setdefault("active", None)
29
+ d.setdefault("previous", None)
30
+ d.setdefault("releases", [])
31
+ d.setdefault("files", {})
32
+ d.setdefault("simulators", [])
33
+ d.setdefault("sdk", None)
34
+ d.setdefault("accounts", {})
35
+ d.setdefault("redis", {})
36
+ d.setdefault("steps", [])
37
+ d.setdefault("command", None)
38
+ self.data = d
39
+
40
+ # -- releases ---------------------------------------------------------
41
+ def release(self, release_id: Optional[str]) -> Optional[Dict]:
42
+ for r in self.data["releases"]:
43
+ if r["id"] == release_id:
44
+ return r
45
+ return None
46
+
47
+ def put_release(self, entry: Dict) -> None:
48
+ old = self.release(entry["id"])
49
+ if old is None:
50
+ self.data["releases"].append(entry)
51
+ else:
52
+ old.update(entry)
53
+
54
+ @property
55
+ def active(self) -> Optional[str]:
56
+ return self.data["active"]
57
+
58
+ # -- files hfim wrote -------------------------------------------------
59
+ def record_file(self, path: str, content: Optional[bytes]) -> None:
60
+ if content is None:
61
+ self.data["files"].pop(path, None)
62
+ else:
63
+ self.data["files"][path] = hash_bytes(content)
64
+
65
+ # -- accounts ---------------------------------------------------------
66
+ def account(self, name: str) -> Optional[Dict]:
67
+ return self.data["accounts"].get(name)
68
+
69
+ def enabled_accounts(self) -> List[str]:
70
+ return sorted(n for n, a in self.data["accounts"].items()
71
+ if a.get("state") == "enabled")
72
+
73
+ # -- steps ------------------------------------------------------------
74
+ def begin(self, command: str) -> None:
75
+ """A new command: forget the steps of the last one, unless it stopped."""
76
+ if self.data.get("command") != command or not self.data.get("running"):
77
+ self.data["steps"] = []
78
+ self.data["command"] = command
79
+ self.data["running"] = True
80
+
81
+ def done(self, step: str) -> None:
82
+ if step not in self.data["steps"]:
83
+ self.data["steps"].append(step)
84
+
85
+ def finish(self) -> None:
86
+ self.data["running"] = False
87
+
88
+ def to_bytes(self) -> bytes:
89
+ return (json.dumps(self.data, indent=2, sort_keys=True) + "\n").encode()
90
+
91
+
92
+ def load_lock(privilege) -> Optional[ServerLock]:
93
+ raw = privilege.read(LOCK_PATH)
94
+ if raw is None:
95
+ return None
96
+ return ServerLock(json.loads(raw.decode()))
97
+
98
+
99
+ def save_lock(privilege, lock: ServerLock) -> None:
100
+ privilege.write(LOCK_PATH, lock.to_bytes(), mode=0o644)
@@ -0,0 +1,110 @@
1
+ # SPDX-FileCopyrightText: 2026 HI-REST and the HFIM contributors
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The Server Package Manifest: `manifest.yaml` at the root of hfim-server.
5
+
6
+ The same file kind as a simulator package manifest and hfim-sdk's. It is
7
+ the published language between the two contexts: hfim reads the
8
+ Components and the file of each Server Form from it, and names none of
9
+ them in code. A new Component, such as the Public Endpoint, is a
10
+ manifest entry and needs no change to hfim.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Dict, List, Optional
18
+
19
+ import yaml
20
+
21
+ from fim.core.simulator_manifest import core_in_range
22
+ from fim.provision import Refused
23
+
24
+ SERVER_PACKAGE = "hfim-server"
25
+
26
+ _KEYS = {"name", "version", "core", "python", "components", "forms"}
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Component:
31
+ name: str
32
+ per: str # "account" or "server"
33
+ health: Optional[str] = None
34
+
35
+
36
+ @dataclass
37
+ class ServerPackageManifest:
38
+ path: Path
39
+ name: str
40
+ version: str
41
+ core: str
42
+ python: str
43
+ components: Dict[str, Component]
44
+ forms: Dict[str, Dict] = field(default_factory=dict)
45
+
46
+ @property
47
+ def checkout(self) -> Path:
48
+ return self.path.parent
49
+
50
+ def has_component(self, name: str) -> bool:
51
+ return name in self.components
52
+
53
+ def form(self, form: str) -> Dict:
54
+ spec = self.forms.get(form)
55
+ if not spec:
56
+ raise Refused(f"{self.name}@{self.version} has no {form!r} Server Form",
57
+ fix=f"use one of: {', '.join(sorted(self.forms))}")
58
+ return spec
59
+
60
+ def file(self, form: str, key: str) -> Path:
61
+ """The checkout path of one file that a Server Form names."""
62
+ value = self.form(form).get(key)
63
+ if not value:
64
+ raise Refused(f"{self.path} names no {key!r} for the {form} form")
65
+ return self.checkout / str(value)
66
+
67
+ def units(self, form: str = "native") -> List[Path]:
68
+ return [self.checkout / str(u) for u in (self.form(form).get("units") or [])]
69
+
70
+ def unit_for(self, component: str) -> Optional[str]:
71
+ """The unit template file name of a per-account Component.
72
+
73
+ Matched by the Component name inside the template file name, so a
74
+ renamed unit only needs its manifest entry.
75
+ """
76
+ for unit in self.units("native"):
77
+ if component in unit.name:
78
+ return unit.name
79
+ return None
80
+
81
+ def accepts_core(self, core_version: str) -> bool:
82
+ return core_in_range(self.core, core_version)
83
+
84
+
85
+ def load_package(checkout: Path) -> ServerPackageManifest:
86
+ path = Path(checkout) / "manifest.yaml"
87
+ if not path.is_file():
88
+ raise Refused(f"{checkout} is not an hfim-server checkout (no manifest.yaml)",
89
+ fix="give the path of an hfim-server checkout")
90
+ try:
91
+ data = yaml.safe_load(path.read_text()) or {}
92
+ except yaml.YAMLError as exc:
93
+ raise Refused(f"{path} is not readable YAML: {exc}") from None
94
+ unknown = sorted(set(data) - _KEYS)
95
+ if unknown:
96
+ raise Refused(f"{path}: unknown key {unknown[0]!r}")
97
+ for key in ("name", "version", "core", "components", "forms"):
98
+ if not data.get(key):
99
+ raise Refused(f"{path}: manifest lacks {key!r}")
100
+ components = {}
101
+ for name, spec in (data.get("components") or {}).items():
102
+ spec = spec or {}
103
+ per = spec.get("per")
104
+ if per not in ("account", "server"):
105
+ raise Refused(f"{path}: component {name!r} needs per: account or server")
106
+ components[name] = Component(name, per, spec.get("health"))
107
+ return ServerPackageManifest(
108
+ path=path, name=str(data["name"]), version=str(data["version"]),
109
+ core=str(data["core"]), python=str(data.get("python") or ">=3.11"),
110
+ components=components, forms=dict(data.get("forms") or {}))