deploy.py 95 KB

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