deploy.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import argparse
  2. import hashlib
  3. import json
  4. import os
  5. import re
  6. import shutil
  7. import subprocess
  8. import sys
  9. import tarfile
  10. import tempfile
  11. from pathlib import Path, PurePosixPath
  12. import yaml
  13. from validate_desired_state import validate_state
  14. ROOT = Path(__file__).resolve().parents[1]
  15. STATE_PATH = Path.home() / ".local" / "state" / "rigforge" / "deployment.json"
  16. NAM_RELEASE_ASSET = re.compile(
  17. r"^https://github\.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/"
  18. r"(?P<tag>[A-Za-z0-9._-]+)/neural_amp_modeler_lv2_rpi5\.tgz$"
  19. )
  20. def load_deployment():
  21. with (ROOT / "config" / "desired-state.yaml").open(encoding="utf-8") as stream:
  22. state = yaml.safe_load(stream)
  23. errors = validate_state(state)
  24. deployment = state.get("deployment") if isinstance(state, dict) else None
  25. if not isinstance(deployment, dict):
  26. raise ValueError("deployment must be a mapping")
  27. namlv2 = deployment.get("namlv2")
  28. pipewire = deployment.get("pipewire")
  29. if not isinstance(namlv2, dict) or not isinstance(pipewire, dict):
  30. raise ValueError("deployment.namlv2 and deployment.pipewire must be mappings")
  31. tag = namlv2.get("tag")
  32. match = NAM_RELEASE_ASSET.fullmatch(namlv2.get("archive_url", ""))
  33. if not isinstance(tag, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", tag):
  34. errors.append("NAM LV2 tag is invalid")
  35. if match is None or match.group("tag") != tag:
  36. errors.append("NAM LV2 URL must be the approved release asset for the declared tag")
  37. if namlv2.get("bundle_directory") != "neural_amp_modeler.lv2":
  38. errors.append("NAM LV2 bundle directory is invalid")
  39. source = pipewire.get("fragment_source")
  40. if source != "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf":
  41. errors.append("PipeWire fragment source is invalid")
  42. if pipewire.get("fragment_destination") != ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf":
  43. errors.append("PipeWire fragment destination is invalid")
  44. if pipewire.get("user_service") != "filter-chain.service":
  45. errors.append("PipeWire user service is invalid")
  46. if errors:
  47. raise ValueError("; ".join(errors))
  48. return deployment
  49. def read_registry():
  50. if not STATE_PATH.exists():
  51. return {}
  52. with STATE_PATH.open(encoding="utf-8") as stream:
  53. registry = json.load(stream)
  54. if not isinstance(registry, dict):
  55. raise ValueError(f"deployment registry is not a mapping: {STATE_PATH}")
  56. return registry
  57. def write_registry(registry):
  58. STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
  59. fd, temporary_name = tempfile.mkstemp(prefix="deployment.", dir=STATE_PATH.parent)
  60. try:
  61. with os.fdopen(fd, "w", encoding="utf-8") as stream:
  62. json.dump(registry, stream, indent=2, sort_keys=True)
  63. stream.write("\n")
  64. os.replace(temporary_name, STATE_PATH)
  65. finally:
  66. if os.path.exists(temporary_name):
  67. os.unlink(temporary_name)
  68. def run(command):
  69. subprocess.run(command, check=True)
  70. def tree_sha256(path):
  71. digest = hashlib.sha256()
  72. for item in sorted(path.rglob("*")):
  73. relative = item.relative_to(path).as_posix().encode()
  74. digest.update(relative + b"\\0")
  75. if item.is_symlink():
  76. digest.update(b"link\\0" + os.readlink(item).encode())
  77. elif item.is_file():
  78. digest.update(b"file\\0" + item.read_bytes())
  79. elif item.is_dir():
  80. digest.update(b"directory\\0")
  81. else:
  82. raise RuntimeError(f"unsupported file type in managed bundle: {item}")
  83. return digest.hexdigest()
  84. def validate_user_destination(destination):
  85. home = Path.home().resolve()
  86. parent = destination.parent.resolve()
  87. if not parent.is_relative_to(home):
  88. raise RuntimeError(f"deployment path escapes the user home directory: {destination}")
  89. if destination.is_symlink():
  90. raise RuntimeError(f"refusing to manage a symlink destination: {destination}")
  91. def validate_backup_path(backup, destination, is_directory=False):
  92. if backup is None:
  93. return None
  94. backup_path = Path(backup)
  95. expected = destination.with_name(destination.name + ".rigforge-backup")
  96. if backup_path != expected:
  97. raise RuntimeError(f"recorded backup path is outside its approved location: {backup_path}")
  98. if backup_path.is_symlink():
  99. raise RuntimeError(f"recorded backup must not be a symlink: {backup_path}")
  100. if backup_path.exists() and backup_path.is_dir() != is_directory:
  101. raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
  102. return backup_path
  103. def atomic_install(source, destination):
  104. destination.parent.mkdir(parents=True, exist_ok=True)
  105. fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent)
  106. os.close(fd)
  107. try:
  108. shutil.copyfile(source, temporary_name)
  109. shutil.copymode(source, temporary_name)
  110. os.replace(temporary_name, destination)
  111. finally:
  112. if os.path.exists(temporary_name):
  113. os.unlink(temporary_name)
  114. def apply_quantum(frames):
  115. run(["pw-metadata", "-n", "settings", "0", "clock.force-quantum", str(frames)])
  116. def restart_filter_service(service):
  117. run(["systemctl", "--user", "restart", service])
  118. run(["systemctl", "--user", "is-active", "--quiet", service])
  119. def deploy_pipewire(action, config, registry, quantum_frames):
  120. destination = Path.home() / config["fragment_destination"]
  121. validate_user_destination(destination)
  122. source = ROOT / config["fragment_source"]
  123. managed = registry.get("pipewire")
  124. pending_reload = registry.get("pipewire_pending_reload")
  125. if pending_reload is not None:
  126. apply_quantum(pending_reload["quantum_frames"])
  127. restart_filter_service(config["user_service"])
  128. registry.pop("pipewire_pending_reload")
  129. write_registry(registry)
  130. managed = registry.get("pipewire")
  131. if action == "reload":
  132. if not source.is_file() or not destination.is_file():
  133. raise RuntimeError("PipeWire reload requires both the repository fragment and installed fragment")
  134. apply_quantum(quantum_frames)
  135. restart_filter_service(config["user_service"])
  136. print("PipeWire runtime quantum applied; filter-chain user service restarted.")
  137. return
  138. if action == "install":
  139. if managed is not None and managed.get("pending_uninstall"):
  140. raise RuntimeError("PipeWire uninstall is incomplete; retry uninstall pipewire first")
  141. if managed is not None:
  142. validate_backup_path(managed.get("backup"), destination)
  143. if not destination.exists():
  144. raise RuntimeError(f"managed PipeWire fragment is missing: {destination}")
  145. if managed is not None and destination.exists():
  146. current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  147. if current_digest != managed["installed_sha256"]:
  148. raise RuntimeError(f"managed file changed locally; refusing overwrite: {destination}")
  149. was_unmanaged = managed is None
  150. changed = not destination.exists() or destination.read_bytes() != source.read_bytes()
  151. if managed is None:
  152. backup_path = None
  153. backup_sha256 = None
  154. if destination.exists():
  155. backup_path = str(destination.with_name(destination.name + ".rigforge-backup"))
  156. if Path(backup_path).exists():
  157. raise RuntimeError(f"backup path already exists: {backup_path}")
  158. shutil.copy2(destination, backup_path)
  159. backup_sha256 = hashlib.sha256(Path(backup_path).read_bytes()).hexdigest()
  160. managed = {
  161. "installed_sha256": "",
  162. "backup": backup_path,
  163. "backup_sha256": backup_sha256,
  164. }
  165. registry["pipewire"] = managed
  166. if changed:
  167. atomic_install(source, destination)
  168. managed["installed_sha256"] = hashlib.sha256(source.read_bytes()).hexdigest()
  169. managed["pending_reload"] = changed or was_unmanaged or managed.get("pending_reload", False)
  170. registry["pipewire"] = managed
  171. write_registry(registry)
  172. apply_quantum(quantum_frames)
  173. if managed["pending_reload"]:
  174. restart_filter_service(config["user_service"])
  175. managed.pop("pending_reload", None)
  176. registry["pipewire"] = managed
  177. write_registry(registry)
  178. print(f"PipeWire fragment {'updated' if changed else 'already current'} at {destination}.")
  179. return
  180. if action == "uninstall":
  181. if managed is None:
  182. print("No managed PipeWire fragment to uninstall.")
  183. return
  184. if managed.get("pending_uninstall"):
  185. backup_path = validate_backup_path(managed.get("backup"), destination)
  186. backup_exists = backup_path is not None and backup_path.is_file()
  187. if backup_path is not None and backup_path.exists():
  188. if not backup_exists:
  189. raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
  190. backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
  191. if backup_digest != managed.get("backup_sha256"):
  192. raise RuntimeError(f"recorded backup changed locally: {backup_path}")
  193. if destination.exists():
  194. current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  195. if backup_exists and current_digest == managed.get("backup_sha256"):
  196. backup_path.unlink()
  197. elif backup_path is not None and not backup_exists and current_digest == managed.get("backup_sha256"):
  198. pass
  199. elif current_digest == managed.get("installed_sha256"):
  200. destination.unlink()
  201. if backup_exists:
  202. os.replace(backup_path, destination)
  203. elif backup_path is not None:
  204. raise RuntimeError(f"recorded backup is missing: {backup_path}")
  205. else:
  206. raise RuntimeError(f"unexpected file blocks pending uninstall: {destination}")
  207. elif backup_exists:
  208. os.replace(backup_path, destination)
  209. elif backup_path is not None:
  210. raise RuntimeError(f"recorded backup is missing: {backup_path}")
  211. registry.pop("pipewire")
  212. write_registry(registry)
  213. apply_quantum(0)
  214. restart_filter_service(config["user_service"])
  215. print("Completed interrupted PipeWire uninstall and restored prior state.")
  216. return
  217. if not destination.exists():
  218. raise RuntimeError(f"managed PipeWire fragment is missing: {destination}")
  219. current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
  220. if current_digest != managed["installed_sha256"]:
  221. raise RuntimeError(f"managed file changed locally; refusing to remove: {destination}")
  222. backup_path = validate_backup_path(managed.get("backup"), destination)
  223. if backup_path is not None and not backup_path.is_file():
  224. raise RuntimeError(f"recorded backup is missing: {backup_path}")
  225. if backup_path is not None:
  226. backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
  227. if backup_digest != managed.get("backup_sha256"):
  228. raise RuntimeError(f"recorded backup changed locally: {backup_path}")
  229. managed["pending_uninstall"] = True
  230. registry["pipewire"] = managed
  231. write_registry(registry)
  232. destination.unlink()
  233. if backup_path is not None:
  234. atomic_install(backup_path, destination)
  235. backup_path.unlink()
  236. registry.pop("pipewire")
  237. registry["pipewire_pending_reload"] = {"quantum_frames": 0}
  238. write_registry(registry)
  239. apply_quantum(0)
  240. restart_filter_service(config["user_service"])
  241. registry.pop("pipewire_pending_reload")
  242. write_registry(registry)
  243. print("Rigforge PipeWire fragment removed or prior file restored; quantum reset to automatic.")
  244. return
  245. def inspect_archive(archive_path, bundle_name):
  246. with tarfile.open(archive_path, "r:gz") as archive:
  247. members = archive.getmembers()
  248. bundle_prefix = PurePosixPath(bundle_name)
  249. matching = []
  250. for member in members:
  251. member_path = PurePosixPath(member.name)
  252. if member_path.is_absolute() or ".." in member_path.parts:
  253. raise RuntimeError(f"unsafe archive path: {member.name}")
  254. if member_path.parts and member_path.parts[0] == bundle_prefix.name:
  255. if not member_path.is_relative_to(bundle_prefix):
  256. raise RuntimeError(f"unexpected bundle path: {member.name}")
  257. if not (member.isdir() or member.isfile()):
  258. raise RuntimeError(f"unsupported archive member type: {member.name}")
  259. matching.append(member)
  260. else:
  261. raise RuntimeError(f"unexpected archive path: {member.name}")
  262. if not matching or not any(member.name == bundle_name and member.isdir() for member in matching):
  263. raise RuntimeError(f"archive does not contain expected bundle directory {bundle_name}")
  264. return members
  265. def extract_bundle(archive_path, destination, bundle_name):
  266. with tarfile.open(archive_path, "r:gz") as archive:
  267. members = inspect_archive(archive_path, bundle_name)
  268. for member in members:
  269. member_path = PurePosixPath(member.name)
  270. relative_parts = member_path.parts[1:]
  271. output_path = destination.joinpath(*relative_parts) if relative_parts else destination
  272. if member.isdir():
  273. output_path.mkdir(parents=True, exist_ok=True)
  274. output_path.chmod(0o755)
  275. continue
  276. output_path.parent.mkdir(parents=True, exist_ok=True)
  277. extracted = archive.extractfile(member)
  278. if extracted is None:
  279. raise RuntimeError(f"unable to read archive member: {member.name}")
  280. with extracted, output_path.open("wb") as output:
  281. shutil.copyfileobj(extracted, output)
  282. output_path.chmod(0o755 if member.mode & 0o111 else 0o644)
  283. def download_archive(url, destination):
  284. run(["curl", "--fail", "--location", "--silent", "--show-error", "--output", str(destination), url])
  285. def deploy_namlv2(action, config, registry):
  286. bundle_name = config["bundle_directory"]
  287. destination = Path.home() / ".lv2" / bundle_name
  288. validate_user_destination(destination)
  289. managed = registry.get("namlv2")
  290. if action == "reload":
  291. print("Nothing to reload for the NAM LV2 plugin; restart its LV2 host after installation.")
  292. return
  293. if action == "uninstall":
  294. if managed is None:
  295. print("No managed NAM LV2 bundle to uninstall.")
  296. return
  297. if managed.get("pending_uninstall"):
  298. backup_path = validate_backup_path(managed.get("backup"), destination, is_directory=True)
  299. backup_exists = backup_path is not None and backup_path.is_dir()
  300. if backup_path is not None and backup_path.exists() and not backup_exists:
  301. raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
  302. if backup_exists and tree_sha256(backup_path) != managed.get("backup_sha256"):
  303. raise RuntimeError(f"recorded backup bundle changed locally: {backup_path}")
  304. if destination.exists():
  305. destination_digest = tree_sha256(destination)
  306. if backup_exists and destination_digest == managed.get("backup_sha256"):
  307. shutil.rmtree(backup_path)
  308. elif destination_digest == managed.get("installed_sha256"):
  309. shutil.rmtree(destination)
  310. if backup_exists:
  311. os.replace(backup_path, destination)
  312. else:
  313. raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
  314. elif backup_exists:
  315. os.replace(backup_path, destination)
  316. elif backup_path is not None:
  317. raise RuntimeError(f"recorded backup bundle is missing: {backup_path}")
  318. registry.pop("namlv2")
  319. write_registry(registry)
  320. print(f"Completed interrupted NAM LV2 uninstall at {destination}.")
  321. return
  322. if not destination.exists():
  323. raise RuntimeError(f"managed NAM LV2 bundle is missing: {destination}")
  324. if managed.get("installed_path") != str(destination):
  325. raise RuntimeError(f"managed NAM LV2 path changed: {destination}")
  326. if tree_sha256(destination) != managed.get("installed_sha256"):
  327. raise RuntimeError(f"managed NAM LV2 bundle changed locally; refusing to remove: {destination}")
  328. backup_path = validate_backup_path(managed.get("backup"), destination, is_directory=True)
  329. if backup_path is not None and not backup_path.is_dir():
  330. raise RuntimeError(f"recorded backup bundle is missing: {backup_path}")
  331. if backup_path is not None and tree_sha256(backup_path) != managed.get("backup_sha256"):
  332. raise RuntimeError(f"recorded backup bundle changed locally: {backup_path}")
  333. managed["pending_uninstall"] = True
  334. registry["namlv2"] = managed
  335. write_registry(registry)
  336. shutil.rmtree(destination)
  337. if backup_path is not None:
  338. os.replace(backup_path, destination)
  339. registry.pop("namlv2")
  340. write_registry(registry)
  341. print(f"Removed managed NAM LV2 bundle from {destination}.")
  342. return
  343. if managed is not None:
  344. if managed.get("pending_uninstall"):
  345. raise RuntimeError("NAM LV2 uninstall is incomplete; retry uninstall namlv2 first")
  346. if not destination.is_dir():
  347. raise RuntimeError(f"managed NAM LV2 bundle is missing: {destination}")
  348. if tree_sha256(destination) != managed.get("installed_sha256"):
  349. raise RuntimeError(f"managed NAM LV2 bundle changed locally; refusing overwrite: {destination}")
  350. if managed.get("tag") == config["tag"]:
  351. print(f"NAM LV2 tag {config['tag']} is already installed and unchanged.")
  352. return
  353. backup = validate_backup_path(managed.get("backup"), destination, is_directory=True)
  354. backup_sha256 = managed.get("backup_sha256")
  355. elif destination.exists():
  356. backup = destination.with_name(destination.name + ".rigforge-backup")
  357. if backup.exists():
  358. raise RuntimeError(f"backup path already exists: {backup}")
  359. backup_sha256 = None
  360. else:
  361. backup = None
  362. backup_sha256 = None
  363. with tempfile.TemporaryDirectory(prefix="rigforge-namlv2-") as temporary_dir:
  364. temporary = Path(temporary_dir)
  365. archive_path = temporary / "namlv2.tgz"
  366. download_archive(config["archive_url"], archive_path)
  367. archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()
  368. inspect_archive(archive_path, bundle_name)
  369. extraction_root = temporary / "extract"
  370. extraction_root.mkdir()
  371. extracted_bundle = extraction_root / bundle_name
  372. extracted_bundle.mkdir()
  373. extract_bundle(archive_path, extracted_bundle, bundle_name)
  374. if not extracted_bundle.is_dir():
  375. raise RuntimeError(f"expected bundle missing after extraction: {extracted_bundle}")
  376. destination.parent.mkdir(parents=True, exist_ok=True)
  377. staged_bundle = destination.with_name(destination.name + ".rigforge-new")
  378. previous_bundle = destination.with_name(destination.name + ".rigforge-old")
  379. if staged_bundle.exists() or previous_bundle.exists():
  380. raise RuntimeError("NAM LV2 staging or recovery path already exists")
  381. backup_created = False
  382. moved_previous = False
  383. try:
  384. shutil.copytree(extracted_bundle, staged_bundle)
  385. if managed is None and backup is not None:
  386. shutil.copytree(destination, backup)
  387. backup_created = True
  388. backup_sha256 = tree_sha256(backup)
  389. if destination.exists():
  390. os.replace(destination, previous_bundle)
  391. moved_previous = True
  392. os.replace(staged_bundle, destination)
  393. except (OSError, shutil.Error):
  394. if moved_previous and previous_bundle.exists() and not destination.exists():
  395. os.replace(previous_bundle, destination)
  396. if backup_created and backup.exists():
  397. shutil.rmtree(backup)
  398. raise
  399. finally:
  400. if staged_bundle.exists():
  401. shutil.rmtree(staged_bundle)
  402. if previous_bundle.exists():
  403. shutil.rmtree(previous_bundle)
  404. registry["namlv2"] = {
  405. "tag": config["tag"],
  406. "archive_sha256": archive_digest,
  407. "installed_path": str(destination),
  408. "backup": str(backup) if backup is not None else None,
  409. "backup_sha256": backup_sha256,
  410. "installed_sha256": tree_sha256(destination),
  411. }
  412. write_registry(registry)
  413. print(f"Installed NAM LV2 tag {config['tag']} at {destination}.")
  414. print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}")
  415. def main(argv=None):
  416. parser = argparse.ArgumentParser()
  417. parser.add_argument("action", choices=("install", "uninstall", "reload"))
  418. parser.add_argument("target", choices=("namlv2", "pipewire"))
  419. args = parser.parse_args(argv)
  420. try:
  421. state = yaml.safe_load((ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8"))
  422. deployment = load_deployment()
  423. quantum_frames = state["parameters"]["quantum_frames"]
  424. if not isinstance(quantum_frames, int) or isinstance(quantum_frames, bool) or quantum_frames < 1:
  425. raise ValueError("parameters.quantum_frames must be a positive integer")
  426. registry = read_registry()
  427. if args.target == "namlv2":
  428. deploy_namlv2(args.action, deployment["namlv2"], registry)
  429. else:
  430. deploy_pipewire(args.action, deployment["pipewire"], registry, quantum_frames)
  431. except (OSError, ValueError, RuntimeError, KeyError, TypeError, subprocess.CalledProcessError, tarfile.TarError, yaml.YAMLError) as error:
  432. print(f"ERROR: {error}", file=sys.stderr)
  433. return 1
  434. return 0
  435. if __name__ == "__main__":
  436. raise SystemExit(main())