prepare_mod_ui_pedalboard.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. #!/usr/bin/env python3
  2. """Prepare a clean, validated mod-ui pedalboard once per system boot."""
  3. import argparse
  4. import hashlib
  5. import os
  6. import shutil
  7. import sys
  8. import tempfile
  9. from pathlib import Path, PurePosixPath
  10. import yaml
  11. ROOT = Path(__file__).resolve().parents[1]
  12. sys.path.insert(0, str(ROOT / "scripts"))
  13. from generate_mod_ui_pedalboard import generate_bundle_files
  14. def bundle_digest(files):
  15. digest = hashlib.sha256()
  16. for name, content in sorted(files.items()):
  17. digest.update(name.encode("utf-8") + b"\0" + content + b"\0")
  18. return digest.hexdigest()
  19. def destination_under_home(home, relative):
  20. relative = Path(relative)
  21. if relative.is_absolute() or ".." in relative.parts:
  22. raise ValueError(f"unsafe mod-ui path: {relative}")
  23. destination = home / relative
  24. if not destination.resolve().is_relative_to(home.resolve()):
  25. raise ValueError(f"mod-ui path escapes the user home directory: {destination}")
  26. return destination
  27. def validate_generated_bundle(files):
  28. required = {
  29. "manifest.ttl",
  30. "rigforge-guitar.ttl",
  31. "addressings.json",
  32. "snapshots.json",
  33. *{
  34. f"effect-{instance}/{filename}"
  35. for instance in range(6)
  36. for filename in ("manifest.ttl", "effect.ttl")
  37. },
  38. "screenshot.png",
  39. "thumbnail.png",
  40. }
  41. missing = required - set(files)
  42. if missing:
  43. raise RuntimeError(
  44. "generated pedalboard is missing required files: "
  45. + ", ".join(sorted(missing))
  46. )
  47. empty = sorted(name for name, content in files.items() if not content)
  48. if empty:
  49. raise RuntimeError(
  50. "generated pedalboard contains empty files: " + ", ".join(empty)
  51. )
  52. graph = files["rigforge-guitar.ttl"].decode("utf-8")
  53. if (
  54. "pedal:Pedalboard" not in graph
  55. or "rigforge_nam" not in graph
  56. or "rigforge_ir" not in graph
  57. or "rigforge_voice_high_pass" not in graph
  58. or "rigforge_voice_compressor" not in graph
  59. or "rigforge_voice_de_esser" not in graph
  60. or "rigforge_voice_reverb" not in graph
  61. ):
  62. raise RuntimeError("generated pedalboard graph is incomplete")
  63. def read_bundle(directory):
  64. if directory.is_symlink() or not directory.is_dir():
  65. raise RuntimeError(f"pedalboard bundle is missing or not a directory: {directory}")
  66. files = {}
  67. for path in directory.rglob("*"):
  68. if path.is_symlink():
  69. raise RuntimeError(f"pedalboard bundle contains a symlink: {path}")
  70. if path.is_file():
  71. files[path.relative_to(directory).as_posix()] = path.read_bytes()
  72. return files
  73. def validate_existing_default(directory):
  74. if directory.is_symlink() or not directory.is_dir():
  75. raise RuntimeError(f"prepared default pedalboard is unavailable: {directory}")
  76. for name in ("manifest.ttl", "rigforge-guitar.ttl"):
  77. path = directory / name
  78. if path.is_symlink() or not path.is_file() or path.stat().st_size == 0:
  79. raise RuntimeError(
  80. f"default pedalboard is invalid after boot preparation: {path}"
  81. )
  82. graph = (directory / "rigforge-guitar.ttl").read_text(encoding="utf-8")
  83. if "pedal:Pedalboard" not in graph:
  84. raise RuntimeError(f"default pedalboard graph is invalid: {directory}")
  85. def reference_bundle_for_state(state, repo_root, home):
  86. config = state["deployment"]["mod_ui"]
  87. nam = state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
  88. nam_model_path = destination_under_home(
  89. home,
  90. Path(config["user_files_directory"])
  91. / "NAM Models"
  92. / "Rigforge"
  93. / Path(nam["asset_path"]).name,
  94. )
  95. expected_files = generate_bundle_files(
  96. state, repo_root=repo_root, nam_model_path=nam_model_path
  97. )
  98. reference_directory = destination_under_home(home, config["reference_directory"])
  99. if reference_directory.is_dir() and not reference_directory.is_symlink():
  100. for candidate in sorted(reference_directory.glob("rigforge-guitar-*.pedalboard")):
  101. if not candidate.is_dir() or candidate.is_symlink():
  102. continue
  103. try:
  104. files = read_bundle(candidate)
  105. validate_generated_bundle(files)
  106. except (OSError, RuntimeError):
  107. continue
  108. if files == expected_files:
  109. return candidate
  110. raise RuntimeError("prepared mod-ui reference bundle is unavailable")
  111. def next_backup_path(path, boot_id, backup_directory=None):
  112. parent = backup_directory or path.parent
  113. parent.mkdir(parents=True, exist_ok=True)
  114. base = parent / f"{path.name}.rigforge-boot-backup-{boot_id}"
  115. candidate = base
  116. suffix = 2
  117. while candidate.exists() or candidate.is_symlink():
  118. candidate = base.with_name(f"{base.name}.{suffix}")
  119. suffix += 1
  120. return candidate
  121. def is_legacy_pedalboard_backup(path):
  122. return (
  123. path.name == "default.pedalboard.rigforge-backup"
  124. or path.name.startswith("default.pedalboard.rigforge-reset-backup")
  125. or path.name.startswith("default.pedalboard.rigforge-boot-backup-")
  126. )
  127. def next_migrated_backup_path(backup_directory, original, boot_id):
  128. candidate = backup_directory / original.name
  129. if not candidate.exists() and not candidate.is_symlink():
  130. return candidate
  131. base = backup_directory / f"{original.name}.migrated-{boot_id}"
  132. candidate = base
  133. suffix = 2
  134. while candidate.exists() or candidate.is_symlink():
  135. candidate = backup_directory / f"{base.name}.{suffix}"
  136. suffix += 1
  137. return candidate
  138. def migrate_legacy_pedalboard_backups(pedalboards, backup_directory, boot_id):
  139. if not pedalboards.is_dir() or pedalboards.is_symlink():
  140. return
  141. legacy = sorted(path for path in pedalboards.iterdir() if is_legacy_pedalboard_backup(path))
  142. if not legacy:
  143. return
  144. backup_directory.mkdir(parents=True, exist_ok=True)
  145. for path in legacy:
  146. if path.is_symlink():
  147. raise RuntimeError(f"refusing to migrate a symlinked pedalboard backup: {path}")
  148. if not path.is_dir():
  149. raise RuntimeError(f"legacy pedalboard backup is not a directory: {path}")
  150. destination = next_migrated_backup_path(backup_directory, path, boot_id)
  151. os.replace(path, destination)
  152. print(f"Moved legacy mod-ui backup outside pedalboard scan path: {destination}")
  153. def write_staged_bundle(files, destination):
  154. destination.parent.mkdir(parents=True, exist_ok=True)
  155. staged = Path(
  156. tempfile.mkdtemp(prefix=f".{destination.name}.rigforge-new-", dir=destination.parent)
  157. )
  158. try:
  159. for relative, content in files.items():
  160. relative_path = PurePosixPath(relative)
  161. if relative_path.is_absolute() or ".." in relative_path.parts:
  162. raise RuntimeError(f"unsafe generated pedalboard path: {relative}")
  163. path = staged.joinpath(*relative_path.parts)
  164. path.parent.mkdir(parents=True, exist_ok=True)
  165. path.write_bytes(content)
  166. if read_bundle(staged) != files:
  167. raise RuntimeError(f"staged pedalboard verification failed: {staged}")
  168. return staged
  169. except BaseException:
  170. shutil.rmtree(staged, ignore_errors=True)
  171. raise
  172. def atomic_write_marker(marker, boot_id):
  173. marker.parent.mkdir(parents=True, exist_ok=True)
  174. fd, temporary_name = tempfile.mkstemp(prefix=f".{marker.name}.", dir=marker.parent)
  175. try:
  176. with os.fdopen(fd, "w", encoding="utf-8") as stream:
  177. stream.write(boot_id + "\n")
  178. os.replace(temporary_name, marker)
  179. finally:
  180. if os.path.exists(temporary_name):
  181. os.unlink(temporary_name)
  182. def prepare_pedalboard(state, repo_root, home, runtime_dir, boot_id):
  183. config = state["deployment"]["mod_ui"]
  184. marker = runtime_dir / "prepared-boot-id"
  185. default_board = destination_under_home(
  186. home, Path(config["pedalboards_directory"]) / "default.pedalboard"
  187. )
  188. last_state = destination_under_home(home, config["last_state_file"])
  189. backup_directory = destination_under_home(
  190. home, Path(config["last_state_file"]).parent / "boot-backups"
  191. )
  192. migrate_legacy_pedalboard_backups(
  193. default_board.parent, backup_directory, boot_id
  194. )
  195. if marker.is_file() and marker.read_text(encoding="utf-8").strip() == boot_id:
  196. validate_existing_default(default_board)
  197. if last_state.is_symlink():
  198. raise RuntimeError(f"refusing to move a mod-ui state symlink: {last_state}")
  199. if last_state.exists() and not last_state.is_file():
  200. raise RuntimeError(f"mod-ui last-state path is not a file: {last_state}")
  201. reference_bundle = reference_bundle_for_state(state, repo_root, home)
  202. current_state = (
  203. last_state.read_text(encoding="utf-8")
  204. if last_state.is_file()
  205. else None
  206. )
  207. expected_state = (
  208. f'{{"bank":-2,"pedalboard":"{reference_bundle}","supportsDividers":true}}'
  209. )
  210. if current_state != expected_state:
  211. if last_state.exists():
  212. backup = next_backup_path(last_state, boot_id, backup_directory)
  213. os.replace(last_state, backup)
  214. print(f"Preserved previous mod-ui state at {backup}")
  215. last_state.parent.mkdir(parents=True, exist_ok=True)
  216. last_state.write_text(expected_state, encoding="utf-8")
  217. else:
  218. print(
  219. "mod-ui pedalboard already prepared during this boot; "
  220. "preserving current board"
  221. )
  222. return
  223. nam = state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
  224. nam_model_path = destination_under_home(
  225. home,
  226. Path(config["user_files_directory"])
  227. / "NAM Models"
  228. / "Rigforge"
  229. / Path(nam["asset_path"]).name,
  230. )
  231. files = generate_bundle_files(
  232. state, repo_root=repo_root, nam_model_path=nam_model_path
  233. )
  234. validate_generated_bundle(files)
  235. reference = destination_under_home(
  236. home,
  237. Path(config["reference_directory"])
  238. / f"rigforge-guitar-{bundle_digest(files)[:16]}.pedalboard",
  239. )
  240. for path in (reference, default_board):
  241. if path.is_symlink():
  242. raise RuntimeError(f"refusing to replace a mod-ui symlink: {path}")
  243. if path.exists() and not path.is_dir():
  244. raise RuntimeError(f"mod-ui pedalboard path is not a directory: {path}")
  245. if last_state.is_symlink():
  246. raise RuntimeError(f"refusing to move a mod-ui state symlink: {last_state}")
  247. if last_state.exists() and not last_state.is_file():
  248. raise RuntimeError(f"mod-ui last-state path is not a file: {last_state}")
  249. reference_files = (
  250. read_bundle(reference)
  251. if reference.exists()
  252. else None
  253. )
  254. replace_reference = reference_files != files
  255. staged_reference = write_staged_bundle(files, reference) if replace_reference else None
  256. staged_default = write_staged_bundle(files, default_board)
  257. backups = []
  258. installed = []
  259. try:
  260. if replace_reference and reference.exists():
  261. backup = next_backup_path(reference, boot_id)
  262. os.replace(reference, backup)
  263. backups.append((reference, backup))
  264. if default_board.exists():
  265. backup = next_backup_path(default_board, boot_id, backup_directory)
  266. os.replace(default_board, backup)
  267. backups.append((default_board, backup))
  268. last_state_backup = None
  269. if last_state.exists():
  270. last_state_backup = next_backup_path(last_state, boot_id, backup_directory)
  271. os.replace(last_state, last_state_backup)
  272. if staged_reference is not None:
  273. os.replace(staged_reference, reference)
  274. installed.append(reference)
  275. os.replace(staged_default, default_board)
  276. installed.append(default_board)
  277. validate_existing_default(default_board)
  278. if last_state_backup is not None:
  279. print(f"Preserved previous mod-ui state at {last_state_backup}")
  280. last_state.parent.mkdir(parents=True, exist_ok=True)
  281. last_state.write_text(
  282. f'{{"bank":-2,"pedalboard":"{reference}","supportsDividers":true}}',
  283. encoding="utf-8",
  284. )
  285. atomic_write_marker(marker, boot_id)
  286. except BaseException:
  287. if last_state_backup is not None and last_state_backup.exists():
  288. os.replace(last_state_backup, last_state)
  289. for path in reversed(installed):
  290. if path.is_dir() and not path.is_symlink():
  291. shutil.rmtree(path)
  292. elif path.exists() or path.is_symlink():
  293. path.unlink()
  294. for original, backup in reversed(backups):
  295. if backup.exists() or backup.is_symlink():
  296. os.replace(backup, original)
  297. raise
  298. finally:
  299. for staged in (staged_reference, staged_default):
  300. if staged is not None and staged.exists():
  301. shutil.rmtree(staged, ignore_errors=True)
  302. print(f"Prepared a clean mod-ui pedalboard for boot {boot_id}")
  303. def main(argv=None):
  304. parser = argparse.ArgumentParser(description=__doc__)
  305. parser.add_argument("--state", type=Path, default=ROOT / "config" / "desired-state.yaml")
  306. parser.add_argument("--runtime-dir", type=Path, required=True)
  307. args = parser.parse_args(argv)
  308. try:
  309. state = yaml.safe_load(args.state.read_text(encoding="utf-8"))
  310. boot_id = Path("/proc/sys/kernel/random/boot_id").read_text(encoding="ascii").strip()
  311. if not boot_id:
  312. raise RuntimeError("could not determine the current system boot ID")
  313. prepare_pedalboard(
  314. state,
  315. repo_root=ROOT,
  316. home=Path.home(),
  317. runtime_dir=args.runtime_dir,
  318. boot_id=boot_id,
  319. )
  320. except (OSError, RuntimeError, ValueError, KeyError) as error:
  321. print(f"ERROR: {error}", file=sys.stderr)
  322. return 1
  323. return 0
  324. if __name__ == "__main__":
  325. raise SystemExit(main())