Coverage for src/romfarmer/farmhand/analyzer.py: 0%
202 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
1"""Target system analyzer — introspects remote hosts via SSH.
3Discovers volumes, existing ROMs, installed binaries, emulator capabilities,
4and system information. Populates a TargetProfile with everything the
5planner needs to make deployment decisions.
6"""
8from __future__ import annotations
10import logging
11import re
12from datetime import datetime
13from pathlib import PurePosixPath
15from romfarmer.farmhand.models import (
16 SystemInfo,
17 TargetCapabilities,
18 TargetProfile,
19 VolumeInfo,
20 VolumeRole,
21)
22from romfarmer.farmhand.ssh import SSHClient
24logger = logging.getLogger(__name__)
26# Default Batocera ROM path on the primary data partition
27BATOCERA_ROM_PATH = "/userdata/roms"
28# Batocera secondary storage convention — ROMs can live under /media/*/roms
29BATOCERA_MEDIA_PREFIX = "/media"
31# Common emulator-related binaries to check for
32_EMULATOR_BINARIES = [
33 "retroarch",
34 "mame",
35 "dolphin-emu",
36 "dolphin-emu-nogui",
37 "ppsspp",
38 "pcsx2",
39 "rpcs3",
40 "duckstation",
41 "flycast",
42 "mednafen",
43 "mupen64plus",
44 "citra",
45 "yuzu",
46 "ryujinx",
47 "xemu",
48 "cemu",
49]
51# Utility binaries relevant to ROM format support
52_UTILITY_BINARIES = [
53 "7z",
54 "7zr",
55 "7za",
56 "unzip",
57 "zip",
58 "chdman",
59 "extract-xiso",
60 "maxcso",
61 "rsync",
62 "md5sum",
63 "sha1sum",
64]
67class TargetAnalyzer:
68 """Analyzes a remote target system to build a complete TargetProfile.
70 Usage:
71 analyzer = TargetAnalyzer(ssh_client)
72 profile = analyzer.full_scan(name="batocera-nuc", frontend="batocera")
73 """
75 def __init__(self, ssh: SSHClient) -> None:
76 self.ssh = ssh
78 # ------------------------------------------------------------------
79 # Full scan — combines all the sub-scans
80 # ------------------------------------------------------------------
82 def full_scan(
83 self,
84 name: str,
85 frontend: str = "batocera",
86 device_type: str = "pc",
87 ) -> TargetProfile:
88 """Run a full analysis of the target and return a populated TargetProfile."""
89 logger.info("Starting full scan of %s (%s)", self.ssh.host, frontend)
91 profile = TargetProfile(
92 name=name,
93 host=self.ssh.host,
94 port=self.ssh.port,
95 user=self.ssh.user,
96 auth_method="key_file" if self.ssh.key_file else "password",
97 key_file=self.ssh.key_file,
98 frontend=frontend,
99 device_type=device_type,
100 )
102 profile.system_info = self.scan_system_info()
103 profile.volumes = self.scan_volumes(frontend=frontend)
104 profile.capabilities = self.scan_capabilities()
105 profile.existing_roms = self.scan_existing_roms(profile.volumes)
106 profile.last_scanned = datetime.now()
108 logger.info(
109 "Scan complete: %d volumes, %d platforms with existing ROMs, %d binaries",
110 len(profile.volumes),
111 len(profile.existing_roms),
112 len(profile.capabilities.binaries) if profile.capabilities else 0,
113 )
114 return profile
116 # ------------------------------------------------------------------
117 # System information
118 # ------------------------------------------------------------------
120 def scan_system_info(self) -> SystemInfo:
121 """Gather system information from the target."""
122 info = SystemInfo()
124 # Hostname
125 try:
126 info.hostname = self.ssh.run("hostname").strip()
127 except Exception:
128 pass
130 # Kernel / architecture
131 try:
132 uname = self.ssh.run("uname -srm").strip()
133 parts = uname.split()
134 if len(parts) >= 1:
135 info.os_name = parts[0] # Linux
136 if len(parts) >= 2:
137 info.kernel_version = parts[1]
138 if len(parts) >= 3:
139 info.architecture = parts[2]
140 except Exception:
141 pass
143 # CPU info
144 try:
145 cpu_out = self.ssh.run("cat /proc/cpuinfo | head -30").strip()
146 for line in cpu_out.splitlines():
147 if line.startswith("model name"):
148 info.cpu_model = line.split(":", 1)[1].strip()
149 elif line.startswith("cpu cores"):
150 try:
151 info.cpu_cores = int(line.split(":", 1)[1].strip())
152 except ValueError:
153 pass
154 # Thread count
155 nproc = self.ssh.run("nproc 2>/dev/null").strip()
156 try:
157 info.cpu_threads = int(nproc)
158 except ValueError:
159 pass
160 except Exception:
161 pass
163 # Memory
164 try:
165 mem_out = self.ssh.run("cat /proc/meminfo | head -3").strip()
166 for line in mem_out.splitlines():
167 if line.startswith("MemTotal"):
168 kb = int(re.search(r"(\d+)", line).group(1)) # type: ignore[union-attr]
169 info.memory_total_mb = kb // 1024
170 elif line.startswith("MemAvailable"):
171 kb = int(re.search(r"(\d+)", line).group(1)) # type: ignore[union-attr]
172 info.memory_available_mb = kb // 1024
173 except Exception:
174 pass
176 # Batocera-specific: OS version
177 try:
178 batocera_version = self.ssh.run(
179 "cat /usr/share/batocera/batocera.version 2>/dev/null"
180 ).strip()
181 if batocera_version:
182 info.os_name = "Batocera"
183 info.os_version = batocera_version
184 except Exception:
185 pass
187 # Display resolution
188 try:
189 xrandr = self.ssh.run("cat /sys/class/drm/card*/modes 2>/dev/null | head -1").strip()
190 if xrandr:
191 info.display_resolution = xrandr
192 except Exception:
193 pass
195 logger.info(
196 "System: %s %s, %s, %s, %d MB RAM",
197 info.os_name,
198 info.os_version,
199 info.architecture,
200 info.cpu_model,
201 info.memory_total_mb,
202 )
203 return info
205 # ------------------------------------------------------------------
206 # Volume discovery
207 # ------------------------------------------------------------------
209 def scan_volumes(self, frontend: str = "batocera") -> list[VolumeInfo]:
210 """Discover and classify storage volumes on the target."""
211 raw_df = self.ssh.run("df -B1 --output=source,fstype,size,used,avail,pcent,target")
212 volumes: list[VolumeInfo] = []
214 for line in raw_df.strip().splitlines()[1:]: # skip header
215 parts = line.split()
216 if len(parts) < 7:
217 continue
219 device = parts[0]
220 fstype = parts[1]
221 mount_point = parts[-1]
223 # Skip pseudo-filesystems and system paths
224 if fstype in ("tmpfs", "devtmpfs", "overlay", "squashfs", "none", "efivarfs"):
225 continue
226 if mount_point in ("/", "/boot"):
227 continue
228 if mount_point.startswith(("/sys/", "/proc/", "/run/")):
229 continue
231 try:
232 total = int(parts[2])
233 used = int(parts[3])
234 avail = int(parts[4])
235 pct_str = parts[5].rstrip("%")
236 pct = float(pct_str)
237 except (ValueError, IndexError):
238 continue
240 # Classify the volume's role
241 role = self._classify_volume(mount_point, frontend)
242 rom_path = self._infer_rom_path(mount_point, role, frontend)
244 vol = VolumeInfo(
245 mount_point=mount_point,
246 filesystem=fstype,
247 device=device,
248 total_bytes=total,
249 used_bytes=used,
250 available_bytes=avail,
251 use_percent=pct,
252 role=role,
253 rom_path=rom_path,
254 )
255 volumes.append(vol)
256 logger.info(
257 "Volume %s: %.1f GB total, %.1f GB free, role=%s, rom_path=%s",
258 mount_point,
259 vol.total_gb,
260 vol.available_gb,
261 role.value,
262 rom_path or "none",
263 )
265 return volumes
267 def _classify_volume(self, mount_point: str, frontend: str) -> VolumeRole:
268 """Determine the role of a volume based on its mount point."""
269 if frontend == "batocera":
270 if mount_point == "/userdata":
271 return VolumeRole.PRIMARY
272 elif mount_point.startswith("/media/"):
273 return VolumeRole.SECONDARY
274 elif frontend == "rocknix":
275 if mount_point in ("/storage", "/userdata"):
276 return VolumeRole.PRIMARY
277 elif mount_point.startswith("/media/") or mount_point.startswith("/mnt/"):
278 return VolumeRole.SECONDARY
279 # Generic fallback
280 if mount_point == "/":
281 return VolumeRole.SYSTEM
282 return VolumeRole.SECONDARY
284 def _infer_rom_path(self, mount_point: str, role: VolumeRole, frontend: str) -> str | None:
285 """Infer where ROMs should be stored on a given volume."""
286 if role == VolumeRole.SYSTEM:
287 return None
289 if frontend == "batocera":
290 if mount_point == "/userdata":
291 return "/userdata/roms"
292 elif mount_point.startswith("/media/"):
293 # Secondary drives: ROMs go in a roms/ subdirectory
294 return f"{mount_point}/roms"
295 elif frontend == "rocknix":
296 if mount_point in ("/storage", "/userdata"):
297 return f"{mount_point}/roms"
298 else:
299 return f"{mount_point}/roms"
301 return f"{mount_point}/roms"
303 # ------------------------------------------------------------------
304 # Capability detection
305 # ------------------------------------------------------------------
307 def scan_capabilities(self) -> TargetCapabilities:
308 """Detect available binaries and emulator capabilities on the target."""
309 caps = TargetCapabilities()
311 # Check for utility binaries
312 all_binaries = _EMULATOR_BINARIES + _UTILITY_BINARIES
313 which_cmd = " && ".join(f"which {b} 2>/dev/null || true" for b in all_binaries)
314 output = self.ssh.run(which_cmd, timeout=15)
316 found_paths = [line.strip() for line in output.splitlines() if line.strip()]
317 for path in found_paths:
318 binary_name = PurePosixPath(path).name
319 caps.binaries.append(binary_name)
320 if binary_name in _EMULATOR_BINARIES:
321 caps.emulators.append(binary_name)
323 caps.has_7z = any(b in caps.binaries for b in ("7z", "7zr", "7za"))
324 caps.has_chdman = "chdman" in caps.binaries
326 # Try to discover Batocera emulator configuration
327 try:
328 es_systems = self.ssh.run(
329 "cat /usr/share/batocera/configgen/configgen-defaults.yml 2>/dev/null | head -100",
330 timeout=10,
331 )
332 if es_systems.strip():
333 logger.info("Found Batocera configgen defaults — can parse emulator assignments")
334 # We could parse this deeply; for now just note it exists
335 except Exception:
336 pass
338 # Detect RetroArch cores if available
339 try:
340 cores_output = self.ssh.run("ls /usr/lib/libretro/ 2>/dev/null | head -50", timeout=10)
341 if cores_output.strip():
342 cores = [
343 line.strip().replace("_libretro.so", "").replace(".so", "")
344 for line in cores_output.splitlines()
345 if line.strip()
346 ]
347 caps.emulators.extend(cores[:50]) # cap at 50 to avoid bloat
348 except Exception:
349 pass
351 logger.info(
352 "Capabilities: %d binaries, %d emulators, 7z=%s, chdman=%s",
353 len(caps.binaries),
354 len(caps.emulators),
355 caps.has_7z,
356 caps.has_chdman,
357 )
358 return caps
360 # ------------------------------------------------------------------
361 # Existing ROM discovery
362 # ------------------------------------------------------------------
364 def scan_existing_roms(
365 self,
366 volumes: list[VolumeInfo],
367 max_files_per_platform: int = 10000,
368 ) -> dict[str, list[str]]:
369 """Scan target volumes for existing ROMs, organized by platform folder.
371 Returns:
372 Dict mapping platform folder name -> list of ROM filenames.
373 e.g., {"psx": ["Final Fantasy VII (USA).chd", ...], "nes": [...]}
374 """
375 existing: dict[str, list[str]] = {}
377 for vol in volumes:
378 if not vol.rom_path:
379 continue
381 # Check if the roms directory exists
382 try:
383 entries = self.ssh.run(f"ls -1 {vol.rom_path}/ 2>/dev/null", timeout=15).strip()
384 if not entries:
385 continue
386 except Exception:
387 continue
389 platform_dirs = [d.strip() for d in entries.splitlines() if d.strip()]
391 for platform_dir in platform_dirs:
392 platform_path = f"{vol.rom_path}/{platform_dir}"
393 try:
394 # Get file listing (just names, not directories)
395 files_output = self.ssh.run(
396 f"find {platform_path} -maxdepth 1 -type f -printf '%f\\n' "
397 f"2>/dev/null | head -{max_files_per_platform}",
398 timeout=30,
399 )
400 files = [f.strip() for f in files_output.splitlines() if f.strip()]
401 if files:
402 # Accumulate across volumes
403 if platform_dir in existing:
404 existing[platform_dir].extend(files)
405 else:
406 existing[platform_dir] = files
407 except Exception as exc:
408 logger.warning("Failed to scan %s: %s", platform_path, exc)
409 continue
411 total_roms = sum(len(v) for v in existing.values())
412 logger.info(
413 "Found existing ROMs: %d platforms, %d files total",
414 len(existing),
415 total_roms,
416 )
417 return existing
419 # ------------------------------------------------------------------
420 # Utility: quick probe
421 # ------------------------------------------------------------------
423 def quick_probe(self) -> dict:
424 """Fast probe — just hostname, OS, and disk space. No ROM scanning."""
425 hostname = self.ssh.run("hostname").strip()
426 df_output = self.ssh.run("df -h")
427 uname = self.ssh.run("uname -srm").strip()
428 return {
429 "hostname": hostname,
430 "uname": uname,
431 "disk_usage": df_output,
432 "connected": True,
433 }