deploy.py 66 KB

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