deploy.py 76 KB

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