Coverage for src/romfarmer/farmhand/deployer.py: 0%

173 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-01 23:08 -0700

1"""Deployer — executes a DeploymentPlan by transferring ROMs to the target. 

2 

3Handles file comparison (delta sync), SFTP transfers with progress, 

4and optional post-deploy actions (EmulationStation restart, etc.). 

5""" 

6 

7from __future__ import annotations 

8 

9import logging 

10import os 

11from collections.abc import Callable 

12from datetime import datetime 

13from pathlib import Path 

14from typing import Any 

15 

16from romfarmer.farmhand.models import ( 

17 DeploymentPlan, 

18 DeploymentStatus, 

19 PlatformAllocation, 

20 SelectionAction, 

21 TransferProgress, 

22) 

23from romfarmer.farmhand.ssh import SSHClient 

24 

25logger = logging.getLogger(__name__) 

26 

27# Type for deployment event callbacks 

28DeployCallback = Callable[[str, dict[str, Any]], None] 

29 

30 

31class Deployer: 

32 """Executes a deployment plan by transferring ROM files to the target. 

33 

34 Supports delta sync (only transfer new/changed files), progress 

35 tracking, dry-run mode, and post-deploy hooks. 

36 

37 Usage: 

38 deployer = Deployer(ssh_client, output_root=Path("output/build-name")) 

39 deployer.deploy(plan, dry_run=True) 

40 deployer.deploy(plan) 

41 """ 

42 

43 def __init__( 

44 self, 

45 ssh: SSHClient, 

46 output_root: Path, 

47 frontend_config: dict | None = None, 

48 on_event: DeployCallback | None = None, 

49 ) -> None: 

50 """ 

51 Args: 

52 ssh: Connected SSH client. 

53 output_root: Local path to the build output (e.g., output/nointro-1g1r-eng-7z-batocera-v2). 

54 frontend_config: Frontend folder mapping (platform -> folder name). 

55 on_event: Callback for deployment events (for progress tracking). 

56 """ 

57 self.ssh = ssh 

58 self.output_root = output_root 

59 self.frontend_config = frontend_config or {} 

60 self.on_event = on_event 

61 

62 self._progress = TransferProgress() 

63 self._cancelled = False 

64 

65 # ------------------------------------------------------------------ 

66 # Main deployment entry point 

67 # ------------------------------------------------------------------ 

68 

69 def deploy( 

70 self, 

71 plan: DeploymentPlan, 

72 dry_run: bool = False, 

73 delta_sync: bool = True, 

74 verify: bool = False, 

75 ) -> DeploymentPlan: 

76 """Execute the deployment plan. 

77 

78 Args: 

79 plan: The deployment plan to execute. 

80 dry_run: If True, log what would be done without transferring. 

81 delta_sync: If True, skip files that already exist on target with same size. 

82 verify: If True, verify file sizes after transfer. 

83 

84 Returns: 

85 Updated plan with actual transfer stats. 

86 """ 

87 plan.status = DeploymentStatus.TRANSFERRING 

88 self._cancelled = False 

89 

90 included = [a for a in plan.allocations if a.action != SelectionAction.SKIP] 

91 

92 logger.info( 

93 "Deploying %d platforms to %s (%s mode)", 

94 len(included), 

95 plan.target_name, 

96 "dry-run" if dry_run else "live", 

97 ) 

98 

99 total_bytes_sent = 0 

100 total_files_sent = 0 

101 errors: list[str] = [] 

102 

103 for alloc in included: 

104 if self._cancelled: 

105 plan.status = DeploymentStatus.CANCELLED 

106 plan.notes.append("Deployment cancelled by user") 

107 return plan 

108 

109 try: 

110 bytes_sent, files_sent = self._deploy_platform( 

111 alloc, dry_run=dry_run, delta_sync=delta_sync 

112 ) 

113 alloc.bytes_transferred = bytes_sent 

114 alloc.files_transferred = files_sent 

115 total_bytes_sent += bytes_sent 

116 total_files_sent += files_sent 

117 

118 self._emit( 

119 "platform_done", 

120 { 

121 "platform": alloc.platform, 

122 "files": files_sent, 

123 "bytes": bytes_sent, 

124 }, 

125 ) 

126 except Exception as exc: 

127 msg = f"Failed to deploy {alloc.platform}: {exc}" 

128 logger.error(msg) 

129 errors.append(msg) 

130 

131 if errors: 

132 plan.status = DeploymentStatus.FAILED 

133 plan.notes.extend(errors) 

134 else: 

135 plan.status = DeploymentStatus.COMPLETED 

136 

137 plan.notes.append( 

138 f"Transfer complete: {total_files_sent} files, {total_bytes_sent / 1024**3:.1f} GB" 

139 ) 

140 

141 logger.info( 

142 "Deployment %s: %d files, %.1f GB", 

143 plan.status.value, 

144 total_files_sent, 

145 total_bytes_sent / 1024**3, 

146 ) 

147 

148 return plan 

149 

150 def cancel(self) -> None: 

151 """Cancel the current deployment.""" 

152 self._cancelled = True 

153 

154 # ------------------------------------------------------------------ 

155 # Per-platform deployment 

156 # ------------------------------------------------------------------ 

157 

158 def _deploy_platform( 

159 self, 

160 alloc: PlatformAllocation, 

161 dry_run: bool = False, 

162 delta_sync: bool = True, 

163 ) -> tuple[int, int]: 

164 """Deploy a single platform's files to the target. 

165 

166 Returns: 

167 Tuple of (bytes_transferred, files_transferred). 

168 """ 

169 # Resolve local source directory 

170 local_dir = self._resolve_local_dir(alloc.platform) 

171 if local_dir is None or not local_dir.exists(): 

172 logger.warning("No local output for %s at expected path", alloc.platform) 

173 return 0, 0 

174 

175 # Resolve remote destination 

176 remote_dir = self._resolve_remote_dir(alloc) 

177 if not remote_dir: 

178 logger.warning("No remote path resolved for %s", alloc.platform) 

179 return 0, 0 

180 

181 # Collect local files to transfer 

182 local_files = self._collect_local_files(local_dir) 

183 if not local_files: 

184 logger.info("No files to deploy for %s", alloc.platform) 

185 return 0, 0 

186 

187 alloc.files_total = len(local_files) 

188 

189 # Delta sync: check what already exists on target 

190 skip_files: set[str] = set() 

191 if delta_sync and not dry_run: 

192 skip_files = self._compute_delta(local_files, local_dir, remote_dir) 

193 if skip_files: 

194 logger.info( 

195 "%s: %d/%d files already on target (skipping)", 

196 alloc.platform, 

197 len(skip_files), 

198 len(local_files), 

199 ) 

200 

201 files_to_send = [f for f in local_files if f not in skip_files] 

202 

203 if dry_run: 

204 total_size = sum( 

205 (local_dir / f).stat().st_size for f in files_to_send if (local_dir / f).exists() 

206 ) 

207 logger.info( 

208 "[DRY RUN] %s: would transfer %d files (%.1f GB) to %s", 

209 alloc.platform, 

210 len(files_to_send), 

211 total_size / 1024**3, 

212 remote_dir, 

213 ) 

214 return 0, 0 

215 

216 # Create remote directory 

217 self.ssh.mkdir_p(remote_dir) 

218 

219 # Transfer files 

220 bytes_sent = 0 

221 files_sent = 0 

222 

223 self._progress = TransferProgress( 

224 platform=alloc.platform, 

225 files_total=len(files_to_send), 

226 bytes_total=sum( 

227 (local_dir / f).stat().st_size for f in files_to_send if (local_dir / f).exists() 

228 ), 

229 started_at=datetime.now(), 

230 ) 

231 

232 for relative_path in files_to_send: 

233 if self._cancelled: 

234 break 

235 

236 local_file = local_dir / relative_path 

237 if not local_file.exists(): 

238 continue 

239 

240 remote_file = f"{remote_dir}/{relative_path}" 

241 file_size = local_file.stat().st_size 

242 

243 self._progress.current_file = relative_path 

244 

245 try: 

246 self.ssh.upload( 

247 local_file, 

248 remote_file, 

249 progress_callback=self._on_file_progress, 

250 ) 

251 bytes_sent += file_size 

252 files_sent += 1 

253 self._progress.files_done = files_sent 

254 self._progress.bytes_done = bytes_sent 

255 

256 self._emit( 

257 "file_done", 

258 { 

259 "platform": alloc.platform, 

260 "file": relative_path, 

261 "size": file_size, 

262 "progress": self._progress.percent, 

263 }, 

264 ) 

265 except Exception as exc: 

266 logger.error("Failed to upload %s: %s", local_file, exc) 

267 

268 return bytes_sent, files_sent 

269 

270 # ------------------------------------------------------------------ 

271 # Path resolution 

272 # ------------------------------------------------------------------ 

273 

274 def _resolve_local_dir(self, platform: str) -> Path | None: 

275 """Find the local output directory for a platform. 

276 

277 Checks both the platform name and frontend folder mapping. 

278 """ 

279 # Direct match 

280 direct = self.output_root / platform 

281 if direct.exists(): 

282 return direct 

283 

284 # Check frontend folder mapping (reverse: folder_name -> platform) 

285 for internal_name, folder_name in self.frontend_config.items(): 

286 if internal_name == platform: 

287 mapped = self.output_root / folder_name 

288 if mapped.exists(): 

289 return mapped 

290 

291 # Try just listing the output root for a fuzzy match 

292 if self.output_root.exists(): 

293 for child in self.output_root.iterdir(): 

294 if child.is_dir() and child.name.lower() == platform.lower(): 

295 return child 

296 

297 return None 

298 

299 def _resolve_remote_dir(self, alloc: PlatformAllocation) -> str | None: 

300 """Determine the remote path for a platform on the target volume.""" 

301 if not alloc.target_volume: 

302 return None 

303 

304 # The folder name on the target follows the frontend convention 

305 folder_name = self.frontend_config.get(alloc.platform, alloc.platform) 

306 

307 # Find the volume's rom_path 

308 # We stored the volume mount point in alloc.target_volume 

309 # Convention: rom_path = {mount_point}/roms/{folder_name} 

310 rom_base = f"{alloc.target_volume}/roms" 

311 if alloc.target_volume == "/userdata": 

312 rom_base = "/userdata/roms" 

313 

314 return f"{rom_base}/{folder_name}" 

315 

316 # ------------------------------------------------------------------ 

317 # File collection and delta sync 

318 # ------------------------------------------------------------------ 

319 

320 def _collect_local_files(self, local_dir: Path) -> list[str]: 

321 """Collect all files in a local directory (relative paths).""" 

322 files: list[str] = [] 

323 for root, _dirs, filenames in os.walk(local_dir): 

324 for fname in filenames: 

325 full_path = Path(root) / fname 

326 rel_path = full_path.relative_to(local_dir) 

327 files.append(str(rel_path)) 

328 return sorted(files) 

329 

330 def _compute_delta( 

331 self, 

332 local_files: list[str], 

333 local_dir: Path, 

334 remote_dir: str, 

335 ) -> set[str]: 

336 """Determine which local files already exist on target with matching size. 

337 

338 Returns set of relative paths to skip. 

339 """ 

340 skip: set[str] = set() 

341 

342 # Get remote file listing with sizes 

343 try: 

344 output = self.ssh.run( 

345 f"find {remote_dir} -type f -printf '%P\\t%s\\n' 2>/dev/null", 

346 timeout=60, 

347 ) 

348 except Exception: 

349 return skip 

350 

351 remote_files: dict[str, int] = {} 

352 for line in output.strip().splitlines(): 

353 parts = line.split("\t", 1) 

354 if len(parts) == 2: 

355 try: 

356 remote_files[parts[0]] = int(parts[1]) 

357 except ValueError: 

358 pass 

359 

360 for local_file in local_files: 

361 if local_file in remote_files: 

362 local_size = (local_dir / local_file).stat().st_size 

363 if local_size == remote_files[local_file]: 

364 skip.add(local_file) 

365 

366 return skip 

367 

368 # ------------------------------------------------------------------ 

369 # Post-deploy actions 

370 # ------------------------------------------------------------------ 

371 

372 def restart_emulationstation(self) -> str: 

373 """Restart EmulationStation on the target (Batocera).""" 

374 logger.info("Restarting EmulationStation on target") 

375 try: 

376 return self.ssh.run( 

377 "batocera-es-swissknife --restart 2>&1 || " 

378 "systemctl restart emulationstation 2>&1 || " 

379 "echo 'Could not restart ES'", 

380 timeout=30, 

381 ) 

382 except Exception as exc: 

383 return f"Failed to restart ES: {exc}" 

384 

385 def trigger_rom_rescan(self) -> str: 

386 """Trigger a ROM rescan on the target.""" 

387 logger.info("Triggering ROM rescan on target") 

388 try: 

389 return self.ssh.run( 

390 "batocera-es-swissknife --gamesdb-reinit 2>&1 || echo 'Rescan not available'", 

391 timeout=60, 

392 ) 

393 except Exception as exc: 

394 return f"Failed to trigger rescan: {exc}" 

395 

396 # ------------------------------------------------------------------ 

397 # Progress callbacks 

398 # ------------------------------------------------------------------ 

399 

400 def _on_file_progress(self, transferred: int, total: int) -> None: 

401 """Called by SFTP upload for per-file progress.""" 

402 if total > 0 and self.on_event: 

403 self._emit( 

404 "file_progress", 

405 { 

406 "platform": self._progress.platform, 

407 "file": self._progress.current_file, 

408 "transferred": transferred, 

409 "total": total, 

410 }, 

411 ) 

412 

413 def _emit(self, event: str, data: dict[str, Any]) -> None: 

414 """Emit a deployment event.""" 

415 if self.on_event: 

416 try: 

417 self.on_event(event, data) 

418 except Exception: 

419 pass 

420 

421 @property 

422 def progress(self) -> TransferProgress: 

423 """Current transfer progress.""" 

424 return self._progress