prepare_mod_ui_pedalboard.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. "effect-0/manifest.ttl",
  34. "effect-0/effect.ttl",
  35. "effect-1/manifest.ttl",
  36. "effect-1/effect.ttl",
  37. "screenshot.png",
  38. "thumbnail.png",
  39. }
  40. missing = required - set(files)
  41. if missing:
  42. raise RuntimeError(
  43. "generated pedalboard is missing required files: "
  44. + ", ".join(sorted(missing))
  45. )
  46. empty = sorted(name for name, content in files.items() if not content)
  47. if empty:
  48. raise RuntimeError(
  49. "generated pedalboard contains empty files: " + ", ".join(empty)
  50. )
  51. graph = files["rigforge-guitar.ttl"].decode("utf-8")
  52. if "pedal:Pedalboard" not in graph or "ingen:block <rigforge_nam>, <rigforge_ir>" not in graph:
  53. raise RuntimeError("generated pedalboard graph is incomplete")
  54. def read_bundle(directory):
  55. if directory.is_symlink() or not directory.is_dir():
  56. raise RuntimeError(f"pedalboard bundle is missing or not a directory: {directory}")
  57. files = {}
  58. for path in directory.rglob("*"):
  59. if path.is_symlink():
  60. raise RuntimeError(f"pedalboard bundle contains a symlink: {path}")
  61. if path.is_file():
  62. files[path.relative_to(directory).as_posix()] = path.read_bytes()
  63. return files
  64. def validate_existing_default(directory):
  65. if directory.is_symlink() or not directory.is_dir():
  66. raise RuntimeError(f"prepared default pedalboard is unavailable: {directory}")
  67. for name in ("manifest.ttl", "rigforge-guitar.ttl"):
  68. path = directory / name
  69. if path.is_symlink() or not path.is_file() or path.stat().st_size == 0:
  70. raise RuntimeError(
  71. f"default pedalboard is invalid after boot preparation: {path}"
  72. )
  73. graph = (directory / "rigforge-guitar.ttl").read_text(encoding="utf-8")
  74. if "pedal:Pedalboard" not in graph:
  75. raise RuntimeError(f"default pedalboard graph is invalid: {directory}")
  76. def next_backup_path(path, boot_id, backup_directory=None):
  77. parent = backup_directory or path.parent
  78. parent.mkdir(parents=True, exist_ok=True)
  79. base = parent / f"{path.name}.rigforge-boot-backup-{boot_id}"
  80. candidate = base
  81. suffix = 2
  82. while candidate.exists() or candidate.is_symlink():
  83. candidate = base.with_name(f"{base.name}.{suffix}")
  84. suffix += 1
  85. return candidate
  86. def is_legacy_pedalboard_backup(path):
  87. return (
  88. path.name == "default.pedalboard.rigforge-backup"
  89. or path.name.startswith("default.pedalboard.rigforge-reset-backup")
  90. or path.name.startswith("default.pedalboard.rigforge-boot-backup-")
  91. )
  92. def next_migrated_backup_path(backup_directory, original, boot_id):
  93. candidate = backup_directory / original.name
  94. if not candidate.exists() and not candidate.is_symlink():
  95. return candidate
  96. base = backup_directory / f"{original.name}.migrated-{boot_id}"
  97. candidate = base
  98. suffix = 2
  99. while candidate.exists() or candidate.is_symlink():
  100. candidate = backup_directory / f"{base.name}.{suffix}"
  101. suffix += 1
  102. return candidate
  103. def migrate_legacy_pedalboard_backups(pedalboards, backup_directory, boot_id):
  104. if not pedalboards.is_dir() or pedalboards.is_symlink():
  105. return
  106. legacy = sorted(path for path in pedalboards.iterdir() if is_legacy_pedalboard_backup(path))
  107. if not legacy:
  108. return
  109. backup_directory.mkdir(parents=True, exist_ok=True)
  110. for path in legacy:
  111. if path.is_symlink():
  112. raise RuntimeError(f"refusing to migrate a symlinked pedalboard backup: {path}")
  113. if not path.is_dir():
  114. raise RuntimeError(f"legacy pedalboard backup is not a directory: {path}")
  115. destination = next_migrated_backup_path(backup_directory, path, boot_id)
  116. os.replace(path, destination)
  117. print(f"Moved legacy mod-ui backup outside pedalboard scan path: {destination}")
  118. def write_staged_bundle(files, destination):
  119. destination.parent.mkdir(parents=True, exist_ok=True)
  120. staged = Path(
  121. tempfile.mkdtemp(prefix=f".{destination.name}.rigforge-new-", dir=destination.parent)
  122. )
  123. try:
  124. for relative, content in files.items():
  125. relative_path = PurePosixPath(relative)
  126. if relative_path.is_absolute() or ".." in relative_path.parts:
  127. raise RuntimeError(f"unsafe generated pedalboard path: {relative}")
  128. path = staged.joinpath(*relative_path.parts)
  129. path.parent.mkdir(parents=True, exist_ok=True)
  130. path.write_bytes(content)
  131. if read_bundle(staged) != files:
  132. raise RuntimeError(f"staged pedalboard verification failed: {staged}")
  133. return staged
  134. except BaseException:
  135. shutil.rmtree(staged, ignore_errors=True)
  136. raise
  137. def atomic_write_marker(marker, boot_id):
  138. marker.parent.mkdir(parents=True, exist_ok=True)
  139. fd, temporary_name = tempfile.mkstemp(prefix=f".{marker.name}.", dir=marker.parent)
  140. try:
  141. with os.fdopen(fd, "w", encoding="utf-8") as stream:
  142. stream.write(boot_id + "\n")
  143. os.replace(temporary_name, marker)
  144. finally:
  145. if os.path.exists(temporary_name):
  146. os.unlink(temporary_name)
  147. def prepare_pedalboard(state, repo_root, home, runtime_dir, boot_id):
  148. config = state["deployment"]["mod_ui"]
  149. marker = runtime_dir / "prepared-boot-id"
  150. default_board = destination_under_home(
  151. home, Path(config["pedalboards_directory"]) / "default.pedalboard"
  152. )
  153. last_state = destination_under_home(home, config["last_state_file"])
  154. backup_directory = destination_under_home(
  155. home, Path(config["last_state_file"]).parent / "boot-backups"
  156. )
  157. migrate_legacy_pedalboard_backups(
  158. default_board.parent, backup_directory, boot_id
  159. )
  160. if marker.is_file() and marker.read_text(encoding="utf-8").strip() == boot_id:
  161. validate_existing_default(default_board)
  162. print("mod-ui pedalboard already prepared during this boot; preserving session state")
  163. return
  164. nam = state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
  165. nam_model_path = destination_under_home(
  166. home,
  167. Path(config["user_files_directory"])
  168. / "NAM Models"
  169. / "Rigforge"
  170. / Path(nam["asset_path"]).name,
  171. )
  172. files = generate_bundle_files(
  173. state, repo_root=repo_root, nam_model_path=nam_model_path
  174. )
  175. validate_generated_bundle(files)
  176. reference = destination_under_home(
  177. home,
  178. Path(config["reference_directory"])
  179. / f"rigforge-guitar-{bundle_digest(files)[:16]}.pedalboard",
  180. )
  181. for path in (reference, default_board):
  182. if path.is_symlink():
  183. raise RuntimeError(f"refusing to replace a mod-ui symlink: {path}")
  184. if path.exists() and not path.is_dir():
  185. raise RuntimeError(f"mod-ui pedalboard path is not a directory: {path}")
  186. if last_state.is_symlink():
  187. raise RuntimeError(f"refusing to move a mod-ui state symlink: {last_state}")
  188. if last_state.exists() and not last_state.is_file():
  189. raise RuntimeError(f"mod-ui last-state path is not a file: {last_state}")
  190. reference_files = (
  191. read_bundle(reference)
  192. if reference.exists()
  193. else None
  194. )
  195. replace_reference = reference_files != files
  196. staged_reference = write_staged_bundle(files, reference) if replace_reference else None
  197. staged_default = write_staged_bundle(files, default_board)
  198. backups = []
  199. installed = []
  200. try:
  201. if replace_reference and reference.exists():
  202. backup = next_backup_path(reference, boot_id)
  203. os.replace(reference, backup)
  204. backups.append((reference, backup))
  205. if default_board.exists():
  206. backup = next_backup_path(default_board, boot_id, backup_directory)
  207. os.replace(default_board, backup)
  208. backups.append((default_board, backup))
  209. if last_state.exists():
  210. backup = next_backup_path(last_state, boot_id, backup_directory)
  211. os.replace(last_state, backup)
  212. backups.append((last_state, backup))
  213. if staged_reference is not None:
  214. os.replace(staged_reference, reference)
  215. installed.append(reference)
  216. os.replace(staged_default, default_board)
  217. installed.append(default_board)
  218. validate_existing_default(default_board)
  219. atomic_write_marker(marker, boot_id)
  220. except BaseException:
  221. for path in reversed(installed):
  222. if path.is_dir() and not path.is_symlink():
  223. shutil.rmtree(path)
  224. elif path.exists() or path.is_symlink():
  225. path.unlink()
  226. for original, backup in reversed(backups):
  227. if backup.exists() or backup.is_symlink():
  228. os.replace(backup, original)
  229. raise
  230. finally:
  231. for staged in (staged_reference, staged_default):
  232. if staged is not None and staged.exists():
  233. shutil.rmtree(staged, ignore_errors=True)
  234. print(f"Prepared a clean mod-ui pedalboard for boot {boot_id}")
  235. def main(argv=None):
  236. parser = argparse.ArgumentParser(description=__doc__)
  237. parser.add_argument("--state", type=Path, default=ROOT / "config" / "desired-state.yaml")
  238. parser.add_argument("--runtime-dir", type=Path, required=True)
  239. args = parser.parse_args(argv)
  240. try:
  241. state = yaml.safe_load(args.state.read_text(encoding="utf-8"))
  242. boot_id = Path("/proc/sys/kernel/random/boot_id").read_text(encoding="ascii").strip()
  243. if not boot_id:
  244. raise RuntimeError("could not determine the current system boot ID")
  245. prepare_pedalboard(
  246. state,
  247. repo_root=ROOT,
  248. home=Path.home(),
  249. runtime_dir=args.runtime_dir,
  250. boot_id=boot_id,
  251. )
  252. except (OSError, RuntimeError, ValueError, KeyError) as error:
  253. print(f"ERROR: {error}", file=sys.stderr)
  254. return 1
  255. return 0
  256. if __name__ == "__main__":
  257. raise SystemExit(main())