deploy.py 80 KB

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