manager.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  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 = True,
  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.api.routes.settings import get_setting
  204. from backend.app.services.archive import ArchiveService
  205. async with self._session_factory() as db:
  206. name_source = await get_setting(db, "virtual_printer_archive_name_source")
  207. prefer_filename = name_source == "filename"
  208. service = ArchiveService(db)
  209. archive = await service.archive_print(
  210. printer_id=None,
  211. source_file=file_path,
  212. print_data={
  213. "status": "archived",
  214. "source": "virtual_printer",
  215. "source_ip": source_ip,
  216. },
  217. prefer_filename_for_name=prefer_filename,
  218. )
  219. if archive:
  220. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  221. try:
  222. file_path.unlink()
  223. except OSError:
  224. pass
  225. self._pending_files.pop(file_path.name, None)
  226. else:
  227. logger.error("Failed to archive file: %s", file_path.name)
  228. except Exception as e:
  229. logger.error("Error archiving file: %s", e)
  230. async def _queue_file(self, file_path: Path, source_ip: str) -> None:
  231. """Queue file for user review."""
  232. if not self._session_factory:
  233. logger.error("Cannot queue: no database session factory configured")
  234. return
  235. if file_path.suffix.lower() != ".3mf":
  236. self._pending_files.pop(file_path.name, None)
  237. try:
  238. file_path.unlink()
  239. except OSError:
  240. pass
  241. return
  242. try:
  243. from backend.app.models.pending_upload import PendingUpload
  244. async with self._session_factory() as db:
  245. pending = PendingUpload(
  246. filename=file_path.name,
  247. file_path=str(file_path),
  248. file_size=file_path.stat().st_size,
  249. source_ip=source_ip,
  250. status="pending",
  251. uploaded_at=datetime.now(timezone.utc),
  252. )
  253. db.add(pending)
  254. await db.commit()
  255. logger.info("[VP %s] Queued: %s - %s", self.name, pending.id, file_path.name)
  256. self._pending_files.pop(file_path.name, None)
  257. except Exception as e:
  258. logger.error("Error queueing file: %s", e)
  259. async def _add_to_print_queue(self, file_path: Path, source_ip: str) -> None:
  260. """Archive file and add to print queue, assigned to target printer or model."""
  261. if not self._session_factory:
  262. logger.error("Cannot add to print queue: no database session factory configured")
  263. return
  264. if file_path.suffix.lower() != ".3mf":
  265. self._pending_files.pop(file_path.name, None)
  266. try:
  267. file_path.unlink()
  268. except OSError:
  269. pass
  270. return
  271. try:
  272. from backend.app.api.routes.settings import get_setting
  273. from backend.app.models.print_queue import PrintQueueItem
  274. from backend.app.services.archive import ArchiveService
  275. async with self._session_factory() as db:
  276. name_source = await get_setting(db, "virtual_printer_archive_name_source")
  277. prefer_filename = name_source == "filename"
  278. service = ArchiveService(db)
  279. archive = await service.archive_print(
  280. printer_id=None,
  281. source_file=file_path,
  282. print_data={
  283. "status": "archived",
  284. "source": "virtual_printer",
  285. "source_ip": source_ip,
  286. },
  287. prefer_filename_for_name=prefer_filename,
  288. )
  289. if archive:
  290. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  291. # Assign to specific printer if configured, otherwise use model for "Any X" scheduling
  292. target_model = None
  293. if not self.target_printer_id and self.model:
  294. target_model = VIRTUAL_PRINTER_MODELS.get(self.model)
  295. plate_id = self._extract_plate_id(file_path)
  296. queue_item = PrintQueueItem(
  297. printer_id=self.target_printer_id,
  298. target_model=target_model,
  299. archive_id=archive.id,
  300. plate_id=plate_id,
  301. position=1,
  302. status="pending",
  303. manual_start=not self.auto_dispatch,
  304. )
  305. db.add(queue_item)
  306. await db.commit()
  307. logger.info("[VP %s] Added to queue: %s", self.name, queue_item.id)
  308. try:
  309. file_path.unlink()
  310. except OSError:
  311. pass
  312. self._pending_files.pop(file_path.name, None)
  313. else:
  314. logger.error("Failed to archive file: %s", file_path.name)
  315. except Exception as e:
  316. logger.error("Error adding to print queue: %s", e)
  317. @staticmethod
  318. def _extract_plate_id(file_path: Path) -> int | None:
  319. """Extract plate index from 3MF slice_info.config."""
  320. try:
  321. import xml.etree.ElementTree as ET
  322. import zipfile
  323. with zipfile.ZipFile(file_path, "r") as zf:
  324. if "Metadata/slice_info.config" in zf.namelist():
  325. content = zf.read("Metadata/slice_info.config").decode()
  326. root = ET.fromstring(content) # noqa: S314 # nosec B314
  327. plate = root.find(".//plate")
  328. if plate is not None:
  329. for meta in plate.findall("metadata"):
  330. if meta.get("key") == "index" and meta.get("value"):
  331. return int(meta.get("value"))
  332. except Exception:
  333. return None
  334. return None
  335. # -- Service lifecycle --
  336. async def _cancel_renewal_task(self) -> None:
  337. """Cancel the cert renewal task and await its completion."""
  338. if self._cert_renewal_task:
  339. self._cert_renewal_task.cancel()
  340. try:
  341. await self._cert_renewal_task
  342. except asyncio.CancelledError:
  343. pass
  344. except Exception as e:
  345. logger.warning("[VP %s] Unexpected error in cert renewal task: %s", self.name, e)
  346. self._cert_renewal_task = None
  347. async def _cancel_restart_task(self) -> None:
  348. """Cancel the cert restart task and await its completion.
  349. Skip when the caller IS the restart task itself — stop_server() /
  350. stop_proxy() are called from inside _restart_for_cert_renewal,
  351. which runs AS _cert_restart_task. Cancelling + awaiting self
  352. flags a CancelledError on the next `await` in stop_server,
  353. which tears down the old listeners but never lets start_server
  354. run — the VP would sit on an expired cert until process restart.
  355. """
  356. task = self._cert_restart_task
  357. if task is asyncio.current_task():
  358. # Renewal path cleaning up its own restart task: clear the
  359. # reference so future callers don't see a stale task handle,
  360. # but do NOT cancel-and-await ourselves.
  361. self._cert_restart_task = None
  362. return
  363. if task and not task.done():
  364. task.cancel()
  365. try:
  366. await task
  367. except asyncio.CancelledError:
  368. pass
  369. except Exception as e:
  370. logger.warning("[VP %s] Unexpected error in cert restart task: %s", self.name, e)
  371. self._cert_restart_task = None
  372. async def _restart_for_cert_renewal(self) -> None:
  373. """Restart VP services to load the newly renewed Tailscale cert into TLS listeners."""
  374. logger.info("[VP %s] Restarting services to apply renewed Tailscale cert", self.name)
  375. try:
  376. if self.is_proxy:
  377. await self.stop_proxy()
  378. await self.start_proxy()
  379. else:
  380. await self.stop_server()
  381. await self.start_server()
  382. except asyncio.CancelledError:
  383. raise
  384. except Exception as e:
  385. logger.error("[VP %s] Failed to restart after cert renewal: %s", self.name, e)
  386. async def _cert_renewal_loop(self) -> None:
  387. """Daily background check for Tailscale cert renewal while VP is running.
  388. Checks first, then sleeps, so a cert that was just barely renewed at startup
  389. is not re-checked for another 24 h. When a renewal actually happens the loop
  390. schedules a VP restart so the new cert is loaded into the running TLS listeners.
  391. _cert_renewal_task is tracked separately from _tasks because it has a different
  392. lifecycle: it runs for the entire lifetime of the VP, not just during service start.
  393. """
  394. while True:
  395. try:
  396. if self.tailscale_fqdn:
  397. needs_renewal = tailscale_service.cert_needs_renewal(
  398. self._cert_service.ts_cert_path, fqdn=self.tailscale_fqdn
  399. )
  400. if needs_renewal:
  401. renewed = await self._cert_service.use_tailscale_cert(self.tailscale_fqdn, tailscale_service)
  402. if renewed:
  403. logger.info(
  404. "[VP %s] Tailscale cert renewed for %s, scheduling restart",
  405. self.name,
  406. self.tailscale_fqdn,
  407. )
  408. # Schedule restart in a separate task; this loop ends here
  409. # so the restart can cleanly cancel _cert_renewal_task and
  410. # create a fresh one via start_server/start_proxy.
  411. self._cert_restart_task = asyncio.create_task(
  412. self._restart_for_cert_renewal(),
  413. name=f"vp_{self.id}_cert_restart",
  414. )
  415. break
  416. await asyncio.sleep(86400) # check once per day
  417. except asyncio.CancelledError:
  418. break
  419. except Exception as e:
  420. logger.error("[VP %s] Cert renewal loop error: %s", self.name, e)
  421. await asyncio.sleep(3600) # back off 1 h on unexpected error
  422. async def _resolve_cert_and_advertise(self) -> tuple[Path, Path, str]:
  423. """Return (cert_path, key_path, advertise_address) for TLS services.
  424. When Tailscale is available, provisions a LE cert and returns the
  425. Tailscale FQDN as the advertise address so SSDP broadcasts the hostname
  426. that matches the trusted cert.
  427. Falls back to the self-signed cert and IP-based advertising when
  428. Tailscale is absent or provisioning fails.
  429. """
  430. if self.tailscale_disabled:
  431. logger.info("[VP %s] Tailscale integration disabled by user, using self-signed cert", self.name)
  432. else:
  433. try:
  434. ts_status = await tailscale_service.get_status()
  435. if ts_status.available:
  436. ts_result = await self._cert_service.use_tailscale_cert(ts_status.fqdn, tailscale_service)
  437. if ts_result:
  438. self.tailscale_fqdn = ts_status.fqdn
  439. logger.info("[VP %s] Using Tailscale cert for %s", self.name, ts_status.fqdn)
  440. return ts_result[0], ts_result[1], ts_status.fqdn
  441. logger.warning(
  442. "[VP %s] Tailscale available (%s) but cert provisioning failed, falling back to self-signed cert",
  443. self.name,
  444. ts_status.fqdn,
  445. )
  446. else:
  447. logger.info(
  448. "[VP %s] Tailscale not available (%s), using self-signed cert",
  449. self.name,
  450. ts_status.error or "not connected",
  451. )
  452. except Exception as e:
  453. logger.warning("[VP %s] Tailscale cert check failed, falling back to self-signed: %s", self.name, e)
  454. self.tailscale_fqdn = None
  455. cert_path, key_path = self.generate_certificates()
  456. advertise = self.remote_interface_ip or self.bind_ip or ""
  457. return cert_path, key_path, advertise
  458. async def start_server(self) -> None:
  459. """Start server-mode services (FTP, MQTT, SSDP, Bind) on this VP's bind_ip."""
  460. logger.info("[VP %s] Starting server-mode services on %s", self.name, self.bind_ip)
  461. cert_path, key_path, advertise_addr = await self._resolve_cert_and_advertise()
  462. bind_addr = self.bind_ip or "0.0.0.0" # nosec B104
  463. async def run_with_logging(coro, svc_name):
  464. try:
  465. await coro
  466. except Exception as e:
  467. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  468. self._tasks = []
  469. # FTP server
  470. self._ftp = VirtualPrinterFTPServer(
  471. upload_dir=self.upload_dir,
  472. access_code=self.access_code,
  473. cert_path=cert_path,
  474. key_path=key_path,
  475. on_file_received=self.on_file_received,
  476. bind_address=bind_addr,
  477. vp_name=self.name,
  478. )
  479. self._tasks.append(
  480. asyncio.create_task(
  481. run_with_logging(self._ftp.start(), "FTP"),
  482. name=f"vp_{self.id}_ftp",
  483. )
  484. )
  485. # MQTT server
  486. self._mqtt = SimpleMQTTServer(
  487. serial=self.serial,
  488. access_code=self.access_code,
  489. cert_path=cert_path,
  490. key_path=key_path,
  491. on_print_command=self.on_print_command,
  492. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  493. bind_address=bind_addr,
  494. vp_name=self.name,
  495. )
  496. self._tasks.append(
  497. asyncio.create_task(
  498. run_with_logging(self._mqtt.start(), "MQTT"),
  499. name=f"vp_{self.id}_mqtt",
  500. )
  501. )
  502. # Bind server
  503. self._bind = BindServer(
  504. serial=self.serial,
  505. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  506. name=self.name,
  507. bind_address=bind_addr,
  508. cert_path=cert_path,
  509. key_path=key_path,
  510. )
  511. self._tasks.append(
  512. asyncio.create_task(
  513. run_with_logging(self._bind.start(), "Bind"),
  514. name=f"vp_{self.id}_bind",
  515. )
  516. )
  517. # SSDP server — advertise_addr is the Tailscale FQDN when available,
  518. # otherwise the bind/remote IP (existing behaviour)
  519. self._ssdp = VirtualPrinterSSDPServer(
  520. name=self.name,
  521. serial=self.serial,
  522. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  523. advertise_ip=advertise_addr,
  524. bind_ip=bind_addr,
  525. )
  526. self._tasks.append(
  527. asyncio.create_task(
  528. run_with_logging(self._ssdp.start(), "SSDP"),
  529. name=f"vp_{self.id}_ssdp",
  530. )
  531. )
  532. # Guard against double-start: cancel any orphaned task before creating a new one
  533. await self._cancel_renewal_task()
  534. self._cert_renewal_task = asyncio.create_task(self._cert_renewal_loop(), name=f"vp_{self.id}_cert_renewal")
  535. logger.info("[VP %s] Server-mode services started on %s", self.name, bind_addr)
  536. async def stop_server(self) -> None:
  537. """Stop server-mode services."""
  538. await self._cancel_renewal_task()
  539. await self._cancel_restart_task()
  540. if self._ftp:
  541. await self._ftp.stop()
  542. self._ftp = None
  543. if self._mqtt:
  544. await self._mqtt.stop()
  545. self._mqtt = None
  546. if self._bind:
  547. await self._bind.stop()
  548. self._bind = None
  549. if self._ssdp:
  550. await self._ssdp.stop()
  551. self._ssdp = None
  552. await self._cancel_tasks()
  553. async def start_proxy(self) -> None:
  554. """Start proxy mode services for this instance."""
  555. logger.info("[VP %s] Starting proxy mode to %s", self.name, self.target_printer_ip)
  556. cert_path, key_path, _ = await self._resolve_cert_and_advertise()
  557. self._proxy = SlicerProxyManager(
  558. target_host=self.target_printer_ip,
  559. cert_path=cert_path,
  560. key_path=key_path,
  561. on_activity=lambda n, m: logger.info("[VP %s] Proxy %s: %s", self.name, n, m),
  562. bind_address=self.bind_ip or "0.0.0.0", # nosec B104
  563. bind_identity={
  564. "serial": self.target_printer_serial or self.serial,
  565. "model": self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  566. "name": self.name,
  567. "version": "01.00.00.00",
  568. },
  569. )
  570. async def run_with_logging(coro, svc_name):
  571. try:
  572. await coro
  573. except Exception as e:
  574. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  575. self._tasks = []
  576. # SSDP for proxy
  577. proxy_serial = self.target_printer_serial or self.serial
  578. if self.remote_interface_ip:
  579. from backend.app.services.network_utils import find_interface_for_ip
  580. local_iface = find_interface_for_ip(self.target_printer_ip)
  581. if local_iface:
  582. self._ssdp_proxy = SSDPProxy(
  583. local_interface_ip=local_iface["ip"],
  584. remote_interface_ip=self.remote_interface_ip,
  585. target_printer_ip=self.target_printer_ip,
  586. name=self.name,
  587. )
  588. self._tasks.append(
  589. asyncio.create_task(
  590. run_with_logging(self._ssdp_proxy.start(), "SSDP Proxy"),
  591. name=f"vp_{self.id}_ssdp_proxy",
  592. )
  593. )
  594. else:
  595. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  596. else:
  597. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  598. self._tasks.append(
  599. asyncio.create_task(
  600. run_with_logging(self._proxy.start(), "Proxy"),
  601. name=f"vp_{self.id}_proxy",
  602. )
  603. )
  604. # Guard against double-start: cancel any orphaned task before creating a new one
  605. await self._cancel_renewal_task()
  606. self._cert_renewal_task = asyncio.create_task(self._cert_renewal_loop(), name=f"vp_{self.id}_cert_renewal")
  607. def _start_fallback_ssdp(self, proxy_serial: str, run_with_logging) -> None:
  608. """Start single-interface SSDP server as fallback for proxy mode."""
  609. self._ssdp = VirtualPrinterSSDPServer(
  610. name=f"{self.name} (Proxy)",
  611. serial=proxy_serial,
  612. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  613. advertise_ip=self.bind_ip or "",
  614. bind_ip=self.bind_ip or "",
  615. )
  616. self._tasks.append(
  617. asyncio.create_task(
  618. run_with_logging(self._ssdp.start(), "SSDP"),
  619. name=f"vp_{self.id}_ssdp",
  620. )
  621. )
  622. async def stop_proxy(self) -> None:
  623. """Stop proxy mode services for this instance."""
  624. await self._cancel_renewal_task()
  625. await self._cancel_restart_task()
  626. if self._proxy:
  627. await self._proxy.stop()
  628. self._proxy = None
  629. if self._ssdp:
  630. await self._ssdp.stop()
  631. self._ssdp = None
  632. if self._ssdp_proxy:
  633. await self._ssdp_proxy.stop()
  634. self._ssdp_proxy = None
  635. await self._cancel_tasks()
  636. async def _cancel_tasks(self) -> None:
  637. """Cancel all running tasks and wait for cleanup."""
  638. for task in self._tasks:
  639. task.cancel()
  640. if self._tasks:
  641. try:
  642. await asyncio.wait_for(asyncio.gather(*self._tasks, return_exceptions=True), timeout=1.0)
  643. except TimeoutError:
  644. pass
  645. self._tasks = []
  646. def get_status(self) -> dict:
  647. """Get status for this instance."""
  648. status: dict = {
  649. "running": self.is_running,
  650. "pending_files": len(self._pending_files),
  651. }
  652. if self.tailscale_fqdn:
  653. status["tailscale_fqdn"] = self.tailscale_fqdn
  654. if self.is_proxy and self._proxy:
  655. status["proxy"] = self._proxy.get_status()
  656. return status
  657. class VirtualPrinterManager:
  658. """Multi-instance virtual printer registry and orchestrator.
  659. Every VP runs its own independent services on a dedicated bind IP.
  660. """
  661. def __init__(self):
  662. self._session_factory: Callable | None = None
  663. self._instances: dict[int, VirtualPrinterInstance] = {}
  664. # Directories
  665. self._base_dir = app_settings.base_dir / "virtual_printer"
  666. # Ensure base directories exist
  667. self._ensure_base_directories()
  668. def _ensure_base_directories(self) -> None:
  669. """Create base directories at startup."""
  670. for dir_path in [self._base_dir, self._base_dir / "uploads", self._base_dir / "certs"]:
  671. try:
  672. dir_path.mkdir(parents=True, exist_ok=True)
  673. except PermissionError:
  674. logger.error(
  675. f"Cannot create directory {dir_path}: Permission denied. "
  676. f"For Docker: ensure the data volume is writable by the container user. "
  677. f"For bare metal: run 'sudo chown -R $(whoami) {self._base_dir}'"
  678. )
  679. def set_session_factory(self, session_factory: Callable) -> None:
  680. """Set the database session factory."""
  681. self._session_factory = session_factory
  682. @property
  683. def is_enabled(self) -> bool:
  684. """Check if any virtual printer is running."""
  685. return len(self._instances) > 0
  686. async def sync_from_db(self) -> None:
  687. """Load all VPs from DB, reconcile running state."""
  688. if not self._session_factory:
  689. logger.warning("Cannot sync virtual printers: no session factory")
  690. return
  691. from sqlalchemy import select
  692. from backend.app.models.printer import Printer
  693. from backend.app.models.virtual_printer import VirtualPrinter
  694. async with self._session_factory() as db:
  695. result = await db.execute(
  696. select(VirtualPrinter).where(VirtualPrinter.enabled == True).order_by(VirtualPrinter.position) # noqa: E712
  697. )
  698. enabled_vps = result.scalars().all()
  699. # Stop instances that are no longer enabled or changed mode
  700. enabled_ids = {vp.id for vp in enabled_vps}
  701. for vp_id in list(self._instances.keys()):
  702. if vp_id not in enabled_ids:
  703. await self.remove_instance(vp_id)
  704. # Look up printer IPs for proxy VPs
  705. proxy_vps = [vp for vp in enabled_vps if vp.mode == "proxy"]
  706. proxy_ips: dict[int, tuple[str, str]] = {}
  707. if proxy_vps:
  708. async with self._session_factory() as db:
  709. for pvp in proxy_vps:
  710. if pvp.target_printer_id:
  711. result = await db.execute(select(Printer).where(Printer.id == pvp.target_printer_id))
  712. printer = result.scalar_one_or_none()
  713. if printer:
  714. proxy_ips[pvp.id] = (printer.ip_address, printer.serial_number)
  715. # Detect config changes on running instances and restart if needed
  716. for vp in enabled_vps:
  717. instance = self._instances.get(vp.id)
  718. if not instance:
  719. continue
  720. changed = (
  721. instance.mode != vp.mode
  722. or instance.model != (vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL)
  723. or instance.access_code != (vp.access_code or "")
  724. or instance.bind_ip != (vp.bind_ip or "")
  725. or instance.remote_interface_ip != (vp.remote_interface_ip or "")
  726. or instance.target_printer_id != vp.target_printer_id
  727. or instance.auto_dispatch != vp.auto_dispatch
  728. or instance.tailscale_disabled != vp.tailscale_disabled
  729. )
  730. if changed:
  731. logger.info(
  732. "VP %s config changed (mode: %s→%s), restarting",
  733. instance.name,
  734. instance.mode,
  735. vp.mode,
  736. )
  737. await self.remove_instance(vp.id)
  738. # Start instances for all enabled VPs (skip already running)
  739. for vp in enabled_vps:
  740. if vp.id in self._instances:
  741. continue
  742. if vp.mode == "proxy":
  743. ip_info = proxy_ips.get(vp.id)
  744. if not ip_info:
  745. logger.warning("Proxy VP %s: target printer not found, skipping", vp.name)
  746. continue
  747. target_ip, target_serial = ip_info
  748. instance = VirtualPrinterInstance(
  749. vp_id=vp.id,
  750. name=vp.name,
  751. mode=vp.mode,
  752. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  753. access_code=vp.access_code or "",
  754. serial_suffix=vp.serial_suffix,
  755. target_printer_ip=target_ip,
  756. target_printer_serial=target_serial,
  757. auto_dispatch=vp.auto_dispatch,
  758. bind_ip=vp.bind_ip or "",
  759. remote_interface_ip=vp.remote_interface_ip or "",
  760. tailscale_disabled=vp.tailscale_disabled,
  761. base_dir=self._base_dir,
  762. session_factory=self._session_factory,
  763. )
  764. self._instances[vp.id] = instance
  765. await instance.start_proxy()
  766. logger.info("Started proxy VP: %s → %s (bind=%s)", instance.name, target_ip, instance.bind_ip)
  767. else:
  768. instance = VirtualPrinterInstance(
  769. vp_id=vp.id,
  770. name=vp.name,
  771. mode=vp.mode,
  772. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  773. access_code=vp.access_code or "",
  774. serial_suffix=vp.serial_suffix,
  775. target_printer_id=vp.target_printer_id,
  776. auto_dispatch=vp.auto_dispatch,
  777. bind_ip=vp.bind_ip or "",
  778. remote_interface_ip=vp.remote_interface_ip or "",
  779. tailscale_disabled=vp.tailscale_disabled,
  780. base_dir=self._base_dir,
  781. session_factory=self._session_factory,
  782. )
  783. self._instances[vp.id] = instance
  784. await instance.start_server()
  785. logger.info("Started server-mode VP: %s on %s", instance.name, vp.bind_ip)
  786. async def remove_instance(self, vp_id: int) -> None:
  787. """Stop and remove a single VP instance."""
  788. instance = self._instances.pop(vp_id, None)
  789. if instance:
  790. if instance.is_proxy:
  791. await instance.stop_proxy()
  792. else:
  793. await instance.stop_server()
  794. logger.info("Removed VP instance: %s", instance.name)
  795. async def stop_all(self) -> None:
  796. """Shutdown all virtual printer services."""
  797. logger.info("Stopping all virtual printer services...")
  798. for vp_id in list(self._instances.keys()):
  799. await self.remove_instance(vp_id)
  800. logger.info("All virtual printer services stopped")
  801. def get_instance(self, vp_id: int) -> VirtualPrinterInstance | None:
  802. """Get a running instance by ID."""
  803. return self._instances.get(vp_id)
  804. def get_all_status(self) -> list[dict]:
  805. """Get status for all running instances."""
  806. return [
  807. {
  808. "id": inst.id,
  809. "name": inst.name,
  810. "mode": inst.mode,
  811. **inst.get_status(),
  812. }
  813. for inst in self._instances.values()
  814. ]
  815. # -- Legacy single-printer compat --
  816. def get_status(self) -> dict:
  817. """Get status for first virtual printer (backward compat)."""
  818. if self._instances:
  819. first = next(iter(self._instances.values()))
  820. return {
  821. "enabled": True,
  822. "running": first.is_running,
  823. "mode": first.mode,
  824. "name": first.name,
  825. "serial": first.serial,
  826. "model": first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  827. "model_name": VIRTUAL_PRINTER_MODELS.get(
  828. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  829. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  830. ),
  831. "pending_files": first.get_status().get("pending_files", 0),
  832. **({"target_printer_ip": first.target_printer_ip} if first.is_proxy else {}),
  833. **({"proxy": first.get_status().get("proxy", {})} if first.is_proxy else {}),
  834. }
  835. return {
  836. "enabled": False,
  837. "running": False,
  838. "mode": "immediate",
  839. "name": "Bambuddy",
  840. "serial": "",
  841. "model": DEFAULT_VIRTUAL_PRINTER_MODEL,
  842. "model_name": VIRTUAL_PRINTER_MODELS[DEFAULT_VIRTUAL_PRINTER_MODEL],
  843. "pending_files": 0,
  844. }
  845. async def configure(
  846. self,
  847. enabled: bool,
  848. access_code: str = "",
  849. mode: str = "immediate",
  850. model: str = "",
  851. target_printer_ip: str = "",
  852. target_printer_serial: str = "",
  853. remote_interface_ip: str = "",
  854. ) -> None:
  855. """Legacy single-printer configure. Delegates to sync_from_db()."""
  856. # This method is kept for backward compat with the settings endpoint.
  857. # The actual work is done by sync_from_db() which reads from the DB.
  858. await self.sync_from_db()
  859. # Global instance
  860. virtual_printer_manager = VirtualPrinterManager()