deploy.py 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  1. import argparse
  2. import hashlib
  3. import json
  4. import os
  5. import re
  6. import shutil
  7. import socket
  8. import subprocess
  9. import sys
  10. import tarfile
  11. import tempfile
  12. from pathlib import Path, PurePosixPath
  13. import yaml
  14. from validate_desired_state import validate_state
  15. ROOT = Path(__file__).resolve().parents[1]
  16. STATE_PATH = Path.home() / ".local" / "state" / "rigforge" / "deployment.json"
  17. NAM_RELEASE_ASSET = re.compile(
  18. r"^https://github\.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/"
  19. r"(?P<tag>[A-Za-z0-9._-]+)/neural_amp_modeler_lv2_rpi5\.tgz$"
  20. )
  21. PLUGIN_ARCHIVES = {
  22. "lsp": "7z",
  23. "dragonfly_reverb": "tar.xz",
  24. }
  25. def load_deployment():
  26. with (ROOT / "config" / "desired-state.yaml").open(encoding="utf-8") as stream:
  27. state = yaml.safe_load(stream)
  28. errors = validate_state(state)
  29. deployment = state.get("deployment") if isinstance(state, dict) else None
  30. if not isinstance(deployment, dict):
  31. raise ValueError("deployment must be a mapping")
  32. namlv2 = deployment.get("namlv2")
  33. pipewire = deployment.get("pipewire")
  34. if not isinstance(namlv2, dict) or not isinstance(pipewire, dict):
  35. raise ValueError("deployment.namlv2 and deployment.pipewire must be mappings")
  36. for component, archive_format in PLUGIN_ARCHIVES.items():
  37. plugin = deployment.get(component)
  38. if not isinstance(plugin, dict):
  39. raise ValueError(f"deployment.{component} must be a mapping")
  40. if plugin.get("archive_format") != archive_format:
  41. errors.append(f"{component} archive format is invalid")
  42. if not isinstance(plugin.get("bundle_paths"), dict) or not plugin["bundle_paths"]:
  43. errors.append(f"{component} bundle paths are invalid")
  44. tag = namlv2.get("tag")
  45. match = NAM_RELEASE_ASSET.fullmatch(namlv2.get("archive_url", ""))
  46. if not isinstance(tag, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", tag):
  47. errors.append("NAM LV2 tag is invalid")
  48. if match is None or match.group("tag") != tag:
  49. errors.append("NAM LV2 URL must be the approved release asset for the declared tag")
  50. if namlv2.get("bundle_directory") != "neural_amp_modeler.lv2":
  51. errors.append("NAM LV2 bundle directory is invalid")
  52. source = pipewire.get("fragment_source")
  53. if source != "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf":
  54. errors.append("PipeWire fragment source is invalid")
  55. if pipewire.get("fragment_destination") != ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf":
  56. errors.append("PipeWire fragment destination is invalid")
  57. if pipewire.get("user_service") != "filter-chain.service":
  58. errors.append("PipeWire user service is invalid")
  59. if errors:
  60. raise ValueError("; ".join(errors))
  61. return deployment
  62. def read_registry():
  63. if not STATE_PATH.exists():
  64. return {}
  65. with STATE_PATH.open(encoding="utf-8") as stream:
  66. registry = json.load(stream)
  67. if not isinstance(registry, dict):
  68. raise ValueError(f"deployment registry is not a mapping: {STATE_PATH}")
  69. return registry
  70. def write_registry(registry):
  71. STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
  72. fd, temporary_name = tempfile.mkstemp(prefix="deployment.", dir=STATE_PATH.parent)
  73. try:
  74. with os.fdopen(fd, "w", encoding="utf-8") as stream:
  75. json.dump(registry, stream, indent=2, sort_keys=True)
  76. stream.write("\n")
  77. os.replace(temporary_name, STATE_PATH)
  78. finally:
  79. if os.path.exists(temporary_name):
  80. os.unlink(temporary_name)
  81. def run(command):
  82. subprocess.run(command, check=True)
  83. def tree_sha256(path):
  84. digest = hashlib.sha256()
  85. for item in sorted(path.rglob("*")):
  86. relative = item.relative_to(path).as_posix().encode()
  87. digest.update(relative + b"\\0")
  88. if item.is_symlink():
  89. digest.update(b"link\\0" + os.readlink(item).encode())
  90. elif item.is_file():
  91. digest.update(b"file\\0" + item.read_bytes())
  92. elif item.is_dir():
  93. digest.update(b"directory\\0")
  94. else:
  95. raise RuntimeError(f"unsupported file type in managed bundle: {item}")
  96. return digest.hexdigest()
  97. def validate_user_destination(destination):
  98. home = Path.home().resolve()
  99. parent = destination.parent.resolve()
  100. if not parent.is_relative_to(home):
  101. raise RuntimeError(f"deployment path escapes the user home directory: {destination}")
  102. if destination.is_symlink():
  103. raise RuntimeError(f"refusing to manage a symlink destination: {destination}")
  104. def validate_backup_path(backup, destination, is_directory=False):
  105. if backup is None:
  106. return None
  107. backup_path = Path(backup)
  108. expected = destination.with_name(destination.name + ".rigforge-backup")
  109. if backup_path != expected:
  110. raise RuntimeError(f"recorded backup path is outside its approved location: {backup_path}")
  111. if backup_path.is_symlink():
  112. raise RuntimeError(f"recorded backup must not be a symlink: {backup_path}")
  113. if backup_path.exists() and backup_path.is_dir() != is_directory:
  114. raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
  115. return backup_path
  116. def atomic_install(source, destination):
  117. destination.parent.mkdir(parents=True, exist_ok=True)
  118. fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent)
  119. os.close(fd)
  120. try:
  121. shutil.copyfile(source, temporary_name)
  122. shutil.copymode(source, temporary_name)
  123. os.replace(temporary_name, destination)
  124. finally:
  125. if os.path.exists(temporary_name):
  126. os.unlink(temporary_name)
  127. def apply_quantum(frames):
  128. run(["pw-metadata", "-n", "settings", "0", "clock.force-quantum", str(frames)])
  129. def restart_filter_service(service):
  130. run(["systemctl", "--user", "restart", service])
  131. run(["systemctl", "--user", "is-active", "--quiet", service])
  132. def deploy_pipewire(action, config, registry, quantum_frames):
  133. destination = Path.home() / config["fragment_destination"]
  134. validate_user_destination(destination)
  135. source = ROOT / config["fragment_source"]
  136. managed = registry.get("pipewire")
  137. pending_reload = registry.get("pipewire_pending_reload")
  138. if pending_reload is not None:
  139. apply_quantum(pending_reload["quantum_frames"])
  140. restart_filter_service(config["user_service"])
  141. registry.pop("pipewire_pending_reload")
  142. write_registry(registry)
  143. managed = registry.get("pipewire")
  144. if action == "reload":
  145. if not source.is_file() or not destination.is_file():
  146. raise RuntimeError("PipeWire reload requires both the repository fragment and installed fragment")
  147. apply_quantum(quantum_frames)
  148. restart_filter_service(config["user_service"])
  149. print("PipeWire runtime quantum applied; filter-chain user service restarted.")
  150. return
  151. if action == "install":
  152. if managed is not None and managed.get("pending_uninstall"):
  153. raise RuntimeError("PipeWire uninstall is incomplete; retry uninstall pipewire first")
  154. if managed is not None:
  155. validate_backup_path(managed.get("backup"), destination)
  156. if not destination.exists():
  157. raise RuntimeError(f"managed PipeWire fragment is missing: {destination}")
  158. if managed is not None and destination.exists():
  159. current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  160. if current_digest != managed["installed_sha256"]:
  161. raise RuntimeError(f"managed file changed locally; refusing overwrite: {destination}")
  162. was_unmanaged = managed is None
  163. changed = not destination.exists() or destination.read_bytes() != source.read_bytes()
  164. if managed is None:
  165. backup_path = None
  166. backup_sha256 = None
  167. if destination.exists():
  168. backup_path = str(destination.with_name(destination.name + ".rigforge-backup"))
  169. if Path(backup_path).exists():
  170. raise RuntimeError(f"backup path already exists: {backup_path}")
  171. shutil.copy2(destination, backup_path)
  172. backup_sha256 = hashlib.sha256(Path(backup_path).read_bytes()).hexdigest()
  173. managed = {
  174. "installed_sha256": "",
  175. "backup": backup_path,
  176. "backup_sha256": backup_sha256,
  177. }
  178. registry["pipewire"] = managed
  179. if changed:
  180. atomic_install(source, destination)
  181. managed["installed_sha256"] = hashlib.sha256(source.read_bytes()).hexdigest()
  182. managed["pending_reload"] = changed or was_unmanaged or managed.get("pending_reload", False)
  183. registry["pipewire"] = managed
  184. write_registry(registry)
  185. apply_quantum(quantum_frames)
  186. if managed["pending_reload"]:
  187. restart_filter_service(config["user_service"])
  188. managed.pop("pending_reload", None)
  189. registry["pipewire"] = managed
  190. write_registry(registry)
  191. print(f"PipeWire fragment {'updated' if changed else 'already current'} at {destination}.")
  192. return
  193. if action == "uninstall":
  194. if managed is None:
  195. print("No managed PipeWire fragment to uninstall.")
  196. return
  197. if managed.get("pending_uninstall"):
  198. backup_path = validate_backup_path(managed.get("backup"), destination)
  199. backup_exists = backup_path is not None and backup_path.is_file()
  200. if backup_path is not None and backup_path.exists():
  201. if not backup_exists:
  202. raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
  203. backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
  204. if backup_digest != managed.get("backup_sha256"):
  205. raise RuntimeError(f"recorded backup changed locally: {backup_path}")
  206. if destination.exists():
  207. current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  208. if backup_exists and current_digest == managed.get("backup_sha256"):
  209. backup_path.unlink()
  210. elif backup_path is not None and not backup_exists and current_digest == managed.get("backup_sha256"):
  211. pass
  212. elif current_digest == managed.get("installed_sha256"):
  213. destination.unlink()
  214. if backup_exists:
  215. os.replace(backup_path, destination)
  216. elif backup_path is not None:
  217. raise RuntimeError(f"recorded backup is missing: {backup_path}")
  218. else:
  219. raise RuntimeError(f"unexpected file blocks pending uninstall: {destination}")
  220. elif backup_exists:
  221. os.replace(backup_path, destination)
  222. elif backup_path is not None:
  223. raise RuntimeError(f"recorded backup is missing: {backup_path}")
  224. registry.pop("pipewire")
  225. write_registry(registry)
  226. apply_quantum(0)
  227. restart_filter_service(config["user_service"])
  228. print("Completed interrupted PipeWire uninstall and restored prior state.")
  229. return
  230. if not destination.exists():
  231. raise RuntimeError(f"managed PipeWire fragment is missing: {destination}")
  232. current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  233. if current_digest != managed["installed_sha256"]:
  234. raise RuntimeError(f"managed file changed locally; refusing to remove: {destination}")
  235. backup_path = validate_backup_path(managed.get("backup"), destination)
  236. if backup_path is not None and not backup_path.is_file():
  237. raise RuntimeError(f"recorded backup is missing: {backup_path}")
  238. if backup_path is not None:
  239. backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
  240. if backup_digest != managed.get("backup_sha256"):
  241. raise RuntimeError(f"recorded backup changed locally: {backup_path}")
  242. managed["pending_uninstall"] = True
  243. registry["pipewire"] = managed
  244. write_registry(registry)
  245. destination.unlink()
  246. if backup_path is not None:
  247. atomic_install(backup_path, destination)
  248. backup_path.unlink()
  249. registry.pop("pipewire")
  250. registry["pipewire_pending_reload"] = {"quantum_frames": 0}
  251. write_registry(registry)
  252. apply_quantum(0)
  253. restart_filter_service(config["user_service"])
  254. registry.pop("pipewire_pending_reload")
  255. write_registry(registry)
  256. print("Rigforge PipeWire fragment removed or prior file restored; quantum reset to automatic.")
  257. return
  258. def inspect_archive(archive_path, bundle_name):
  259. with tarfile.open(archive_path, "r:gz") as archive:
  260. members = archive.getmembers()
  261. bundle_prefix = PurePosixPath(bundle_name)
  262. matching = []
  263. for member in members:
  264. member_path = PurePosixPath(member.name)
  265. if member_path.is_absolute() or ".." in member_path.parts:
  266. raise RuntimeError(f"unsafe archive path: {member.name}")
  267. if member_path.parts and member_path.parts[0] == bundle_prefix.name:
  268. if not member_path.is_relative_to(bundle_prefix):
  269. raise RuntimeError(f"unexpected bundle path: {member.name}")
  270. if not (member.isdir() or member.isfile()):
  271. raise RuntimeError(f"unsupported archive member type: {member.name}")
  272. matching.append(member)
  273. else:
  274. raise RuntimeError(f"unexpected archive path: {member.name}")
  275. if not matching or not any(member.name == bundle_name and member.isdir() for member in matching):
  276. raise RuntimeError(f"archive does not contain expected bundle directory {bundle_name}")
  277. return members
  278. def extract_bundle(archive_path, destination, bundle_name):
  279. with tarfile.open(archive_path, "r:gz") as archive:
  280. members = inspect_archive(archive_path, bundle_name)
  281. for member in members:
  282. member_path = PurePosixPath(member.name)
  283. relative_parts = member_path.parts[1:]
  284. output_path = destination.joinpath(*relative_parts) if relative_parts else destination
  285. if member.isdir():
  286. output_path.mkdir(parents=True, exist_ok=True)
  287. output_path.chmod(0o755)
  288. continue
  289. output_path.parent.mkdir(parents=True, exist_ok=True)
  290. extracted = archive.extractfile(member)
  291. if extracted is None:
  292. raise RuntimeError(f"unable to read archive member: {member.name}")
  293. with extracted, output_path.open("wb") as output:
  294. shutil.copyfileobj(extracted, output)
  295. output_path.chmod(0o755 if member.mode & 0o111 else 0o644)
  296. def download_archive(url, destination):
  297. run(["curl", "--fail", "--location", "--silent", "--show-error", "--output", str(destination), url])
  298. def inspect_tar_archive(archive_path, bundle_paths):
  299. expected_roots = {PurePosixPath(path) for path in bundle_paths.values()}
  300. with tarfile.open(archive_path, "r:xz") as archive:
  301. members = archive.getmembers()
  302. for member in members:
  303. member_path = PurePosixPath(member.name)
  304. if member_path.is_absolute() or ".." in member_path.parts:
  305. raise RuntimeError(f"unsafe archive path: {member.name}")
  306. if not member.isfile() and not member.isdir():
  307. raise RuntimeError(f"unsupported archive member type: {member.name}")
  308. for bundle_root in expected_roots:
  309. if not any(member.name.rstrip("/") == str(bundle_root) and member.isdir() for member in members):
  310. raise RuntimeError(f"archive does not contain expected bundle directory {bundle_root}")
  311. if not any(member.name == f"{bundle_root}/manifest.ttl" and member.isfile() for member in members):
  312. raise RuntimeError(f"archive bundle is missing manifest.ttl: {bundle_root}")
  313. return expected_roots
  314. def extract_tar_bundles(archive_path, bundle_paths, extraction_root):
  315. expected_roots = inspect_tar_archive(archive_path, bundle_paths)
  316. extracted = {bundle_name: extraction_root / bundle_name for bundle_name in bundle_paths}
  317. with tarfile.open(archive_path, "r:xz") as archive:
  318. for member in archive.getmembers():
  319. member_path = PurePosixPath(member.name)
  320. bundle_root = next(
  321. (root for root in expected_roots if member_path == root or member_path.is_relative_to(root)),
  322. None,
  323. )
  324. if bundle_root is None:
  325. continue
  326. bundle_name = next(name for name, path in bundle_paths.items() if PurePosixPath(path) == bundle_root)
  327. output_path = extracted[bundle_name].joinpath(*member_path.parts[len(bundle_root.parts):])
  328. if member.isdir():
  329. output_path.mkdir(parents=True, exist_ok=True)
  330. output_path.chmod(0o755)
  331. continue
  332. output_path.parent.mkdir(parents=True, exist_ok=True)
  333. source = archive.extractfile(member)
  334. if source is None:
  335. raise RuntimeError(f"unable to read archive member: {member.name}")
  336. with source, output_path.open("wb") as destination:
  337. shutil.copyfileobj(source, destination)
  338. output_path.chmod(0o755 if member.mode & 0o111 else 0o644)
  339. return extracted
  340. def inspect_7z_archive(bundle_paths, listing):
  341. paths = []
  342. current = {}
  343. for line in listing.splitlines() + [""]:
  344. if not line and current:
  345. path = current.get("Path")
  346. attributes = current.get("Attributes", "")
  347. if path and attributes:
  348. member_path = PurePosixPath(path)
  349. if member_path.is_absolute() or ".." in member_path.parts:
  350. raise RuntimeError(f"unsafe archive path: {path}")
  351. if "L" in attributes or "H" in attributes:
  352. raise RuntimeError(f"unsupported archive member type: {path}")
  353. paths.append((member_path, "D" in attributes))
  354. current = {}
  355. elif " = " in line:
  356. key, value = line.split(" = ", 1)
  357. current[key] = value
  358. expected_roots = {PurePosixPath(path) for path in bundle_paths.values()}
  359. present_roots = {path for path, is_directory in paths if is_directory and path in expected_roots}
  360. if present_roots != expected_roots:
  361. raise RuntimeError(f"7z archive is missing expected LV2 bundles: {sorted(map(str, expected_roots - present_roots))}")
  362. for root in expected_roots:
  363. if not any(path == root / "manifest.ttl" and not is_directory for path, is_directory in paths):
  364. raise RuntimeError(f"7z archive bundle is missing manifest.ttl: {root}")
  365. return expected_roots, paths
  366. def extract_7z_bundles(archive_path, bundle_paths, extraction_root):
  367. executable = shutil.which("7z") or shutil.which("7zz") or shutil.which("7za")
  368. if executable is None:
  369. raise RuntimeError("installing LSP plugins requires 7z, 7zz, or 7za on PATH")
  370. listing = subprocess.run(
  371. [executable, "l", "-slt", str(archive_path)],
  372. check=True,
  373. capture_output=True,
  374. text=True,
  375. ).stdout
  376. expected_roots, paths = inspect_7z_archive(bundle_paths, listing)
  377. temporary_output = extraction_root / "7z-output"
  378. temporary_output.mkdir()
  379. result = subprocess.run(
  380. [executable, "x", "-y", f"-o{temporary_output}", str(archive_path)],
  381. check=False,
  382. capture_output=True,
  383. text=True,
  384. )
  385. if result.returncode != 0:
  386. missing_files = [
  387. path
  388. for path, is_directory in paths
  389. if not is_directory
  390. and any(path.is_relative_to(root) for root in expected_roots)
  391. and not temporary_output.joinpath(*path.parts).is_file()
  392. ]
  393. if missing_files:
  394. raise subprocess.CalledProcessError(
  395. result.returncode,
  396. result.args,
  397. output=result.stdout,
  398. stderr=result.stderr,
  399. )
  400. extracted = {}
  401. for bundle_name, path in bundle_paths.items():
  402. bundle_root = PurePosixPath(path)
  403. source = temporary_output.joinpath(*bundle_root.parts)
  404. if not source.is_dir():
  405. raise RuntimeError(f"expected LV2 bundle missing after extraction: {source}")
  406. target = extraction_root / bundle_name
  407. shutil.copytree(source, target, symlinks=False)
  408. extracted[bundle_name] = target
  409. return extracted
  410. def deploy_lv2_archives(action, component, config, registry):
  411. bundle_paths = config["bundle_paths"]
  412. bundle_names = list(bundle_paths)
  413. destinations = {name: Path.home() / ".lv2" / name for name in bundle_names}
  414. for destination in destinations.values():
  415. validate_user_destination(destination)
  416. managed = registry.get(component)
  417. if action == "reload":
  418. print(f"Nothing to reload for {component}; restart its LV2 host after installation.")
  419. return
  420. if action == "uninstall":
  421. if managed is None:
  422. print(f"No managed {component} bundles to uninstall.")
  423. return
  424. recorded = managed.get("bundles")
  425. if not isinstance(recorded, dict) or set(recorded) != set(bundle_names):
  426. raise RuntimeError(f"managed {component} bundle declaration changed")
  427. if managed.get("pending_uninstall"):
  428. for name, destination in destinations.items():
  429. record = recorded[name]
  430. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  431. backup_exists = backup is not None and backup.is_dir()
  432. if backup is not None and backup.exists() and not backup_exists:
  433. raise RuntimeError(f"recorded backup has the wrong type: {backup}")
  434. if backup_exists and tree_sha256(backup) != record.get("backup_sha256"):
  435. raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
  436. if destination.exists():
  437. current = tree_sha256(destination)
  438. if backup_exists and current == record.get("backup_sha256"):
  439. continue
  440. if backup is None and record.get("backup_sha256") is None:
  441. if current == record.get("installed_sha256"):
  442. continue
  443. raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
  444. if not backup_exists and current == record.get("backup_sha256"):
  445. continue
  446. if current != record.get("installed_sha256"):
  447. raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
  448. elif backup is not None and not backup_exists:
  449. raise RuntimeError(f"recorded backup bundle is missing: {backup}")
  450. for name, destination in destinations.items():
  451. record = recorded[name]
  452. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  453. backup_exists = backup is not None and backup.is_dir()
  454. if destination.exists() and tree_sha256(destination) == record.get("installed_sha256"):
  455. shutil.rmtree(destination)
  456. if backup_exists:
  457. os.replace(backup, destination)
  458. registry.pop(component)
  459. write_registry(registry)
  460. print(f"Completed interrupted {component} uninstall at {Path.home() / '.lv2'}.")
  461. return
  462. for name, destination in destinations.items():
  463. record = recorded[name]
  464. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  465. if not destination.is_dir():
  466. raise RuntimeError(f"managed {component} bundle is missing: {destination}")
  467. if record.get("installed_path") != str(destination):
  468. raise RuntimeError(f"managed {component} path changed: {destination}")
  469. if tree_sha256(destination) != record.get("installed_sha256"):
  470. raise RuntimeError(f"managed {component} bundle changed locally; refusing to remove: {destination}")
  471. if backup is not None:
  472. if not backup.is_dir():
  473. raise RuntimeError(f"recorded backup bundle is missing: {backup}")
  474. if tree_sha256(backup) != record.get("backup_sha256"):
  475. raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
  476. managed["pending_uninstall"] = True
  477. registry[component] = managed
  478. write_registry(registry)
  479. for name, destination in destinations.items():
  480. record = recorded[name]
  481. shutil.rmtree(destination)
  482. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  483. if backup is not None:
  484. os.replace(backup, destination)
  485. registry.pop(component)
  486. write_registry(registry)
  487. print(f"Removed managed {component} bundles from {Path.home() / '.lv2'}.")
  488. return
  489. if managed is not None:
  490. if managed.get("pending_uninstall"):
  491. raise RuntimeError(f"{component} uninstall is incomplete; retry uninstall {component} first")
  492. recorded = managed.get("bundles")
  493. if not isinstance(recorded, dict) or set(recorded) != set(bundle_names):
  494. raise RuntimeError(f"managed {component} bundle declaration changed")
  495. for name, destination in destinations.items():
  496. record = recorded[name]
  497. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  498. if backup is not None:
  499. if not backup.is_dir() or tree_sha256(backup) != record.get("backup_sha256"):
  500. raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
  501. if not destination.is_dir():
  502. raise RuntimeError(f"managed {component} bundle is missing: {destination}")
  503. if tree_sha256(destination) != record.get("installed_sha256"):
  504. raise RuntimeError(f"managed {component} bundle changed locally; refusing overwrite: {destination}")
  505. if managed.get("tag") == config["tag"]:
  506. print(f"{component} tag {config['tag']} is already installed and unchanged.")
  507. return
  508. for name, destination in destinations.items():
  509. previous = managed.get("bundles", {}).get(name) if managed else None
  510. if previous is not None:
  511. backup = validate_backup_path(previous.get("backup"), destination, is_directory=True)
  512. if backup is not None:
  513. if not backup.is_dir():
  514. raise RuntimeError(f"recorded backup bundle is missing: {backup}")
  515. if tree_sha256(backup) != previous.get("backup_sha256"):
  516. raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
  517. if previous is None and destination.exists():
  518. backup = destination.with_name(destination.name + ".rigforge-backup")
  519. if backup.exists():
  520. raise RuntimeError(f"backup path already exists: {backup}")
  521. staged = destination.with_name(destination.name + ".rigforge-new")
  522. previous_path = destination.with_name(destination.name + ".rigforge-old")
  523. if staged.exists() or previous_path.exists():
  524. raise RuntimeError(f"{component} staging or recovery path already exists: {destination}")
  525. with tempfile.TemporaryDirectory(prefix=f"rigforge-{component}-") as temporary_dir:
  526. temporary = Path(temporary_dir)
  527. archive_path = temporary / (
  528. "plugin.tar.xz" if config["archive_format"] == "tar.xz" else "plugin.7z"
  529. )
  530. download_archive(config["archive_url"], archive_path)
  531. archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()
  532. extraction_root = temporary / "extract"
  533. extraction_root.mkdir()
  534. if config["archive_format"] == "tar.xz":
  535. extracted = extract_tar_bundles(archive_path, config["bundle_paths"], extraction_root)
  536. else:
  537. extracted = extract_7z_bundles(archive_path, config["bundle_paths"], extraction_root)
  538. records = {}
  539. created_backups = []
  540. installed_destinations = []
  541. try:
  542. for name, destination in destinations.items():
  543. previous = managed.get("bundles", {}).get(name) if managed else None
  544. backup = (
  545. validate_backup_path(previous.get("backup"), destination, is_directory=True)
  546. if previous is not None
  547. else destination.with_name(destination.name + ".rigforge-backup")
  548. if destination.exists()
  549. else None
  550. )
  551. backup_digest = previous.get("backup_sha256") if previous is not None else None
  552. if backup is not None and previous is None:
  553. shutil.copytree(destination, backup, symlinks=True)
  554. created_backups.append(backup)
  555. backup_digest = tree_sha256(backup)
  556. destination.parent.mkdir(parents=True, exist_ok=True)
  557. staged = destination.with_name(destination.name + ".rigforge-new")
  558. previous_path = destination.with_name(destination.name + ".rigforge-old")
  559. shutil.copytree(extracted[name], staged, symlinks=False)
  560. try:
  561. if destination.exists():
  562. os.replace(destination, previous_path)
  563. os.replace(staged, destination)
  564. installed_destinations.append((destination, previous_path))
  565. except OSError:
  566. if previous_path.exists() and not destination.exists():
  567. os.replace(previous_path, destination)
  568. if staged.exists():
  569. shutil.rmtree(staged)
  570. raise
  571. records[name] = {
  572. "installed_path": str(destination),
  573. "backup": str(backup) if backup is not None else None,
  574. "backup_sha256": backup_digest,
  575. "installed_sha256": tree_sha256(destination),
  576. }
  577. for _, previous_path in installed_destinations:
  578. if previous_path.exists():
  579. shutil.rmtree(previous_path)
  580. except (OSError, shutil.Error):
  581. for destination, previous_path in reversed(installed_destinations):
  582. if destination.exists():
  583. shutil.rmtree(destination)
  584. if previous_path.exists():
  585. os.replace(previous_path, destination)
  586. for destination in destinations.values():
  587. staged = destination.with_name(destination.name + ".rigforge-new")
  588. if staged.exists():
  589. shutil.rmtree(staged)
  590. for backup in created_backups:
  591. if backup.exists():
  592. shutil.rmtree(backup)
  593. raise
  594. registry[component] = {
  595. "tag": config["tag"],
  596. "archive_sha256": archive_digest,
  597. "bundles": records,
  598. }
  599. write_registry(registry)
  600. print(f"Installed {component} tag {config['tag']} under {Path.home() / '.lv2'}.")
  601. print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}")
  602. def deploy_namlv2(action, config, registry):
  603. bundle_name = config["bundle_directory"]
  604. destination = Path.home() / ".lv2" / bundle_name
  605. validate_user_destination(destination)
  606. managed = registry.get("namlv2")
  607. if action == "reload":
  608. print("Nothing to reload for the NAM LV2 plugin; restart its LV2 host after installation.")
  609. return
  610. if action == "uninstall":
  611. if managed is None:
  612. print("No managed NAM LV2 bundle to uninstall.")
  613. return
  614. if managed.get("pending_uninstall"):
  615. backup_path = validate_backup_path(managed.get("backup"), destination, is_directory=True)
  616. backup_exists = backup_path is not None and backup_path.is_dir()
  617. if backup_path is not None and backup_path.exists() and not backup_exists:
  618. raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
  619. if backup_exists and tree_sha256(backup_path) != managed.get("backup_sha256"):
  620. raise RuntimeError(f"recorded backup bundle changed locally: {backup_path}")
  621. if destination.exists():
  622. destination_digest = tree_sha256(destination)
  623. if backup_exists and destination_digest == managed.get("backup_sha256"):
  624. shutil.rmtree(backup_path)
  625. elif destination_digest == managed.get("installed_sha256"):
  626. shutil.rmtree(destination)
  627. if backup_exists:
  628. os.replace(backup_path, destination)
  629. else:
  630. raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
  631. elif backup_exists:
  632. os.replace(backup_path, destination)
  633. elif backup_path is not None:
  634. raise RuntimeError(f"recorded backup bundle is missing: {backup_path}")
  635. registry.pop("namlv2")
  636. write_registry(registry)
  637. print(f"Completed interrupted NAM LV2 uninstall at {destination}.")
  638. return
  639. if not destination.exists():
  640. raise RuntimeError(f"managed NAM LV2 bundle is missing: {destination}")
  641. if managed.get("installed_path") != str(destination):
  642. raise RuntimeError(f"managed NAM LV2 path changed: {destination}")
  643. if tree_sha256(destination) != managed.get("installed_sha256"):
  644. raise RuntimeError(f"managed NAM LV2 bundle changed locally; refusing to remove: {destination}")
  645. backup_path = validate_backup_path(managed.get("backup"), destination, is_directory=True)
  646. if backup_path is not None and not backup_path.is_dir():
  647. raise RuntimeError(f"recorded backup bundle is missing: {backup_path}")
  648. if backup_path is not None and tree_sha256(backup_path) != managed.get("backup_sha256"):
  649. raise RuntimeError(f"recorded backup bundle changed locally: {backup_path}")
  650. managed["pending_uninstall"] = True
  651. registry["namlv2"] = managed
  652. write_registry(registry)
  653. shutil.rmtree(destination)
  654. if backup_path is not None:
  655. os.replace(backup_path, destination)
  656. registry.pop("namlv2")
  657. write_registry(registry)
  658. print(f"Removed managed NAM LV2 bundle from {destination}.")
  659. return
  660. if managed is not None:
  661. if managed.get("pending_uninstall"):
  662. raise RuntimeError("NAM LV2 uninstall is incomplete; retry uninstall namlv2 first")
  663. if not destination.is_dir():
  664. raise RuntimeError(f"managed NAM LV2 bundle is missing: {destination}")
  665. if tree_sha256(destination) != managed.get("installed_sha256"):
  666. raise RuntimeError(f"managed NAM LV2 bundle changed locally; refusing overwrite: {destination}")
  667. if managed.get("tag") == config["tag"]:
  668. print(f"NAM LV2 tag {config['tag']} is already installed and unchanged.")
  669. return
  670. backup = validate_backup_path(managed.get("backup"), destination, is_directory=True)
  671. backup_sha256 = managed.get("backup_sha256")
  672. elif destination.exists():
  673. backup = destination.with_name(destination.name + ".rigforge-backup")
  674. if backup.exists():
  675. raise RuntimeError(f"backup path already exists: {backup}")
  676. backup_sha256 = None
  677. else:
  678. backup = None
  679. backup_sha256 = None
  680. with tempfile.TemporaryDirectory(prefix="rigforge-namlv2-") as temporary_dir:
  681. temporary = Path(temporary_dir)
  682. archive_path = temporary / "namlv2.tgz"
  683. download_archive(config["archive_url"], archive_path)
  684. archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()
  685. inspect_archive(archive_path, bundle_name)
  686. extraction_root = temporary / "extract"
  687. extraction_root.mkdir()
  688. extracted_bundle = extraction_root / bundle_name
  689. extracted_bundle.mkdir()
  690. extract_bundle(archive_path, extracted_bundle, bundle_name)
  691. if not extracted_bundle.is_dir():
  692. raise RuntimeError(f"expected bundle missing after extraction: {extracted_bundle}")
  693. destination.parent.mkdir(parents=True, exist_ok=True)
  694. staged_bundle = destination.with_name(destination.name + ".rigforge-new")
  695. previous_bundle = destination.with_name(destination.name + ".rigforge-old")
  696. if staged_bundle.exists() or previous_bundle.exists():
  697. raise RuntimeError("NAM LV2 staging or recovery path already exists")
  698. backup_created = False
  699. moved_previous = False
  700. try:
  701. shutil.copytree(extracted_bundle, staged_bundle)
  702. if managed is None and backup is not None:
  703. shutil.copytree(destination, backup)
  704. backup_created = True
  705. backup_sha256 = tree_sha256(backup)
  706. if destination.exists():
  707. os.replace(destination, previous_bundle)
  708. moved_previous = True
  709. os.replace(staged_bundle, destination)
  710. except (OSError, shutil.Error):
  711. if moved_previous and previous_bundle.exists() and not destination.exists():
  712. os.replace(previous_bundle, destination)
  713. if backup_created and backup.exists():
  714. shutil.rmtree(backup)
  715. raise
  716. finally:
  717. if staged_bundle.exists():
  718. shutil.rmtree(staged_bundle)
  719. if previous_bundle.exists():
  720. shutil.rmtree(previous_bundle)
  721. registry["namlv2"] = {
  722. "tag": config["tag"],
  723. "archive_sha256": archive_digest,
  724. "installed_path": str(destination),
  725. "backup": str(backup) if backup is not None else None,
  726. "backup_sha256": backup_sha256,
  727. "installed_sha256": tree_sha256(destination),
  728. }
  729. write_registry(registry)
  730. print(f"Installed NAM LV2 tag {config['tag']} at {destination}.")
  731. print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}")
  732. def systemd_quote(value):
  733. value = str(value).replace("%", "%%").replace("\\", "\\\\").replace('"', '\\"')
  734. return f'"{value}"'
  735. def render_mod_host_service(config):
  736. binary = ROOT / config["binary_source"]
  737. service_template = ROOT / config["service_source"]
  738. configure_script = ROOT / config["configure_script"]
  739. state_file = ROOT / "config" / "desired-state.yaml"
  740. if not binary.is_file() or not os.access(binary, os.X_OK):
  741. raise RuntimeError(f"ARM64 mod-host artifact is missing or not executable: {binary}")
  742. if not service_template.is_file():
  743. raise RuntimeError(f"mod-host service template is missing: {service_template}")
  744. if not configure_script.is_file():
  745. raise RuntimeError(f"mod-host startup configurator is missing: {configure_script}")
  746. replacements = {
  747. "@PW_JACK@": systemd_quote(config["pw_jack_path"]),
  748. "@MOD_HOST_BINARY@": systemd_quote(binary.resolve()),
  749. "@SOCKET_PORT@": str(config["socket_port"]),
  750. "@PYTHON@": systemd_quote(config["python_path"]),
  751. "@CONFIGURE_SCRIPT@": systemd_quote(configure_script.resolve()),
  752. "@DESIRED_STATE@": systemd_quote(state_file.resolve()),
  753. "@REPOSITORY_ROOT@": systemd_quote(ROOT.resolve()),
  754. }
  755. content = service_template.read_text(encoding="utf-8")
  756. for placeholder, replacement in replacements.items():
  757. content = content.replace(placeholder, replacement)
  758. if re.search(r"@[A-Z_]+@", content):
  759. raise RuntimeError("unexpanded placeholder remains in mod-host service template")
  760. return content.encode("utf-8")
  761. def mod_host_runtime_digest(config):
  762. state_path = ROOT / "config" / "desired-state.yaml"
  763. script_path = ROOT / config["configure_script"]
  764. binary_path = ROOT / config["binary_source"]
  765. with state_path.open(encoding="utf-8") as stream:
  766. state = yaml.safe_load(stream)
  767. files = [state_path, script_path, binary_path]
  768. for processor in state["routing"]["mod_host_chains"]["guitar"]["processors"]:
  769. asset_path = PurePosixPath(processor["asset_path"])
  770. if asset_path.is_absolute() or ".." in asset_path.parts:
  771. raise RuntimeError(f"unsafe mod-host asset path: {processor['asset_path']!r}")
  772. resolved = (ROOT / Path(*asset_path.parts)).resolve()
  773. if not resolved.is_relative_to(ROOT.resolve()) or not resolved.is_file():
  774. raise RuntimeError(f"declared mod-host asset is missing or escapes the repository: {resolved}")
  775. files.append(resolved)
  776. digest = hashlib.sha256()
  777. for path in files:
  778. if not path.is_file():
  779. raise RuntimeError(f"mod-host runtime input is missing: {path}")
  780. digest.update(str(path.relative_to(ROOT.resolve())).encode("utf-8") + b"\0")
  781. digest.update(path.read_bytes())
  782. digest.update(b"\0")
  783. return digest.hexdigest()
  784. def mod_host_port_is_open(port):
  785. try:
  786. with socket.create_connection(("127.0.0.1", port), timeout=0.25):
  787. return True
  788. except OSError:
  789. return False
  790. def mod_host_unit_is_active(service_name):
  791. result = subprocess.run(
  792. ["systemctl", "--user", "is-active", "--quiet", service_name],
  793. check=False,
  794. stdout=subprocess.DEVNULL,
  795. stderr=subprocess.DEVNULL,
  796. )
  797. return result.returncode == 0
  798. def mod_host_unit_is_enabled(service_name):
  799. result = subprocess.run(
  800. ["systemctl", "--user", "is-enabled", "--quiet", service_name],
  801. check=False,
  802. stdout=subprocess.DEVNULL,
  803. stderr=subprocess.DEVNULL,
  804. )
  805. return result.returncode == 0
  806. def deploy_mod_host(action, config, registry):
  807. destination = Path.home() / config["service_destination"]
  808. validate_user_destination(destination)
  809. service_name = config["user_service"]
  810. managed = registry.get("mod_host")
  811. if action == "reload":
  812. if managed is None:
  813. raise RuntimeError("mod-host is not managed; install mod-host before reloading it")
  814. if managed.get("pending_uninstall"):
  815. raise RuntimeError("mod-host uninstall is incomplete; retry uninstall mod-host first")
  816. if not destination.is_file():
  817. raise RuntimeError(f"managed mod-host service file is missing: {destination}")
  818. digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  819. if digest != managed.get("installed_sha256"):
  820. raise RuntimeError(f"managed mod-host service file changed locally: {destination}")
  821. run(["systemctl", "--user", "restart", service_name])
  822. run(["systemctl", "--user", "is-active", "--quiet", service_name])
  823. print("Rigforge mod-host user service restarted.")
  824. return
  825. if action == "uninstall":
  826. if managed is None:
  827. print("No managed mod-host service to uninstall.")
  828. return
  829. backup_path = validate_backup_path(managed.get("backup"), destination)
  830. if backup_path is not None and backup_path.exists():
  831. if not backup_path.is_file():
  832. raise RuntimeError(f"recorded mod-host service backup has the wrong type: {backup_path}")
  833. if hashlib.sha256(backup_path.read_bytes()).hexdigest() != managed.get("backup_sha256"):
  834. raise RuntimeError(f"recorded mod-host service backup changed locally: {backup_path}")
  835. if not managed.get("pending_uninstall"):
  836. if not destination.is_file():
  837. raise RuntimeError(f"managed mod-host service file is missing: {destination}")
  838. digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  839. if digest != managed.get("installed_sha256"):
  840. raise RuntimeError(f"managed mod-host service file changed locally; refusing removal: {destination}")
  841. managed["pending_uninstall"] = True
  842. registry["mod_host"] = managed
  843. write_registry(registry)
  844. destination_digest = (
  845. hashlib.sha256(destination.read_bytes()).hexdigest()
  846. if destination.is_file()
  847. else None
  848. )
  849. backup_digest = (
  850. hashlib.sha256(backup_path.read_bytes()).hexdigest()
  851. if backup_path is not None and backup_path.is_file()
  852. else None
  853. )
  854. installed_digest = managed.get("installed_sha256")
  855. already_restored = (
  856. backup_path is not None
  857. and destination_digest == managed.get("backup_sha256")
  858. )
  859. already_removed = destination_digest is None and backup_digest is None and backup_path is None
  860. if not already_restored and not already_removed:
  861. if destination_digest not in {installed_digest, None}:
  862. raise RuntimeError(f"unexpected file blocks mod-host uninstall: {destination}")
  863. run(["systemctl", "--user", "disable", "--now", service_name])
  864. if destination_digest == installed_digest:
  865. destination.unlink()
  866. if backup_path is not None and backup_path.exists():
  867. os.replace(backup_path, destination)
  868. elif backup_path is not None:
  869. raise RuntimeError(f"recorded mod-host service backup is missing: {backup_path}")
  870. run(["systemctl", "--user", "daemon-reload"])
  871. registry.pop("mod_host")
  872. write_registry(registry)
  873. print("Rigforge mod-host user service removed; prior unit state restored if present.")
  874. return
  875. # Install is intentionally an explicit target, not part of "all": it
  876. # activates the guitar processing chain and can make audio audible.
  877. content = render_mod_host_service(config)
  878. installed_digest = hashlib.sha256(content).hexdigest()
  879. runtime_digest = mod_host_runtime_digest(config)
  880. previous_runtime_digest = managed.get("runtime_sha256") if managed is not None else None
  881. restart_required = managed is None or runtime_digest != previous_runtime_digest
  882. if managed is not None:
  883. if managed.get("pending_uninstall"):
  884. raise RuntimeError("mod-host uninstall is incomplete; retry uninstall mod-host first")
  885. backup_path = validate_backup_path(managed.get("backup"), destination)
  886. if backup_path is not None:
  887. if not backup_path.is_file():
  888. raise RuntimeError(f"recorded mod-host service backup is missing: {backup_path}")
  889. if hashlib.sha256(backup_path.read_bytes()).hexdigest() != managed.get("backup_sha256"):
  890. raise RuntimeError(f"recorded mod-host service backup changed locally: {backup_path}")
  891. if not destination.is_file():
  892. if not managed.get("pending_install"):
  893. raise RuntimeError(f"managed mod-host service file is missing: {destination}")
  894. if destination.exists() and not destination.is_file():
  895. raise RuntimeError(f"managed mod-host service destination has the wrong type: {destination}")
  896. current_digest = (
  897. hashlib.sha256(destination.read_bytes()).hexdigest()
  898. if destination.is_file()
  899. else None
  900. )
  901. if current_digest is not None and current_digest != managed.get("installed_sha256"):
  902. prior_digest = managed.get("backup_sha256")
  903. if not managed.get("pending_install") or current_digest != prior_digest:
  904. raise RuntimeError(
  905. f"managed mod-host service file changed locally; refusing overwrite: {destination}"
  906. )
  907. elif not destination.exists() and not managed.get("pending_install"):
  908. raise RuntimeError(f"managed mod-host service file changed locally; refusing overwrite: {destination}")
  909. backup = managed.get("backup")
  910. backup_sha256 = managed.get("backup_sha256")
  911. else:
  912. if mod_host_unit_is_active(service_name) or mod_host_unit_is_enabled(service_name):
  913. raise RuntimeError(
  914. f"an unmanaged {service_name} is already active or enabled; "
  915. "inspect and disable it before installing Rigforge's unit"
  916. )
  917. if mod_host_port_is_open(config["socket_port"]):
  918. raise RuntimeError(
  919. f"mod-host control port {config['socket_port']} is already in use; "
  920. "stop the unmanaged test process before installing the user service"
  921. )
  922. backup = None
  923. backup_sha256 = None
  924. if destination.exists():
  925. backup_path = destination.with_name(destination.name + ".rigforge-backup")
  926. if backup_path.exists():
  927. raise RuntimeError(f"backup path already exists: {backup_path}")
  928. shutil.copy2(destination, backup_path)
  929. backup = str(backup_path)
  930. backup_sha256 = hashlib.sha256(backup_path.read_bytes()).hexdigest()
  931. unit_changed = not destination.exists() or destination.read_bytes() != content
  932. restart_required = (
  933. restart_required
  934. or unit_changed
  935. or (managed is not None and managed.get("pending_activation", False))
  936. )
  937. if managed is None:
  938. managed = {
  939. "installed_sha256": installed_digest,
  940. "runtime_sha256": runtime_digest,
  941. "backup": backup,
  942. "backup_sha256": backup_sha256,
  943. "pending_install": unit_changed,
  944. "pending_activation": True,
  945. }
  946. else:
  947. managed["installed_sha256"] = installed_digest
  948. managed["runtime_sha256"] = runtime_digest
  949. managed["pending_install"] = unit_changed
  950. managed["pending_activation"] = True
  951. registry["mod_host"] = managed
  952. write_registry(registry)
  953. if unit_changed:
  954. destination.parent.mkdir(parents=True, exist_ok=True)
  955. fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent)
  956. try:
  957. with os.fdopen(fd, "wb") as stream:
  958. stream.write(content)
  959. os.chmod(temporary_name, 0o644)
  960. os.replace(temporary_name, destination)
  961. finally:
  962. if os.path.exists(temporary_name):
  963. os.unlink(temporary_name)
  964. managed.pop("pending_install", None)
  965. registry["mod_host"] = managed
  966. write_registry(registry)
  967. run(["systemctl", "--user", "daemon-reload"])
  968. run(["systemctl", "--user", "enable", service_name])
  969. if restart_required:
  970. run(["systemctl", "--user", "restart", service_name])
  971. else:
  972. run(["systemctl", "--user", "start", service_name])
  973. run(["systemctl", "--user", "is-active", "--quiet", service_name])
  974. managed.pop("pending_activation", None)
  975. registry["mod_host"] = managed
  976. write_registry(registry)
  977. print(f"Installed and activated Rigforge mod-host user service at {destination}.")
  978. def main(argv=None):
  979. parser = argparse.ArgumentParser()
  980. parser.add_argument("action", choices=("install", "uninstall", "reload"))
  981. parser.add_argument(
  982. "target",
  983. choices=("namlv2", "lsp", "dragonfly-reverb", "pipewire", "mod-host"),
  984. )
  985. args = parser.parse_args(argv)
  986. try:
  987. state = yaml.safe_load((ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8"))
  988. deployment = load_deployment()
  989. quantum_frames = state["parameters"]["quantum_frames"]
  990. if not isinstance(quantum_frames, int) or isinstance(quantum_frames, bool) or quantum_frames < 1:
  991. raise ValueError("parameters.quantum_frames must be a positive integer")
  992. registry = read_registry()
  993. if args.target == "namlv2":
  994. deploy_namlv2(args.action, deployment["namlv2"], registry)
  995. elif args.target == "pipewire":
  996. deploy_pipewire(args.action, deployment["pipewire"], registry, quantum_frames)
  997. elif args.target == "mod-host":
  998. deploy_mod_host(args.action, deployment["mod_host"], registry)
  999. else:
  1000. component = "dragonfly_reverb" if args.target == "dragonfly-reverb" else args.target
  1001. deploy_lv2_archives(args.action, component, deployment[component], registry)
  1002. except (OSError, ValueError, RuntimeError, KeyError, TypeError, subprocess.CalledProcessError, tarfile.TarError, yaml.YAMLError) as error:
  1003. print(f"ERROR: {error}", file=sys.stderr)
  1004. return 1
  1005. return 0
  1006. if __name__ == "__main__":
  1007. raise SystemExit(main())