deploy.py 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299
  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. from generate_mod_ui_pedalboard import generate_bundle_files
  16. ROOT = Path(__file__).resolve().parents[1]
  17. STATE_PATH = Path.home() / ".local" / "state" / "rigforge" / "deployment.json"
  18. NAM_RELEASE_ASSET = re.compile(
  19. r"^https://github\.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/"
  20. r"(?P<tag>[A-Za-z0-9._-]+)/neural_amp_modeler_lv2_rpi5\.tgz$"
  21. )
  22. PLUGIN_ARCHIVES = {
  23. "lsp": "7z",
  24. "dragonfly_reverb": "tar.xz",
  25. }
  26. def load_deployment():
  27. with (ROOT / "config" / "desired-state.yaml").open(encoding="utf-8") as stream:
  28. state = yaml.safe_load(stream)
  29. errors = validate_state(state)
  30. deployment = state.get("deployment") if isinstance(state, dict) else None
  31. if not isinstance(deployment, dict):
  32. raise ValueError("deployment must be a mapping")
  33. namlv2 = deployment.get("namlv2")
  34. sooperlooper = deployment.get("sooperlooper")
  35. pipewire = deployment.get("pipewire")
  36. reconcile = deployment.get("reconcile")
  37. midi_bridge = deployment.get("midi_bridge")
  38. mod_host_ports = deployment.get("mod_host_ports")
  39. mod_ui = deployment.get("mod_ui")
  40. if (
  41. not isinstance(namlv2, dict)
  42. or not isinstance(sooperlooper, dict)
  43. or not isinstance(pipewire, dict)
  44. or not isinstance(reconcile, dict)
  45. or not isinstance(midi_bridge, dict)
  46. or not isinstance(mod_host_ports, dict)
  47. or not isinstance(mod_ui, dict)
  48. ):
  49. raise ValueError(
  50. "deployment.namlv2, deployment.sooperlooper, deployment.pipewire, deployment.reconcile, "
  51. "deployment.midi_bridge, deployment.mod_host_ports, and deployment.mod_ui must be mappings"
  52. )
  53. for component, archive_format in PLUGIN_ARCHIVES.items():
  54. plugin = deployment.get(component)
  55. if not isinstance(plugin, dict):
  56. raise ValueError(f"deployment.{component} must be a mapping")
  57. if plugin.get("archive_format") != archive_format:
  58. errors.append(f"{component} archive format is invalid")
  59. if not isinstance(plugin.get("bundle_paths"), dict) or not plugin["bundle_paths"]:
  60. errors.append(f"{component} bundle paths are invalid")
  61. tag = namlv2.get("tag")
  62. match = NAM_RELEASE_ASSET.fullmatch(namlv2.get("archive_url", ""))
  63. if namlv2.get("source_url") != "https://github.com/mikeoliphant/neural-amp-modeler-lv2":
  64. errors.append("NAM LV2 source URL is invalid")
  65. if not isinstance(tag, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", tag):
  66. errors.append("NAM LV2 tag is invalid")
  67. if match is None or match.group("tag") != tag:
  68. errors.append("NAM LV2 URL must be the approved release asset for the declared tag")
  69. if namlv2.get("bundle_directory") != "neural_amp_modeler.lv2":
  70. errors.append("NAM LV2 bundle directory is invalid")
  71. if namlv2.get("backup_directory") != ".local/state/rigforge/namlv2-backups":
  72. errors.append("NAM LV2 backup directory is invalid")
  73. source = pipewire.get("fragment_source")
  74. if source != "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf":
  75. errors.append("PipeWire fragment source is invalid")
  76. if pipewire.get("fragment_destination") != ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf":
  77. errors.append("PipeWire fragment destination is invalid")
  78. if pipewire.get("user_service") != "filter-chain.service":
  79. errors.append("PipeWire user service is invalid")
  80. if errors:
  81. raise ValueError("; ".join(errors))
  82. return deployment
  83. def read_registry():
  84. if not STATE_PATH.exists():
  85. return {}
  86. with STATE_PATH.open(encoding="utf-8") as stream:
  87. registry = json.load(stream)
  88. if not isinstance(registry, dict):
  89. raise ValueError(f"deployment registry is not a mapping: {STATE_PATH}")
  90. return registry
  91. def write_registry(registry):
  92. STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
  93. fd, temporary_name = tempfile.mkstemp(prefix="deployment.", dir=STATE_PATH.parent)
  94. try:
  95. with os.fdopen(fd, "w", encoding="utf-8") as stream:
  96. json.dump(registry, stream, indent=2, sort_keys=True)
  97. stream.write("\n")
  98. os.replace(temporary_name, STATE_PATH)
  99. finally:
  100. if os.path.exists(temporary_name):
  101. os.unlink(temporary_name)
  102. def run(command):
  103. subprocess.run(command, check=True)
  104. def tree_sha256(path):
  105. digest = hashlib.sha256()
  106. for item in sorted(path.rglob("*")):
  107. relative = item.relative_to(path).as_posix().encode()
  108. digest.update(relative + b"\\0")
  109. if item.is_symlink():
  110. digest.update(b"link\\0" + os.readlink(item).encode())
  111. elif item.is_file():
  112. digest.update(b"file\\0" + item.read_bytes())
  113. elif item.is_dir():
  114. digest.update(b"directory\\0")
  115. else:
  116. raise RuntimeError(f"unsupported file type in managed bundle: {item}")
  117. return digest.hexdigest()
  118. def runtime_tree_sha256(path):
  119. digest = hashlib.sha256()
  120. for item in sorted(path.rglob("*")):
  121. if "__pycache__" in item.parts or item.suffix in {".pyc", ".pyo"}:
  122. continue
  123. relative = item.relative_to(path).as_posix().encode()
  124. digest.update(relative + b"\0")
  125. if item.is_symlink():
  126. digest.update(b"link\0" + os.readlink(item).encode())
  127. elif item.is_file():
  128. digest.update(b"file\0" + item.read_bytes())
  129. elif item.is_dir():
  130. digest.update(b"directory\0")
  131. else:
  132. raise RuntimeError(f"unsupported file type in runtime bundle: {item}")
  133. return digest.hexdigest()
  134. def validate_user_destination(destination):
  135. home = Path.home().resolve()
  136. parent = destination.parent.resolve()
  137. if not parent.is_relative_to(home):
  138. raise RuntimeError(f"deployment path escapes the user home directory: {destination}")
  139. if destination.is_symlink():
  140. raise RuntimeError(f"refusing to manage a symlink destination: {destination}")
  141. def validate_backup_path(backup, destination, is_directory=False):
  142. if backup is None:
  143. return None
  144. backup_path = Path(backup)
  145. expected = destination.with_name(destination.name + ".rigforge-backup")
  146. if backup_path != expected:
  147. raise RuntimeError(f"recorded backup path is outside its approved location: {backup_path}")
  148. if backup_path.is_symlink():
  149. raise RuntimeError(f"recorded backup must not be a symlink: {backup_path}")
  150. if backup_path.exists() and backup_path.is_dir() != is_directory:
  151. raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
  152. return backup_path
  153. def namlv2_backup_path(config, destination):
  154. relative = PurePosixPath(config.get("backup_directory", ""))
  155. if relative.is_absolute() or ".." in relative.parts or not relative.parts:
  156. raise RuntimeError("NAM LV2 backup directory must be a safe relative path")
  157. home = Path.home().resolve()
  158. backup_root = (home / Path(*relative.parts)).resolve()
  159. if not backup_root.is_relative_to(home):
  160. raise RuntimeError("NAM LV2 backup directory escapes the user home directory")
  161. backup = backup_root / f"{destination.name}.rigforge-backup"
  162. validate_user_destination(backup)
  163. return backup
  164. def validate_nam_backup_path(backup, destination, config):
  165. if backup is None:
  166. return None
  167. backup_path = Path(backup)
  168. approved = {
  169. destination.with_name(destination.name + ".rigforge-backup"),
  170. namlv2_backup_path(config, destination),
  171. }
  172. if backup_path not in approved:
  173. raise RuntimeError(f"recorded NAM LV2 backup path is outside approved locations: {backup_path}")
  174. if backup_path.is_symlink():
  175. raise RuntimeError(f"recorded NAM LV2 backup must not be a symlink: {backup_path}")
  176. if backup_path.exists() and not backup_path.is_dir():
  177. raise RuntimeError(f"recorded NAM LV2 backup has the wrong type: {backup_path}")
  178. return backup_path
  179. def migrate_namlv2_backup(config, backup, destination, backup_sha256):
  180. """Move legacy in-~/.lv2 backups out of Lilv's plugin search path."""
  181. if backup is None or not backup.exists():
  182. return backup
  183. target = namlv2_backup_path(config, destination)
  184. if backup == target:
  185. return backup
  186. legacy = destination.with_name(destination.name + ".rigforge-backup")
  187. if backup != legacy:
  188. return backup
  189. if tree_sha256(backup) != backup_sha256:
  190. raise RuntimeError(f"recorded NAM LV2 backup changed locally: {backup}")
  191. if target.exists() or target.is_symlink():
  192. raise RuntimeError(f"NAM LV2 backup destination already exists: {target}")
  193. target.parent.mkdir(parents=True, exist_ok=True)
  194. os.replace(backup, target)
  195. return target
  196. def atomic_install(source, destination):
  197. destination.parent.mkdir(parents=True, exist_ok=True)
  198. fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent)
  199. os.close(fd)
  200. try:
  201. shutil.copyfile(source, temporary_name)
  202. shutil.copymode(source, temporary_name)
  203. os.replace(temporary_name, destination)
  204. finally:
  205. if os.path.exists(temporary_name):
  206. os.unlink(temporary_name)
  207. def apply_quantum(frames):
  208. run(["pw-metadata", "-n", "settings", "0", "clock.force-quantum", str(frames)])
  209. def restart_filter_service(service):
  210. run(["systemctl", "--user", "restart", service])
  211. run(["systemctl", "--user", "is-active", "--quiet", service])
  212. def deploy_pipewire(action, config, registry, quantum_frames):
  213. destination = Path.home() / config["fragment_destination"]
  214. validate_user_destination(destination)
  215. source = ROOT / config["fragment_source"]
  216. managed = registry.get("pipewire")
  217. pending_reload = registry.get("pipewire_pending_reload")
  218. if pending_reload is not None:
  219. apply_quantum(pending_reload["quantum_frames"])
  220. restart_filter_service(config["user_service"])
  221. registry.pop("pipewire_pending_reload")
  222. write_registry(registry)
  223. managed = registry.get("pipewire")
  224. if action == "reload":
  225. if not source.is_file() or not destination.is_file():
  226. raise RuntimeError("PipeWire reload requires both the repository fragment and installed fragment")
  227. apply_quantum(quantum_frames)
  228. restart_filter_service(config["user_service"])
  229. print("PipeWire runtime quantum applied; filter-chain user service restarted.")
  230. return
  231. if action == "install":
  232. if managed is not None and managed.get("pending_uninstall"):
  233. raise RuntimeError("PipeWire uninstall is incomplete; retry uninstall pipewire first")
  234. if managed is not None:
  235. validate_backup_path(managed.get("backup"), destination)
  236. if not destination.exists():
  237. raise RuntimeError(f"managed PipeWire fragment is missing: {destination}")
  238. if managed is not None and destination.exists():
  239. current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  240. if current_digest != managed["installed_sha256"]:
  241. raise RuntimeError(f"managed file changed locally; refusing overwrite: {destination}")
  242. was_unmanaged = managed is None
  243. changed = not destination.exists() or destination.read_bytes() != source.read_bytes()
  244. if managed is None:
  245. backup_path = None
  246. backup_sha256 = None
  247. if destination.exists():
  248. backup_path = str(destination.with_name(destination.name + ".rigforge-backup"))
  249. if Path(backup_path).exists():
  250. raise RuntimeError(f"backup path already exists: {backup_path}")
  251. shutil.copy2(destination, backup_path)
  252. backup_sha256 = hashlib.sha256(Path(backup_path).read_bytes()).hexdigest()
  253. managed = {
  254. "installed_sha256": "",
  255. "backup": backup_path,
  256. "backup_sha256": backup_sha256,
  257. }
  258. registry["pipewire"] = managed
  259. if changed:
  260. atomic_install(source, destination)
  261. managed["installed_sha256"] = hashlib.sha256(source.read_bytes()).hexdigest()
  262. managed["pending_reload"] = changed or was_unmanaged or managed.get("pending_reload", False)
  263. registry["pipewire"] = managed
  264. write_registry(registry)
  265. apply_quantum(quantum_frames)
  266. if managed["pending_reload"]:
  267. restart_filter_service(config["user_service"])
  268. managed.pop("pending_reload", None)
  269. registry["pipewire"] = managed
  270. write_registry(registry)
  271. print(f"PipeWire fragment {'updated' if changed else 'already current'} at {destination}.")
  272. return
  273. if action == "uninstall":
  274. if managed is None:
  275. print("No managed PipeWire fragment to uninstall.")
  276. return
  277. if managed.get("pending_uninstall"):
  278. backup_path = validate_backup_path(managed.get("backup"), destination)
  279. backup_exists = backup_path is not None and backup_path.is_file()
  280. if backup_path is not None and backup_path.exists():
  281. if not backup_exists:
  282. raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
  283. backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
  284. if backup_digest != managed.get("backup_sha256"):
  285. raise RuntimeError(f"recorded backup changed locally: {backup_path}")
  286. if destination.exists():
  287. current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  288. if backup_exists and current_digest == managed.get("backup_sha256"):
  289. backup_path.unlink()
  290. elif backup_path is not None and not backup_exists and current_digest == managed.get("backup_sha256"):
  291. pass
  292. elif current_digest == managed.get("installed_sha256"):
  293. destination.unlink()
  294. if backup_exists:
  295. os.replace(backup_path, destination)
  296. elif backup_path is not None:
  297. raise RuntimeError(f"recorded backup is missing: {backup_path}")
  298. else:
  299. raise RuntimeError(f"unexpected file blocks pending uninstall: {destination}")
  300. elif backup_exists:
  301. os.replace(backup_path, destination)
  302. elif backup_path is not None:
  303. raise RuntimeError(f"recorded backup is missing: {backup_path}")
  304. registry.pop("pipewire")
  305. write_registry(registry)
  306. apply_quantum(0)
  307. restart_filter_service(config["user_service"])
  308. print("Completed interrupted PipeWire uninstall and restored prior state.")
  309. return
  310. if not destination.exists():
  311. raise RuntimeError(f"managed PipeWire fragment is missing: {destination}")
  312. current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  313. if current_digest != managed["installed_sha256"]:
  314. raise RuntimeError(f"managed file changed locally; refusing to remove: {destination}")
  315. backup_path = validate_backup_path(managed.get("backup"), destination)
  316. if backup_path is not None and not backup_path.is_file():
  317. raise RuntimeError(f"recorded backup is missing: {backup_path}")
  318. if backup_path is not None:
  319. backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
  320. if backup_digest != managed.get("backup_sha256"):
  321. raise RuntimeError(f"recorded backup changed locally: {backup_path}")
  322. managed["pending_uninstall"] = True
  323. registry["pipewire"] = managed
  324. write_registry(registry)
  325. destination.unlink()
  326. if backup_path is not None:
  327. atomic_install(backup_path, destination)
  328. backup_path.unlink()
  329. registry.pop("pipewire")
  330. registry["pipewire_pending_reload"] = {"quantum_frames": 0}
  331. write_registry(registry)
  332. apply_quantum(0)
  333. restart_filter_service(config["user_service"])
  334. registry.pop("pipewire_pending_reload")
  335. write_registry(registry)
  336. print("Rigforge PipeWire fragment removed or prior file restored; quantum reset to automatic.")
  337. return
  338. def inspect_archive(archive_path, bundle_name):
  339. with tarfile.open(archive_path, "r:gz") as archive:
  340. members = archive.getmembers()
  341. bundle_prefix = PurePosixPath(bundle_name)
  342. matching = []
  343. for member in members:
  344. member_path = PurePosixPath(member.name)
  345. if member_path.is_absolute() or ".." in member_path.parts:
  346. raise RuntimeError(f"unsafe archive path: {member.name}")
  347. if member_path.parts and member_path.parts[0] == bundle_prefix.name:
  348. if not member_path.is_relative_to(bundle_prefix):
  349. raise RuntimeError(f"unexpected bundle path: {member.name}")
  350. if not (member.isdir() or member.isfile()):
  351. raise RuntimeError(f"unsupported archive member type: {member.name}")
  352. matching.append(member)
  353. else:
  354. raise RuntimeError(f"unexpected archive path: {member.name}")
  355. if not matching or not any(member.name == bundle_name and member.isdir() for member in matching):
  356. raise RuntimeError(f"archive does not contain expected bundle directory {bundle_name}")
  357. return members
  358. def extract_bundle(archive_path, destination, bundle_name):
  359. with tarfile.open(archive_path, "r:gz") as archive:
  360. members = inspect_archive(archive_path, bundle_name)
  361. for member in members:
  362. member_path = PurePosixPath(member.name)
  363. relative_parts = member_path.parts[1:]
  364. output_path = destination.joinpath(*relative_parts) if relative_parts else destination
  365. if member.isdir():
  366. output_path.mkdir(parents=True, exist_ok=True)
  367. output_path.chmod(0o755)
  368. continue
  369. output_path.parent.mkdir(parents=True, exist_ok=True)
  370. extracted = archive.extractfile(member)
  371. if extracted is None:
  372. raise RuntimeError(f"unable to read archive member: {member.name}")
  373. with extracted, output_path.open("wb") as output:
  374. shutil.copyfileobj(extracted, output)
  375. output_path.chmod(0o755 if member.mode & 0o111 else 0o644)
  376. def download_archive(url, destination):
  377. run(["curl", "--fail", "--location", "--silent", "--show-error", "--output", str(destination), url])
  378. def inspect_tar_archive(archive_path, bundle_paths):
  379. expected_roots = {PurePosixPath(path) for path in bundle_paths.values()}
  380. with tarfile.open(archive_path, "r:xz") as archive:
  381. members = archive.getmembers()
  382. for member in members:
  383. member_path = PurePosixPath(member.name)
  384. if member_path.is_absolute() or ".." in member_path.parts:
  385. raise RuntimeError(f"unsafe archive path: {member.name}")
  386. if not member.isfile() and not member.isdir():
  387. raise RuntimeError(f"unsupported archive member type: {member.name}")
  388. for bundle_root in expected_roots:
  389. if not any(member.name.rstrip("/") == str(bundle_root) and member.isdir() for member in members):
  390. raise RuntimeError(f"archive does not contain expected bundle directory {bundle_root}")
  391. if not any(member.name == f"{bundle_root}/manifest.ttl" and member.isfile() for member in members):
  392. raise RuntimeError(f"archive bundle is missing manifest.ttl: {bundle_root}")
  393. return expected_roots
  394. def extract_tar_bundles(archive_path, bundle_paths, extraction_root):
  395. expected_roots = inspect_tar_archive(archive_path, bundle_paths)
  396. extracted = {bundle_name: extraction_root / bundle_name for bundle_name in bundle_paths}
  397. with tarfile.open(archive_path, "r:xz") as archive:
  398. for member in archive.getmembers():
  399. member_path = PurePosixPath(member.name)
  400. bundle_root = next(
  401. (root for root in expected_roots if member_path == root or member_path.is_relative_to(root)),
  402. None,
  403. )
  404. if bundle_root is None:
  405. continue
  406. bundle_name = next(name for name, path in bundle_paths.items() if PurePosixPath(path) == bundle_root)
  407. output_path = extracted[bundle_name].joinpath(*member_path.parts[len(bundle_root.parts):])
  408. if member.isdir():
  409. output_path.mkdir(parents=True, exist_ok=True)
  410. output_path.chmod(0o755)
  411. continue
  412. output_path.parent.mkdir(parents=True, exist_ok=True)
  413. source = archive.extractfile(member)
  414. if source is None:
  415. raise RuntimeError(f"unable to read archive member: {member.name}")
  416. with source, output_path.open("wb") as destination:
  417. shutil.copyfileobj(source, destination)
  418. output_path.chmod(0o755 if member.mode & 0o111 else 0o644)
  419. return extracted
  420. def inspect_7z_archive(bundle_paths, listing):
  421. paths = []
  422. current = {}
  423. for line in listing.splitlines() + [""]:
  424. if not line and current:
  425. path = current.get("Path")
  426. attributes = current.get("Attributes", "")
  427. if path and attributes:
  428. member_path = PurePosixPath(path)
  429. if member_path.is_absolute() or ".." in member_path.parts:
  430. raise RuntimeError(f"unsafe archive path: {path}")
  431. if "L" in attributes or "H" in attributes:
  432. raise RuntimeError(f"unsupported archive member type: {path}")
  433. paths.append((member_path, "D" in attributes))
  434. current = {}
  435. elif " = " in line:
  436. key, value = line.split(" = ", 1)
  437. current[key] = value
  438. expected_roots = {PurePosixPath(path) for path in bundle_paths.values()}
  439. present_roots = {path for path, is_directory in paths if is_directory and path in expected_roots}
  440. if present_roots != expected_roots:
  441. raise RuntimeError(f"7z archive is missing expected LV2 bundles: {sorted(map(str, expected_roots - present_roots))}")
  442. for root in expected_roots:
  443. if not any(path == root / "manifest.ttl" and not is_directory for path, is_directory in paths):
  444. raise RuntimeError(f"7z archive bundle is missing manifest.ttl: {root}")
  445. return expected_roots, paths
  446. def extract_7z_bundles(archive_path, bundle_paths, extraction_root):
  447. executable = shutil.which("7z") or shutil.which("7zz") or shutil.which("7za")
  448. if executable is None:
  449. raise RuntimeError("installing LSP plugins requires 7z, 7zz, or 7za on PATH")
  450. listing = subprocess.run(
  451. [executable, "l", "-slt", str(archive_path)],
  452. check=True,
  453. capture_output=True,
  454. text=True,
  455. ).stdout
  456. expected_roots, paths = inspect_7z_archive(bundle_paths, listing)
  457. temporary_output = extraction_root / "7z-output"
  458. temporary_output.mkdir()
  459. result = subprocess.run(
  460. [executable, "x", "-y", f"-o{temporary_output}", str(archive_path)],
  461. check=False,
  462. capture_output=True,
  463. text=True,
  464. )
  465. if result.returncode != 0:
  466. missing_files = [
  467. path
  468. for path, is_directory in paths
  469. if not is_directory
  470. and any(path.is_relative_to(root) for root in expected_roots)
  471. and not temporary_output.joinpath(*path.parts).is_file()
  472. ]
  473. if missing_files:
  474. raise subprocess.CalledProcessError(
  475. result.returncode,
  476. result.args,
  477. output=result.stdout,
  478. stderr=result.stderr,
  479. )
  480. extracted = {}
  481. for bundle_name, path in bundle_paths.items():
  482. bundle_root = PurePosixPath(path)
  483. source = temporary_output.joinpath(*bundle_root.parts)
  484. if not source.is_dir():
  485. raise RuntimeError(f"expected LV2 bundle missing after extraction: {source}")
  486. target = extraction_root / bundle_name
  487. shutil.copytree(source, target, symlinks=False)
  488. extracted[bundle_name] = target
  489. return extracted
  490. def deploy_lv2_archives(action, component, config, registry):
  491. bundle_paths = config["bundle_paths"]
  492. bundle_names = list(bundle_paths)
  493. destinations = {name: Path.home() / ".lv2" / name for name in bundle_names}
  494. for destination in destinations.values():
  495. validate_user_destination(destination)
  496. managed = registry.get(component)
  497. if action == "reload":
  498. print(f"Nothing to reload for {component}; restart its LV2 host after installation.")
  499. return
  500. if action == "uninstall":
  501. if managed is None:
  502. print(f"No managed {component} bundles to uninstall.")
  503. return
  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. if managed.get("pending_uninstall"):
  508. for name, destination in destinations.items():
  509. record = recorded[name]
  510. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  511. backup_exists = backup is not None and backup.is_dir()
  512. if backup is not None and backup.exists() and not backup_exists:
  513. raise RuntimeError(f"recorded backup has the wrong type: {backup}")
  514. if backup_exists and tree_sha256(backup) != record.get("backup_sha256"):
  515. raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
  516. if destination.exists():
  517. current = tree_sha256(destination)
  518. if backup_exists and current == record.get("backup_sha256"):
  519. continue
  520. if backup is None and record.get("backup_sha256") is None:
  521. if current == record.get("installed_sha256"):
  522. continue
  523. raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
  524. if not backup_exists and current == record.get("backup_sha256"):
  525. continue
  526. if current != record.get("installed_sha256"):
  527. raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
  528. elif backup is not None and not backup_exists:
  529. raise RuntimeError(f"recorded backup bundle is missing: {backup}")
  530. for name, destination in destinations.items():
  531. record = recorded[name]
  532. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  533. backup_exists = backup is not None and backup.is_dir()
  534. if destination.exists() and tree_sha256(destination) == record.get("installed_sha256"):
  535. shutil.rmtree(destination)
  536. if backup_exists:
  537. os.replace(backup, destination)
  538. registry.pop(component)
  539. write_registry(registry)
  540. print(f"Completed interrupted {component} uninstall at {Path.home() / '.lv2'}.")
  541. return
  542. for name, destination in destinations.items():
  543. record = recorded[name]
  544. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  545. if not destination.is_dir():
  546. raise RuntimeError(f"managed {component} bundle is missing: {destination}")
  547. if record.get("installed_path") != str(destination):
  548. raise RuntimeError(f"managed {component} path changed: {destination}")
  549. if tree_sha256(destination) != record.get("installed_sha256"):
  550. raise RuntimeError(f"managed {component} bundle changed locally; refusing to remove: {destination}")
  551. if backup is not None:
  552. if not backup.is_dir():
  553. raise RuntimeError(f"recorded backup bundle is missing: {backup}")
  554. if tree_sha256(backup) != record.get("backup_sha256"):
  555. raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
  556. managed["pending_uninstall"] = True
  557. registry[component] = managed
  558. write_registry(registry)
  559. for name, destination in destinations.items():
  560. record = recorded[name]
  561. shutil.rmtree(destination)
  562. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  563. if backup is not None:
  564. os.replace(backup, destination)
  565. registry.pop(component)
  566. write_registry(registry)
  567. print(f"Removed managed {component} bundles from {Path.home() / '.lv2'}.")
  568. return
  569. if managed is not None:
  570. if managed.get("pending_uninstall"):
  571. raise RuntimeError(f"{component} uninstall is incomplete; retry uninstall {component} first")
  572. recorded = managed.get("bundles")
  573. if not isinstance(recorded, dict) or set(recorded) != set(bundle_names):
  574. raise RuntimeError(f"managed {component} bundle declaration changed")
  575. for name, destination in destinations.items():
  576. record = recorded[name]
  577. backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
  578. if backup is not None:
  579. if not backup.is_dir() or tree_sha256(backup) != record.get("backup_sha256"):
  580. raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
  581. if not destination.is_dir():
  582. raise RuntimeError(f"managed {component} bundle is missing: {destination}")
  583. if tree_sha256(destination) != record.get("installed_sha256"):
  584. raise RuntimeError(f"managed {component} bundle changed locally; refusing overwrite: {destination}")
  585. if managed.get("tag") == config["tag"]:
  586. print(f"{component} tag {config['tag']} is already installed and unchanged.")
  587. return
  588. for name, destination in destinations.items():
  589. previous = managed.get("bundles", {}).get(name) if managed else None
  590. if previous is not None:
  591. backup = validate_backup_path(previous.get("backup"), destination, is_directory=True)
  592. if backup is not None:
  593. if not backup.is_dir():
  594. raise RuntimeError(f"recorded backup bundle is missing: {backup}")
  595. if tree_sha256(backup) != previous.get("backup_sha256"):
  596. raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
  597. if previous is None and destination.exists():
  598. backup = destination.with_name(destination.name + ".rigforge-backup")
  599. if backup.exists():
  600. raise RuntimeError(f"backup path already exists: {backup}")
  601. staged = destination.with_name(destination.name + ".rigforge-new")
  602. previous_path = destination.with_name(destination.name + ".rigforge-old")
  603. if staged.exists() or previous_path.exists():
  604. raise RuntimeError(f"{component} staging or recovery path already exists: {destination}")
  605. with tempfile.TemporaryDirectory(prefix=f"rigforge-{component}-") as temporary_dir:
  606. temporary = Path(temporary_dir)
  607. archive_path = temporary / (
  608. "plugin.tar.xz" if config["archive_format"] == "tar.xz" else "plugin.7z"
  609. )
  610. download_archive(config["archive_url"], archive_path)
  611. archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()
  612. extraction_root = temporary / "extract"
  613. extraction_root.mkdir()
  614. if config["archive_format"] == "tar.xz":
  615. extracted = extract_tar_bundles(archive_path, config["bundle_paths"], extraction_root)
  616. else:
  617. extracted = extract_7z_bundles(archive_path, config["bundle_paths"], extraction_root)
  618. records = {}
  619. created_backups = []
  620. installed_destinations = []
  621. try:
  622. for name, destination in destinations.items():
  623. previous = managed.get("bundles", {}).get(name) if managed else None
  624. backup = (
  625. validate_backup_path(previous.get("backup"), destination, is_directory=True)
  626. if previous is not None
  627. else destination.with_name(destination.name + ".rigforge-backup")
  628. if destination.exists()
  629. else None
  630. )
  631. backup_digest = previous.get("backup_sha256") if previous is not None else None
  632. if backup is not None and previous is None:
  633. shutil.copytree(destination, backup, symlinks=True)
  634. created_backups.append(backup)
  635. backup_digest = tree_sha256(backup)
  636. destination.parent.mkdir(parents=True, exist_ok=True)
  637. staged = destination.with_name(destination.name + ".rigforge-new")
  638. previous_path = destination.with_name(destination.name + ".rigforge-old")
  639. shutil.copytree(extracted[name], staged, symlinks=False)
  640. try:
  641. if destination.exists():
  642. os.replace(destination, previous_path)
  643. os.replace(staged, destination)
  644. installed_destinations.append((destination, previous_path))
  645. except OSError:
  646. if previous_path.exists() and not destination.exists():
  647. os.replace(previous_path, destination)
  648. if staged.exists():
  649. shutil.rmtree(staged)
  650. raise
  651. records[name] = {
  652. "installed_path": str(destination),
  653. "backup": str(backup) if backup is not None else None,
  654. "backup_sha256": backup_digest,
  655. "installed_sha256": tree_sha256(destination),
  656. }
  657. for _, previous_path in installed_destinations:
  658. if previous_path.exists():
  659. shutil.rmtree(previous_path)
  660. except (OSError, shutil.Error):
  661. for destination, previous_path in reversed(installed_destinations):
  662. if destination.exists():
  663. shutil.rmtree(destination)
  664. if previous_path.exists():
  665. os.replace(previous_path, destination)
  666. for destination in destinations.values():
  667. staged = destination.with_name(destination.name + ".rigforge-new")
  668. if staged.exists():
  669. shutil.rmtree(staged)
  670. for backup in created_backups:
  671. if backup.exists():
  672. shutil.rmtree(backup)
  673. raise
  674. registry[component] = {
  675. "tag": config["tag"],
  676. "archive_sha256": archive_digest,
  677. "bundles": records,
  678. }
  679. write_registry(registry)
  680. print(f"Installed {component} tag {config['tag']} under {Path.home() / '.lv2'}.")
  681. print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}")
  682. def deploy_namlv2(action, config, registry):
  683. bundle_name = config["bundle_directory"]
  684. destination = Path.home() / ".lv2" / bundle_name
  685. validate_user_destination(destination)
  686. managed = registry.get("namlv2")
  687. artifact_directory = config.get("artifact_directory")
  688. artifact_bundle = None
  689. artifact_digest = None
  690. if artifact_directory is not None:
  691. relative = PurePosixPath(artifact_directory)
  692. if relative.is_absolute() or ".." in relative.parts or not relative.parts:
  693. raise RuntimeError("NAM LV2 artifact directory must be a safe repository path")
  694. artifact_root = (ROOT / Path(*relative.parts)).resolve()
  695. if not artifact_root.is_relative_to(ROOT.resolve()):
  696. raise RuntimeError("NAM LV2 artifact directory escapes the repository")
  697. artifact_bundle = artifact_root / bundle_name
  698. provenance_path = artifact_root / "provenance.json"
  699. if not artifact_bundle.is_dir() or not provenance_path.is_file():
  700. raise FileNotFoundError(
  701. f"built NAM LV2 artifact is missing: {artifact_bundle}"
  702. )
  703. with provenance_path.open(encoding="utf-8") as stream:
  704. provenance = json.load(stream)
  705. if (
  706. provenance.get("source_url") != "https://github.com/mikeoliphant/neural-amp-modeler-lv2"
  707. or provenance.get("tag") != config["tag"]
  708. or provenance.get("linkage") != "system libstdc++ and libgcc_s"
  709. ):
  710. raise RuntimeError("built NAM LV2 artifact provenance does not match desired state")
  711. plugin_binary = artifact_bundle / "neural_amp_modeler.so"
  712. if (
  713. not (artifact_bundle / "manifest.ttl").is_file()
  714. or not (artifact_bundle / "neural_amp_modeler.ttl").is_file()
  715. or not plugin_binary.is_file()
  716. or file_sha256(plugin_binary) != provenance.get("artifact_sha256")
  717. ):
  718. raise RuntimeError("built NAM LV2 artifact failed its provenance check")
  719. artifact_digest = tree_sha256(artifact_bundle)
  720. if action == "reload":
  721. print("Nothing to reload for the NAM LV2 plugin; restart mod-host after installation.")
  722. return
  723. if action == "uninstall":
  724. if managed is None:
  725. print("No managed NAM LV2 bundle to uninstall.")
  726. return
  727. if managed.get("pending_uninstall"):
  728. backup_path = validate_nam_backup_path(
  729. managed.get("backup"), destination, config
  730. )
  731. backup_exists = backup_path is not None and backup_path.is_dir()
  732. if backup_path is not None and backup_path.exists() and not backup_exists:
  733. raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
  734. if backup_exists and tree_sha256(backup_path) != managed.get("backup_sha256"):
  735. raise RuntimeError(f"recorded backup bundle changed locally: {backup_path}")
  736. if destination.exists():
  737. destination_digest = tree_sha256(destination)
  738. if backup_exists and destination_digest == managed.get("backup_sha256"):
  739. shutil.rmtree(backup_path)
  740. elif destination_digest == managed.get("installed_sha256"):
  741. shutil.rmtree(destination)
  742. if backup_exists:
  743. os.replace(backup_path, destination)
  744. else:
  745. raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
  746. elif backup_exists:
  747. os.replace(backup_path, destination)
  748. elif backup_path is not None:
  749. raise RuntimeError(f"recorded backup bundle is missing: {backup_path}")
  750. registry.pop("namlv2")
  751. write_registry(registry)
  752. print(f"Completed interrupted NAM LV2 uninstall at {destination}.")
  753. return
  754. if not destination.exists():
  755. raise RuntimeError(f"managed NAM LV2 bundle is missing: {destination}")
  756. if managed.get("installed_path") != str(destination):
  757. raise RuntimeError(f"managed NAM LV2 path changed: {destination}")
  758. if tree_sha256(destination) != managed.get("installed_sha256"):
  759. raise RuntimeError(f"managed NAM LV2 bundle changed locally; refusing to remove: {destination}")
  760. backup_path = validate_nam_backup_path(
  761. managed.get("backup"), destination, config
  762. )
  763. if backup_path is not None and not backup_path.is_dir():
  764. raise RuntimeError(f"recorded backup bundle is missing: {backup_path}")
  765. if backup_path is not None and tree_sha256(backup_path) != managed.get("backup_sha256"):
  766. raise RuntimeError(f"recorded backup bundle changed locally: {backup_path}")
  767. managed["pending_uninstall"] = True
  768. registry["namlv2"] = managed
  769. write_registry(registry)
  770. shutil.rmtree(destination)
  771. if backup_path is not None:
  772. os.replace(backup_path, destination)
  773. registry.pop("namlv2")
  774. write_registry(registry)
  775. print(f"Removed managed NAM LV2 bundle from {destination}.")
  776. return
  777. if managed is not None:
  778. if managed.get("pending_uninstall"):
  779. raise RuntimeError("NAM LV2 uninstall is incomplete; retry uninstall namlv2 first")
  780. if not destination.is_dir():
  781. raise RuntimeError(f"managed NAM LV2 bundle is missing: {destination}")
  782. if tree_sha256(destination) != managed.get("installed_sha256"):
  783. raise RuntimeError(f"managed NAM LV2 bundle changed locally; refusing overwrite: {destination}")
  784. backup = validate_nam_backup_path(managed.get("backup"), destination, config)
  785. backup_sha256 = managed.get("backup_sha256")
  786. if backup is not None:
  787. backup = migrate_namlv2_backup(
  788. config, backup, destination, backup_sha256
  789. )
  790. managed["backup"] = str(backup)
  791. registry["namlv2"] = managed
  792. write_registry(registry)
  793. if managed.get("tag") == config["tag"] and (
  794. artifact_digest is None or managed.get("artifact_sha256") == artifact_digest
  795. ):
  796. print(f"NAM LV2 tag {config['tag']} is already installed and unchanged.")
  797. return
  798. elif destination.exists():
  799. backup = namlv2_backup_path(config, destination)
  800. if backup.exists():
  801. raise RuntimeError(f"backup path already exists: {backup}")
  802. backup_sha256 = None
  803. else:
  804. backup = None
  805. backup_sha256 = None
  806. with tempfile.TemporaryDirectory(prefix="rigforge-namlv2-") as temporary_dir:
  807. temporary = Path(temporary_dir)
  808. archive_digest = None
  809. if artifact_bundle is not None:
  810. extracted_bundle = artifact_bundle
  811. else:
  812. archive_path = temporary / "namlv2.tgz"
  813. download_archive(config["archive_url"], archive_path)
  814. archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()
  815. inspect_archive(archive_path, bundle_name)
  816. extraction_root = temporary / "extract"
  817. extraction_root.mkdir()
  818. extracted_bundle = extraction_root / bundle_name
  819. extracted_bundle.mkdir()
  820. extract_bundle(archive_path, extracted_bundle, bundle_name)
  821. if (
  822. not extracted_bundle.is_dir()
  823. or not (extracted_bundle / "manifest.ttl").is_file()
  824. or not (extracted_bundle / "neural_amp_modeler.so").is_file()
  825. ):
  826. raise RuntimeError(f"expected NAM LV2 bundle missing or incomplete: {extracted_bundle}")
  827. destination.parent.mkdir(parents=True, exist_ok=True)
  828. staged_bundle = destination.with_name(destination.name + ".rigforge-new")
  829. previous_bundle = destination.with_name(destination.name + ".rigforge-old")
  830. if staged_bundle.exists() or previous_bundle.exists():
  831. raise RuntimeError("NAM LV2 staging or recovery path already exists")
  832. backup_created = False
  833. moved_previous = False
  834. try:
  835. shutil.copytree(extracted_bundle, staged_bundle)
  836. if managed is None and backup is not None:
  837. backup.parent.mkdir(parents=True, exist_ok=True)
  838. shutil.copytree(destination, backup)
  839. backup_created = True
  840. backup_sha256 = tree_sha256(backup)
  841. if destination.exists():
  842. os.replace(destination, previous_bundle)
  843. moved_previous = True
  844. os.replace(staged_bundle, destination)
  845. except (OSError, shutil.Error):
  846. if moved_previous and previous_bundle.exists() and not destination.exists():
  847. os.replace(previous_bundle, destination)
  848. if backup_created and backup.exists():
  849. shutil.rmtree(backup)
  850. raise
  851. finally:
  852. if staged_bundle.exists():
  853. shutil.rmtree(staged_bundle)
  854. if previous_bundle.exists():
  855. shutil.rmtree(previous_bundle)
  856. registry["namlv2"] = {
  857. "tag": config["tag"],
  858. "archive_sha256": archive_digest,
  859. "installed_path": str(destination),
  860. "backup": str(backup) if backup is not None else None,
  861. "backup_sha256": backup_sha256,
  862. "installed_sha256": tree_sha256(destination),
  863. }
  864. if artifact_digest is not None:
  865. registry["namlv2"]["artifact_sha256"] = artifact_digest
  866. registry["namlv2"]["build_provenance"] = str(artifact_root / "provenance.json")
  867. write_registry(registry)
  868. print(f"Installed NAM LV2 tag {config['tag']} at {destination}.")
  869. if artifact_digest is not None:
  870. print(f"Installed built NAM LV2 artifact SHA-256: {artifact_digest}")
  871. elif archive_digest is not None:
  872. print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}")
  873. def systemd_quote(value):
  874. value = str(value).replace("%", "%%").replace("\\", "\\\\").replace('"', '\\"')
  875. return f'"{value}"'
  876. def render_mod_host_service(config):
  877. binary = ROOT / config["binary_source"]
  878. service_template = ROOT / config["service_source"]
  879. readiness_script = ROOT / config["readiness_script"]
  880. state_file = ROOT / "config" / "desired-state.yaml"
  881. if not binary.is_file() or not os.access(binary, os.X_OK):
  882. raise RuntimeError(f"ARM64 mod-host artifact is missing or not executable: {binary}")
  883. if not service_template.is_file():
  884. raise RuntimeError(f"mod-host service template is missing: {service_template}")
  885. if not readiness_script.is_file():
  886. raise RuntimeError(f"mod-host PipeWire readiness checker is missing: {readiness_script}")
  887. replacements = {
  888. "@PW_JACK@": systemd_quote(config["pw_jack_path"]),
  889. "@MOD_HOST_BINARY@": systemd_quote(binary.resolve()),
  890. "@SOCKET_PORT@": str(config["socket_port"]),
  891. "@FEEDBACK_PORT@": str(config["feedback_port"]),
  892. "@PYTHON@": systemd_quote(config["python_path"]),
  893. "@READINESS_SCRIPT@": systemd_quote(readiness_script.resolve()),
  894. "@PORT_WAIT_TIMEOUT_SECONDS@": str(config["port_wait_timeout_seconds"]),
  895. "@DESIRED_STATE@": systemd_quote(state_file.resolve()),
  896. }
  897. content = service_template.read_text(encoding="utf-8")
  898. for placeholder, replacement in replacements.items():
  899. content = content.replace(placeholder, replacement)
  900. if re.search(r"@[A-Z_]+@", content):
  901. raise RuntimeError("unexpanded placeholder remains in mod-host service template")
  902. return content.encode("utf-8")
  903. def render_mod_host_ports_service(config):
  904. state_file = ROOT / "config" / "desired-state.yaml"
  905. runner_script = ROOT / config["runner_script"]
  906. service_template = ROOT / config["service_source"]
  907. binary = Path(config["binary_path"])
  908. for description, path in (
  909. ("mod-host port runner", runner_script),
  910. ("mod-host ports service template", service_template),
  911. ):
  912. if not path.is_file():
  913. raise RuntimeError(f"{description} is missing: {path}")
  914. replacements = {
  915. "@PYTHON@": systemd_quote(config["python_path"]),
  916. "@RUNNER_SCRIPT@": systemd_quote(runner_script.resolve()),
  917. "@DESIRED_STATE@": systemd_quote(state_file.resolve()),
  918. "@PW_LOOPBACK@": systemd_quote(binary),
  919. }
  920. content = service_template.read_text(encoding="utf-8")
  921. for placeholder, replacement in replacements.items():
  922. content = content.replace(placeholder, replacement)
  923. if re.search(r"@[A-Z_]+@", content):
  924. raise RuntimeError("unexpanded placeholder remains in mod-host ports service template")
  925. fingerprint = hashlib.sha256(
  926. json.dumps(config, sort_keys=True, separators=(",", ":")).encode("utf-8")
  927. + runner_script.read_bytes()
  928. + (ROOT / "scripts" / "validate_desired_state.py").read_bytes()
  929. + state_file.read_bytes()
  930. ).hexdigest()
  931. return {
  932. "name": config["user_service"],
  933. "destination": Path.home() / config["service_destination"],
  934. "content": (content + f"\n# Rigforge runtime fingerprint: {fingerprint}\n").encode("utf-8"),
  935. }
  936. def render_mod_ui_service(config):
  937. state_file = ROOT / "config" / "desired-state.yaml"
  938. launcher = ROOT / config["launcher"]
  939. runner_script = ROOT / config["runner_script"]
  940. service_template = ROOT / config["service_source"]
  941. with state_file.open(encoding="utf-8") as stream:
  942. state = yaml.safe_load(stream)
  943. nam_processor = state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
  944. nam_model_path = (
  945. Path.home()
  946. / config["user_files_directory"]
  947. / "NAM Models"
  948. / "Rigforge"
  949. / Path(nam_processor["asset_path"]).name
  950. )
  951. reference_files = generate_bundle_files(
  952. state, ROOT, nam_model_path=nam_model_path
  953. )
  954. bundle_digest = hashlib.sha256()
  955. for name, content_bytes in sorted(reference_files.items()):
  956. bundle_digest.update(name.encode("utf-8") + b"\0" + content_bytes + b"\0")
  957. reference_pedalboard = (
  958. Path.home()
  959. / config["reference_directory"]
  960. / f"rigforge-guitar-{bundle_digest.hexdigest()[:16]}.pedalboard"
  961. )
  962. for description, path in (
  963. ("mod-ui launcher", launcher),
  964. ("mod-ui service runner", runner_script),
  965. ("mod-ui service template", service_template),
  966. ):
  967. if not path.is_file():
  968. raise RuntimeError(f"{description} is missing: {path}")
  969. home = Path.home()
  970. replacements = {
  971. "@PYTHON@": systemd_quote(config["python_path"]),
  972. "@RUNNER_SCRIPT@": systemd_quote(runner_script.resolve()),
  973. "@MOD_UI_LAUNCHER@": systemd_quote(launcher.resolve()),
  974. "@PW_JACK@": systemd_quote(config["pw_jack_path"]),
  975. "@WEBSOCKET_HOST@": config["websocket_host"],
  976. "@WEBSOCKET_PORT@": str(config["websocket_port"]),
  977. "@MOD_DATA_DIR@": systemd_quote(home / ".local" / "share" / "rigforge" / "mod-ui"),
  978. "@MOD_LAST_STATE@": systemd_quote(home / config["last_state_file"]),
  979. "@PEDALBOARDS_DIR@": systemd_quote(home / config["pedalboards_directory"]),
  980. "@USER_FILES_DIR@": systemd_quote(home / config["user_files_directory"]),
  981. "@REFERENCE_PEDALBOARD@": systemd_quote(reference_pedalboard),
  982. "@HARDWARE_INPUT_PORTS@": systemd_quote(",".join(config["hardware_input_ports"])),
  983. "@HARDWARE_OUTPUT_PORTS@": systemd_quote(",".join(config["hardware_output_ports"])),
  984. }
  985. content = service_template.read_text(encoding="utf-8")
  986. for placeholder, replacement in replacements.items():
  987. content = content.replace(placeholder, replacement)
  988. if re.search(r"@[A-Z_]+@", content):
  989. raise RuntimeError("unexpanded placeholder remains in mod-ui service template")
  990. artifact_root = ROOT / config["artifact_directory"]
  991. runtime_digest = hashlib.sha256()
  992. runtime_digest.update(runtime_tree_sha256(artifact_root).encode("ascii"))
  993. runtime_digest.update(runner_script.read_bytes())
  994. runtime_digest.update((ROOT / "scripts" / "mod_ui_websocket.py").read_bytes())
  995. runtime_digest.update((ROOT / "scripts" / "generate_mod_ui_pedalboard.py").read_bytes())
  996. for name, content_bytes in sorted(reference_files.items()):
  997. runtime_digest.update(name.encode("utf-8") + b"\0" + content_bytes + b"\0")
  998. content += f"\n# Rigforge runtime fingerprint: {runtime_digest.hexdigest()}\n"
  999. return {
  1000. "name": config["user_service"],
  1001. "destination": home / config["service_destination"],
  1002. "content": content.encode("utf-8"),
  1003. "reference_bundle": reference_pedalboard,
  1004. "reference_files": reference_files,
  1005. }
  1006. def render_reconcile_units(config):
  1007. repository_root = ROOT.resolve()
  1008. state_file = repository_root / "config" / "desired-state.yaml"
  1009. observer_script = repository_root / config["observer_script"]
  1010. service_template = repository_root / config["service_source"]
  1011. timer_template = repository_root / config["timer_source"]
  1012. for description, path in (
  1013. ("PipeWire observer", observer_script),
  1014. ("reconciliation service template", service_template),
  1015. ("reconciliation timer template", timer_template),
  1016. ):
  1017. if not path.is_file():
  1018. raise RuntimeError(f"reconciliation {description} is missing: {path}")
  1019. service_replacements = {
  1020. "@PYTHON@": systemd_quote(config["python_path"]),
  1021. "@OBSERVER_SCRIPT@": systemd_quote(observer_script),
  1022. "@DESIRED_STATE@": systemd_quote(state_file),
  1023. }
  1024. service_content = service_template.read_text(encoding="utf-8")
  1025. for placeholder, replacement in service_replacements.items():
  1026. service_content = service_content.replace(placeholder, replacement)
  1027. if re.search(r"@[A-Z_]+@", service_content):
  1028. raise RuntimeError("unexpanded placeholder remains in reconciliation service template")
  1029. timer_content = timer_template.read_text(encoding="utf-8").replace(
  1030. "@RECONCILE_INTERVAL_SECONDS@",
  1031. str(config["interval_seconds"]),
  1032. )
  1033. if re.search(r"@[A-Z_]+@", timer_content):
  1034. raise RuntimeError("unexpanded placeholder remains in reconciliation timer template")
  1035. return {
  1036. "service": {
  1037. "name": config["user_service"],
  1038. "destination": Path.home() / config["service_destination"],
  1039. "content": service_content.encode("utf-8"),
  1040. },
  1041. "timer": {
  1042. "name": config["user_timer"],
  1043. "destination": Path.home() / config["timer_destination"],
  1044. "content": timer_content.encode("utf-8"),
  1045. },
  1046. }
  1047. def render_midi_bridge_service(config):
  1048. repository_root = ROOT.resolve()
  1049. state_file = repository_root / "config" / "desired-state.yaml"
  1050. bridge_script = repository_root / config["bridge_script"]
  1051. service_template = repository_root / config["service_source"]
  1052. for description, path in (
  1053. ("MIDI action bridge script", bridge_script),
  1054. ("MIDI bridge service template", service_template),
  1055. ):
  1056. if not path.is_file():
  1057. raise RuntimeError(f"{description} is missing: {path}")
  1058. replacements = {
  1059. "@PYTHON@": systemd_quote(config["python_path"]),
  1060. "@BRIDGE_SCRIPT@": systemd_quote(bridge_script),
  1061. "@DESIRED_STATE@": systemd_quote(state_file),
  1062. "@REPOSITORY_ROOT@": systemd_quote(repository_root),
  1063. }
  1064. content = service_template.read_text(encoding="utf-8")
  1065. for placeholder, replacement in replacements.items():
  1066. content = content.replace(placeholder, replacement)
  1067. if re.search(r"@[A-Z_]+@", content):
  1068. raise RuntimeError("unexpanded placeholder remains in MIDI bridge service template")
  1069. fingerprint = hashlib.sha256(
  1070. bridge_script.read_bytes()
  1071. + (ROOT / "scripts" / "mod_ui_websocket.py").read_bytes()
  1072. + (ROOT / "config" / "midi-bindings.yaml").read_bytes()
  1073. + state_file.read_bytes()
  1074. ).hexdigest()
  1075. content += f"\n# Rigforge runtime fingerprint: {fingerprint}\n"
  1076. return {
  1077. "name": config["user_service"],
  1078. "destination": Path.home() / config["service_destination"],
  1079. "content": content.encode("utf-8"),
  1080. }
  1081. def render_sooperlooper_service(config, state):
  1082. repository_root = ROOT.resolve()
  1083. binary = repository_root / config["binary_source"]
  1084. service_template = repository_root / config["service_source"]
  1085. binding_file = repository_root / config["binding_file"]
  1086. for description, path in (
  1087. ("ARM64 SooperLooper artifact", binary),
  1088. ("SooperLooper service template", service_template),
  1089. ("SooperLooper MIDI binding file", binding_file),
  1090. ):
  1091. if not path.is_file():
  1092. raise RuntimeError(f"{description} is missing: {path}")
  1093. if not os.access(binary, os.X_OK):
  1094. raise RuntimeError(f"ARM64 SooperLooper artifact is not executable: {binary}")
  1095. components = state.get("system", {}).get("components", [])
  1096. loopers = [
  1097. component for component in components
  1098. if isinstance(component, dict) and component.get("id") == "looper"
  1099. ] if isinstance(components, list) else []
  1100. if len(loopers) != 1:
  1101. raise RuntimeError("desired state must declare exactly one SooperLooper component")
  1102. loop_count = loopers[0].get("loop_count")
  1103. channels_per_loop = loopers[0].get("channels_per_loop")
  1104. if (
  1105. not isinstance(loop_count, int)
  1106. or isinstance(loop_count, bool)
  1107. or loop_count < 1
  1108. or not isinstance(channels_per_loop, int)
  1109. or isinstance(channels_per_loop, bool)
  1110. or channels_per_loop < 1
  1111. ):
  1112. raise RuntimeError("desired SooperLooper loop and channel counts must be positive integers")
  1113. osc = config["osc"]
  1114. replacements = {
  1115. "@PW_JACK@": systemd_quote(config["pw_jack_path"]),
  1116. "@SOOPERLOOPER_BINARY@": systemd_quote(binary.resolve()),
  1117. "@LOOP_COUNT@": str(loop_count),
  1118. "@CHANNELS_PER_LOOP@": str(channels_per_loop),
  1119. "@TIMEOUT_SECONDS@": str(config["timeout_seconds"]),
  1120. "@BINDING_FILE@": systemd_quote(binding_file.resolve()),
  1121. "@POST_START_DELAY_SECONDS@": str(osc["post_start_delay_seconds"]),
  1122. "@OSCSEND@": systemd_quote(config["oscsend_path"]),
  1123. "@OSC_HOST@": systemd_quote(osc["host"]),
  1124. "@OSC_PORT@": str(osc["port"]),
  1125. "@DISCRETE_PREFADER@": str(osc["discrete_prefader"]),
  1126. }
  1127. content = service_template.read_text(encoding="utf-8")
  1128. for placeholder, replacement in replacements.items():
  1129. content = content.replace(placeholder, replacement)
  1130. if re.search(r"@[A-Z_]+@", content):
  1131. raise RuntimeError("unexpanded placeholder remains in SooperLooper service template")
  1132. return {
  1133. "name": config["user_service"],
  1134. "destination": Path.home() / config["service_destination"],
  1135. "content": content.encode("utf-8"),
  1136. }
  1137. def atomic_install_bytes(content, destination):
  1138. destination.parent.mkdir(parents=True, exist_ok=True)
  1139. fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent)
  1140. try:
  1141. with os.fdopen(fd, "wb") as stream:
  1142. stream.write(content)
  1143. os.chmod(temporary_name, 0o644)
  1144. os.replace(temporary_name, destination)
  1145. finally:
  1146. if os.path.exists(temporary_name):
  1147. os.unlink(temporary_name)
  1148. def deploy_single_user_service(action, registry_key, target_name, display_name, unit, registry):
  1149. destination = unit["destination"]
  1150. service_name = unit["name"]
  1151. validate_user_destination(destination)
  1152. if destination.exists() and not destination.is_file():
  1153. raise RuntimeError(f"{display_name} service destination has the wrong type: {destination}")
  1154. managed = registry.get(registry_key)
  1155. if action == "reload":
  1156. if managed is None:
  1157. raise RuntimeError(
  1158. f"{display_name} is not managed; install {target_name} before reloading it"
  1159. )
  1160. if managed.get("pending_uninstall"):
  1161. raise RuntimeError(
  1162. f"{display_name} uninstall is incomplete; retry uninstall {target_name} first"
  1163. )
  1164. if not destination.is_file():
  1165. raise RuntimeError(f"managed {display_name} service file is missing: {destination}")
  1166. if file_sha256(destination) != managed.get("installed_sha256"):
  1167. raise RuntimeError(f"managed {display_name} service file changed locally: {destination}")
  1168. run(["systemctl", "--user", "restart", service_name])
  1169. run(["systemctl", "--user", "is-active", "--quiet", service_name])
  1170. print(f"Rigforge {display_name} user service restarted.")
  1171. return
  1172. if action == "uninstall":
  1173. if managed is None:
  1174. print(f"No managed {display_name} service to uninstall.")
  1175. return
  1176. backup_path = validate_backup_path(managed.get("backup"), destination)
  1177. backup_digest = managed.get("backup_sha256")
  1178. if backup_path is not None and backup_path.exists():
  1179. if not backup_path.is_file() or file_sha256(backup_path) != backup_digest:
  1180. raise RuntimeError(
  1181. f"recorded {display_name} service backup changed locally: {backup_path}"
  1182. )
  1183. elif backup_path is not None and not managed.get("pending_uninstall"):
  1184. raise RuntimeError(f"recorded {display_name} service backup is missing: {backup_path}")
  1185. if (backup_path is None) != (backup_digest is None):
  1186. raise RuntimeError(f"invalid {display_name} service backup record")
  1187. current_digest = file_sha256(destination)
  1188. recoverable_digests = {managed.get("installed_sha256"), backup_digest, None}
  1189. if managed.get("pending_uninstall"):
  1190. if current_digest not in recoverable_digests:
  1191. raise RuntimeError(f"unexpected file blocks {display_name} uninstall: {destination}")
  1192. elif current_digest != managed.get("installed_sha256"):
  1193. raise RuntimeError(
  1194. f"managed {display_name} service file changed locally; refusing removal: {destination}"
  1195. )
  1196. if (
  1197. backup_path is not None
  1198. and not backup_path.exists()
  1199. and current_digest == managed.get("installed_sha256")
  1200. ):
  1201. raise RuntimeError(
  1202. f"recorded {display_name} service backup is missing; refusing removal: {backup_path}"
  1203. )
  1204. managed["pending_uninstall"] = True
  1205. registry[registry_key] = managed
  1206. write_registry(registry)
  1207. run(["systemctl", "--user", "disable", "--now", service_name])
  1208. if backup_path is not None and current_digest == backup_digest:
  1209. if backup_path.exists():
  1210. backup_path.unlink()
  1211. else:
  1212. if current_digest == managed.get("installed_sha256"):
  1213. destination.unlink()
  1214. elif current_digest is not None:
  1215. raise RuntimeError(f"unexpected file blocks {display_name} uninstall: {destination}")
  1216. if backup_path is not None:
  1217. if backup_path.exists():
  1218. os.replace(backup_path, destination)
  1219. elif file_sha256(destination) != backup_digest:
  1220. raise RuntimeError(
  1221. f"recorded {display_name} service backup is missing: {backup_path}"
  1222. )
  1223. run(["systemctl", "--user", "daemon-reload"])
  1224. registry.pop(registry_key)
  1225. write_registry(registry)
  1226. print(f"Rigforge {display_name} user service removed; prior unit restored if present.")
  1227. return
  1228. content = unit["content"]
  1229. installed_digest = hashlib.sha256(content).hexdigest()
  1230. if managed is not None and managed.get("pending_uninstall"):
  1231. raise RuntimeError(
  1232. f"{display_name} uninstall is incomplete; retry uninstall {target_name} first"
  1233. )
  1234. if managed is None:
  1235. if user_unit_is_active(service_name) or user_unit_is_enabled(service_name):
  1236. raise RuntimeError(
  1237. f"an unmanaged {service_name} is already active or enabled; "
  1238. "inspect it before installing Rigforge's unit"
  1239. )
  1240. backup_path = (
  1241. destination.with_name(destination.name + ".rigforge-backup")
  1242. if destination.is_file()
  1243. else None
  1244. )
  1245. if backup_path is not None and (backup_path.exists() or backup_path.is_symlink()):
  1246. raise RuntimeError(f"backup path already exists: {backup_path}")
  1247. backup = str(backup_path) if destination.is_file() else None
  1248. backup_digest = file_sha256(destination)
  1249. previous_digest = None
  1250. pending_install = True
  1251. else:
  1252. if managed.get("destination") != str(destination):
  1253. raise RuntimeError(f"recorded {display_name} service path changed")
  1254. backup_path = validate_backup_path(managed.get("backup"), destination)
  1255. backup = str(backup_path) if backup_path is not None else None
  1256. backup_digest = managed.get("backup_sha256")
  1257. if (backup_path is None) != (backup_digest is None):
  1258. raise RuntimeError(f"invalid {display_name} service backup record")
  1259. if backup_path is not None and backup_path.exists():
  1260. if not backup_path.is_file() or file_sha256(backup_path) != backup_digest:
  1261. raise RuntimeError(
  1262. f"recorded {display_name} service backup changed locally: {backup_path}"
  1263. )
  1264. elif backup_path is not None and not managed.get("pending_install"):
  1265. raise RuntimeError(f"recorded {display_name} service backup is missing: {backup_path}")
  1266. previous_digest = (
  1267. managed.get("previous_installed_sha256")
  1268. if managed.get("pending_install")
  1269. else managed.get("installed_sha256")
  1270. )
  1271. current_digest = file_sha256(destination)
  1272. if managed.get("pending_install"):
  1273. if current_digest not in {previous_digest, backup_digest, None}:
  1274. raise RuntimeError(
  1275. f"{display_name} service changed locally during interrupted install: {destination}"
  1276. )
  1277. elif current_digest != previous_digest:
  1278. raise RuntimeError(f"managed {display_name} service file changed locally: {destination}")
  1279. pending_install = current_digest != installed_digest
  1280. unit_changed = file_sha256(destination) != installed_digest
  1281. restart_required = managed is None or unit_changed or bool(
  1282. managed and managed.get("pending_activation")
  1283. )
  1284. managed = managed or {}
  1285. managed.update({
  1286. "destination": str(destination),
  1287. "installed_sha256": installed_digest,
  1288. "previous_installed_sha256": previous_digest,
  1289. "backup": backup,
  1290. "backup_sha256": backup_digest,
  1291. "pending_install": pending_install,
  1292. "pending_activation": True,
  1293. })
  1294. registry[registry_key] = managed
  1295. write_registry(registry)
  1296. if backup_path is not None:
  1297. if backup_path.exists():
  1298. if not backup_path.is_file() or file_sha256(backup_path) != backup_digest:
  1299. raise RuntimeError(
  1300. f"recorded {display_name} service backup changed locally: {backup_path}"
  1301. )
  1302. elif file_sha256(destination) == backup_digest:
  1303. shutil.copy2(destination, backup_path)
  1304. else:
  1305. raise RuntimeError(f"recorded {display_name} service backup is missing: {backup_path}")
  1306. if unit_changed:
  1307. atomic_install_bytes(content, destination)
  1308. managed.pop("previous_installed_sha256", None)
  1309. managed.pop("pending_install", None)
  1310. registry[registry_key] = managed
  1311. write_registry(registry)
  1312. run(["systemctl", "--user", "daemon-reload"])
  1313. run(["systemctl", "--user", "enable", service_name])
  1314. run([
  1315. "systemctl",
  1316. "--user",
  1317. "restart" if restart_required else "start",
  1318. service_name,
  1319. ])
  1320. run(["systemctl", "--user", "is-active", "--quiet", service_name])
  1321. managed.pop("pending_activation", None)
  1322. registry[registry_key] = managed
  1323. write_registry(registry)
  1324. print(f"Installed and activated Rigforge {display_name} user service at {destination}.")
  1325. def deploy_midi_bridge(action, config, registry):
  1326. if action == "install" and "mod_ui" not in registry:
  1327. raise RuntimeError("install mod-ui before installing the MIDI bridge")
  1328. unit = render_midi_bridge_service(config)
  1329. deploy_single_user_service(
  1330. action, "midi_bridge", "midi-bridge", "MIDI bridge", unit, registry
  1331. )
  1332. def deploy_mod_host_ports(action, config, registry):
  1333. if action == "uninstall" and (
  1334. "mod_host" in registry or "mod_ui" in registry
  1335. ):
  1336. raise RuntimeError("uninstall mod-ui and mod-host before uninstalling mod-host-ports")
  1337. unit = render_mod_host_ports_service(config)
  1338. deploy_single_user_service(
  1339. action,
  1340. "mod_host_ports",
  1341. "mod-host-ports",
  1342. "mod-host PipeWire ports",
  1343. unit,
  1344. registry,
  1345. )
  1346. def mod_ui_nam_model_sources(state):
  1347. nam = state["routing"]["mod_host_chains"]["guitar"]["processors"][0]
  1348. relative_paths = {nam["asset_path"], *nam.get("available_models", {}).values()}
  1349. sources = {}
  1350. for relative in sorted(relative_paths):
  1351. source = (ROOT / Path(*PurePosixPath(relative).parts)).resolve()
  1352. if not source.is_relative_to(ROOT.resolve()) or not source.is_file():
  1353. raise FileNotFoundError(
  1354. f"declared NAM model is missing or outside repository: {source}"
  1355. )
  1356. if source.name in sources and sources[source.name] != source:
  1357. raise RuntimeError(
  1358. f"declared NAM models have a filename collision: {source.name}"
  1359. )
  1360. sources[source.name] = source
  1361. return sources
  1362. def manage_mod_ui_nam_models(action, config, registry, state):
  1363. key = "mod_ui_nam_models"
  1364. root = Path.home() / config["user_files_directory"] / "NAM Models" / "Rigforge"
  1365. managed = registry.get(key)
  1366. if action == "uninstall":
  1367. if managed is None:
  1368. return
  1369. if managed.get("directory") != str(root):
  1370. raise RuntimeError("managed mod-ui NAM model directory changed")
  1371. recorded = managed.get("files")
  1372. if not isinstance(recorded, dict):
  1373. raise RuntimeError("managed mod-ui NAM model registry is invalid")
  1374. for name, digest in recorded.items():
  1375. destination = root / name
  1376. validate_user_destination(destination)
  1377. if destination.is_symlink():
  1378. raise RuntimeError(f"managed NAM model became a symlink: {destination}")
  1379. if destination.exists() and (
  1380. not destination.is_file() or file_sha256(destination) != digest
  1381. ):
  1382. raise RuntimeError(
  1383. f"managed NAM model changed locally; refusing to remove: {destination}"
  1384. )
  1385. for name in recorded:
  1386. (root / name).unlink(missing_ok=True)
  1387. try:
  1388. root.rmdir()
  1389. except OSError:
  1390. pass
  1391. registry.pop(key)
  1392. write_registry(registry)
  1393. return
  1394. if action != "install":
  1395. return
  1396. sources = mod_ui_nam_model_sources(state)
  1397. if managed is None:
  1398. recorded = {}
  1399. else:
  1400. if managed.get("directory") != str(root):
  1401. raise RuntimeError("managed mod-ui NAM model directory changed")
  1402. recorded = managed.get("files")
  1403. if not isinstance(recorded, dict):
  1404. raise RuntimeError("managed mod-ui NAM model registry is invalid")
  1405. if set(recorded) - set(sources):
  1406. raise RuntimeError("managed mod-ui NAM model set changed; uninstall mod-ui first")
  1407. root.mkdir(parents=True, exist_ok=True)
  1408. plan = []
  1409. for name, source in sources.items():
  1410. destination = root / name
  1411. validate_user_destination(destination)
  1412. if destination.is_symlink():
  1413. raise RuntimeError(
  1414. f"refusing to replace symlink in mod-ui NAM directory: {destination}"
  1415. )
  1416. expected_digest = file_sha256(source)
  1417. current_digest = file_sha256(destination)
  1418. prior_digest = recorded.get(name)
  1419. if prior_digest is not None:
  1420. if current_digest != prior_digest:
  1421. raise RuntimeError(
  1422. f"managed NAM model changed locally; refusing overwrite: {destination}"
  1423. )
  1424. plan.append((name, source, destination, expected_digest, current_digest != expected_digest))
  1425. elif current_digest is None:
  1426. plan.append((name, source, destination, expected_digest, True))
  1427. elif current_digest != expected_digest:
  1428. raise RuntimeError(
  1429. f"unmanaged file conflicts with declared NAM model: {destination}"
  1430. )
  1431. installed = dict(recorded)
  1432. for name, source, destination, expected_digest, needs_install in plan:
  1433. if needs_install:
  1434. atomic_install(source, destination)
  1435. installed[name] = expected_digest
  1436. registry[key] = {"directory": str(root), "files": installed}
  1437. write_registry(registry)
  1438. def deploy_mod_ui(action, config, registry):
  1439. if action == "install":
  1440. if "mod_host_ports" not in registry:
  1441. raise RuntimeError("install mod-host-ports before installing mod-ui")
  1442. if "mod_host" not in registry:
  1443. raise RuntimeError("install mod-host before installing mod-ui")
  1444. if "mod_ui" not in registry and mod_ui_port_is_open(
  1445. config["websocket_host"], config["websocket_port"]
  1446. ):
  1447. raise RuntimeError(
  1448. f"mod-ui web port {config['websocket_port']} is already in use; "
  1449. "stop any manually launched mod-ui before installing the service"
  1450. )
  1451. if "mod_ui" not in registry and (
  1452. user_unit_is_active(config["user_service"])
  1453. or user_unit_is_enabled(config["user_service"])
  1454. ):
  1455. raise RuntimeError(
  1456. f"an unmanaged {config['user_service']} is already active or enabled; "
  1457. "inspect it before installing Rigforge's unit"
  1458. )
  1459. if action == "reset":
  1460. reset_mod_ui_reference(config, registry)
  1461. return
  1462. if action == "uninstall" and "midi_bridge" in registry:
  1463. raise RuntimeError("uninstall midi-bridge before uninstalling mod-ui")
  1464. state = yaml.safe_load(
  1465. (ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8")
  1466. )
  1467. if action == "install":
  1468. manage_mod_ui_nam_models("install", config, registry, state)
  1469. unit = render_mod_ui_service(config)
  1470. reference_sha256 = None
  1471. if action != "uninstall":
  1472. reference_sha256 = prepare_mod_ui_reference_bundle(unit)
  1473. deploy_single_user_service(
  1474. action,
  1475. "mod_ui",
  1476. "mod-ui",
  1477. "mod-ui",
  1478. unit,
  1479. registry,
  1480. )
  1481. if action == "uninstall":
  1482. manage_mod_ui_nam_models("uninstall", config, registry, state)
  1483. if action == "install":
  1484. registry["mod_ui"]["reference_bundle"] = {
  1485. "destination": str(unit["reference_bundle"]),
  1486. "installed_sha256": reference_sha256,
  1487. }
  1488. write_registry(registry)
  1489. def next_reset_backup_path(path):
  1490. base = path.with_name(path.name + ".rigforge-reset-backup")
  1491. candidate = base
  1492. suffix = 1
  1493. while candidate.exists() or candidate.is_symlink():
  1494. suffix += 1
  1495. candidate = base.with_name(base.name + f".{suffix}")
  1496. validate_user_destination(candidate)
  1497. return candidate
  1498. def prepare_mod_ui_reference_bundle(unit):
  1499. destination = unit["reference_bundle"]
  1500. files = unit["reference_files"]
  1501. validate_user_destination(destination)
  1502. if destination.exists():
  1503. if destination.is_symlink() or not destination.is_dir():
  1504. raise RuntimeError(f"generated mod-ui reference path has the wrong type: {destination}")
  1505. current_files = {}
  1506. for path in destination.rglob("*"):
  1507. if path.is_symlink():
  1508. raise RuntimeError(f"generated mod-ui reference contains a symlink: {path}")
  1509. if path.is_file():
  1510. current_files[path.relative_to(destination).as_posix()] = path.read_bytes()
  1511. if current_files != files:
  1512. raise RuntimeError(f"generated mod-ui reference changed locally: {destination}")
  1513. else:
  1514. destination.parent.mkdir(parents=True, exist_ok=True)
  1515. staged = Path(tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination.parent))
  1516. try:
  1517. for relative, content in files.items():
  1518. path = staged / relative
  1519. path.parent.mkdir(parents=True, exist_ok=True)
  1520. path.write_bytes(content)
  1521. os.replace(staged, destination)
  1522. finally:
  1523. if staged.exists():
  1524. shutil.rmtree(staged)
  1525. return tree_sha256(destination)
  1526. def reset_mod_ui_reference(config, registry):
  1527. managed = registry.get("mod_ui")
  1528. if managed is None:
  1529. raise RuntimeError("mod-ui is not managed; install mod-ui before resetting it")
  1530. if managed.get("pending_uninstall"):
  1531. raise RuntimeError("mod-ui uninstall is incomplete; retry uninstall mod-ui first")
  1532. unit = render_mod_ui_service(config)
  1533. destination = unit["destination"]
  1534. if not destination.is_file() or file_sha256(destination) != managed.get("installed_sha256"):
  1535. raise RuntimeError(f"managed mod-ui service file changed locally: {destination}")
  1536. reference = unit["reference_bundle"]
  1537. reference_record = managed.get("reference_bundle")
  1538. if not isinstance(reference_record, dict):
  1539. raise RuntimeError("mod-ui reference bundle is missing from the deployment registry")
  1540. reference_sha256 = reference_record.get("installed_sha256")
  1541. if (
  1542. reference_record.get("destination") != str(reference)
  1543. or not reference.is_dir()
  1544. or tree_sha256(reference) != reference_sha256
  1545. ):
  1546. raise RuntimeError(f"managed mod-ui reference pedalboard changed locally: {reference}")
  1547. pedalboards = Path.home() / config["pedalboards_directory"]
  1548. default_board = pedalboards / "default.pedalboard"
  1549. last_state = Path.home() / config["last_state_file"]
  1550. for path in (default_board, last_state):
  1551. validate_user_destination(path)
  1552. if path.is_symlink():
  1553. raise RuntimeError(f"refusing to reset a symlink: {path}")
  1554. if default_board.exists() and not default_board.is_dir():
  1555. raise RuntimeError(f"mod-ui default pedalboard has the wrong type: {default_board}")
  1556. if last_state.exists() and not last_state.is_file():
  1557. raise RuntimeError(f"mod-ui last-state path has the wrong type: {last_state}")
  1558. backup_board = next_reset_backup_path(default_board)
  1559. backup_state = next_reset_backup_path(last_state)
  1560. staged = default_board.with_name(default_board.name + ".rigforge-reset-new")
  1561. if staged.exists() or staged.is_symlink():
  1562. raise RuntimeError(f"reset staging path already exists: {staged}")
  1563. default_board.parent.mkdir(parents=True, exist_ok=True)
  1564. shutil.copytree(reference, staged, symlinks=False)
  1565. run(["systemctl", "--user", "stop", config["user_service"]])
  1566. board_backed_up = False
  1567. state_backed_up = False
  1568. reference_installed = False
  1569. try:
  1570. if default_board.exists():
  1571. os.replace(default_board, backup_board)
  1572. board_backed_up = True
  1573. if last_state.exists():
  1574. os.replace(last_state, backup_state)
  1575. state_backed_up = True
  1576. os.replace(staged, default_board)
  1577. reference_installed = True
  1578. run(["systemctl", "--user", "start", config["user_service"]])
  1579. run(["systemctl", "--user", "is-active", "--quiet", config["user_service"]])
  1580. if "midi_bridge" in registry:
  1581. run(["systemctl", "--user", "start", "rigforge-midi-bridge.service"])
  1582. run(["systemctl", "--user", "is-active", "--quiet", "rigforge-midi-bridge.service"])
  1583. except (OSError, subprocess.CalledProcessError):
  1584. try:
  1585. run(["systemctl", "--user", "stop", config["user_service"]])
  1586. except subprocess.CalledProcessError:
  1587. pass
  1588. if staged.exists():
  1589. shutil.rmtree(staged)
  1590. if reference_installed and default_board.exists():
  1591. shutil.rmtree(default_board)
  1592. if board_backed_up and backup_board.exists():
  1593. os.replace(backup_board, default_board)
  1594. if state_backed_up and backup_state.exists():
  1595. os.replace(backup_state, last_state)
  1596. run(["systemctl", "--user", "start", config["user_service"]])
  1597. raise
  1598. print(
  1599. "Rigforge reference pedalboard restored. Previous default and last-state data "
  1600. "were preserved as adjacent .rigforge-reset-backup files when present."
  1601. )
  1602. def deploy_sooperlooper(action, config, registry, state=None):
  1603. if state is None:
  1604. state = yaml.safe_load(
  1605. (ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8")
  1606. )
  1607. unit = render_sooperlooper_service(config, state)
  1608. deploy_single_user_service(
  1609. action, "sooperlooper", "sooperlooper", "SooperLooper", unit, registry
  1610. )
  1611. def file_sha256(path):
  1612. return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None
  1613. def install_reconcile_units(config, registry):
  1614. units = render_reconcile_units(config)
  1615. managed = registry.get("reconcile")
  1616. if managed is not None and managed.get("pending_uninstall"):
  1617. raise RuntimeError("reconciliation units are pending uninstall; retry uninstall reconcile first")
  1618. if managed is None and (
  1619. user_unit_is_active(config["user_service"])
  1620. or user_unit_is_active(config["user_timer"])
  1621. or user_unit_is_enabled(config["user_timer"])
  1622. ):
  1623. raise RuntimeError(
  1624. "an unmanaged Rigforge reconciliation unit is already active or enabled; "
  1625. "inspect it before installing the managed timer"
  1626. )
  1627. prior_files = managed.get("files", {}) if managed is not None else {}
  1628. if managed is not None and set(prior_files) != set(units):
  1629. raise RuntimeError("managed reconciliation unit registry has an unexpected file set")
  1630. records = {}
  1631. for key, unit in units.items():
  1632. destination = unit["destination"]
  1633. validate_user_destination(destination)
  1634. if destination.exists() and not destination.is_file():
  1635. raise RuntimeError(f"reconciliation unit destination has the wrong type: {destination}")
  1636. current_digest = file_sha256(destination)
  1637. prior = prior_files.get(key) if managed is not None else None
  1638. if prior is None:
  1639. if managed is not None:
  1640. raise RuntimeError(f"reconciliation unit is missing from deployment registry: {key}")
  1641. backup_path = destination.with_name(destination.name + ".rigforge-backup")
  1642. if backup_path.exists() or backup_path.is_symlink():
  1643. raise RuntimeError(f"backup path already exists: {backup_path}")
  1644. backup = str(backup_path) if destination.is_file() else None
  1645. backup_digest = current_digest
  1646. previous_digest = None
  1647. else:
  1648. if prior.get("destination") != str(destination):
  1649. raise RuntimeError(f"recorded reconciliation unit path changed: {key}")
  1650. backup_path = validate_backup_path(prior.get("backup"), destination)
  1651. backup = str(backup_path) if backup_path is not None else None
  1652. backup_digest = prior.get("backup_sha256")
  1653. if (backup_path is None) != (backup_digest is None):
  1654. raise RuntimeError(f"invalid reconciliation unit backup record: {key}")
  1655. previous_digest = prior.get("installed_sha256")
  1656. if backup_path is not None and backup_path.exists():
  1657. if not backup_path.is_file() or file_sha256(backup_path) != backup_digest:
  1658. raise RuntimeError(f"recorded reconciliation unit backup changed locally: {backup_path}")
  1659. elif (
  1660. backup_path is not None
  1661. and not managed.get("pending_install")
  1662. ):
  1663. raise RuntimeError(f"recorded reconciliation unit backup is missing: {backup_path}")
  1664. if managed.get("pending_install"):
  1665. accepted_digests = {
  1666. prior.get("installed_sha256"),
  1667. prior.get("previous_installed_sha256"),
  1668. backup_digest,
  1669. None,
  1670. }
  1671. if current_digest not in accepted_digests:
  1672. raise RuntimeError(
  1673. f"reconciliation unit changed locally during interrupted install: {destination}"
  1674. )
  1675. elif current_digest != prior.get("installed_sha256"):
  1676. raise RuntimeError(f"managed reconciliation unit changed locally: {destination}")
  1677. records[key] = {
  1678. "destination": str(destination),
  1679. "installed_sha256": hashlib.sha256(unit["content"]).hexdigest(),
  1680. "previous_installed_sha256": previous_digest,
  1681. "backup": backup,
  1682. "backup_sha256": backup_digest,
  1683. }
  1684. managed = managed or {}
  1685. managed["files"] = records
  1686. managed["pending_install"] = True
  1687. registry["reconcile"] = managed
  1688. write_registry(registry)
  1689. for key, unit in units.items():
  1690. record = records[key]
  1691. backup_path = validate_backup_path(record["backup"], unit["destination"])
  1692. if backup_path is not None:
  1693. if backup_path.exists():
  1694. if not backup_path.is_file() or file_sha256(backup_path) != record["backup_sha256"]:
  1695. raise RuntimeError(f"reconciliation unit backup changed locally: {backup_path}")
  1696. elif file_sha256(unit["destination"]) == record["backup_sha256"]:
  1697. shutil.copy2(unit["destination"], backup_path)
  1698. else:
  1699. raise RuntimeError(f"reconciliation unit backup is missing: {backup_path}")
  1700. unit_changed = (
  1701. not unit["destination"].is_file()
  1702. or unit["destination"].read_bytes() != unit["content"]
  1703. )
  1704. if unit_changed:
  1705. atomic_install_bytes(unit["content"], unit["destination"])
  1706. for record in records.values():
  1707. record.pop("previous_installed_sha256", None)
  1708. managed.pop("pending_install", None)
  1709. registry["reconcile"] = managed
  1710. write_registry(registry)
  1711. timer_name = units["timer"]["name"]
  1712. timer_changed = (
  1713. prior_files.get("timer", {}).get("installed_sha256")
  1714. != records["timer"]["installed_sha256"]
  1715. )
  1716. run(["systemctl", "--user", "daemon-reload"])
  1717. run(["systemctl", "--user", "enable", timer_name])
  1718. run(
  1719. [
  1720. "systemctl",
  1721. "--user",
  1722. "restart" if timer_changed else "start",
  1723. timer_name,
  1724. ]
  1725. )
  1726. run(["systemctl", "--user", "is-active", "--quiet", timer_name])
  1727. print(f"Installed and activated Rigforge reconciliation timer ({timer_name}).")
  1728. def uninstall_reconcile_units(config, registry):
  1729. managed = registry.get("reconcile")
  1730. if managed is None:
  1731. return
  1732. units = render_reconcile_units(config)
  1733. records = managed.get("files")
  1734. if not isinstance(records, dict) or set(records) != set(units):
  1735. raise RuntimeError("managed reconciliation unit registry has an unexpected file set")
  1736. for key, unit in units.items():
  1737. record = records[key]
  1738. destination = unit["destination"]
  1739. validate_user_destination(destination)
  1740. if record.get("destination") != str(destination):
  1741. raise RuntimeError(f"recorded reconciliation unit path changed: {key}")
  1742. if destination.exists() and not destination.is_file():
  1743. raise RuntimeError(f"reconciliation unit destination has the wrong type: {destination}")
  1744. backup_path = validate_backup_path(record.get("backup"), destination)
  1745. if backup_path is not None and backup_path.exists():
  1746. if not backup_path.is_file() or file_sha256(backup_path) != record.get("backup_sha256"):
  1747. raise RuntimeError(f"recorded reconciliation unit backup changed locally: {backup_path}")
  1748. elif backup_path is not None and not managed.get("pending_uninstall"):
  1749. raise RuntimeError(f"recorded reconciliation unit backup is missing: {backup_path}")
  1750. if (backup_path is None) != (record.get("backup_sha256") is None):
  1751. raise RuntimeError(f"invalid reconciliation unit backup record: {key}")
  1752. current_digest = file_sha256(destination)
  1753. recoverable_digests = {
  1754. record.get("installed_sha256"),
  1755. record.get("backup_sha256"),
  1756. None,
  1757. }
  1758. if managed.get("pending_uninstall"):
  1759. if current_digest not in recoverable_digests:
  1760. raise RuntimeError(f"unexpected file blocks reconciliation unit uninstall: {destination}")
  1761. elif current_digest != record.get("installed_sha256"):
  1762. raise RuntimeError(f"managed reconciliation unit changed locally; refusing removal: {destination}")
  1763. managed["pending_uninstall"] = True
  1764. registry["reconcile"] = managed
  1765. write_registry(registry)
  1766. run(["systemctl", "--user", "disable", "--now", config["user_timer"]])
  1767. run(["systemctl", "--user", "stop", config["user_service"]])
  1768. for key, unit in units.items():
  1769. record = records[key]
  1770. destination = unit["destination"]
  1771. backup_path = validate_backup_path(record.get("backup"), destination)
  1772. current_digest = file_sha256(destination)
  1773. if backup_path is not None and current_digest == record.get("backup_sha256"):
  1774. if backup_path.exists():
  1775. backup_path.unlink()
  1776. continue
  1777. if current_digest == record.get("installed_sha256"):
  1778. destination.unlink()
  1779. elif current_digest is not None:
  1780. raise RuntimeError(f"unexpected file blocks reconciliation unit uninstall: {destination}")
  1781. if backup_path is not None:
  1782. if backup_path.exists():
  1783. os.replace(backup_path, destination)
  1784. elif file_sha256(destination) != record.get("backup_sha256"):
  1785. raise RuntimeError(f"recorded reconciliation unit backup is missing: {backup_path}")
  1786. run(["systemctl", "--user", "daemon-reload"])
  1787. registry.pop("reconcile")
  1788. write_registry(registry)
  1789. print("Rigforge reconciliation timer and units removed.")
  1790. def deploy_reconcile(action, config, registry):
  1791. if action == "install":
  1792. install_reconcile_units(config, registry)
  1793. return
  1794. if action == "uninstall":
  1795. uninstall_reconcile_units(config, registry)
  1796. if "reconcile" not in registry:
  1797. print("No managed reconciliation units to uninstall.")
  1798. return
  1799. managed = registry.get("reconcile")
  1800. if managed is None:
  1801. raise RuntimeError("reconciliation timer is not managed; install reconcile first")
  1802. if managed.get("pending_install") or managed.get("pending_uninstall"):
  1803. raise RuntimeError("reconciliation unit deployment is incomplete; retry install or uninstall reconcile")
  1804. units = render_reconcile_units(config)
  1805. records = managed.get("files")
  1806. if not isinstance(records, dict) or set(records) != set(units):
  1807. raise RuntimeError("managed reconciliation unit registry has an unexpected file set")
  1808. for key, unit in units.items():
  1809. destination = unit["destination"]
  1810. validate_user_destination(destination)
  1811. if not destination.is_file() or file_sha256(destination) != records[key].get("installed_sha256"):
  1812. raise RuntimeError(f"managed reconciliation unit changed locally or is missing: {destination}")
  1813. run(["systemctl", "--user", "start", config["user_timer"]])
  1814. run(["systemctl", "--user", "is-active", "--quiet", config["user_timer"]])
  1815. run(["systemctl", "--user", "start", config["user_service"]])
  1816. print("Rigforge desired PipeWire graph reconciled once.")
  1817. def mod_host_runtime_digest(config):
  1818. state_path = ROOT / "config" / "desired-state.yaml"
  1819. readiness_script = ROOT / config["readiness_script"]
  1820. validator_path = ROOT / "scripts" / "validate_desired_state.py"
  1821. binary_path = ROOT / config["binary_source"]
  1822. with state_path.open(encoding="utf-8") as stream:
  1823. state = yaml.safe_load(stream)
  1824. guitar_chain = state["routing"]["mod_host_chains"]["guitar"]
  1825. mod_host_config = state["deployment"]["mod_host"]
  1826. files = [readiness_script, validator_path, binary_path]
  1827. digest = hashlib.sha256()
  1828. digest.update(
  1829. json.dumps(
  1830. {
  1831. "deployment.mod_host": mod_host_config,
  1832. "deployment.mod_host_ports": state["deployment"]["mod_host_ports"],
  1833. "routing.mod_host_chains.guitar": guitar_chain,
  1834. },
  1835. sort_keys=True,
  1836. separators=(",", ":"),
  1837. ).encode("utf-8")
  1838. + b"\0"
  1839. )
  1840. for path in files:
  1841. if not path.is_file():
  1842. raise RuntimeError(f"mod-host runtime input is missing: {path}")
  1843. digest.update(str(path.relative_to(ROOT.resolve())).encode("utf-8") + b"\0")
  1844. digest.update(path.read_bytes())
  1845. digest.update(b"\0")
  1846. return digest.hexdigest()
  1847. def mod_host_port_is_open(port):
  1848. try:
  1849. with socket.create_connection(("127.0.0.1", port), timeout=0.25):
  1850. return True
  1851. except OSError:
  1852. return False
  1853. def mod_ui_port_is_open(host, port):
  1854. try:
  1855. with socket.create_connection((host, port), timeout=0.25):
  1856. return True
  1857. except OSError:
  1858. return False
  1859. def user_unit_is_active(service_name):
  1860. result = subprocess.run(
  1861. ["systemctl", "--user", "is-active", "--quiet", service_name],
  1862. check=False,
  1863. stdout=subprocess.DEVNULL,
  1864. stderr=subprocess.DEVNULL,
  1865. )
  1866. return result.returncode == 0
  1867. def user_unit_is_enabled(service_name):
  1868. result = subprocess.run(
  1869. ["systemctl", "--user", "is-enabled", "--quiet", service_name],
  1870. check=False,
  1871. stdout=subprocess.DEVNULL,
  1872. stderr=subprocess.DEVNULL,
  1873. )
  1874. return result.returncode == 0
  1875. def deploy_mod_host(action, config, registry):
  1876. destination = Path.home() / config["service_destination"]
  1877. validate_user_destination(destination)
  1878. service_name = config["user_service"]
  1879. managed = registry.get("mod_host")
  1880. if action == "install" and "mod_host_ports" not in registry:
  1881. raise RuntimeError("install mod-host-ports before installing mod-host")
  1882. if action == "uninstall" and "mod_ui" in registry:
  1883. raise RuntimeError("uninstall mod-ui before uninstalling mod-host")
  1884. if managed is not None and not user_unit_is_active(service_name):
  1885. occupied_ports = [
  1886. port
  1887. for port in (config["socket_port"], config["feedback_port"])
  1888. if mod_host_port_is_open(port)
  1889. ]
  1890. if occupied_ports:
  1891. raise RuntimeError(
  1892. "mod-host TCP port(s) "
  1893. f"{occupied_ports} are open while the managed service is inactive; "
  1894. "stop any unmanaged/manual mod-host process before retrying"
  1895. )
  1896. if action == "reload":
  1897. if managed is None:
  1898. raise RuntimeError("mod-host is not managed; install mod-host before reloading it")
  1899. if managed.get("pending_uninstall"):
  1900. raise RuntimeError("mod-host uninstall is incomplete; retry uninstall mod-host first")
  1901. if not destination.is_file():
  1902. raise RuntimeError(f"managed mod-host service file is missing: {destination}")
  1903. digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  1904. if digest != managed.get("installed_sha256"):
  1905. raise RuntimeError(f"managed mod-host service file changed locally: {destination}")
  1906. run(["systemctl", "--user", "restart", service_name])
  1907. run(["systemctl", "--user", "is-active", "--quiet", service_name])
  1908. print("Rigforge mod-host user service restarted.")
  1909. return
  1910. if action == "uninstall":
  1911. if managed is None:
  1912. print("No managed mod-host service to uninstall.")
  1913. return
  1914. backup_path = validate_backup_path(managed.get("backup"), destination)
  1915. if backup_path is not None and backup_path.exists():
  1916. if not backup_path.is_file():
  1917. raise RuntimeError(f"recorded mod-host service backup has the wrong type: {backup_path}")
  1918. if hashlib.sha256(backup_path.read_bytes()).hexdigest() != managed.get("backup_sha256"):
  1919. raise RuntimeError(f"recorded mod-host service backup changed locally: {backup_path}")
  1920. if not managed.get("pending_uninstall"):
  1921. if not destination.is_file():
  1922. raise RuntimeError(f"managed mod-host service file is missing: {destination}")
  1923. digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  1924. if digest != managed.get("installed_sha256"):
  1925. raise RuntimeError(f"managed mod-host service file changed locally; refusing removal: {destination}")
  1926. managed["pending_uninstall"] = True
  1927. registry["mod_host"] = managed
  1928. write_registry(registry)
  1929. destination_digest = (
  1930. hashlib.sha256(destination.read_bytes()).hexdigest()
  1931. if destination.is_file()
  1932. else None
  1933. )
  1934. backup_digest = (
  1935. hashlib.sha256(backup_path.read_bytes()).hexdigest()
  1936. if backup_path is not None and backup_path.is_file()
  1937. else None
  1938. )
  1939. installed_digest = managed.get("installed_sha256")
  1940. already_restored = (
  1941. backup_path is not None
  1942. and destination_digest == managed.get("backup_sha256")
  1943. )
  1944. already_removed = destination_digest is None and backup_digest is None and backup_path is None
  1945. if not already_restored and not already_removed:
  1946. if destination_digest not in {installed_digest, None}:
  1947. raise RuntimeError(f"unexpected file blocks mod-host uninstall: {destination}")
  1948. run(["systemctl", "--user", "disable", "--now", service_name])
  1949. if destination_digest == installed_digest:
  1950. destination.unlink()
  1951. if backup_path is not None and backup_path.exists():
  1952. os.replace(backup_path, destination)
  1953. elif backup_path is not None:
  1954. raise RuntimeError(f"recorded mod-host service backup is missing: {backup_path}")
  1955. run(["systemctl", "--user", "daemon-reload"])
  1956. registry.pop("mod_host")
  1957. write_registry(registry)
  1958. print("Rigforge mod-host user service removed; prior unit state restored if present.")
  1959. return
  1960. # Install is intentionally an explicit target, not part of "all": it
  1961. # activates the guitar processing chain and can make audio audible.
  1962. content = render_mod_host_service(config)
  1963. installed_digest = hashlib.sha256(content).hexdigest()
  1964. runtime_digest = mod_host_runtime_digest(config)
  1965. previous_runtime_digest = managed.get("runtime_sha256") if managed is not None else None
  1966. restart_required = managed is None or runtime_digest != previous_runtime_digest
  1967. if managed is not None:
  1968. if managed.get("pending_uninstall"):
  1969. raise RuntimeError("mod-host uninstall is incomplete; retry uninstall mod-host first")
  1970. backup_path = validate_backup_path(managed.get("backup"), destination)
  1971. if backup_path is not None:
  1972. if not backup_path.is_file():
  1973. raise RuntimeError(f"recorded mod-host service backup is missing: {backup_path}")
  1974. if hashlib.sha256(backup_path.read_bytes()).hexdigest() != managed.get("backup_sha256"):
  1975. raise RuntimeError(f"recorded mod-host service backup changed locally: {backup_path}")
  1976. if not destination.is_file():
  1977. if not managed.get("pending_install"):
  1978. raise RuntimeError(f"managed mod-host service file is missing: {destination}")
  1979. if destination.exists() and not destination.is_file():
  1980. raise RuntimeError(f"managed mod-host service destination has the wrong type: {destination}")
  1981. current_digest = (
  1982. hashlib.sha256(destination.read_bytes()).hexdigest()
  1983. if destination.is_file()
  1984. else None
  1985. )
  1986. if current_digest is not None and current_digest != managed.get("installed_sha256"):
  1987. prior_digest = managed.get("backup_sha256")
  1988. if not managed.get("pending_install") or current_digest != prior_digest:
  1989. raise RuntimeError(
  1990. f"managed mod-host service file changed locally; refusing overwrite: {destination}"
  1991. )
  1992. elif not destination.exists() and not managed.get("pending_install"):
  1993. raise RuntimeError(f"managed mod-host service file changed locally; refusing overwrite: {destination}")
  1994. backup = managed.get("backup")
  1995. backup_sha256 = managed.get("backup_sha256")
  1996. else:
  1997. if user_unit_is_active(service_name) or user_unit_is_enabled(service_name):
  1998. raise RuntimeError(
  1999. f"an unmanaged {service_name} is already active or enabled; "
  2000. "inspect and disable it before installing Rigforge's unit"
  2001. )
  2002. if mod_host_port_is_open(config["socket_port"]):
  2003. raise RuntimeError(
  2004. f"mod-host control port {config['socket_port']} is already in use; "
  2005. "stop the unmanaged test process before installing the user service"
  2006. )
  2007. if mod_host_port_is_open(config["feedback_port"]):
  2008. raise RuntimeError(
  2009. f"mod-host feedback port {config['feedback_port']} is already in use; "
  2010. "stop the unmanaged test process before installing the user service"
  2011. )
  2012. backup = None
  2013. backup_sha256 = None
  2014. if destination.exists():
  2015. backup_path = destination.with_name(destination.name + ".rigforge-backup")
  2016. if backup_path.exists():
  2017. raise RuntimeError(f"backup path already exists: {backup_path}")
  2018. shutil.copy2(destination, backup_path)
  2019. backup = str(backup_path)
  2020. backup_sha256 = hashlib.sha256(backup_path.read_bytes()).hexdigest()
  2021. unit_changed = not destination.exists() or destination.read_bytes() != content
  2022. restart_required = (
  2023. restart_required
  2024. or unit_changed
  2025. or (managed is not None and managed.get("pending_activation", False))
  2026. )
  2027. if managed is None:
  2028. managed = {
  2029. "installed_sha256": installed_digest,
  2030. "runtime_sha256": runtime_digest,
  2031. "backup": backup,
  2032. "backup_sha256": backup_sha256,
  2033. "pending_install": unit_changed,
  2034. "pending_activation": True,
  2035. }
  2036. else:
  2037. managed["installed_sha256"] = installed_digest
  2038. managed["runtime_sha256"] = runtime_digest
  2039. managed["pending_install"] = unit_changed
  2040. managed["pending_activation"] = True
  2041. registry["mod_host"] = managed
  2042. write_registry(registry)
  2043. if unit_changed:
  2044. destination.parent.mkdir(parents=True, exist_ok=True)
  2045. fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent)
  2046. try:
  2047. with os.fdopen(fd, "wb") as stream:
  2048. stream.write(content)
  2049. os.chmod(temporary_name, 0o644)
  2050. os.replace(temporary_name, destination)
  2051. finally:
  2052. if os.path.exists(temporary_name):
  2053. os.unlink(temporary_name)
  2054. managed.pop("pending_install", None)
  2055. registry["mod_host"] = managed
  2056. write_registry(registry)
  2057. run(["systemctl", "--user", "daemon-reload"])
  2058. run(["systemctl", "--user", "enable", service_name])
  2059. if restart_required:
  2060. run(["systemctl", "--user", "restart", service_name])
  2061. else:
  2062. run(["systemctl", "--user", "start", service_name])
  2063. run(["systemctl", "--user", "is-active", "--quiet", service_name])
  2064. managed.pop("pending_activation", None)
  2065. registry["mod_host"] = managed
  2066. write_registry(registry)
  2067. print(f"Installed and activated Rigforge mod-host user service at {destination}.")
  2068. def main(argv=None):
  2069. parser = argparse.ArgumentParser()
  2070. parser.add_argument("action", choices=("install", "uninstall", "reload", "reset"))
  2071. parser.add_argument(
  2072. "target",
  2073. choices=(
  2074. "namlv2",
  2075. "lsp",
  2076. "dragonfly-reverb",
  2077. "pipewire",
  2078. "mod-host-ports",
  2079. "mod-host",
  2080. "mod-ui",
  2081. "reconcile",
  2082. "midi-bridge",
  2083. "sooperlooper",
  2084. ),
  2085. )
  2086. args = parser.parse_args(argv)
  2087. if args.action == "reset" and args.target != "mod-ui":
  2088. parser.error("reset is only supported for mod-ui")
  2089. try:
  2090. state = yaml.safe_load((ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8"))
  2091. deployment = load_deployment()
  2092. quantum_frames = state["parameters"]["quantum_frames"]
  2093. if not isinstance(quantum_frames, int) or isinstance(quantum_frames, bool) or quantum_frames < 1:
  2094. raise ValueError("parameters.quantum_frames must be a positive integer")
  2095. registry = read_registry()
  2096. if args.target == "namlv2":
  2097. deploy_namlv2(args.action, deployment["namlv2"], registry)
  2098. elif args.target == "pipewire":
  2099. deploy_pipewire(args.action, deployment["pipewire"], registry, quantum_frames)
  2100. elif args.target == "mod-host":
  2101. deploy_mod_host(args.action, deployment["mod_host"], registry)
  2102. elif args.target == "mod-host-ports":
  2103. deploy_mod_host_ports(args.action, deployment["mod_host_ports"], registry)
  2104. elif args.target == "mod-ui":
  2105. deploy_mod_ui(args.action, deployment["mod_ui"], registry)
  2106. elif args.target == "reconcile":
  2107. deploy_reconcile(args.action, deployment["reconcile"], registry)
  2108. elif args.target == "midi-bridge":
  2109. deploy_midi_bridge(args.action, deployment["midi_bridge"], registry)
  2110. elif args.target == "sooperlooper":
  2111. deploy_sooperlooper(
  2112. args.action, deployment["sooperlooper"], registry, state=state
  2113. )
  2114. else:
  2115. component = "dragonfly_reverb" if args.target == "dragonfly-reverb" else args.target
  2116. deploy_lv2_archives(args.action, component, deployment[component], registry)
  2117. except (OSError, ValueError, RuntimeError, KeyError, TypeError, subprocess.CalledProcessError, tarfile.TarError, yaml.YAMLError) as error:
  2118. print(f"ERROR: {error}", file=sys.stderr)
  2119. return 1
  2120. return 0
  2121. if __name__ == "__main__":
  2122. raise SystemExit(main())