runner.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. # -*- coding: utf-8 -*-
  2. """
  3. InstallRunner — Fuehrt Installationsschritte aus.
  4. Steuert Progress, Logging und Abbruch.
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. import os
  9. import shutil
  10. from typing import Callable
  11. from .config import InstallerConfig
  12. from .steps import InstallationStep, get_steps
  13. class InstallRunner:
  14. """
  15. Fuehrt Installationsschritte sequentiell aus.
  16. Bietet gewichtete Progress-Updates und Echtzeit-Log.
  17. """
  18. def __init__(
  19. self,
  20. config: InstallerConfig,
  21. log_callback: Callable[[str], None],
  22. progress_callback: Callable[[float, str], None],
  23. ) -> None:
  24. self._config = config
  25. self._log = log_callback
  26. self._progress = progress_callback
  27. self._cancelled = False
  28. self._current_process: asyncio.subprocess.Process | None = None
  29. def cancel(self) -> None:
  30. """Bricht die Installation ab."""
  31. self._cancelled = True
  32. if self._current_process and self._current_process.returncode is None:
  33. self._current_process.terminate()
  34. async def run(self) -> bool:
  35. """
  36. Fuehrt alle Schritte aus.
  37. Returns:
  38. True bei Erfolg, False bei Fehler/Abbruch.
  39. """
  40. steps = get_steps(self._config.mode)
  41. total_weight = sum(s.weight for s in steps)
  42. completed_weight = 0
  43. self._log(f"=== Trixy {self._config.mode.title()} Installation ===")
  44. self._log(f"Version: {self._config.version}")
  45. self._log(f"Ziel: {self._config.install_path}")
  46. self._log("")
  47. # Sudo-Rechte vorab sicherstellen
  48. needs_sudo = any(
  49. s.command_fn in (
  50. "step_apt_packages", "step_hostname", "step_wifi_ap",
  51. "step_directories", "step_systemd",
  52. )
  53. for s in steps
  54. )
  55. if needs_sudo:
  56. self._log("Pruefe sudo-Rechte...")
  57. code, _ = await self._run_cmd("sudo", "-v", check=False)
  58. if code != 0:
  59. self._log(" FEHLER: sudo-Rechte benoetigt aber nicht verfuegbar.")
  60. self._log(" Bitte Installer mit 'sudo ./install-{mode}.sh' starten")
  61. self._log(" oder den Benutzer zur sudoers-Gruppe hinzufuegen.")
  62. return False
  63. self._log(" -> sudo verfuegbar\n")
  64. for i, step in enumerate(steps, 1):
  65. if self._cancelled:
  66. self._log("\n[ABBRUCH] Installation wurde abgebrochen.")
  67. return False
  68. self._log(f"[{i}/{len(steps)}] {step.name}...")
  69. self._progress(completed_weight / total_weight, step.name)
  70. method = getattr(self, step.command_fn, None)
  71. if method is None:
  72. self._log(f" WARNUNG: Methode {step.command_fn} nicht implementiert")
  73. completed_weight += step.weight
  74. continue
  75. try:
  76. success = await method()
  77. if not success:
  78. self._log(f" FEHLER bei Schritt: {step.name}")
  79. return False
  80. except Exception as e:
  81. self._log(f" FEHLER: {e}")
  82. return False
  83. completed_weight += step.weight
  84. self._progress(completed_weight / total_weight, step.name)
  85. self._log(f" -> {step.name} abgeschlossen\n")
  86. self._progress(1.0, "Fertig")
  87. self._log("=== Installation erfolgreich abgeschlossen ===")
  88. return True
  89. # --- Hilfsmethoden ---
  90. _ANSI_RE = None # Lazy-compiled Regex
  91. @staticmethod
  92. def _clean_ansi(text: str) -> str:
  93. """Entfernt ANSI Escape-Sequenzen aus Text."""
  94. import re
  95. if InstallRunner._ANSI_RE is None:
  96. InstallRunner._ANSI_RE = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]")
  97. return InstallRunner._ANSI_RE.sub("", text)
  98. async def _run_cmd(self, *args: str, check: bool = True) -> tuple[int, str]:
  99. """Fuehrt einen Befehl aus und loggt die Ausgabe."""
  100. self._log(f" $ {' '.join(args)}")
  101. # TMPDIR auf Installationspfad umleiten (tmpfs auf Pi zu klein fuer pip)
  102. env = os.environ.copy()
  103. tmp_dir = f"{self._config.install_path}/tmp"
  104. os.makedirs(tmp_dir, exist_ok=True)
  105. env["TMPDIR"] = tmp_dir
  106. env["PIP_CACHE_DIR"] = f"{self._config.install_path}/pip-cache"
  107. proc = await asyncio.create_subprocess_exec(
  108. *args,
  109. stdout=asyncio.subprocess.PIPE,
  110. stderr=asyncio.subprocess.STDOUT,
  111. env=env,
  112. )
  113. self._current_process = proc
  114. output_lines: list[str] = []
  115. assert proc.stdout is not None
  116. while True:
  117. line = await proc.stdout.readline()
  118. if not line:
  119. break
  120. decoded = line.decode("utf-8", errors="replace").rstrip()
  121. # \r-basierte Progress-Zeilen: nur letzten Teil nehmen
  122. if "\r" in decoded:
  123. decoded = decoded.rsplit("\r", 1)[-1].strip()
  124. # ANSI-Codes entfernen
  125. decoded = self._clean_ansi(decoded)
  126. if not decoded:
  127. continue
  128. output_lines.append(decoded)
  129. self._log(f" {decoded}")
  130. if self._cancelled:
  131. proc.terminate()
  132. await proc.wait()
  133. return -1, "Abgebrochen"
  134. await proc.wait()
  135. self._current_process = None
  136. output = "\n".join(output_lines)
  137. if check and proc.returncode != 0:
  138. self._log(f" Befehl fehlgeschlagen (Exit-Code: {proc.returncode})")
  139. return proc.returncode or 0, output
  140. async def _run_sudo(self, *args: str, check: bool = True) -> tuple[int, str]:
  141. """Fuehrt einen Befehl mit sudo aus."""
  142. return await self._run_cmd("sudo", *args, check=check)
  143. # --- Installations-Schritte ---
  144. async def step_extract(self) -> bool:
  145. """Entpackt das Quellarchiv nach source/."""
  146. archive = self._config.source_archive
  147. source = self._config.source_path # install_path/source
  148. if not os.path.isfile(archive):
  149. self._log(f" Archiv nicht gefunden: {archive}")
  150. return False
  151. # source-Verzeichnis erstellen
  152. code, _ = await self._run_sudo("mkdir", "-p", source)
  153. if code != 0:
  154. return False
  155. # Besitzer setzen
  156. await self._run_sudo("chown", self._config.username, self._config.install_path)
  157. # Entpacken — strip-components=1 entfernt den Prefix (trixy-server-1.0.0/)
  158. self._log(f" Entpacke nach {source}...")
  159. code, _ = await self._run_cmd(
  160. "tar", "xzf", archive, "-C", source, "--strip-components=1",
  161. )
  162. return code == 0
  163. # Paketnamen pro Paketmanager
  164. # Schluessel = kanonischer Name, Werte = {pm: paketname}
  165. _PKG_MAP: dict[str, dict[str, str]] = {
  166. "python3": {"apt": "python3", "dnf": "python3", "pacman": "python", "zypper": "python3"},
  167. "python3-venv": {"apt": "python3-venv", "dnf": "python3-venv", "pacman": "python", "zypper": "python3-venv"},
  168. "python3-pip": {"apt": "python3-pip", "dnf": "python3-pip", "pacman": "python-pip", "zypper": "python3-pip"},
  169. "python3-dev": {"apt": "python3-dev", "dnf": "python3-devel", "pacman": "python", "zypper": "python3-devel"},
  170. "git": {"apt": "git", "dnf": "git", "pacman": "git", "zypper": "git"},
  171. "curl": {"apt": "curl", "dnf": "curl", "pacman": "curl", "zypper": "curl"},
  172. "wget": {"apt": "wget", "dnf": "wget", "pacman": "wget", "zypper": "wget"},
  173. "alsa-utils": {"apt": "alsa-utils", "dnf": "alsa-utils", "pacman": "alsa-utils", "zypper": "alsa-utils"},
  174. "ffmpeg": {"apt": "ffmpeg", "dnf": "ffmpeg-free", "pacman": "ffmpeg", "zypper": "ffmpeg"},
  175. "portaudio-dev": {"apt": "portaudio19-dev", "dnf": "portaudio-devel", "pacman": "portaudio", "zypper": "portaudio-devel"},
  176. "alsa-dev": {"apt": "libasound2-dev", "dnf": "alsa-lib-devel", "pacman": "alsa-lib", "zypper": "alsa-devel"},
  177. "openblas-dev": {"apt": "libopenblas-dev", "dnf": "openblas-devel", "pacman": "openblas", "zypper": "openblas-devel"},
  178. "lapack-dev": {"apt": "liblapack-dev", "dnf": "lapack-devel", "pacman": "lapack", "zypper": "lapack-devel"},
  179. "gfortran": {"apt": "gfortran", "dnf": "gcc-gfortran", "pacman": "gcc-fortran", "zypper": "gcc-fortran"},
  180. "ffi-dev": {"apt": "libffi-dev", "dnf": "libffi-devel", "pacman": "libffi", "zypper": "libffi-devel"},
  181. "ssl-dev": {"apt": "libssl-dev", "dnf": "openssl-devel", "pacman": "openssl", "zypper": "libopenssl-devel"},
  182. "hostapd": {"apt": "hostapd", "dnf": "hostapd", "pacman": "hostapd", "zypper": "hostapd"},
  183. "dnsmasq": {"apt": "dnsmasq", "dnf": "dnsmasq", "pacman": "dnsmasq", "zypper": "dnsmasq"},
  184. "iptables": {"apt": "iptables", "dnf": "iptables", "pacman": "iptables", "zypper": "iptables"},
  185. "cmake": {"apt": "cmake", "dnf": "cmake", "pacman": "cmake", "zypper": "cmake"},
  186. "g++": {"apt": "g++", "dnf": "gcc-c++", "pacman": "gcc", "zypper": "gcc-c++"},
  187. "evtest": {"apt": "evtest", "dnf": "evtest", "pacman": "evtest", "zypper": "evtest"},
  188. "input-utils": {"apt": "input-utils", "dnf": "input-utils", "pacman": "input-utils", "zypper": "input-utils"},
  189. }
  190. def _detect_pkg_manager(self) -> tuple[str, list[str], list[str], list[str]]:
  191. """
  192. Erkennt den Paketmanager.
  193. Returns:
  194. (name, update_cmd, install_cmd, check_cmd)
  195. install_cmd hat Platzhalter — Pakete werden angehaengt.
  196. """
  197. managers = [
  198. ("apt", ["apt-get", "update", "-qq"], ["apt-get", "install", "-y", "-qq"], ["dpkg", "-s"]),
  199. ("dnf", ["dnf", "check-update"], ["dnf", "install", "-y", "-q"], ["rpm", "-q"]),
  200. ("pacman", ["pacman", "-Sy"], ["pacman", "-S", "--noconfirm", "--needed"], ["pacman", "-Q"]),
  201. ("zypper", ["zypper", "refresh", "-q"], ["zypper", "install", "-y", "-q"], ["rpm", "-q"]),
  202. ]
  203. for name, update, install, check in managers:
  204. if shutil.which(install[0]):
  205. return name, update, install, check
  206. return "", [], [], []
  207. def _resolve_pkg(self, canonical: str, pm: str) -> str:
  208. """Loest einen kanonischen Paketnamen fuer den erkannten Paketmanager auf."""
  209. mapping = self._PKG_MAP.get(canonical, {})
  210. return mapping.get(pm, canonical)
  211. async def _install_pkg_group(
  212. self, name: str, canonical_names: list[str], required: bool = True,
  213. ) -> bool:
  214. """Installiert eine Paketgruppe mit dem erkannten Paketmanager."""
  215. pm_name, _, install_cmd, _ = self._detect_pkg_manager()
  216. if not pm_name:
  217. self._log(f" FEHLER: Kein unterstuetzter Paketmanager gefunden (apt/dnf/pacman/zypper)")
  218. return not required
  219. # Paketnamen aufloesen
  220. packages = []
  221. for canonical in canonical_names:
  222. resolved = self._resolve_pkg(canonical, pm_name)
  223. if resolved not in packages:
  224. packages.append(resolved)
  225. self._log(f" {name} ({pm_name}): {', '.join(packages)}")
  226. code, _ = await self._run_sudo(*install_cmd, *packages)
  227. if code != 0:
  228. # Einzeln versuchen
  229. self._log(f" Gruppeninstallation fehlgeschlagen — installiere einzeln...")
  230. failed = []
  231. for pkg in packages:
  232. c, _ = await self._run_sudo(*install_cmd, pkg)
  233. if c != 0:
  234. failed.append(pkg)
  235. if failed:
  236. self._log(f" WARNUNG: Nicht verfuegbar: {', '.join(failed)}")
  237. if required:
  238. return False
  239. return True
  240. async def step_apt_packages(self) -> bool:
  241. """Installiert System-Pakete in Gruppen."""
  242. pm_name, update_cmd, _, _ = self._detect_pkg_manager()
  243. if not pm_name:
  244. self._log(" FEHLER: Kein unterstuetzter Paketmanager gefunden")
  245. self._log(" Unterstuetzt: apt (Debian/Ubuntu), dnf (Fedora/RHEL),")
  246. self._log(" pacman (Arch), zypper (openSUSE)")
  247. self._log(" Bitte Pakete manuell installieren.")
  248. return False
  249. self._log(f" Paketmanager: {pm_name}")
  250. self._log(f" Aktualisiere Paketlisten...")
  251. # dnf check-update gibt Exit 100 bei verfuegbaren Updates — das ist OK
  252. code, _ = await self._run_sudo(*update_cmd, check=False)
  253. if code != 0 and pm_name != "dnf":
  254. self._log(f" WARNUNG: Paketlisten-Update fehlgeschlagen")
  255. # Runtime-Pakete (immer benoetigt)
  256. runtime = ["python3", "python3-venv", "python3-pip", "git", "curl", "wget"]
  257. if not await self._install_pkg_group("Runtime", runtime):
  258. return False
  259. # Audio-Runtime
  260. audio = ["alsa-utils", "ffmpeg"]
  261. if not await self._install_pkg_group("Audio", audio):
  262. return False
  263. # Build-Abhaengigkeiten (optional auf x86_64 mit Wheels)
  264. build = [
  265. "python3-dev", "portaudio-dev", "alsa-dev",
  266. "openblas-dev", "lapack-dev", "gfortran",
  267. "ffi-dev", "ssl-dev",
  268. ]
  269. await self._install_pkg_group("Build-Abhaengigkeiten", build, required=False)
  270. # HID / Input-Tools (Client/Standalone — Konferenzmikrofone, Headsets)
  271. if self._config.mode in ("client", "standalone"):
  272. hid = ["evtest", "input-utils"]
  273. await self._install_pkg_group("HID/Input", hid, required=False)
  274. # WiFi-Hotspot (nur Server)
  275. if self._config.mode == "server" and self._config.wifi_enabled:
  276. wifi = ["hostapd", "dnsmasq", "iptables"]
  277. if not await self._install_pkg_group("WiFi-Hotspot", wifi):
  278. return False
  279. return True
  280. async def step_hostname(self) -> bool:
  281. """Setzt den Hostnamen."""
  282. code, _ = await self._run_sudo(
  283. "hostnamectl", "set-hostname", self._config.hostname,
  284. )
  285. return code == 0
  286. async def step_wifi_connect(self) -> bool:
  287. """Konfiguriert WLAN-Verbindung (Client/Standalone)."""
  288. if not self._config.wifi_connect:
  289. self._log(" Keine WLAN-Aenderung — uebersprungen")
  290. return True
  291. ssid = self._config.wifi_connect_ssid
  292. password = self._config.wifi_connect_password
  293. self._log(f" Konfiguriere WLAN: {ssid}")
  294. # Methode 1: nmcli (NetworkManager — modernes Debian/Ubuntu/Raspberry Pi OS)
  295. if shutil.which("nmcli"):
  296. self._log(" Verwende NetworkManager (nmcli)...")
  297. # Bestehende Verbindung mit gleichem Namen entfernen
  298. await self._run_cmd(
  299. "nmcli", "connection", "delete", ssid, check=False,
  300. )
  301. # Neue Verbindung erstellen
  302. code, _ = await self._run_sudo(
  303. "nmcli", "device", "wifi", "connect", ssid,
  304. "password", password,
  305. )
  306. if code == 0:
  307. self._log(f" -> WLAN verbunden: {ssid}")
  308. return True
  309. else:
  310. self._log(f" WARNUNG: nmcli fehlgeschlagen — versuche wpa_supplicant")
  311. # Methode 2: wpa_supplicant (aeltere Systeme / Raspberry Pi OS Lite)
  312. self._log(" Verwende wpa_supplicant...")
  313. wpa_conf = "/etc/wpa_supplicant/wpa_supplicant.conf"
  314. # wpa_passphrase generiert verschluesselten PSK
  315. code, output = await self._run_cmd(
  316. "wpa_passphrase", ssid, password, check=False,
  317. )
  318. if code != 0:
  319. # Fallback: Klartext-Config
  320. network_block = f"""
  321. network={{
  322. ssid="{ssid}"
  323. psk="{password}"
  324. key_mgmt=WPA-PSK
  325. }}
  326. """
  327. else:
  328. network_block = output
  329. # Pruefen ob Basis-Header vorhanden
  330. wpa_header = (
  331. 'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n'
  332. 'update_config=1\n'
  333. 'country=DE\n'
  334. )
  335. # Config schreiben
  336. proc = await asyncio.create_subprocess_exec(
  337. "sudo", "tee", wpa_conf,
  338. stdin=asyncio.subprocess.PIPE,
  339. stdout=asyncio.subprocess.DEVNULL,
  340. )
  341. full_config = wpa_header + "\n" + network_block
  342. await proc.communicate(full_config.encode())
  343. # wlan0 neu verbinden
  344. await self._run_sudo("wpa_cli", "-i", "wlan0", "reconfigure", check=False)
  345. self._log(f" -> WLAN konfiguriert: {ssid}")
  346. return True
  347. async def step_wifi_ap(self) -> bool:
  348. """Konfiguriert WiFi Access Point."""
  349. if not self._config.wifi_enabled:
  350. self._log(" WiFi-Hotspot deaktiviert — uebersprungen")
  351. return True
  352. cfg = self._config
  353. # hostapd konfigurieren
  354. hostapd_conf = f"""# Trixy Access Point
  355. interface=wlan0
  356. driver=nl80211
  357. ssid={cfg.wifi_ssid}
  358. hw_mode=g
  359. channel={cfg.wifi_channel}
  360. wmm_enabled=0
  361. macaddr_acl=0
  362. auth_algs=1
  363. ignore_broadcast_ssid=0
  364. wpa=2
  365. wpa_passphrase={cfg.wifi_password}
  366. wpa_key_mgmt=WPA-PSK
  367. wpa_pairwise=TKIP
  368. rsn_pairwise=CCMP
  369. country_code=DE
  370. ieee80211n=1
  371. ieee80211d=1
  372. """
  373. # Ueber tee schreiben (braucht sudo)
  374. proc = await asyncio.create_subprocess_exec(
  375. "sudo", "tee", "/etc/hostapd/hostapd.conf",
  376. stdin=asyncio.subprocess.PIPE,
  377. stdout=asyncio.subprocess.DEVNULL,
  378. )
  379. await proc.communicate(hostapd_conf.encode())
  380. # dnsmasq konfigurieren
  381. dnsmasq_conf = f"""# Trixy DHCP-Server
  382. interface=wlan0
  383. bind-interfaces
  384. dhcp-range={cfg.dhcp_range_start},{cfg.dhcp_range_end},255.255.255.0,12h
  385. server=8.8.8.8
  386. server=8.8.4.4
  387. address=/{cfg.wifi_ssid}/{cfg.ap_ip}
  388. """
  389. proc = await asyncio.create_subprocess_exec(
  390. "sudo", "tee", "/etc/dnsmasq.conf",
  391. stdin=asyncio.subprocess.PIPE,
  392. stdout=asyncio.subprocess.DEVNULL,
  393. )
  394. await proc.communicate(dnsmasq_conf.encode())
  395. # dhcpcd — statische IP
  396. dhcpcd_block = f"""
  397. # Trixy AP — wlan0 statische IP
  398. interface wlan0
  399. static ip_address={cfg.ap_ip}/24
  400. nohook wpa_supplicant
  401. """
  402. proc = await asyncio.create_subprocess_exec(
  403. "sudo", "tee", "-a", "/etc/dhcpcd.conf",
  404. stdin=asyncio.subprocess.PIPE,
  405. stdout=asyncio.subprocess.DEVNULL,
  406. )
  407. await proc.communicate(dhcpcd_block.encode())
  408. # IP-Forwarding und NAT
  409. await self._run_sudo("sysctl", "-w", "net.ipv4.ip_forward=1")
  410. await self._run_sudo(
  411. "iptables", "-t", "nat", "-A", "POSTROUTING", "-o", "eth0", "-j", "MASQUERADE",
  412. )
  413. # Services aktivieren
  414. await self._run_sudo("systemctl", "unmask", "hostapd")
  415. await self._run_sudo("systemctl", "enable", "hostapd")
  416. await self._run_sudo("systemctl", "enable", "dnsmasq")
  417. return True
  418. @staticmethod
  419. def _parse_requirements(path: str) -> list[str]:
  420. """
  421. Liest eine requirements.txt und gibt aktive Paketnamen zurueck.
  422. Ignoriert leere Zeilen, Kommentare (#) und Options-Zeilen (--, -r).
  423. """
  424. packages: list[str] = []
  425. try:
  426. with open(path) as f:
  427. for line in f:
  428. line = line.strip()
  429. # Leer, Kommentar, Option
  430. if not line or line.startswith("#") or line.startswith("-"):
  431. continue
  432. # Inline-Kommentar entfernen: "numpy # Array-Verarbeitung"
  433. if " #" in line:
  434. line = line.split(" #")[0].strip()
  435. if line:
  436. packages.append(line)
  437. except OSError:
  438. pass
  439. return packages
  440. async def _pip_install_packages(
  441. self, pip: str, packages: list[str], label: str = "",
  442. ) -> tuple[int, int]:
  443. """
  444. Installiert Pakete einzeln via pip.
  445. Jedes Paket wird separat installiert — so bleibt /tmp sauber
  446. und der Fortschritt ist sichtbar.
  447. Args:
  448. pip: Pfad zu pip im venv
  449. packages: Liste der zu installierenden Pakete
  450. label: Kontext-Label fuer Log (z.B. "Kern" oder Plugin-Name)
  451. Returns:
  452. (erfolgreich, fehlgeschlagen)
  453. """
  454. success = 0
  455. failed = 0
  456. total = len(packages)
  457. for i, pkg in enumerate(packages, 1):
  458. if self._cancelled:
  459. return success, failed
  460. prefix = f" [{i}/{total}]" if total > 1 else " "
  461. self._log(f"{prefix} {pkg}...")
  462. code, _ = await self._run_cmd(pip, "install", pkg)
  463. if code == 0:
  464. success += 1
  465. else:
  466. failed += 1
  467. self._log(f" WARNUNG: {pkg} fehlgeschlagen")
  468. return success, failed
  469. async def step_venv(self) -> bool:
  470. """Erstellt Python venv und installiert Requirements einzeln."""
  471. venv = self._config.venv_path
  472. source = self._config.source_path
  473. # venv erstellen
  474. self._log(" Erstelle Python venv...")
  475. code, _ = await self._run_cmd("python3", "-m", "venv", venv)
  476. if code != 0:
  477. return False
  478. # pip aktualisieren
  479. pip = f"{venv}/bin/pip"
  480. self._log(" Aktualisiere pip...")
  481. code, _ = await self._run_cmd(pip, "install", "--upgrade", "pip", "setuptools", "wheel")
  482. if code != 0:
  483. return False
  484. # Kern-Requirements einzeln installieren
  485. req_file = f"{source}/requirements.txt"
  486. packages = self._parse_requirements(req_file)
  487. if not packages:
  488. self._log(" Keine Requirements gefunden")
  489. return True
  490. self._log(f" Installiere {len(packages)} Kern-Pakete...\n")
  491. ok, fail = await self._pip_install_packages(pip, packages, "Kern")
  492. self._log(f"\n Ergebnis: {ok} installiert, {fail} fehlgeschlagen")
  493. if fail > 0:
  494. self._log(" WARNUNG: Einige Pakete konnten nicht installiert werden")
  495. # Nicht abbrechen — manche Pakete sind optional (z.B. kenlm)
  496. return True
  497. # Zusaetzliche pip-Pakete pro Plugin die nicht in requirements.txt stehen
  498. # (weil sie auskommentiert sind oder backend-abhaengig)
  499. _PLUGIN_EXTRA_DEPS: dict[str, list[str]] = {
  500. "stt_vosk": ["vosk"],
  501. "stt_whisper": ["openai-whisper"],
  502. "tts_coqui": ["TTS"],
  503. "tts_piper": ["piper-tts"],
  504. "tts_google": ["google-cloud-texttospeech"],
  505. }
  506. # apt/system-Pakete die vor pip install noetig sind (fuer Kompilierung)
  507. _PLUGIN_SYSTEM_DEPS: dict[str, list[str]] = {
  508. "nlp_llm": ["cmake"], # llama-cpp-python braucht cmake zum Bauen
  509. }
  510. async def step_plugin_deps(self) -> bool:
  511. """Installiert Plugin-Abhaengigkeiten einzeln inkl. Backend-spezifischer Pakete."""
  512. pip = f"{self._config.venv_path}/bin/pip"
  513. source = self._config.source_path
  514. cfg = self._config
  515. total_ok = 0
  516. total_fail = 0
  517. for plugin in cfg.selected_plugins:
  518. if self._cancelled:
  519. return False
  520. # 1. requirements.txt parsen und einzeln installieren
  521. req_file = f"{source}/plugins/{plugin}/requirements.txt"
  522. packages = self._parse_requirements(req_file)
  523. # 2. Zusaetzliche Pakete hinzufuegen
  524. extras = self._PLUGIN_EXTRA_DEPS.get(plugin, [])
  525. packages.extend(extras)
  526. if not packages:
  527. continue
  528. self._log(f"\n Plugin: {plugin} ({len(packages)} Pakete)")
  529. ok, fail = await self._pip_install_packages(pip, packages, plugin)
  530. total_ok += ok
  531. total_fail += fail
  532. # 3. NLP Backend — spezielle Behandlung
  533. if "nlp_llm" in cfg.selected_plugins:
  534. await self._install_nlp_backend()
  535. if total_ok > 0 or total_fail > 0:
  536. self._log(f"\n Plugin-Pakete: {total_ok} installiert, {total_fail} fehlgeschlagen")
  537. return True
  538. async def _install_nlp_backend(self) -> None:
  539. """Installiert das gewaehlte NLP-Backend."""
  540. pip = f"{self._config.venv_path}/bin/pip"
  541. source = self._config.source_path
  542. backend = self._config.nlp_backend
  543. self._log(f" NLP Backend: {backend}")
  544. if backend == "llama_cpp":
  545. # cmake als System-Dep (fuer C++ Kompilierung)
  546. pm_name, _, install_cmd, _ = self._detect_pkg_manager()
  547. if pm_name:
  548. cmake_pkg = self._resolve_pkg("cmake", pm_name) if "cmake" in self._PKG_MAP else "cmake"
  549. self._log(f" Installiere cmake (Build-Abhaengigkeit)...")
  550. await self._run_sudo(*install_cmd, cmake_pkg, check=False)
  551. # llama-cpp-python installieren (kann auf ARM lange dauern)
  552. self._log(f" Installiere llama-cpp-python (kann 10-30 Min dauern auf ARM)...")
  553. code, _ = await self._run_cmd(
  554. pip, "install", "llama-cpp-python",
  555. )
  556. if code != 0:
  557. self._log(f" FEHLER: llama-cpp-python Installation fehlgeschlagen")
  558. self._log(f" Alternativ: Backend auf 'ollama' umstellen")
  559. else:
  560. self._log(f" -> llama-cpp-python installiert")
  561. elif backend in ("ollama", "ollama_remote"):
  562. # aiohttp fuer Ollama REST-API
  563. self._log(f" Installiere aiohttp (Ollama Client)...")
  564. code, _ = await self._run_cmd(pip, "install", "aiohttp")
  565. if code != 0:
  566. self._log(f" WARNUNG: aiohttp fehlgeschlagen")
  567. if backend == "ollama":
  568. # Lokales Ollama — pruefen ob installiert
  569. if not shutil.which("ollama"):
  570. self._log(f" WARNUNG: Ollama nicht gefunden!")
  571. self._log(f" Installieren mit: curl -fsSL https://ollama.com/install.sh | sh")
  572. self._log(f" Danach: ollama pull qwen2.5:1.5b")
  573. else:
  574. self._log(f" -> Ollama gefunden: {shutil.which('ollama')}")
  575. else:
  576. # Externer Ollama-Server
  577. host = self._config.ollama_host
  578. self._log(f" Externer Ollama-Server: {host}")
  579. self._log(f" Stelle sicher dass der Server erreichbar ist und")
  580. self._log(f" das Modell geladen wurde (ollama pull qwen2.5:1.5b)")
  581. # 4. Config anpassen
  582. # ollama_remote wird intern als "ollama" gespeichert (selbes Backend, anderer Host)
  583. config_backend = "ollama" if backend == "ollama_remote" else backend
  584. config_file = f"{source}/plugins/nlp_llm/config.json"
  585. if os.path.isfile(config_file):
  586. try:
  587. import json
  588. with open(config_file) as f:
  589. nlp_cfg = json.load(f)
  590. nlp_cfg["backend"] = config_backend
  591. nlp_cfg["ollama_host"] = self._config.ollama_host
  592. if config_backend == "ollama":
  593. nlp_cfg["model_name"] = nlp_cfg.get("model_name", "qwen2.5:1.5b")
  594. with open(config_file, "w") as f:
  595. json.dump(nlp_cfg, f, indent=4, ensure_ascii=False)
  596. self._log(f" -> config.json: backend={config_backend}, host={self._config.ollama_host}")
  597. except Exception as e:
  598. self._log(f" WARNUNG: Config-Update fehlgeschlagen: {e}")
  599. async def step_directories(self) -> bool:
  600. """Erstellt Verzeichnisse und setzt Berechtigungen."""
  601. source = self._config.source_path
  602. mode = self._config.mode
  603. # Basis-Verzeichnisse (alle Modi)
  604. dirs = [
  605. "data",
  606. "logs",
  607. "cache",
  608. "certs",
  609. ]
  610. # Modell-Verzeichnisse — exakte Struktur, verhindert Tippfehler
  611. model_dirs = [
  612. "models",
  613. "models/wakeword",
  614. "models/wakeword/trixy",
  615. "models/wakeword/system_command",
  616. "models/wakeword/alexa",
  617. "models/wakeword/hey_jarvis",
  618. "models/wakeword/hey_mycroft",
  619. "models/piper",
  620. "models/nlp",
  621. "models/symspell",
  622. ]
  623. # Server/Standalone-spezifisch
  624. if mode in ("server", "standalone"):
  625. dirs.extend([
  626. "satellites",
  627. "sync_data",
  628. "assets",
  629. "assets/default",
  630. ])
  631. # Plugin-Modell-Verzeichnisse
  632. for plugin in self._config.selected_plugins:
  633. dirs.append(f"plugins/{plugin}/models")
  634. # Client-spezifisch
  635. if mode == "client":
  636. dirs.extend([
  637. "assets",
  638. ])
  639. # Trainer-Verzeichnisse (Server/Standalone)
  640. if mode in ("server", "standalone"):
  641. dirs.extend([
  642. "trainer/data/raw",
  643. "trainer/data/processed",
  644. "trainer/cache",
  645. "trainer/assets",
  646. ])
  647. all_dirs = dirs + model_dirs
  648. self._log(f" Erstelle {len(all_dirs)} Verzeichnisse...")
  649. for d in all_dirs:
  650. path = f"{source}/{d}"
  651. await self._run_sudo("mkdir", "-p", path)
  652. # Shell-Scripte ausfuehrbar machen
  653. scripts = [
  654. "run_linux.sh",
  655. "install_linux.sh",
  656. "install_requirements.sh",
  657. "bash/update_linux.sh",
  658. "bash/prepare_linux.sh",
  659. ]
  660. made_exec = 0
  661. for script in scripts:
  662. path = f"{source}/{script}"
  663. if os.path.isfile(path):
  664. await self._run_cmd("chmod", "+x", path)
  665. made_exec += 1
  666. # User zur 'input'-Gruppe hinzufuegen (fuer HID Media Keys / /dev/input/event*)
  667. if mode in ("client", "standalone"):
  668. code, _ = await self._run_sudo(
  669. "usermod", "-aG", "input", self._config.username, check=False,
  670. )
  671. if code == 0:
  672. self._log(f" -> User '{self._config.username}' zur Gruppe 'input' hinzugefuegt (HID)")
  673. # Besitzer setzen
  674. await self._run_sudo(
  675. "chown", "-R",
  676. f"{self._config.username}:{self._config.username}",
  677. self._config.install_path,
  678. )
  679. self._log(f" -> {len(all_dirs)} Verzeichnisse erstellt, {made_exec} Scripte ausfuehrbar")
  680. return True
  681. async def step_systemd(self) -> bool:
  682. """Erstellt den systemd-Service und aktiviert ihn bei Bedarf."""
  683. cfg = self._config
  684. if not cfg.install_service:
  685. self._log(" Service-Installation deaktiviert — uebersprungen")
  686. return True
  687. service_name = f"trixy-{cfg.mode}"
  688. # ExecStart zusammenbauen
  689. # run_linux.sh fuehrt Update + Bereinigung + Start durch
  690. run_script = f"{cfg.source_path}/run_linux.sh"
  691. exec_args = ["/bin/bash", run_script]
  692. if cfg.mode == "client":
  693. exec_args.extend([
  694. "client",
  695. "--host", cfg.server_host,
  696. "--port", str(cfg.server_port),
  697. "--room", cfg.room,
  698. "--alias", cfg.alias,
  699. ])
  700. else:
  701. exec_args.append(cfg.mode)
  702. if cfg.auto_regist and cfg.mode in ("server", "standalone"):
  703. exec_args.append("--auto-regist")
  704. exec_args.append("--debug")
  705. exec_start = " ".join(exec_args)
  706. # After-Deps fuer Server mit WiFi-AP
  707. after_deps = "network-online.target"
  708. if cfg.mode == "server" and cfg.wifi_enabled:
  709. after_deps = "network-online.target hostapd.service dnsmasq.service"
  710. service_content = f"""[Unit]
  711. Description=Trixy Voice Assistant ({cfg.mode.title()})
  712. After={after_deps}
  713. Wants=network-online.target
  714. [Service]
  715. Type=simple
  716. User={cfg.username}
  717. Group={cfg.username}
  718. WorkingDirectory={cfg.source_path}
  719. ExecStart={exec_start}
  720. Restart=on-failure
  721. RestartSec=5
  722. StartLimitIntervalSec=60
  723. StartLimitBurst=5
  724. Environment=PYTHONUNBUFFERED=1
  725. Environment=HOME=/home/{cfg.username}
  726. StandardOutput=journal
  727. StandardError=journal
  728. SyslogIdentifier=trixy
  729. [Install]
  730. WantedBy=multi-user.target
  731. """
  732. # Service-Datei schreiben
  733. proc = await asyncio.create_subprocess_exec(
  734. "sudo", "tee", f"/etc/systemd/system/{service_name}.service",
  735. stdin=asyncio.subprocess.PIPE,
  736. stdout=asyncio.subprocess.DEVNULL,
  737. )
  738. await proc.communicate(service_content.encode())
  739. await self._run_sudo("systemctl", "daemon-reload")
  740. # Autostart je nach Einstellung
  741. if cfg.autostart:
  742. await self._run_sudo("systemctl", "enable", f"{service_name}.service")
  743. self._log(f" -> {service_name}.service aktiviert (Autostart)")
  744. else:
  745. await self._run_sudo("systemctl", "disable", f"{service_name}.service")
  746. self._log(f" -> {service_name}.service erstellt (kein Autostart)")
  747. self._log(f" Manuell starten: sudo systemctl start {service_name}")
  748. return True
  749. def _get_model_downloads(self) -> list[tuple[str, str, str, bool, str | None]]:
  750. """
  751. Gibt die Download-Liste basierend auf Hardware-Empfehlung zurueck.
  752. Returns:
  753. Liste von (name, url, ziel_relativ_zu_source, entpacken?, plugin_name).
  754. plugin_name ist None fuer Core-Modelle.
  755. """
  756. from .system_info import detect_system, get_model_recommendations
  757. info = detect_system()
  758. recs = get_model_recommendations(info, self._config.selected_plugins)
  759. downloads: list[tuple[str, str, str, bool, str | None]] = []
  760. # Empfohlene Modelle ermitteln
  761. rec_names = {r.name for r in recs if r.recommended}
  762. self._log(f" Hardware: {info.ram_total_mb}MB RAM, {info.disk_free_mb}MB frei")
  763. if info.gpu.cuda_available:
  764. self._log(f" GPU: {info.gpu.name} ({info.gpu.vram_mb}MB VRAM)")
  765. else:
  766. self._log(" GPU: Keine CUDA-GPU erkannt")
  767. self._log(f" {len(rec_names)} empfohlene Modelle erkannt")
  768. self._log("")
  769. # --- STT Vosk ---
  770. if "stt_vosk" in self._config.selected_plugins:
  771. if "Vosk STT (Deutsch, gross)" in rec_names:
  772. downloads.append((
  773. "Vosk STT (Deutsch, gross)",
  774. "https://alphacephei.com/vosk/models/vosk-model-de-0.21.zip",
  775. "plugins/stt_vosk/models",
  776. True, "stt_vosk",
  777. ))
  778. elif "Vosk STT (Deutsch, klein)" in rec_names:
  779. downloads.append((
  780. "Vosk STT (Deutsch, klein)",
  781. "https://alphacephei.com/vosk/models/vosk-model-small-de-0.15.zip",
  782. "plugins/stt_vosk/models",
  783. True, "stt_vosk",
  784. ))
  785. # --- STT Whisper ---
  786. if "stt_whisper" in self._config.selected_plugins:
  787. # Bestes empfohlenes Whisper-Modell waehlen
  788. whisper_priority = ["medium", "small", "base", "tiny"]
  789. for model_name in whisper_priority:
  790. full_name = f"Whisper STT ({model_name})"
  791. if full_name in rec_names:
  792. self._log(f" Whisper: {model_name} empfohlen (wird beim Start geladen)")
  793. break
  794. # --- TTS Piper ---
  795. if "tts_piper" in self._config.selected_plugins:
  796. if "Piper TTS (thorsten-medium)" in rec_names:
  797. downloads.append((
  798. "Piper TTS (thorsten-medium, onnx)",
  799. "https://huggingface.co/rhasspy/piper-voices/resolve/main/"
  800. "de/de_DE/thorsten/medium/de_DE-thorsten-medium.onnx",
  801. "models/piper/de_DE-thorsten-medium.onnx",
  802. False, None,
  803. ))
  804. downloads.append((
  805. "Piper TTS (thorsten-medium, config)",
  806. "https://huggingface.co/rhasspy/piper-voices/resolve/main/"
  807. "de/de_DE/thorsten/medium/de_DE-thorsten-medium.onnx.json",
  808. "models/piper/de_DE-thorsten-medium.onnx.json",
  809. False, None,
  810. ))
  811. # --- NLP LLM ---
  812. if "nlp_llm" in self._config.selected_plugins:
  813. if "Qwen 2.5 1.5B (Q4_K_M)" in rec_names:
  814. downloads.append((
  815. "Qwen 2.5 1.5B (Q4_K_M)",
  816. "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/"
  817. "qwen2.5-1.5b-instruct-q4_k_m.gguf",
  818. "models/nlp/qwen2.5-1.5b-instruct-q4_k_m.gguf",
  819. False, None,
  820. ))
  821. return downloads
  822. async def step_download_models(self) -> bool:
  823. """Laedt ML-Modelle basierend auf Hardware-Empfehlung herunter."""
  824. if not self._config.download_models:
  825. self._log(" Modell-Download deaktiviert — uebersprungen")
  826. return True
  827. source = self._config.source_path
  828. downloads = self._get_model_downloads()
  829. if not downloads:
  830. self._log(" Keine Modelle zum Herunterladen (keine passenden Empfehlungen)")
  831. return True
  832. downloaded = 0
  833. total_size = 0
  834. for name, url, target_rel, extract, plugin in downloads:
  835. if self._cancelled:
  836. return False
  837. target = f"{source}/{target_rel}"
  838. # Pruefen ob bereits vorhanden
  839. if not extract and os.path.isfile(target):
  840. self._log(f" {name} — bereits vorhanden")
  841. continue
  842. if extract and os.path.isdir(target) and os.listdir(target):
  843. self._log(f" {name} — bereits vorhanden")
  844. continue
  845. self._log(f" Lade herunter: {name}...")
  846. if extract:
  847. # ZIP herunterladen und entpacken
  848. zip_path = "/tmp/trixy_model_download.zip"
  849. code, _ = await self._run_cmd(
  850. "wget", "-q", "--show-progress", "-O", zip_path, url,
  851. )
  852. if code != 0:
  853. self._log(f" WARNUNG: Download fehlgeschlagen — {name}")
  854. continue
  855. await self._run_sudo("mkdir", "-p", target)
  856. code, _ = await self._run_cmd(
  857. "unzip", "-q", "-o", zip_path, "-d", target,
  858. )
  859. if os.path.exists(zip_path):
  860. os.unlink(zip_path)
  861. if code != 0:
  862. self._log(f" WARNUNG: Entpacken fehlgeschlagen — {name}")
  863. continue
  864. else:
  865. # Direkt herunterladen
  866. target_dir = os.path.dirname(target)
  867. await self._run_sudo("mkdir", "-p", target_dir)
  868. code, _ = await self._run_cmd(
  869. "wget", "-q", "--show-progress", "-O", target, url,
  870. )
  871. if code != 0:
  872. self._log(f" WARNUNG: Download fehlgeschlagen — {name}")
  873. continue
  874. # Groesse ermitteln
  875. if os.path.isfile(target):
  876. total_size += os.path.getsize(target) // (1024 * 1024)
  877. elif os.path.isdir(target):
  878. for dirpath, _, filenames in os.walk(target):
  879. for f in filenames:
  880. total_size += os.path.getsize(os.path.join(dirpath, f)) // (1024 * 1024)
  881. downloaded += 1
  882. self._log(f" -> {name} installiert")
  883. self._log(f" {downloaded} Modell(e) heruntergeladen ({total_size} MB)")
  884. return True
  885. async def step_verify(self) -> bool:
  886. """Verifiziert die Installation."""
  887. checks = ["ffmpeg", "python3"]
  888. all_ok = True
  889. for cmd in checks:
  890. path = shutil.which(cmd)
  891. if path:
  892. self._log(f" OK: {cmd} ({path})")
  893. else:
  894. self._log(f" FEHLT: {cmd}")
  895. all_ok = False
  896. # venv pruefen
  897. venv_python = f"{self._config.venv_path}/bin/python"
  898. if os.path.isfile(venv_python):
  899. self._log(f" OK: venv ({venv_python})")
  900. else:
  901. self._log(f" FEHLT: venv ({venv_python})")
  902. all_ok = False
  903. # Temporaere Verzeichnisse aufraeumen (pip-Cache, TMPDIR)
  904. for tmp_name in ("tmp", "pip-cache"):
  905. tmp_path = f"{self._config.install_path}/{tmp_name}"
  906. if os.path.isdir(tmp_path):
  907. await self._run_sudo("rm", "-rf", tmp_path)
  908. self._log(f" Aufgeraeumt: {tmp_name}")
  909. return all_ok