manager.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. """Virtual Printer Manager - coordinates SSDP, MQTT, and FTP services.
  2. Each virtual printer runs its own independent services (FTP, MQTT, SSDP, Bind)
  3. bound to its dedicated IP address, regardless of mode.
  4. """
  5. import asyncio
  6. import logging
  7. from collections.abc import Callable
  8. from datetime import datetime, timezone
  9. from pathlib import Path
  10. from backend.app.core.config import settings as app_settings
  11. from backend.app.services.virtual_printer.bind_server import BindServer
  12. from backend.app.services.virtual_printer.certificate import CertificateService
  13. from backend.app.services.virtual_printer.ftp_server import VirtualPrinterFTPServer
  14. from backend.app.services.virtual_printer.mqtt_server import SimpleMQTTServer
  15. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy, VirtualPrinterSSDPServer
  16. from backend.app.services.virtual_printer.tailscale import tailscale_service
  17. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  18. logger = logging.getLogger(__name__)
  19. # Mapping of SSDP model codes to display names
  20. # These are the codes that slicers expect during discovery
  21. # Sources:
  22. # - https://gist.github.com/Alex-Schaefer/72a9e2491a42da2ef99fb87601955cc3
  23. # - https://github.com/psychoticbeef/BambuLabOrcaSlicerDiscovery
  24. VIRTUAL_PRINTER_MODELS = {
  25. # X1 Series
  26. "BL-P001": "X1C", # X1 Carbon
  27. "BL-P002": "X1", # X1
  28. "C13": "X1E", # X1E
  29. # X2 Series
  30. "N6": "X2D", # X2D
  31. # P Series
  32. "C11": "P1P", # P1P
  33. "C12": "P1S", # P1S
  34. "N7": "P2S", # P2S
  35. # A1 Series
  36. "N2S": "A1", # A1
  37. "N1": "A1 Mini", # A1 Mini
  38. # H2 Series
  39. "O1D": "H2D", # H2D
  40. "O1C": "H2C", # H2C
  41. "O1C2": "H2C", # H2C (dual nozzle variant)
  42. "O1S": "H2S", # H2S
  43. }
  44. # Serial number prefixes for each model (based on Bambu Lab serial number format)
  45. # Format: MMM??RYMDDUUUUU (15 chars total)
  46. # MMM = Model prefix (3 chars)
  47. # ?? = Unknown/revision code (2 chars)
  48. # R = Revision letter (1 char)
  49. # Y = Year digit (1 char)
  50. # M = Month (1 char, hex: 1-9, A=Oct, B=Nov, C=Dec)
  51. # DD = Day (2 chars)
  52. # UUUUU = Unit number (5 chars)
  53. MODEL_SERIAL_PREFIXES = {
  54. # X1 Series
  55. "BL-P001": "00M00A", # X1C
  56. "BL-P002": "00M00A", # X1
  57. "C13": "03W00A", # X1E
  58. # X2 Series
  59. "N6": "20P90A", # X2D (first 4 chars "20P9" match real serials)
  60. # P Series
  61. "C11": "01S00A", # P1P
  62. "C12": "01P00A", # P1S
  63. "N7": "22E00A", # P2S
  64. # A1 Series
  65. "N2S": "03900A", # A1
  66. "N1": "03000A", # A1 Mini
  67. # H2 Series
  68. "O1D": "09400A", # H2D
  69. "O1C": "09400A", # H2C
  70. "O1C2": "09400A", # H2C (dual nozzle variant)
  71. "O1S": "09400A", # H2S
  72. }
  73. # Reverse mapping: display name → SSDP model code (for auto-inheriting from printer model)
  74. DISPLAY_NAME_TO_MODEL_CODE = {v: k for k, v in VIRTUAL_PRINTER_MODELS.items()}
  75. # Default model
  76. DEFAULT_VIRTUAL_PRINTER_MODEL = "BL-P001" # X1C
  77. def _get_serial_for_model(model: str, serial_suffix: str) -> str:
  78. """Get serial number for the given model and suffix."""
  79. prefix = MODEL_SERIAL_PREFIXES.get(model, "00M09A")
  80. return f"{prefix}{serial_suffix}"
  81. class VirtualPrinterInstance:
  82. """Per-printer state and file handling logic.
  83. Each instance represents one virtual printer with its own config,
  84. upload directory, certificates, and file handling mode.
  85. """
  86. def __init__(
  87. self,
  88. *,
  89. vp_id: int,
  90. name: str,
  91. mode: str,
  92. model: str,
  93. access_code: str,
  94. serial_suffix: str,
  95. target_printer_ip: str = "",
  96. target_printer_serial: str = "",
  97. target_printer_id: int | None = None,
  98. auto_dispatch: bool = True,
  99. bind_ip: str = "",
  100. remote_interface_ip: str = "",
  101. tailscale_disabled: bool = False,
  102. base_dir: Path,
  103. session_factory: Callable | None = None,
  104. ):
  105. self.id = vp_id
  106. self.name = name
  107. self.mode = mode
  108. self.model = model
  109. self.access_code = access_code
  110. self.serial_suffix = serial_suffix
  111. self.target_printer_ip = target_printer_ip
  112. self.target_printer_serial = target_printer_serial
  113. self.target_printer_id = target_printer_id
  114. self.auto_dispatch = auto_dispatch
  115. self.bind_ip = bind_ip
  116. self.remote_interface_ip = remote_interface_ip
  117. self.tailscale_disabled = tailscale_disabled
  118. self._session_factory = session_factory
  119. # Directories
  120. self.upload_dir = base_dir / "uploads" / str(vp_id)
  121. self.cert_dir = base_dir / "certs" / str(vp_id)
  122. shared_ca_dir = base_dir / "certs"
  123. # Ensure directories exist
  124. self.upload_dir.mkdir(parents=True, exist_ok=True)
  125. (self.upload_dir / "cache").mkdir(exist_ok=True)
  126. self.cert_dir.mkdir(parents=True, exist_ok=True)
  127. # Certificate service (shared CA, per-instance printer cert)
  128. self._cert_service = CertificateService(
  129. cert_dir=self.cert_dir,
  130. serial=self.serial,
  131. shared_ca_dir=shared_ca_dir,
  132. )
  133. # Tailscale FQDN used for this instance (set at start_server/start_proxy time)
  134. self.tailscale_fqdn: str | None = None
  135. # Pending files for MQTT correlation
  136. self._pending_files: dict[str, Path] = {}
  137. # Per-instance services
  138. self._proxy: SlicerProxyManager | None = None
  139. self._ftp: VirtualPrinterFTPServer | None = None
  140. self._mqtt: SimpleMQTTServer | None = None
  141. self._bind: BindServer | None = None
  142. self._ssdp: VirtualPrinterSSDPServer | None = None
  143. self._ssdp_proxy: SSDPProxy | None = None
  144. self._tasks: list[asyncio.Task] = []
  145. self._cert_renewal_task: asyncio.Task | None = None
  146. self._cert_restart_task: asyncio.Task | None = None
  147. @property
  148. def serial(self) -> str:
  149. """Full serial number for this virtual printer."""
  150. return _get_serial_for_model(self.model or DEFAULT_VIRTUAL_PRINTER_MODEL, self.serial_suffix)
  151. @property
  152. def cert_path(self) -> Path:
  153. return self._cert_service.cert_path
  154. @property
  155. def key_path(self) -> Path:
  156. return self._cert_service.key_path
  157. @property
  158. def is_proxy(self) -> bool:
  159. return self.mode == "proxy"
  160. @property
  161. def is_running(self) -> bool:
  162. return len(self._tasks) > 0 and all(not t.done() for t in self._tasks)
  163. def generate_certificates(self) -> tuple[Path, Path]:
  164. """Generate certificates for this instance."""
  165. self._cert_service.serial = self.serial if not self.is_proxy else (self.target_printer_serial or self.serial)
  166. additional_ips = [self.remote_interface_ip] if self.remote_interface_ip else None
  167. if self.bind_ip:
  168. additional_ips = additional_ips or []
  169. additional_ips.append(self.bind_ip)
  170. self._cert_service.delete_printer_certificate()
  171. return self._cert_service.generate_certificates(additional_ips=additional_ips)
  172. # -- File handling callbacks --
  173. async def on_file_received(self, file_path: Path, source_ip: str) -> None:
  174. """Handle file upload completion from FTP."""
  175. logger.info("[VP %s] Received file: %s from %s", self.name, file_path.name, source_ip)
  176. self._pending_files[file_path.name] = file_path
  177. if self.mode == "immediate":
  178. await self._archive_file(file_path, source_ip)
  179. elif self.mode == "print_queue":
  180. await self._add_to_print_queue(file_path, source_ip)
  181. else:
  182. await self._queue_file(file_path, source_ip)
  183. # Reset MQTT status back to IDLE
  184. if self._mqtt and file_path.suffix.lower() == ".3mf":
  185. self._mqtt.set_gcode_state("IDLE")
  186. async def on_print_command(self, filename: str, data: dict) -> None:
  187. """Handle print command from MQTT."""
  188. logger.info("[VP %s] Print command for: %s", self.name, filename)
  189. async def _archive_file(self, file_path: Path, source_ip: str) -> None:
  190. """Archive file immediately."""
  191. if not self._session_factory:
  192. logger.error("Cannot archive: no database session factory configured")
  193. return
  194. if file_path.suffix.lower() != ".3mf":
  195. logger.debug("Skipping non-3MF file: %s", file_path.name)
  196. self._pending_files.pop(file_path.name, None)
  197. try:
  198. file_path.unlink()
  199. except OSError:
  200. pass
  201. return
  202. try:
  203. from backend.app.services.archive import ArchiveService
  204. async with self._session_factory() as db:
  205. service = ArchiveService(db)
  206. archive = await service.archive_print(
  207. printer_id=None,
  208. source_file=file_path,
  209. print_data={
  210. "status": "archived",
  211. "source": "virtual_printer",
  212. "source_ip": source_ip,
  213. },
  214. )
  215. if archive:
  216. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  217. try:
  218. file_path.unlink()
  219. except OSError:
  220. pass
  221. self._pending_files.pop(file_path.name, None)
  222. else:
  223. logger.error("Failed to archive file: %s", file_path.name)
  224. except Exception as e:
  225. logger.error("Error archiving file: %s", e)
  226. async def _queue_file(self, file_path: Path, source_ip: str) -> None:
  227. """Queue file for user review."""
  228. if not self._session_factory:
  229. logger.error("Cannot queue: no database session factory configured")
  230. return
  231. if file_path.suffix.lower() != ".3mf":
  232. self._pending_files.pop(file_path.name, None)
  233. try:
  234. file_path.unlink()
  235. except OSError:
  236. pass
  237. return
  238. try:
  239. from backend.app.models.pending_upload import PendingUpload
  240. async with self._session_factory() as db:
  241. pending = PendingUpload(
  242. filename=file_path.name,
  243. file_path=str(file_path),
  244. file_size=file_path.stat().st_size,
  245. source_ip=source_ip,
  246. status="pending",
  247. uploaded_at=datetime.now(timezone.utc),
  248. )
  249. db.add(pending)
  250. await db.commit()
  251. logger.info("[VP %s] Queued: %s - %s", self.name, pending.id, file_path.name)
  252. self._pending_files.pop(file_path.name, None)
  253. except Exception as e:
  254. logger.error("Error queueing file: %s", e)
  255. async def _add_to_print_queue(self, file_path: Path, source_ip: str) -> None:
  256. """Archive file and add to print queue, assigned to target printer or model."""
  257. if not self._session_factory:
  258. logger.error("Cannot add to print queue: no database session factory configured")
  259. return
  260. if file_path.suffix.lower() != ".3mf":
  261. self._pending_files.pop(file_path.name, None)
  262. try:
  263. file_path.unlink()
  264. except OSError:
  265. pass
  266. return
  267. try:
  268. from backend.app.models.print_queue import PrintQueueItem
  269. from backend.app.services.archive import ArchiveService
  270. async with self._session_factory() as db:
  271. service = ArchiveService(db)
  272. archive = await service.archive_print(
  273. printer_id=None,
  274. source_file=file_path,
  275. print_data={
  276. "status": "archived",
  277. "source": "virtual_printer",
  278. "source_ip": source_ip,
  279. },
  280. )
  281. if archive:
  282. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  283. # Assign to specific printer if configured, otherwise use model for "Any X" scheduling
  284. target_model = None
  285. if not self.target_printer_id and self.model:
  286. target_model = VIRTUAL_PRINTER_MODELS.get(self.model)
  287. plate_id = self._extract_plate_id(file_path)
  288. queue_item = PrintQueueItem(
  289. printer_id=self.target_printer_id,
  290. target_model=target_model,
  291. archive_id=archive.id,
  292. plate_id=plate_id,
  293. position=1,
  294. status="pending",
  295. manual_start=not self.auto_dispatch,
  296. )
  297. db.add(queue_item)
  298. await db.commit()
  299. logger.info("[VP %s] Added to queue: %s", self.name, queue_item.id)
  300. try:
  301. file_path.unlink()
  302. except OSError:
  303. pass
  304. self._pending_files.pop(file_path.name, None)
  305. else:
  306. logger.error("Failed to archive file: %s", file_path.name)
  307. except Exception as e:
  308. logger.error("Error adding to print queue: %s", e)
  309. @staticmethod
  310. def _extract_plate_id(file_path: Path) -> int | None:
  311. """Extract plate index from 3MF slice_info.config."""
  312. try:
  313. import xml.etree.ElementTree as ET
  314. import zipfile
  315. with zipfile.ZipFile(file_path, "r") as zf:
  316. if "Metadata/slice_info.config" in zf.namelist():
  317. content = zf.read("Metadata/slice_info.config").decode()
  318. root = ET.fromstring(content) # noqa: S314 # nosec B314
  319. plate = root.find(".//plate")
  320. if plate is not None:
  321. for meta in plate.findall("metadata"):
  322. if meta.get("key") == "index" and meta.get("value"):
  323. return int(meta.get("value"))
  324. except Exception:
  325. return None
  326. return None
  327. # -- Service lifecycle --
  328. async def _cancel_renewal_task(self) -> None:
  329. """Cancel the cert renewal task and await its completion."""
  330. if self._cert_renewal_task:
  331. self._cert_renewal_task.cancel()
  332. try:
  333. await self._cert_renewal_task
  334. except asyncio.CancelledError:
  335. pass
  336. except Exception as e:
  337. logger.warning("[VP %s] Unexpected error in cert renewal task: %s", self.name, e)
  338. self._cert_renewal_task = None
  339. async def _cancel_restart_task(self) -> None:
  340. """Cancel the cert restart task and await its completion."""
  341. if self._cert_restart_task and not self._cert_restart_task.done():
  342. self._cert_restart_task.cancel()
  343. try:
  344. await self._cert_restart_task
  345. except asyncio.CancelledError:
  346. pass
  347. except Exception as e:
  348. logger.warning("[VP %s] Unexpected error in cert restart task: %s", self.name, e)
  349. self._cert_restart_task = None
  350. async def _restart_for_cert_renewal(self) -> None:
  351. """Restart VP services to load the newly renewed Tailscale cert into TLS listeners."""
  352. logger.info("[VP %s] Restarting services to apply renewed Tailscale cert", self.name)
  353. try:
  354. if self.is_proxy:
  355. await self.stop_proxy()
  356. await self.start_proxy()
  357. else:
  358. await self.stop_server()
  359. await self.start_server()
  360. except asyncio.CancelledError:
  361. raise
  362. except Exception as e:
  363. logger.error("[VP %s] Failed to restart after cert renewal: %s", self.name, e)
  364. async def _cert_renewal_loop(self) -> None:
  365. """Daily background check for Tailscale cert renewal while VP is running.
  366. Checks first, then sleeps, so a cert that was just barely renewed at startup
  367. is not re-checked for another 24 h. When a renewal actually happens the loop
  368. schedules a VP restart so the new cert is loaded into the running TLS listeners.
  369. _cert_renewal_task is tracked separately from _tasks because it has a different
  370. lifecycle: it runs for the entire lifetime of the VP, not just during service start.
  371. """
  372. while True:
  373. try:
  374. if self.tailscale_fqdn:
  375. needs_renewal = tailscale_service.cert_needs_renewal(
  376. self._cert_service.ts_cert_path, fqdn=self.tailscale_fqdn
  377. )
  378. if needs_renewal:
  379. renewed = await self._cert_service.use_tailscale_cert(self.tailscale_fqdn, tailscale_service)
  380. if renewed:
  381. logger.info(
  382. "[VP %s] Tailscale cert renewed for %s, scheduling restart",
  383. self.name,
  384. self.tailscale_fqdn,
  385. )
  386. # Schedule restart in a separate task; this loop ends here
  387. # so the restart can cleanly cancel _cert_renewal_task and
  388. # create a fresh one via start_server/start_proxy.
  389. self._cert_restart_task = asyncio.create_task(
  390. self._restart_for_cert_renewal(),
  391. name=f"vp_{self.id}_cert_restart",
  392. )
  393. break
  394. await asyncio.sleep(86400) # check once per day
  395. except asyncio.CancelledError:
  396. break
  397. except Exception as e:
  398. logger.error("[VP %s] Cert renewal loop error: %s", self.name, e)
  399. await asyncio.sleep(3600) # back off 1 h on unexpected error
  400. async def _resolve_cert_and_advertise(self) -> tuple[Path, Path, str]:
  401. """Return (cert_path, key_path, advertise_address) for TLS services.
  402. When Tailscale is available, provisions a LE cert and returns the
  403. Tailscale FQDN as the advertise address so SSDP broadcasts the hostname
  404. that matches the trusted cert.
  405. Falls back to the self-signed cert and IP-based advertising when
  406. Tailscale is absent or provisioning fails.
  407. """
  408. if self.tailscale_disabled:
  409. logger.info("[VP %s] Tailscale integration disabled by user, using self-signed cert", self.name)
  410. else:
  411. try:
  412. ts_status = await tailscale_service.get_status()
  413. if ts_status.available:
  414. ts_result = await self._cert_service.use_tailscale_cert(ts_status.fqdn, tailscale_service)
  415. if ts_result:
  416. self.tailscale_fqdn = ts_status.fqdn
  417. logger.info("[VP %s] Using Tailscale cert for %s", self.name, ts_status.fqdn)
  418. return ts_result[0], ts_result[1], ts_status.fqdn
  419. logger.warning(
  420. "[VP %s] Tailscale available (%s) but cert provisioning failed, falling back to self-signed cert",
  421. self.name,
  422. ts_status.fqdn,
  423. )
  424. else:
  425. logger.info(
  426. "[VP %s] Tailscale not available (%s), using self-signed cert",
  427. self.name,
  428. ts_status.error or "not connected",
  429. )
  430. except Exception as e:
  431. logger.warning("[VP %s] Tailscale cert check failed, falling back to self-signed: %s", self.name, e)
  432. self.tailscale_fqdn = None
  433. cert_path, key_path = self.generate_certificates()
  434. advertise = self.remote_interface_ip or self.bind_ip or ""
  435. return cert_path, key_path, advertise
  436. async def start_server(self) -> None:
  437. """Start server-mode services (FTP, MQTT, SSDP, Bind) on this VP's bind_ip."""
  438. logger.info("[VP %s] Starting server-mode services on %s", self.name, self.bind_ip)
  439. cert_path, key_path, advertise_addr = await self._resolve_cert_and_advertise()
  440. bind_addr = self.bind_ip or "0.0.0.0" # nosec B104
  441. async def run_with_logging(coro, svc_name):
  442. try:
  443. await coro
  444. except Exception as e:
  445. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  446. self._tasks = []
  447. # FTP server
  448. self._ftp = VirtualPrinterFTPServer(
  449. upload_dir=self.upload_dir,
  450. access_code=self.access_code,
  451. cert_path=cert_path,
  452. key_path=key_path,
  453. on_file_received=self.on_file_received,
  454. bind_address=bind_addr,
  455. vp_name=self.name,
  456. )
  457. self._tasks.append(
  458. asyncio.create_task(
  459. run_with_logging(self._ftp.start(), "FTP"),
  460. name=f"vp_{self.id}_ftp",
  461. )
  462. )
  463. # MQTT server
  464. self._mqtt = SimpleMQTTServer(
  465. serial=self.serial,
  466. access_code=self.access_code,
  467. cert_path=cert_path,
  468. key_path=key_path,
  469. on_print_command=self.on_print_command,
  470. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  471. bind_address=bind_addr,
  472. vp_name=self.name,
  473. )
  474. self._tasks.append(
  475. asyncio.create_task(
  476. run_with_logging(self._mqtt.start(), "MQTT"),
  477. name=f"vp_{self.id}_mqtt",
  478. )
  479. )
  480. # Bind server
  481. self._bind = BindServer(
  482. serial=self.serial,
  483. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  484. name=self.name,
  485. bind_address=bind_addr,
  486. cert_path=cert_path,
  487. key_path=key_path,
  488. )
  489. self._tasks.append(
  490. asyncio.create_task(
  491. run_with_logging(self._bind.start(), "Bind"),
  492. name=f"vp_{self.id}_bind",
  493. )
  494. )
  495. # SSDP server — advertise_addr is the Tailscale FQDN when available,
  496. # otherwise the bind/remote IP (existing behaviour)
  497. self._ssdp = VirtualPrinterSSDPServer(
  498. name=self.name,
  499. serial=self.serial,
  500. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  501. advertise_ip=advertise_addr,
  502. bind_ip=bind_addr,
  503. )
  504. self._tasks.append(
  505. asyncio.create_task(
  506. run_with_logging(self._ssdp.start(), "SSDP"),
  507. name=f"vp_{self.id}_ssdp",
  508. )
  509. )
  510. # Guard against double-start: cancel any orphaned task before creating a new one
  511. await self._cancel_renewal_task()
  512. self._cert_renewal_task = asyncio.create_task(self._cert_renewal_loop(), name=f"vp_{self.id}_cert_renewal")
  513. logger.info("[VP %s] Server-mode services started on %s", self.name, bind_addr)
  514. async def stop_server(self) -> None:
  515. """Stop server-mode services."""
  516. await self._cancel_renewal_task()
  517. await self._cancel_restart_task()
  518. if self._ftp:
  519. await self._ftp.stop()
  520. self._ftp = None
  521. if self._mqtt:
  522. await self._mqtt.stop()
  523. self._mqtt = None
  524. if self._bind:
  525. await self._bind.stop()
  526. self._bind = None
  527. if self._ssdp:
  528. await self._ssdp.stop()
  529. self._ssdp = None
  530. await self._cancel_tasks()
  531. async def start_proxy(self) -> None:
  532. """Start proxy mode services for this instance."""
  533. logger.info("[VP %s] Starting proxy mode to %s", self.name, self.target_printer_ip)
  534. cert_path, key_path, _ = await self._resolve_cert_and_advertise()
  535. self._proxy = SlicerProxyManager(
  536. target_host=self.target_printer_ip,
  537. cert_path=cert_path,
  538. key_path=key_path,
  539. on_activity=lambda n, m: logger.info("[VP %s] Proxy %s: %s", self.name, n, m),
  540. bind_address=self.bind_ip or "0.0.0.0", # nosec B104
  541. bind_identity={
  542. "serial": self.target_printer_serial or self.serial,
  543. "model": self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  544. "name": self.name,
  545. "version": "01.00.00.00",
  546. },
  547. )
  548. async def run_with_logging(coro, svc_name):
  549. try:
  550. await coro
  551. except Exception as e:
  552. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  553. self._tasks = []
  554. # SSDP for proxy
  555. proxy_serial = self.target_printer_serial or self.serial
  556. if self.remote_interface_ip:
  557. from backend.app.services.network_utils import find_interface_for_ip
  558. local_iface = find_interface_for_ip(self.target_printer_ip)
  559. if local_iface:
  560. self._ssdp_proxy = SSDPProxy(
  561. local_interface_ip=local_iface["ip"],
  562. remote_interface_ip=self.remote_interface_ip,
  563. target_printer_ip=self.target_printer_ip,
  564. name=self.name,
  565. )
  566. self._tasks.append(
  567. asyncio.create_task(
  568. run_with_logging(self._ssdp_proxy.start(), "SSDP Proxy"),
  569. name=f"vp_{self.id}_ssdp_proxy",
  570. )
  571. )
  572. else:
  573. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  574. else:
  575. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  576. self._tasks.append(
  577. asyncio.create_task(
  578. run_with_logging(self._proxy.start(), "Proxy"),
  579. name=f"vp_{self.id}_proxy",
  580. )
  581. )
  582. # Guard against double-start: cancel any orphaned task before creating a new one
  583. await self._cancel_renewal_task()
  584. self._cert_renewal_task = asyncio.create_task(self._cert_renewal_loop(), name=f"vp_{self.id}_cert_renewal")
  585. def _start_fallback_ssdp(self, proxy_serial: str, run_with_logging) -> None:
  586. """Start single-interface SSDP server as fallback for proxy mode."""
  587. self._ssdp = VirtualPrinterSSDPServer(
  588. name=f"{self.name} (Proxy)",
  589. serial=proxy_serial,
  590. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  591. advertise_ip=self.bind_ip or "",
  592. bind_ip=self.bind_ip or "",
  593. )
  594. self._tasks.append(
  595. asyncio.create_task(
  596. run_with_logging(self._ssdp.start(), "SSDP"),
  597. name=f"vp_{self.id}_ssdp",
  598. )
  599. )
  600. async def stop_proxy(self) -> None:
  601. """Stop proxy mode services for this instance."""
  602. await self._cancel_renewal_task()
  603. await self._cancel_restart_task()
  604. if self._proxy:
  605. await self._proxy.stop()
  606. self._proxy = None
  607. if self._ssdp:
  608. await self._ssdp.stop()
  609. self._ssdp = None
  610. if self._ssdp_proxy:
  611. await self._ssdp_proxy.stop()
  612. self._ssdp_proxy = None
  613. await self._cancel_tasks()
  614. async def _cancel_tasks(self) -> None:
  615. """Cancel all running tasks and wait for cleanup."""
  616. for task in self._tasks:
  617. task.cancel()
  618. if self._tasks:
  619. try:
  620. await asyncio.wait_for(asyncio.gather(*self._tasks, return_exceptions=True), timeout=1.0)
  621. except TimeoutError:
  622. pass
  623. self._tasks = []
  624. def get_status(self) -> dict:
  625. """Get status for this instance."""
  626. status: dict = {
  627. "running": self.is_running,
  628. "pending_files": len(self._pending_files),
  629. }
  630. if self.tailscale_fqdn:
  631. status["tailscale_fqdn"] = self.tailscale_fqdn
  632. if self.is_proxy and self._proxy:
  633. status["proxy"] = self._proxy.get_status()
  634. return status
  635. class VirtualPrinterManager:
  636. """Multi-instance virtual printer registry and orchestrator.
  637. Every VP runs its own independent services on a dedicated bind IP.
  638. """
  639. def __init__(self):
  640. self._session_factory: Callable | None = None
  641. self._instances: dict[int, VirtualPrinterInstance] = {}
  642. # Directories
  643. self._base_dir = app_settings.base_dir / "virtual_printer"
  644. # Ensure base directories exist
  645. self._ensure_base_directories()
  646. def _ensure_base_directories(self) -> None:
  647. """Create base directories at startup."""
  648. for dir_path in [self._base_dir, self._base_dir / "uploads", self._base_dir / "certs"]:
  649. try:
  650. dir_path.mkdir(parents=True, exist_ok=True)
  651. except PermissionError:
  652. logger.error(
  653. f"Cannot create directory {dir_path}: Permission denied. "
  654. f"For Docker: ensure the data volume is writable by the container user. "
  655. f"For bare metal: run 'sudo chown -R $(whoami) {self._base_dir}'"
  656. )
  657. def set_session_factory(self, session_factory: Callable) -> None:
  658. """Set the database session factory."""
  659. self._session_factory = session_factory
  660. @property
  661. def is_enabled(self) -> bool:
  662. """Check if any virtual printer is running."""
  663. return len(self._instances) > 0
  664. async def sync_from_db(self) -> None:
  665. """Load all VPs from DB, reconcile running state."""
  666. if not self._session_factory:
  667. logger.warning("Cannot sync virtual printers: no session factory")
  668. return
  669. from sqlalchemy import select
  670. from backend.app.models.printer import Printer
  671. from backend.app.models.virtual_printer import VirtualPrinter
  672. async with self._session_factory() as db:
  673. result = await db.execute(
  674. select(VirtualPrinter).where(VirtualPrinter.enabled == True).order_by(VirtualPrinter.position) # noqa: E712
  675. )
  676. enabled_vps = result.scalars().all()
  677. # Stop instances that are no longer enabled or changed mode
  678. enabled_ids = {vp.id for vp in enabled_vps}
  679. for vp_id in list(self._instances.keys()):
  680. if vp_id not in enabled_ids:
  681. await self.remove_instance(vp_id)
  682. # Look up printer IPs for proxy VPs
  683. proxy_vps = [vp for vp in enabled_vps if vp.mode == "proxy"]
  684. proxy_ips: dict[int, tuple[str, str]] = {}
  685. if proxy_vps:
  686. async with self._session_factory() as db:
  687. for pvp in proxy_vps:
  688. if pvp.target_printer_id:
  689. result = await db.execute(select(Printer).where(Printer.id == pvp.target_printer_id))
  690. printer = result.scalar_one_or_none()
  691. if printer:
  692. proxy_ips[pvp.id] = (printer.ip_address, printer.serial_number)
  693. # Detect config changes on running instances and restart if needed
  694. for vp in enabled_vps:
  695. instance = self._instances.get(vp.id)
  696. if not instance:
  697. continue
  698. changed = (
  699. instance.mode != vp.mode
  700. or instance.model != (vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL)
  701. or instance.access_code != (vp.access_code or "")
  702. or instance.bind_ip != (vp.bind_ip or "")
  703. or instance.remote_interface_ip != (vp.remote_interface_ip or "")
  704. or instance.target_printer_id != vp.target_printer_id
  705. or instance.auto_dispatch != vp.auto_dispatch
  706. or instance.tailscale_disabled != vp.tailscale_disabled
  707. )
  708. if changed:
  709. logger.info(
  710. "VP %s config changed (mode: %s→%s), restarting",
  711. instance.name,
  712. instance.mode,
  713. vp.mode,
  714. )
  715. await self.remove_instance(vp.id)
  716. # Start instances for all enabled VPs (skip already running)
  717. for vp in enabled_vps:
  718. if vp.id in self._instances:
  719. continue
  720. if vp.mode == "proxy":
  721. ip_info = proxy_ips.get(vp.id)
  722. if not ip_info:
  723. logger.warning("Proxy VP %s: target printer not found, skipping", vp.name)
  724. continue
  725. target_ip, target_serial = ip_info
  726. instance = VirtualPrinterInstance(
  727. vp_id=vp.id,
  728. name=vp.name,
  729. mode=vp.mode,
  730. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  731. access_code=vp.access_code or "",
  732. serial_suffix=vp.serial_suffix,
  733. target_printer_ip=target_ip,
  734. target_printer_serial=target_serial,
  735. auto_dispatch=vp.auto_dispatch,
  736. bind_ip=vp.bind_ip or "",
  737. remote_interface_ip=vp.remote_interface_ip or "",
  738. tailscale_disabled=vp.tailscale_disabled,
  739. base_dir=self._base_dir,
  740. session_factory=self._session_factory,
  741. )
  742. self._instances[vp.id] = instance
  743. await instance.start_proxy()
  744. logger.info("Started proxy VP: %s → %s (bind=%s)", instance.name, target_ip, instance.bind_ip)
  745. else:
  746. instance = VirtualPrinterInstance(
  747. vp_id=vp.id,
  748. name=vp.name,
  749. mode=vp.mode,
  750. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  751. access_code=vp.access_code or "",
  752. serial_suffix=vp.serial_suffix,
  753. target_printer_id=vp.target_printer_id,
  754. auto_dispatch=vp.auto_dispatch,
  755. bind_ip=vp.bind_ip or "",
  756. remote_interface_ip=vp.remote_interface_ip or "",
  757. tailscale_disabled=vp.tailscale_disabled,
  758. base_dir=self._base_dir,
  759. session_factory=self._session_factory,
  760. )
  761. self._instances[vp.id] = instance
  762. await instance.start_server()
  763. logger.info("Started server-mode VP: %s on %s", instance.name, vp.bind_ip)
  764. async def remove_instance(self, vp_id: int) -> None:
  765. """Stop and remove a single VP instance."""
  766. instance = self._instances.pop(vp_id, None)
  767. if instance:
  768. if instance.is_proxy:
  769. await instance.stop_proxy()
  770. else:
  771. await instance.stop_server()
  772. logger.info("Removed VP instance: %s", instance.name)
  773. async def stop_all(self) -> None:
  774. """Shutdown all virtual printer services."""
  775. logger.info("Stopping all virtual printer services...")
  776. for vp_id in list(self._instances.keys()):
  777. await self.remove_instance(vp_id)
  778. logger.info("All virtual printer services stopped")
  779. def get_instance(self, vp_id: int) -> VirtualPrinterInstance | None:
  780. """Get a running instance by ID."""
  781. return self._instances.get(vp_id)
  782. def get_all_status(self) -> list[dict]:
  783. """Get status for all running instances."""
  784. return [
  785. {
  786. "id": inst.id,
  787. "name": inst.name,
  788. "mode": inst.mode,
  789. **inst.get_status(),
  790. }
  791. for inst in self._instances.values()
  792. ]
  793. # -- Legacy single-printer compat --
  794. def get_status(self) -> dict:
  795. """Get status for first virtual printer (backward compat)."""
  796. if self._instances:
  797. first = next(iter(self._instances.values()))
  798. return {
  799. "enabled": True,
  800. "running": first.is_running,
  801. "mode": first.mode,
  802. "name": first.name,
  803. "serial": first.serial,
  804. "model": first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  805. "model_name": VIRTUAL_PRINTER_MODELS.get(
  806. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  807. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  808. ),
  809. "pending_files": first.get_status().get("pending_files", 0),
  810. **({"target_printer_ip": first.target_printer_ip} if first.is_proxy else {}),
  811. **({"proxy": first.get_status().get("proxy", {})} if first.is_proxy else {}),
  812. }
  813. return {
  814. "enabled": False,
  815. "running": False,
  816. "mode": "immediate",
  817. "name": "Bambuddy",
  818. "serial": "",
  819. "model": DEFAULT_VIRTUAL_PRINTER_MODEL,
  820. "model_name": VIRTUAL_PRINTER_MODELS[DEFAULT_VIRTUAL_PRINTER_MODEL],
  821. "pending_files": 0,
  822. }
  823. async def configure(
  824. self,
  825. enabled: bool,
  826. access_code: str = "",
  827. mode: str = "immediate",
  828. model: str = "",
  829. target_printer_ip: str = "",
  830. target_printer_serial: str = "",
  831. remote_interface_ip: str = "",
  832. ) -> None:
  833. """Legacy single-printer configure. Delegates to sync_from_db()."""
  834. # This method is kept for backward compat with the settings endpoint.
  835. # The actual work is done by sync_from_db() which reads from the DB.
  836. await self.sync_from_db()
  837. # Global instance
  838. virtual_printer_manager = VirtualPrinterManager()