deploy.py 114 KB

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