deploy.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. import argparse
  2. import hashlib
  3. import json
  4. import os
  5. import re
  6. import shutil
  7. import subprocess
  8. import sys
  9. import tarfile
  10. import tempfile
  11. from pathlib import Path, PurePosixPath
  12. import yaml
  13. from validate_desired_state import validate_state
  14. ROOT = Path(__file__).resolve().parents[1]
  15. STATE_PATH = Path.home() / ".local" / "state" / "rigforge" / "deployment.json"
  16. NAM_RELEASE_ASSET = re.compile(
  17. r"^https://github\.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/"
  18. r"(?P<tag>[A-Za-z0-9._-]+)/neural_amp_modeler_lv2_rpi5\.tgz$"
  19. )
  20. PLUGIN_ARCHIVES = {
  21. "lsp": "7z",
  22. "dragonfly_reverb": "tar.xz",
  23. }
  24. def load_deployment():
  25. with (ROOT / "config" / "desired-state.yaml").open(encoding="utf-8") as stream:
  26. state = yaml.safe_load(stream)
  27. errors = validate_state(state)
  28. deployment = state.get("deployment") if isinstance(state, dict) else None
  29. if not isinstance(deployment, dict):
  30. raise ValueError("deployment must be a mapping")
  31. namlv2 = deployment.get("namlv2")
  32. pipewire = deployment.get("pipewire")
  33. if not isinstance(namlv2, dict) or not isinstance(pipewire, dict):
  34. raise ValueError("deployment.namlv2 and deployment.pipewire must be mappings")
  35. for component, archive_format in PLUGIN_ARCHIVES.items():
  36. plugin = deployment.get(component)
  37. if not isinstance(plugin, dict):
  38. raise ValueError(f"deployment.{component} must be a mapping")
  39. if plugin.get("archive_format") != archive_format:
  40. errors.append(f"{component} archive format is invalid")
  41. if not isinstance(plugin.get("bundle_paths"), dict) or not plugin["bundle_paths"]:
  42. errors.append(f"{component} bundle paths are invalid")
  43. tag = namlv2.get("tag")
  44. match = NAM_RELEASE_ASSET.fullmatch(namlv2.get("archive_url", ""))
  45. if not isinstance(tag, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", tag):
  46. errors.append("NAM LV2 tag is invalid")
  47. if match is None or match.group("tag") != tag:
  48. errors.append("NAM LV2 URL must be the approved release asset for the declared tag")
  49. if namlv2.get("bundle_directory") != "neural_amp_modeler.lv2":
  50. errors.append("NAM LV2 bundle directory is invalid")
  51. source = pipewire.get("fragment_source")
  52. if source != "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf":
  53. errors.append("PipeWire fragment source is invalid")
  54. if pipewire.get("fragment_destination") != ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf":
  55. errors.append("PipeWire fragment destination is invalid")
  56. if pipewire.get("user_service") != "filter-chain.service":
  57. errors.append("PipeWire user service is invalid")
  58. if errors:
  59. raise ValueError("; ".join(errors))
  60. return deployment
  61. def read_registry():
  62. if not STATE_PATH.exists():
  63. return {}
  64. with STATE_PATH.open(encoding="utf-8") as stream:
  65. registry = json.load(stream)
  66. if not isinstance(registry, dict):
  67. raise ValueError(f"deployment registry is not a mapping: {STATE_PATH}")
  68. return registry
  69. def write_registry(registry):
  70. STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
  71. fd, temporary_name = tempfile.mkstemp(prefix="deployment.", dir=STATE_PATH.parent)
  72. try:
  73. with os.fdopen(fd, "w", encoding="utf-8") as stream:
  74. json.dump(registry, stream, indent=2, sort_keys=True)
  75. stream.write("\n")
  76. os.replace(temporary_name, STATE_PATH)
  77. finally:
  78. if os.path.exists(temporary_name):
  79. os.unlink(temporary_name)
  80. def run(command):
  81. subprocess.run(command, check=True)
  82. def tree_sha256(path):
  83. digest = hashlib.sha256()
  84. for item in sorted(path.rglob("*")):
  85. relative = item.relative_to(path).as_posix().encode()
  86. digest.update(relative + b"\\0")
  87. if item.is_symlink():
  88. digest.update(b"link\\0" + os.readlink(item).encode())
  89. elif item.is_file():
  90. digest.update(b"file\\0" + item.read_bytes())
  91. elif item.is_dir():
  92. digest.update(b"directory\\0")
  93. else:
  94. raise RuntimeError(f"unsupported file type in managed bundle: {item}")
  95. return digest.hexdigest()
  96. def validate_user_destination(destination):
  97. home = Path.home().resolve()
  98. parent = destination.parent.resolve()
  99. if not parent.is_relative_to(home):
  100. raise RuntimeError(f"deployment path escapes the user home directory: {destination}")
  101. if destination.is_symlink():
  102. raise RuntimeError(f"refusing to manage a symlink destination: {destination}")
  103. def validate_backup_path(backup, destination, is_directory=False):
  104. if backup is None:
  105. return None
  106. backup_path = Path(backup)
  107. expected = destination.with_name(destination.name + ".rigforge-backup")
  108. if backup_path != expected:
  109. raise RuntimeError(f"recorded backup path is outside its approved location: {backup_path}")
  110. if backup_path.is_symlink():
  111. raise RuntimeError(f"recorded backup must not be a symlink: {backup_path}")
  112. if backup_path.exists() and backup_path.is_dir() != is_directory:
  113. raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
  114. return backup_path
  115. def atomic_install(source, destination):
  116. destination.parent.mkdir(parents=True, exist_ok=True)
  117. fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent)
  118. os.close(fd)
  119. try:
  120. shutil.copyfile(source, temporary_name)
  121. shutil.copymode(source, temporary_name)
  122. os.replace(temporary_name, destination)
  123. finally:
  124. if os.path.exists(temporary_name):
  125. os.unlink(temporary_name)
  126. def apply_quantum(frames):
  127. run(["pw-metadata", "-n", "settings", "0", "clock.force-quantum", str(frames)])
  128. def restart_filter_service(service):
  129. run(["systemctl", "--user", "restart", service])
  130. run(["systemctl", "--user", "is-active", "--quiet", service])
  131. def deploy_pipewire(action, config, registry, quantum_frames):
  132. destination = Path.home() / config["fragment_destination"]
  133. validate_user_destination(destination)
  134. source = ROOT / config["fragment_source"]
  135. managed = registry.get("pipewire")
  136. pending_reload = registry.get("pipewire_pending_reload")
  137. if pending_reload is not None:
  138. apply_quantum(pending_reload["quantum_frames"])
  139. restart_filter_service(config["user_service"])
  140. registry.pop("pipewire_pending_reload")
  141. write_registry(registry)
  142. managed = registry.get("pipewire")
  143. if action == "reload":
  144. if not source.is_file() or not destination.is_file():
  145. raise RuntimeError("PipeWire reload requires both the repository fragment and installed fragment")
  146. apply_quantum(quantum_frames)
  147. restart_filter_service(config["user_service"])
  148. print("PipeWire runtime quantum applied; filter-chain user service restarted.")
  149. return
  150. if action == "install":
  151. if managed is not None and managed.get("pending_uninstall"):
  152. raise RuntimeError("PipeWire uninstall is incomplete; retry uninstall pipewire first")
  153. if managed is not None:
  154. validate_backup_path(managed.get("backup"), destination)
  155. if not destination.exists():
  156. raise RuntimeError(f"managed PipeWire fragment is missing: {destination}")
  157. if managed is not None and destination.exists():
  158. current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  159. if current_digest != managed["installed_sha256"]:
  160. raise RuntimeError(f"managed file changed locally; refusing overwrite: {destination}")
  161. was_unmanaged = managed is None
  162. changed = not destination.exists() or destination.read_bytes() != source.read_bytes()
  163. if managed is None:
  164. backup_path = None
  165. backup_sha256 = None
  166. if destination.exists():
  167. backup_path = str(destination.with_name(destination.name + ".rigforge-backup"))
  168. if Path(backup_path).exists():
  169. raise RuntimeError(f"backup path already exists: {backup_path}")
  170. shutil.copy2(destination, backup_path)
  171. backup_sha256 = hashlib.sha256(Path(backup_path).read_bytes()).hexdigest()
  172. managed = {
  173. "installed_sha256": "",
  174. "backup": backup_path,
  175. "backup_sha256": backup_sha256,
  176. }
  177. registry["pipewire"] = managed
  178. if changed:
  179. atomic_install(source, destination)
  180. managed["installed_sha256"] = hashlib.sha256(source.read_bytes()).hexdigest()
  181. managed["pending_reload"] = changed or was_unmanaged or managed.get("pending_reload", False)
  182. registry["pipewire"] = managed
  183. write_registry(registry)
  184. apply_quantum(quantum_frames)
  185. if managed["pending_reload"]:
  186. restart_filter_service(config["user_service"])
  187. managed.pop("pending_reload", None)
  188. registry["pipewire"] = managed
  189. write_registry(registry)
  190. print(f"PipeWire fragment {'updated' if changed else 'already current'} at {destination}.")
  191. return
  192. if action == "uninstall":
  193. if managed is None:
  194. print("No managed PipeWire fragment to uninstall.")
  195. return
  196. if managed.get("pending_uninstall"):
  197. backup_path = validate_backup_path(managed.get("backup"), destination)
  198. backup_exists = backup_path is not None and backup_path.is_file()
  199. if backup_path is not None and backup_path.exists():
  200. if not backup_exists:
  201. raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
  202. backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
  203. if backup_digest != managed.get("backup_sha256"):
  204. raise RuntimeError(f"recorded backup changed locally: {backup_path}")
  205. if destination.exists():
  206. current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  207. if backup_exists and current_digest == managed.get("backup_sha256"):
  208. backup_path.unlink()
  209. elif backup_path is not None and not backup_exists and current_digest == managed.get("backup_sha256"):
  210. pass
  211. elif current_digest == managed.get("installed_sha256"):
  212. destination.unlink()
  213. if backup_exists:
  214. os.replace(backup_path, destination)
  215. elif backup_path is not None:
  216. raise RuntimeError(f"recorded backup is missing: {backup_path}")
  217. else:
  218. raise RuntimeError(f"unexpected file blocks pending uninstall: {destination}")
  219. elif backup_exists:
  220. os.replace(backup_path, destination)
  221. elif backup_path is not None:
  222. raise RuntimeError(f"recorded backup is missing: {backup_path}")
  223. registry.pop("pipewire")
  224. write_registry(registry)
  225. apply_quantum(0)
  226. restart_filter_service(config["user_service"])
  227. print("Completed interrupted PipeWire uninstall and restored prior state.")
  228. return
  229. if not destination.exists():
  230. raise RuntimeError(f"managed PipeWire fragment is missing: {destination}")
  231. current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  232. if current_digest != managed["installed_sha256"]:
  233. raise RuntimeError(f"managed file changed locally; refusing to remove: {destination}")
  234. backup_path = validate_backup_path(managed.get("backup"), destination)
  235. if backup_path is not None and not backup_path.is_file():
  236. raise RuntimeError(f"recorded backup is missing: {backup_path}")
  237. if backup_path is not None:
  238. backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
  239. if backup_digest != managed.get("backup_sha256"):
  240. raise RuntimeError(f"recorded backup changed locally: {backup_path}")
  241. managed["pending_uninstall"] = True
  242. registry["pipewire"] = managed
  243. write_registry(registry)
  244. destination.unlink()
  245. if backup_path is not None:
  246. atomic_install(backup_path, destination)
  247. backup_path.unlink()
  248. registry.pop("pipewire")
  249. registry["pipewire_pending_reload"] = {"quantum_frames": 0}
  250. write_registry(registry)
  251. apply_quantum(0)
  252. restart_filter_service(config["user_service"])
  253. registry.pop("pipewire_pending_reload")
  254. write_registry(registry)
  255. print("Rigforge PipeWire fragment removed or prior file restored; quantum reset to automatic.")
  256. return
  257. def inspect_archive(archive_path, bundle_name):
  258. with tarfile.open(archive_path, "r:gz") as archive:
  259. members = archive.getmembers()
  260. bundle_prefix = PurePosixPath(bundle_name)
  261. matching = []
  262. for member in members:
  263. member_path = PurePosixPath(member.name)
  264. if member_path.is_absolute() or ".." in member_path.parts:
  265. raise RuntimeError(f"unsafe archive path: {member.name}")
  266. if member_path.parts and member_path.parts[0] == bundle_prefix.name:
  267. if not member_path.is_relative_to(bundle_prefix):
  268. raise RuntimeError(f"unexpected bundle path: {member.name}")
  269. if not (member.isdir() or member.isfile()):
  270. raise RuntimeError(f"unsupported archive member type: {member.name}")
  271. matching.append(member)
  272. else:
  273. raise RuntimeError(f"unexpected archive path: {member.name}")
  274. if not matching or not any(member.name == bundle_name and member.isdir() for member in matching):
  275. raise RuntimeError(f"archive does not contain expected bundle directory {bundle_name}")
  276. return members
  277. def extract_bundle(archive_path, destination, bundle_name):
  278. with tarfile.open(archive_path, "r:gz") as archive:
  279. members = inspect_archive(archive_path, bundle_name)
  280. for member in members:
  281. member_path = PurePosixPath(member.name)
  282. relative_parts = member_path.parts[1:]
  283. output_path = destination.joinpath(*relative_parts) if relative_parts else destination
  284. if member.isdir():
  285. output_path.mkdir(parents=True, exist_ok=True)
  286. output_path.chmod(0o755)
  287. continue
  288. output_path.parent.mkdir(parents=True, exist_ok=True)
  289. extracted = archive.extractfile(member)
  290. if extracted is None:
  291. raise RuntimeError(f"unable to read archive member: {member.name}")
  292. with extracted, output_path.open("wb") as output:
  293. shutil.copyfileobj(extracted, output)
  294. output_path.chmod(0o755 if member.mode & 0o111 else 0o644)
  295. def download_archive(url, destination):
  296. run(["curl", "--fail", "--location", "--silent", "--show-error", "--output", str(destination), url])
  297. def inspect_tar_archive(archive_path, bundle_paths):
  298. expected_roots = {PurePosixPath(path) for path in bundle_paths.values()}
  299. with tarfile.open(archive_path, "r:xz") as archive:
  300. members = archive.getmembers()
  301. for member in members:
  302. member_path = PurePosixPath(member.name)
  303. if member_path.is_absolute() or ".." in member_path.parts:
  304. raise RuntimeError(f"unsafe archive path: {member.name}")
  305. if not member.isfile() and not member.isdir():
  306. raise RuntimeError(f"unsupported archive member type: {member.name}")
  307. for bundle_root in expected_roots:
  308. if not any(member.name.rstrip("/") == str(bundle_root) and member.isdir() for member in members):
  309. raise RuntimeError(f"archive does not contain expected bundle directory {bundle_root}")
  310. if not any(member.name == f"{bundle_root}/manifest.ttl" and member.isfile() for member in members):
  311. raise RuntimeError(f"archive bundle is missing manifest.ttl: {bundle_root}")
  312. return expected_roots
  313. def extract_tar_bundles(archive_path, bundle_paths, extraction_root):
  314. expected_roots = inspect_tar_archive(archive_path, bundle_paths)
  315. extracted = {bundle_name: extraction_root / bundle_name for bundle_name in bundle_paths}
  316. with tarfile.open(archive_path, "r:xz") as archive:
  317. for member in archive.getmembers():
  318. member_path = PurePosixPath(member.name)
  319. bundle_root = next(
  320. (root for root in expected_roots if member_path == root or member_path.is_relative_to(root)),
  321. None,
  322. )
  323. if bundle_root is None:
  324. continue
  325. bundle_name = next(name for name, path in bundle_paths.items() if PurePosixPath(path) == bundle_root)
  326. output_path = extracted[bundle_name].joinpath(*member_path.parts[len(bundle_root.parts):])
  327. if member.isdir():
  328. output_path.mkdir(parents=True, exist_ok=True)
  329. output_path.chmod(0o755)
  330. continue
  331. output_path.parent.mkdir(parents=True, exist_ok=True)
  332. source = archive.extractfile(member)
  333. if source is None:
  334. raise RuntimeError(f"unable to read archive member: {member.name}")
  335. with source, output_path.open("wb") as destination:
  336. shutil.copyfileobj(source, destination)
  337. output_path.chmod(0o755 if member.mode & 0o111 else 0o644)
  338. return extracted
  339. def inspect_7z_archive(bundle_paths, listing):
  340. paths = []
  341. current = {}
  342. for line in listing.splitlines() + [""]:
  343. if not line and current:
  344. path = current.get("Path")
  345. attributes = current.get("Attributes", "")
  346. if path and attributes:
  347. member_path = PurePosixPath(path)
  348. if member_path.is_absolute() or ".." in member_path.parts:
  349. raise RuntimeError(f"unsafe archive path: {path}")
  350. if "L" in attributes or "H" in attributes:
  351. raise RuntimeError(f"unsupported archive member type: {path}")
  352. paths.append((member_path, "D" in attributes))
  353. current = {}
  354. elif " = " in line:
  355. key, value = line.split(" = ", 1)
  356. current[key] = value
  357. expected_roots = {PurePosixPath(path) for path in bundle_paths.values()}
  358. present_roots = {path for path, is_directory in paths if is_directory and path in expected_roots}
  359. if present_roots != expected_roots:
  360. raise RuntimeError(f"7z archive is missing expected LV2 bundles: {sorted(map(str, expected_roots - present_roots))}")
  361. for root in expected_roots:
  362. if not any(path == root / "manifest.ttl" and not is_directory for path, is_directory in paths):
  363. raise RuntimeError(f"7z archive bundle is missing manifest.ttl: {root}")
  364. return expected_roots, paths
  365. def extract_7z_bundles(archive_path, bundle_paths, extraction_root):
  366. executable = shutil.which("7z") or shutil.which("7zz") or shutil.which("7za")
  367. if executable is None:
  368. raise RuntimeError("installing LSP plugins requires 7z, 7zz, or 7za on PATH")
  369. listing = subprocess.run(
  370. [executable, "l", "-slt", str(archive_path)],
  371. check=True,
  372. capture_output=True,
  373. text=True,
  374. ).stdout
  375. expected_roots, paths = inspect_7z_archive(bundle_paths, listing)
  376. temporary_output = extraction_root / "7z-output"
  377. temporary_output.mkdir()
  378. result = subprocess.run(
  379. [executable, "x", "-y", f"-o{temporary_output}", str(archive_path)],
  380. check=False,
  381. capture_output=True,
  382. text=True,
  383. )
  384. if result.returncode != 0:
  385. missing_files = [
  386. path
  387. for path, is_directory in paths
  388. if not is_directory
  389. and any(path.is_relative_to(root) for root in expected_roots)
  390. and not temporary_output.joinpath(*path.parts).is_file()
  391. ]
  392. if missing_files:
  393. raise subprocess.CalledProcessError(
  394. result.returncode,
  395. result.args,
  396. output=result.stdout,
  397. stderr=result.stderr,
  398. )
  399. extracted = {}
  400. for bundle_name, path in bundle_paths.items():
  401. bundle_root = PurePosixPath(path)
  402. source = temporary_output.joinpath(*bundle_root.parts)
  403. if not source.is_dir():
  404. raise RuntimeError(f"expected LV2 bundle missing after extraction: {source}")
  405. target = extraction_root / bundle_name
  406. shutil.copytree(source, target, symlinks=False)
  407. extracted[bundle_name] = target
  408. return extracted
  409. def deploy_lv2_archives(action, component, config, registry):
  410. bundle_paths = config["bundle_paths"]
  411. bundle_names = list(bundle_paths)
  412. destinations = {name: Path.home() / ".lv2" / name for name in bundle_names}
  413. for destination in destinations.values():
  414. validate_user_destination(destination)
  415. managed = registry.get(component)
  416. if action == "reload":
  417. print(f"Nothing to reload for {component}; restart its LV2 host after installation.")
  418. return
  419. if action == "uninstall":
  420. if managed is None:
  421. print(f"No managed {component} bundles to uninstall.")
  422. return
  423. recorded = managed.get("bundles")
  424. if not isinstance(recorded, dict) or set(recorded) != set(bundle_names):
  425. raise RuntimeError(f"managed {component} bundle declaration changed")
  426. if managed.get("pending_uninstall"):
  427. for name, destination in destinations.items():
  428. record = recorded[name]
  429. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  430. backup_exists = backup is not None and backup.is_dir()
  431. if backup is not None and backup.exists() and not backup_exists:
  432. raise RuntimeError(f"recorded backup has the wrong type: {backup}")
  433. if backup_exists and tree_sha256(backup) != record.get("backup_sha256"):
  434. raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
  435. if destination.exists():
  436. current = tree_sha256(destination)
  437. if backup_exists and current == record.get("backup_sha256"):
  438. continue
  439. if backup is None and record.get("backup_sha256") is None:
  440. if current == record.get("installed_sha256"):
  441. continue
  442. raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
  443. if not backup_exists and current == record.get("backup_sha256"):
  444. continue
  445. if current != record.get("installed_sha256"):
  446. raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
  447. elif backup is not None and not backup_exists:
  448. raise RuntimeError(f"recorded backup bundle is missing: {backup}")
  449. for name, destination in destinations.items():
  450. record = recorded[name]
  451. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  452. backup_exists = backup is not None and backup.is_dir()
  453. if destination.exists() and tree_sha256(destination) == record.get("installed_sha256"):
  454. shutil.rmtree(destination)
  455. if backup_exists:
  456. os.replace(backup, destination)
  457. registry.pop(component)
  458. write_registry(registry)
  459. print(f"Completed interrupted {component} uninstall at {Path.home() / '.lv2'}.")
  460. return
  461. for name, destination in destinations.items():
  462. record = recorded[name]
  463. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  464. if not destination.is_dir():
  465. raise RuntimeError(f"managed {component} bundle is missing: {destination}")
  466. if record.get("installed_path") != str(destination):
  467. raise RuntimeError(f"managed {component} path changed: {destination}")
  468. if tree_sha256(destination) != record.get("installed_sha256"):
  469. raise RuntimeError(f"managed {component} bundle changed locally; refusing to remove: {destination}")
  470. if backup is not None:
  471. if not backup.is_dir():
  472. raise RuntimeError(f"recorded backup bundle is missing: {backup}")
  473. if tree_sha256(backup) != record.get("backup_sha256"):
  474. raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
  475. managed["pending_uninstall"] = True
  476. registry[component] = managed
  477. write_registry(registry)
  478. for name, destination in destinations.items():
  479. record = recorded[name]
  480. shutil.rmtree(destination)
  481. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  482. if backup is not None:
  483. os.replace(backup, destination)
  484. registry.pop(component)
  485. write_registry(registry)
  486. print(f"Removed managed {component} bundles from {Path.home() / '.lv2'}.")
  487. return
  488. if managed is not None:
  489. if managed.get("pending_uninstall"):
  490. raise RuntimeError(f"{component} uninstall is incomplete; retry uninstall {component} first")
  491. recorded = managed.get("bundles")
  492. if not isinstance(recorded, dict) or set(recorded) != set(bundle_names):
  493. raise RuntimeError(f"managed {component} bundle declaration changed")
  494. for name, destination in destinations.items():
  495. record = recorded[name]
  496. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  497. if backup is not None:
  498. if not backup.is_dir() or tree_sha256(backup) != record.get("backup_sha256"):
  499. raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
  500. if not destination.is_dir():
  501. raise RuntimeError(f"managed {component} bundle is missing: {destination}")
  502. if tree_sha256(destination) != record.get("installed_sha256"):
  503. raise RuntimeError(f"managed {component} bundle changed locally; refusing overwrite: {destination}")
  504. if managed.get("tag") == config["tag"]:
  505. print(f"{component} tag {config['tag']} is already installed and unchanged.")
  506. return
  507. for name, destination in destinations.items():
  508. previous = managed.get("bundles", {}).get(name) if managed else None
  509. if previous is not None:
  510. backup = validate_backup_path(previous.get("backup"), destination, is_directory=True)
  511. if backup is not None:
  512. if not backup.is_dir():
  513. raise RuntimeError(f"recorded backup bundle is missing: {backup}")
  514. if tree_sha256(backup) != previous.get("backup_sha256"):
  515. raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
  516. if previous is None and destination.exists():
  517. backup = destination.with_name(destination.name + ".rigforge-backup")
  518. if backup.exists():
  519. raise RuntimeError(f"backup path already exists: {backup}")
  520. staged = destination.with_name(destination.name + ".rigforge-new")
  521. previous_path = destination.with_name(destination.name + ".rigforge-old")
  522. if staged.exists() or previous_path.exists():
  523. raise RuntimeError(f"{component} staging or recovery path already exists: {destination}")
  524. with tempfile.TemporaryDirectory(prefix=f"rigforge-{component}-") as temporary_dir:
  525. temporary = Path(temporary_dir)
  526. archive_path = temporary / (
  527. "plugin.tar.xz" if config["archive_format"] == "tar.xz" else "plugin.7z"
  528. )
  529. download_archive(config["archive_url"], archive_path)
  530. archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()
  531. extraction_root = temporary / "extract"
  532. extraction_root.mkdir()
  533. if config["archive_format"] == "tar.xz":
  534. extracted = extract_tar_bundles(archive_path, config["bundle_paths"], extraction_root)
  535. else:
  536. extracted = extract_7z_bundles(archive_path, config["bundle_paths"], extraction_root)
  537. records = {}
  538. created_backups = []
  539. installed_destinations = []
  540. try:
  541. for name, destination in destinations.items():
  542. previous = managed.get("bundles", {}).get(name) if managed else None
  543. backup = (
  544. validate_backup_path(previous.get("backup"), destination, is_directory=True)
  545. if previous is not None
  546. else destination.with_name(destination.name + ".rigforge-backup")
  547. if destination.exists()
  548. else None
  549. )
  550. backup_digest = previous.get("backup_sha256") if previous is not None else None
  551. if backup is not None and previous is None:
  552. shutil.copytree(destination, backup, symlinks=True)
  553. created_backups.append(backup)
  554. backup_digest = tree_sha256(backup)
  555. destination.parent.mkdir(parents=True, exist_ok=True)
  556. staged = destination.with_name(destination.name + ".rigforge-new")
  557. previous_path = destination.with_name(destination.name + ".rigforge-old")
  558. shutil.copytree(extracted[name], staged, symlinks=False)
  559. try:
  560. if destination.exists():
  561. os.replace(destination, previous_path)
  562. os.replace(staged, destination)
  563. installed_destinations.append((destination, previous_path))
  564. except OSError:
  565. if previous_path.exists() and not destination.exists():
  566. os.replace(previous_path, destination)
  567. if staged.exists():
  568. shutil.rmtree(staged)
  569. raise
  570. records[name] = {
  571. "installed_path": str(destination),
  572. "backup": str(backup) if backup is not None else None,
  573. "backup_sha256": backup_digest,
  574. "installed_sha256": tree_sha256(destination),
  575. }
  576. for _, previous_path in installed_destinations:
  577. if previous_path.exists():
  578. shutil.rmtree(previous_path)
  579. except (OSError, shutil.Error):
  580. for destination, previous_path in reversed(installed_destinations):
  581. if destination.exists():
  582. shutil.rmtree(destination)
  583. if previous_path.exists():
  584. os.replace(previous_path, destination)
  585. for destination in destinations.values():
  586. staged = destination.with_name(destination.name + ".rigforge-new")
  587. if staged.exists():
  588. shutil.rmtree(staged)
  589. for backup in created_backups:
  590. if backup.exists():
  591. shutil.rmtree(backup)
  592. raise
  593. registry[component] = {
  594. "tag": config["tag"],
  595. "archive_sha256": archive_digest,
  596. "bundles": records,
  597. }
  598. write_registry(registry)
  599. print(f"Installed {component} tag {config['tag']} under {Path.home() / '.lv2'}.")
  600. print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}")
  601. def deploy_namlv2(action, config, registry):
  602. bundle_name = config["bundle_directory"]
  603. destination = Path.home() / ".lv2" / bundle_name
  604. validate_user_destination(destination)
  605. managed = registry.get("namlv2")
  606. if action == "reload":
  607. print("Nothing to reload for the NAM LV2 plugin; restart its LV2 host after installation.")
  608. return
  609. if action == "uninstall":
  610. if managed is None:
  611. print("No managed NAM LV2 bundle to uninstall.")
  612. return
  613. if managed.get("pending_uninstall"):
  614. backup_path = validate_backup_path(managed.get("backup"), destination, is_directory=True)
  615. backup_exists = backup_path is not None and backup_path.is_dir()
  616. if backup_path is not None and backup_path.exists() and not backup_exists:
  617. raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
  618. if backup_exists and tree_sha256(backup_path) != managed.get("backup_sha256"):
  619. raise RuntimeError(f"recorded backup bundle changed locally: {backup_path}")
  620. if destination.exists():
  621. destination_digest = tree_sha256(destination)
  622. if backup_exists and destination_digest == managed.get("backup_sha256"):
  623. shutil.rmtree(backup_path)
  624. elif destination_digest == managed.get("installed_sha256"):
  625. shutil.rmtree(destination)
  626. if backup_exists:
  627. os.replace(backup_path, destination)
  628. else:
  629. raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
  630. elif backup_exists:
  631. os.replace(backup_path, destination)
  632. elif backup_path is not None:
  633. raise RuntimeError(f"recorded backup bundle is missing: {backup_path}")
  634. registry.pop("namlv2")
  635. write_registry(registry)
  636. print(f"Completed interrupted NAM LV2 uninstall at {destination}.")
  637. return
  638. if not destination.exists():
  639. raise RuntimeError(f"managed NAM LV2 bundle is missing: {destination}")
  640. if managed.get("installed_path") != str(destination):
  641. raise RuntimeError(f"managed NAM LV2 path changed: {destination}")
  642. if tree_sha256(destination) != managed.get("installed_sha256"):
  643. raise RuntimeError(f"managed NAM LV2 bundle changed locally; refusing to remove: {destination}")
  644. backup_path = validate_backup_path(managed.get("backup"), destination, is_directory=True)
  645. if backup_path is not None and not backup_path.is_dir():
  646. raise RuntimeError(f"recorded backup bundle is missing: {backup_path}")
  647. if backup_path is not None and tree_sha256(backup_path) != managed.get("backup_sha256"):
  648. raise RuntimeError(f"recorded backup bundle changed locally: {backup_path}")
  649. managed["pending_uninstall"] = True
  650. registry["namlv2"] = managed
  651. write_registry(registry)
  652. shutil.rmtree(destination)
  653. if backup_path is not None:
  654. os.replace(backup_path, destination)
  655. registry.pop("namlv2")
  656. write_registry(registry)
  657. print(f"Removed managed NAM LV2 bundle from {destination}.")
  658. return
  659. if managed is not None:
  660. if managed.get("pending_uninstall"):
  661. raise RuntimeError("NAM LV2 uninstall is incomplete; retry uninstall namlv2 first")
  662. if not destination.is_dir():
  663. raise RuntimeError(f"managed NAM LV2 bundle is missing: {destination}")
  664. if tree_sha256(destination) != managed.get("installed_sha256"):
  665. raise RuntimeError(f"managed NAM LV2 bundle changed locally; refusing overwrite: {destination}")
  666. if managed.get("tag") == config["tag"]:
  667. print(f"NAM LV2 tag {config['tag']} is already installed and unchanged.")
  668. return
  669. backup = validate_backup_path(managed.get("backup"), destination, is_directory=True)
  670. backup_sha256 = managed.get("backup_sha256")
  671. elif destination.exists():
  672. backup = destination.with_name(destination.name + ".rigforge-backup")
  673. if backup.exists():
  674. raise RuntimeError(f"backup path already exists: {backup}")
  675. backup_sha256 = None
  676. else:
  677. backup = None
  678. backup_sha256 = None
  679. with tempfile.TemporaryDirectory(prefix="rigforge-namlv2-") as temporary_dir:
  680. temporary = Path(temporary_dir)
  681. archive_path = temporary / "namlv2.tgz"
  682. download_archive(config["archive_url"], archive_path)
  683. archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()
  684. inspect_archive(archive_path, bundle_name)
  685. extraction_root = temporary / "extract"
  686. extraction_root.mkdir()
  687. extracted_bundle = extraction_root / bundle_name
  688. extracted_bundle.mkdir()
  689. extract_bundle(archive_path, extracted_bundle, bundle_name)
  690. if not extracted_bundle.is_dir():
  691. raise RuntimeError(f"expected bundle missing after extraction: {extracted_bundle}")
  692. destination.parent.mkdir(parents=True, exist_ok=True)
  693. staged_bundle = destination.with_name(destination.name + ".rigforge-new")
  694. previous_bundle = destination.with_name(destination.name + ".rigforge-old")
  695. if staged_bundle.exists() or previous_bundle.exists():
  696. raise RuntimeError("NAM LV2 staging or recovery path already exists")
  697. backup_created = False
  698. moved_previous = False
  699. try:
  700. shutil.copytree(extracted_bundle, staged_bundle)
  701. if managed is None and backup is not None:
  702. shutil.copytree(destination, backup)
  703. backup_created = True
  704. backup_sha256 = tree_sha256(backup)
  705. if destination.exists():
  706. os.replace(destination, previous_bundle)
  707. moved_previous = True
  708. os.replace(staged_bundle, destination)
  709. except (OSError, shutil.Error):
  710. if moved_previous and previous_bundle.exists() and not destination.exists():
  711. os.replace(previous_bundle, destination)
  712. if backup_created and backup.exists():
  713. shutil.rmtree(backup)
  714. raise
  715. finally:
  716. if staged_bundle.exists():
  717. shutil.rmtree(staged_bundle)
  718. if previous_bundle.exists():
  719. shutil.rmtree(previous_bundle)
  720. registry["namlv2"] = {
  721. "tag": config["tag"],
  722. "archive_sha256": archive_digest,
  723. "installed_path": str(destination),
  724. "backup": str(backup) if backup is not None else None,
  725. "backup_sha256": backup_sha256,
  726. "installed_sha256": tree_sha256(destination),
  727. }
  728. write_registry(registry)
  729. print(f"Installed NAM LV2 tag {config['tag']} at {destination}.")
  730. print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}")
  731. def main(argv=None):
  732. parser = argparse.ArgumentParser()
  733. parser.add_argument("action", choices=("install", "uninstall", "reload"))
  734. parser.add_argument("target", choices=("namlv2", "lsp", "dragonfly-reverb", "pipewire"))
  735. args = parser.parse_args(argv)
  736. try:
  737. state = yaml.safe_load((ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8"))
  738. deployment = load_deployment()
  739. quantum_frames = state["parameters"]["quantum_frames"]
  740. if not isinstance(quantum_frames, int) or isinstance(quantum_frames, bool) or quantum_frames < 1:
  741. raise ValueError("parameters.quantum_frames must be a positive integer")
  742. registry = read_registry()
  743. if args.target == "namlv2":
  744. deploy_namlv2(args.action, deployment["namlv2"], registry)
  745. elif args.target == "pipewire":
  746. deploy_pipewire(args.action, deployment["pipewire"], registry, quantum_frames)
  747. else:
  748. component = "dragonfly_reverb" if args.target == "dragonfly-reverb" else args.target
  749. deploy_lv2_archives(args.action, component, deployment[component], registry)
  750. except (OSError, ValueError, RuntimeError, KeyError, TypeError, subprocess.CalledProcessError, tarfile.TarError, yaml.YAMLError) as error:
  751. print(f"ERROR: {error}", file=sys.stderr)
  752. return 1
  753. return 0
  754. if __name__ == "__main__":
  755. raise SystemExit(main())