manager.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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 typing import TYPE_CHECKING
  11. from backend.app.core.config import settings as app_settings
  12. from backend.app.services.virtual_printer.bind_server import BindServer
  13. from backend.app.services.virtual_printer.certificate import CertificateService
  14. from backend.app.services.virtual_printer.ftp_server import VirtualPrinterFTPServer
  15. from backend.app.services.virtual_printer.mqtt_bridge import MQTTBridge
  16. from backend.app.services.virtual_printer.mqtt_server import SimpleMQTTServer
  17. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy, VirtualPrinterSSDPServer
  18. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager, TCPProxy
  19. if TYPE_CHECKING:
  20. from backend.app.services.printer_manager import PrinterManager
  21. logger = logging.getLogger(__name__)
  22. # Mapping of SSDP model codes to display names
  23. # These are the codes that slicers expect during discovery
  24. # Sources:
  25. # - https://gist.github.com/Alex-Schaefer/72a9e2491a42da2ef99fb87601955cc3
  26. # - https://github.com/psychoticbeef/BambuLabOrcaSlicerDiscovery
  27. VIRTUAL_PRINTER_MODELS = {
  28. # X1 Series
  29. "BL-P001": "X1C", # X1 Carbon
  30. "BL-P002": "X1", # X1
  31. "C13": "X1E", # X1E
  32. # X2 Series
  33. "N6": "X2D", # X2D
  34. # P Series
  35. "C11": "P1P", # P1P
  36. "C12": "P1S", # P1S
  37. "N7": "P2S", # P2S
  38. # A1 Series
  39. "N2S": "A1", # A1
  40. "N1": "A1 Mini", # A1 Mini
  41. # H2 Series
  42. "O1D": "H2D", # H2D
  43. "O1C": "H2C", # H2C
  44. "O1C2": "H2C", # H2C (dual nozzle variant)
  45. "O1S": "H2S", # H2S
  46. }
  47. # Serial number prefixes for each model (based on Bambu Lab serial number format)
  48. # Format: MMM??RYMDDUUUUU (15 chars total)
  49. # MMM = Model prefix (3 chars)
  50. # ?? = Unknown/revision code (2 chars)
  51. # R = Revision letter (1 char)
  52. # Y = Year digit (1 char)
  53. # M = Month (1 char, hex: 1-9, A=Oct, B=Nov, C=Dec)
  54. # DD = Day (2 chars)
  55. # UUUUU = Unit number (5 chars)
  56. MODEL_SERIAL_PREFIXES = {
  57. # X1 Series
  58. "BL-P001": "00M00A", # X1C
  59. "BL-P002": "00M00A", # X1
  60. "C13": "03W00A", # X1E
  61. # X2 Series
  62. "N6": "20P90A", # X2D (first 4 chars "20P9" match real serials)
  63. # P Series
  64. "C11": "01S00A", # P1P
  65. "C12": "01P00A", # P1S
  66. "N7": "22E00A", # P2S
  67. # A1 Series
  68. "N2S": "03900A", # A1
  69. "N1": "03000A", # A1 Mini
  70. # H2 Series
  71. "O1D": "09400A", # H2D
  72. "O1C": "09400A", # H2C
  73. "O1C2": "09400A", # H2C (dual nozzle variant)
  74. "O1S": "09400A", # H2S
  75. }
  76. # Reverse mapping: display name → SSDP model code (for auto-inheriting from printer model)
  77. DISPLAY_NAME_TO_MODEL_CODE = {v: k for k, v in VIRTUAL_PRINTER_MODELS.items()}
  78. # Default model
  79. DEFAULT_VIRTUAL_PRINTER_MODEL = "BL-P001" # X1C
  80. def _get_serial_for_model(model: str, serial_suffix: str) -> str:
  81. """Get serial number for the given model and suffix."""
  82. prefix = MODEL_SERIAL_PREFIXES.get(model, "00M09A")
  83. return f"{prefix}{serial_suffix}"
  84. class VirtualPrinterInstance:
  85. """Per-printer state and file handling logic.
  86. Each instance represents one virtual printer with its own config,
  87. upload directory, certificates, and file handling mode.
  88. """
  89. def __init__(
  90. self,
  91. *,
  92. vp_id: int,
  93. name: str,
  94. mode: str,
  95. model: str,
  96. access_code: str,
  97. serial_suffix: str,
  98. target_printer_ip: str = "",
  99. target_printer_serial: str = "",
  100. target_printer_id: int | None = None,
  101. auto_dispatch: bool = True,
  102. queue_force_color_match: bool = False,
  103. bind_ip: str = "",
  104. remote_interface_ip: str = "",
  105. tailscale_disabled: bool = True,
  106. base_dir: Path,
  107. session_factory: Callable | None = None,
  108. printer_manager: "PrinterManager | None" = None,
  109. ):
  110. self.id = vp_id
  111. self.name = name
  112. self.mode = mode
  113. self.model = model
  114. self.access_code = access_code
  115. self.serial_suffix = serial_suffix
  116. self.target_printer_ip = target_printer_ip
  117. self.target_printer_serial = target_printer_serial
  118. self.target_printer_id = target_printer_id
  119. self.auto_dispatch = auto_dispatch
  120. self.queue_force_color_match = queue_force_color_match
  121. self.bind_ip = bind_ip
  122. self.remote_interface_ip = remote_interface_ip
  123. self.tailscale_disabled = tailscale_disabled
  124. self._session_factory = session_factory
  125. self._printer_manager = printer_manager
  126. # Directories
  127. self.upload_dir = base_dir / "uploads" / str(vp_id)
  128. self.cert_dir = base_dir / "certs" / str(vp_id)
  129. shared_ca_dir = base_dir / "certs"
  130. # Ensure directories exist
  131. self.upload_dir.mkdir(parents=True, exist_ok=True)
  132. (self.upload_dir / "cache").mkdir(exist_ok=True)
  133. self.cert_dir.mkdir(parents=True, exist_ok=True)
  134. # Certificate service (shared CA, per-instance printer cert)
  135. self._cert_service = CertificateService(
  136. cert_dir=self.cert_dir,
  137. serial=self.serial,
  138. shared_ca_dir=shared_ca_dir,
  139. )
  140. # Pending files for MQTT correlation
  141. self._pending_files: dict[str, Path] = {}
  142. # Per-instance services
  143. self._proxy: SlicerProxyManager | None = None
  144. self._ftp: VirtualPrinterFTPServer | None = None
  145. self._mqtt: SimpleMQTTServer | None = None
  146. self._mqtt_bridge: MQTTBridge | None = None
  147. self._rtsp_proxy: TCPProxy | None = None
  148. self._bind: BindServer | None = None
  149. self._ssdp: VirtualPrinterSSDPServer | None = None
  150. self._ssdp_proxy: SSDPProxy | None = None
  151. self._tasks: list[asyncio.Task] = []
  152. @property
  153. def serial(self) -> str:
  154. """Full serial number for this virtual printer."""
  155. return _get_serial_for_model(self.model or DEFAULT_VIRTUAL_PRINTER_MODEL, self.serial_suffix)
  156. @property
  157. def cert_path(self) -> Path:
  158. return self._cert_service.cert_path
  159. @property
  160. def key_path(self) -> Path:
  161. return self._cert_service.key_path
  162. @property
  163. def is_proxy(self) -> bool:
  164. return self.mode == "proxy"
  165. @property
  166. def is_running(self) -> bool:
  167. return len(self._tasks) > 0 and all(not t.done() for t in self._tasks)
  168. def generate_certificates(self) -> tuple[Path, Path]:
  169. """Generate certificates for this instance."""
  170. self._cert_service.serial = self.serial if not self.is_proxy else (self.target_printer_serial or self.serial)
  171. additional_ips = [self.remote_interface_ip] if self.remote_interface_ip else None
  172. if self.bind_ip:
  173. additional_ips = additional_ips or []
  174. additional_ips.append(self.bind_ip)
  175. self._cert_service.delete_printer_certificate()
  176. return self._cert_service.generate_certificates(additional_ips=additional_ips)
  177. # -- File handling callbacks --
  178. async def on_file_received(self, file_path: Path, source_ip: str) -> None:
  179. """Handle file upload completion from FTP."""
  180. logger.info("[VP %s] Received file: %s from %s", self.name, file_path.name, source_ip)
  181. self._pending_files[file_path.name] = file_path
  182. if self.mode == "immediate":
  183. await self._archive_file(file_path, source_ip)
  184. elif self.mode == "print_queue":
  185. await self._add_to_print_queue(file_path, source_ip)
  186. else:
  187. await self._queue_file(file_path, source_ip)
  188. # Signal job completion to the slicer. Send-flow slicers don't watch the
  189. # post-upload state and would be happy with anything; the Print flow
  190. # (intended for proxy-mode VPs, but users sometimes click it against
  191. # queue/immediate/review modes too — #1280) watches the gcode_state
  192. # cycle and only releases its in-flight-job lock when it sees FINISH.
  193. # Going PREPARE → IDLE wedges the slicer's UI at "Downloading...(0%)"
  194. # and blocks the next dispatch with "busy with another print job".
  195. # PREPARE → FINISH satisfies both flows. prepare_percent=100 also
  196. # unfreezes the slicer's "Downloading X%" progress bar which it ticks
  197. # against the same field during the upload window.
  198. if self._mqtt and file_path.suffix.lower() == ".3mf":
  199. self._mqtt.set_gcode_state("FINISH", filename=file_path.name, prepare_percent="100")
  200. async def on_print_command(self, filename: str, data: dict) -> None:
  201. """Handle print command from MQTT."""
  202. logger.info("[VP %s] Print command for: %s", self.name, filename)
  203. async def _archive_file(self, file_path: Path, source_ip: str) -> None:
  204. """Archive file immediately."""
  205. if not self._session_factory:
  206. logger.error("Cannot archive: no database session factory configured")
  207. return
  208. if file_path.suffix.lower() != ".3mf":
  209. logger.debug("Skipping non-3MF file: %s", file_path.name)
  210. self._pending_files.pop(file_path.name, None)
  211. try:
  212. file_path.unlink()
  213. except OSError:
  214. pass
  215. return
  216. try:
  217. from backend.app.api.routes.settings import get_setting
  218. from backend.app.services.archive import ArchiveService
  219. async with self._session_factory() as db:
  220. name_source = await get_setting(db, "virtual_printer_archive_name_source")
  221. prefer_filename = name_source == "filename"
  222. service = ArchiveService(db)
  223. archive = await service.archive_print(
  224. printer_id=None,
  225. source_file=file_path,
  226. print_data={
  227. "status": "archived",
  228. "source": "virtual_printer",
  229. "source_ip": source_ip,
  230. },
  231. prefer_filename_for_name=prefer_filename,
  232. )
  233. if archive:
  234. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  235. try:
  236. file_path.unlink()
  237. except OSError:
  238. pass
  239. self._pending_files.pop(file_path.name, None)
  240. else:
  241. logger.error("Failed to archive file: %s", file_path.name)
  242. except Exception as e:
  243. logger.error("Error archiving file: %s", e)
  244. async def _queue_file(self, file_path: Path, source_ip: str) -> None:
  245. """Queue file for user review."""
  246. if not self._session_factory:
  247. logger.error("Cannot queue: no database session factory configured")
  248. return
  249. if file_path.suffix.lower() != ".3mf":
  250. self._pending_files.pop(file_path.name, None)
  251. try:
  252. file_path.unlink()
  253. except OSError:
  254. pass
  255. return
  256. # Peek at the 3MF for the embedded title BEFORE we hand it off to the
  257. # DB. Storing it now means the /pending-uploads/ list doesn't have to
  258. # reopen every 3MF on every render to keep the review card and the
  259. # eventual archive name in sync (#1152 follow-up). Failure to parse is
  260. # not fatal — the response model falls back to the filename stem.
  261. metadata_print_name: str | None = None
  262. try:
  263. from backend.app.services.archive import ThreeMFParser
  264. parsed = ThreeMFParser(file_path).parse()
  265. raw_name = parsed.get("print_name")
  266. if isinstance(raw_name, str) and raw_name.strip():
  267. metadata_print_name = raw_name.strip()[:255]
  268. except Exception as e:
  269. logger.debug("[VP %s] Metadata title peek failed for %s: %s", self.name, file_path.name, e)
  270. try:
  271. from backend.app.models.pending_upload import PendingUpload
  272. async with self._session_factory() as db:
  273. pending = PendingUpload(
  274. filename=file_path.name,
  275. file_path=str(file_path),
  276. file_size=file_path.stat().st_size,
  277. source_ip=source_ip,
  278. status="pending",
  279. uploaded_at=datetime.now(timezone.utc),
  280. metadata_print_name=metadata_print_name,
  281. )
  282. db.add(pending)
  283. await db.commit()
  284. logger.info("[VP %s] Queued: %s - %s", self.name, pending.id, file_path.name)
  285. self._pending_files.pop(file_path.name, None)
  286. except Exception as e:
  287. logger.error("Error queueing file: %s", e)
  288. async def _add_to_print_queue(self, file_path: Path, source_ip: str) -> None:
  289. """Archive file and add to print queue, assigned to target printer or model."""
  290. if not self._session_factory:
  291. logger.error("Cannot add to print queue: no database session factory configured")
  292. return
  293. if file_path.suffix.lower() != ".3mf":
  294. self._pending_files.pop(file_path.name, None)
  295. try:
  296. file_path.unlink()
  297. except OSError:
  298. pass
  299. return
  300. try:
  301. import json
  302. from backend.app.api.routes.settings import get_setting
  303. from backend.app.models.print_queue import PrintQueueItem
  304. from backend.app.services.archive import ArchiveService
  305. from backend.app.services.filament_requirements import extract_filament_requirements
  306. async with self._session_factory() as db:
  307. name_source = await get_setting(db, "virtual_printer_archive_name_source")
  308. prefer_filename = name_source == "filename"
  309. # Read workflow defaults from settings. Without this the
  310. # PrintQueueItem below would fall back to the column-level
  311. # defaults and ignore the user's workflow preferences (#1235).
  312. # Fallbacks match AppSettings defaults in schemas/settings.py.
  313. def _bool_setting(value: str | None, default: bool) -> bool:
  314. return value.lower() == "true" if value is not None else default
  315. bed_levelling = _bool_setting(await get_setting(db, "default_bed_levelling"), True)
  316. flow_cali = _bool_setting(await get_setting(db, "default_flow_cali"), False)
  317. vibration_cali = _bool_setting(await get_setting(db, "default_vibration_cali"), True)
  318. layer_inspect = _bool_setting(await get_setting(db, "default_layer_inspect"), False)
  319. timelapse = _bool_setting(await get_setting(db, "default_timelapse"), False)
  320. service = ArchiveService(db)
  321. archive = await service.archive_print(
  322. printer_id=None,
  323. source_file=file_path,
  324. print_data={
  325. "status": "archived",
  326. "source": "virtual_printer",
  327. "source_ip": source_ip,
  328. },
  329. prefer_filename_for_name=prefer_filename,
  330. )
  331. if archive:
  332. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  333. # Assign to specific printer if configured, otherwise use model for "Any X" scheduling
  334. target_model = None
  335. if not self.target_printer_id and self.model:
  336. target_model = VIRTUAL_PRINTER_MODELS.get(self.model)
  337. plate_id = self._extract_plate_id(file_path)
  338. # Parse the 3MF for per-slot filament requirements (#1188).
  339. # The manual /print-queue/ POST flow does this at queue-add
  340. # time; the VP path used to skip it, so the scheduler fell
  341. # through to model-only matching and dispatched onto whatever
  342. # printer happened to be free regardless of loaded colour.
  343. # required_filament_types is populated unconditionally — it's
  344. # cheap, lets the scheduler reject obvious mis-matches even
  345. # without force_color_match. filament_overrides only carries
  346. # force_color_match=True when the per-VP setting is on, so
  347. # upgraders keep the old behaviour by default.
  348. required_filament_types_json: str | None = None
  349. filament_overrides_json: str | None = None
  350. requirements = extract_filament_requirements(file_path, plate_id)
  351. if requirements:
  352. types = sorted({r["type"] for r in requirements if r.get("type")})
  353. if types:
  354. required_filament_types_json = json.dumps(types)
  355. if self.queue_force_color_match:
  356. overrides = [
  357. {
  358. "slot_id": r["slot_id"],
  359. "type": r.get("type", ""),
  360. "color": r.get("color", ""),
  361. "force_color_match": True,
  362. }
  363. for r in requirements
  364. if r.get("type") and r.get("color")
  365. ]
  366. if overrides:
  367. filament_overrides_json = json.dumps(overrides)
  368. queue_item = PrintQueueItem(
  369. printer_id=self.target_printer_id,
  370. target_model=target_model,
  371. archive_id=archive.id,
  372. plate_id=plate_id,
  373. position=1,
  374. status="pending",
  375. manual_start=not self.auto_dispatch,
  376. required_filament_types=required_filament_types_json,
  377. filament_overrides=filament_overrides_json,
  378. bed_levelling=bed_levelling,
  379. flow_cali=flow_cali,
  380. vibration_cali=vibration_cali,
  381. layer_inspect=layer_inspect,
  382. timelapse=timelapse,
  383. )
  384. db.add(queue_item)
  385. await db.commit()
  386. logger.info("[VP %s] Added to queue: %s", self.name, queue_item.id)
  387. try:
  388. file_path.unlink()
  389. except OSError:
  390. pass
  391. self._pending_files.pop(file_path.name, None)
  392. else:
  393. logger.error("Failed to archive file: %s", file_path.name)
  394. except Exception as e:
  395. logger.error("Error adding to print queue: %s", e)
  396. @staticmethod
  397. def _extract_plate_id(file_path: Path) -> int | None:
  398. """Extract plate index from 3MF slice_info.config."""
  399. try:
  400. import xml.etree.ElementTree as ET
  401. import zipfile
  402. with zipfile.ZipFile(file_path, "r") as zf:
  403. if "Metadata/slice_info.config" in zf.namelist():
  404. content = zf.read("Metadata/slice_info.config").decode()
  405. root = ET.fromstring(content) # noqa: S314 # nosec B314
  406. plate = root.find(".//plate")
  407. if plate is not None:
  408. for meta in plate.findall("metadata"):
  409. if meta.get("key") == "index" and meta.get("value"):
  410. return int(meta.get("value"))
  411. except Exception:
  412. return None
  413. return None
  414. # -- Service lifecycle --
  415. def _resolve_cert_and_advertise(self) -> tuple[Path, Path, str]:
  416. """Return (cert_path, key_path, advertise_address) for TLS services.
  417. Always uses the self-signed cert chain (signed by `bbl_ca`). The user
  418. imports `bbl_ca.crt` once into the slicer; per-VP certs validate from
  419. there. Tailscale exposure is handled by the user picking the Tailscale
  420. IP in the bind_ip dropdown.
  421. """
  422. cert_path, key_path = self.generate_certificates()
  423. advertise = self.remote_interface_ip or self.bind_ip or ""
  424. return cert_path, key_path, advertise
  425. async def start_server(self) -> None:
  426. """Start server-mode services (FTP, MQTT, SSDP, Bind) on this VP's bind_ip."""
  427. logger.info("[VP %s] Starting server-mode services on %s", self.name, self.bind_ip)
  428. cert_path, key_path, advertise_addr = self._resolve_cert_and_advertise()
  429. bind_addr = self.bind_ip or "0.0.0.0" # nosec B104
  430. async def run_with_logging(coro, svc_name):
  431. try:
  432. await coro
  433. except Exception as e:
  434. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  435. self._tasks = []
  436. # FTP server
  437. self._ftp = VirtualPrinterFTPServer(
  438. upload_dir=self.upload_dir,
  439. access_code=self.access_code,
  440. cert_path=cert_path,
  441. key_path=key_path,
  442. on_file_received=self.on_file_received,
  443. bind_address=bind_addr,
  444. vp_name=self.name,
  445. )
  446. self._tasks.append(
  447. asyncio.create_task(
  448. run_with_logging(self._ftp.start(), "FTP"),
  449. name=f"vp_{self.id}_ftp",
  450. )
  451. )
  452. # MQTT server
  453. self._mqtt = SimpleMQTTServer(
  454. serial=self.serial,
  455. access_code=self.access_code,
  456. cert_path=cert_path,
  457. key_path=key_path,
  458. on_print_command=self.on_print_command,
  459. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  460. bind_address=bind_addr,
  461. vp_name=self.name,
  462. )
  463. self._tasks.append(
  464. asyncio.create_task(
  465. run_with_logging(self._mqtt.start(), "MQTT"),
  466. name=f"vp_{self.id}_mqtt",
  467. )
  468. )
  469. # MQTT bridge — fans out the target printer's pushes to slicers connected
  470. # to this VP and forwards their commands back to the printer. Only meaningful
  471. # when a target printer is configured AND printer_manager was injected (it
  472. # always is at runtime; tests may omit it).
  473. if self.target_printer_id is not None and self._printer_manager is not None:
  474. self._mqtt_bridge = MQTTBridge(
  475. vp_id=self.id,
  476. vp_name=self.name,
  477. vp_serial=self.serial,
  478. target_printer_id=self.target_printer_id,
  479. mqtt_server=self._mqtt,
  480. printer_manager=self._printer_manager,
  481. )
  482. self._mqtt.set_bridge(self._mqtt_bridge)
  483. await self._mqtt_bridge.start()
  484. # RTSPS camera passthrough on port 322. BambuStudio's camera button
  485. # connects to the device IP it bound on (the VP), not the IP in
  486. # `ipcam.rtsp_url`. Without a listener on <bind_ip>:322 the slicer
  487. # gets connection refused → "LAN connection failed". Same raw TCP
  488. # pass-through used by SlicerProxyManager in proxy mode.
  489. target_client = self._printer_manager.get_client(self.target_printer_id)
  490. target_ip = getattr(target_client, "ip_address", None) if target_client else None
  491. if target_ip:
  492. self._rtsp_proxy = TCPProxy(
  493. name="RTSP",
  494. listen_port=322,
  495. target_host=target_ip,
  496. target_port=322,
  497. bind_address=bind_addr,
  498. )
  499. self._tasks.append(
  500. asyncio.create_task(
  501. run_with_logging(self._rtsp_proxy.start(), "RTSP"),
  502. name=f"vp_{self.id}_rtsp",
  503. )
  504. )
  505. # Bind server
  506. self._bind = BindServer(
  507. serial=self.serial,
  508. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  509. name=self.name,
  510. bind_address=bind_addr,
  511. cert_path=cert_path,
  512. key_path=key_path,
  513. )
  514. self._tasks.append(
  515. asyncio.create_task(
  516. run_with_logging(self._bind.start(), "Bind"),
  517. name=f"vp_{self.id}_bind",
  518. )
  519. )
  520. # SSDP server — advertise_addr is the Tailscale FQDN when available,
  521. # otherwise the bind/remote IP (existing behaviour)
  522. self._ssdp = VirtualPrinterSSDPServer(
  523. name=self.name,
  524. serial=self.serial,
  525. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  526. advertise_ip=advertise_addr,
  527. bind_ip=bind_addr,
  528. )
  529. self._tasks.append(
  530. asyncio.create_task(
  531. run_with_logging(self._ssdp.start(), "SSDP"),
  532. name=f"vp_{self.id}_ssdp",
  533. )
  534. )
  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. if self._mqtt_bridge:
  539. try:
  540. await self._mqtt_bridge.stop()
  541. except Exception:
  542. logger.exception("[VP %s] MQTT bridge stop failed", self.name)
  543. if self._mqtt:
  544. self._mqtt.set_bridge(None)
  545. self._mqtt_bridge = None
  546. if self._rtsp_proxy:
  547. try:
  548. await self._rtsp_proxy.stop()
  549. except Exception:
  550. logger.exception("[VP %s] RTSP proxy stop failed", self.name)
  551. self._rtsp_proxy = None
  552. if self._ftp:
  553. await self._ftp.stop()
  554. self._ftp = None
  555. if self._mqtt:
  556. await self._mqtt.stop()
  557. self._mqtt = None
  558. if self._bind:
  559. await self._bind.stop()
  560. self._bind = None
  561. if self._ssdp:
  562. await self._ssdp.stop()
  563. self._ssdp = None
  564. await self._cancel_tasks()
  565. async def start_proxy(self) -> None:
  566. """Start proxy mode services for this instance."""
  567. logger.info("[VP %s] Starting proxy mode to %s", self.name, self.target_printer_ip)
  568. cert_path, key_path, _ = self._resolve_cert_and_advertise()
  569. self._proxy = SlicerProxyManager(
  570. target_host=self.target_printer_ip,
  571. cert_path=cert_path,
  572. key_path=key_path,
  573. on_activity=lambda n, m: logger.info("[VP %s] Proxy %s: %s", self.name, n, m),
  574. bind_address=self.bind_ip or "0.0.0.0", # nosec B104
  575. bind_identity={
  576. "serial": self.target_printer_serial or self.serial,
  577. "model": self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  578. "name": self.name,
  579. "version": "01.00.00.00",
  580. },
  581. )
  582. async def run_with_logging(coro, svc_name):
  583. try:
  584. await coro
  585. except Exception as e:
  586. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  587. self._tasks = []
  588. # SSDP for proxy
  589. proxy_serial = self.target_printer_serial or self.serial
  590. if self.remote_interface_ip:
  591. from backend.app.services.network_utils import find_interface_for_ip
  592. local_iface = find_interface_for_ip(self.target_printer_ip)
  593. if local_iface:
  594. self._ssdp_proxy = SSDPProxy(
  595. local_interface_ip=local_iface["ip"],
  596. remote_interface_ip=self.remote_interface_ip,
  597. target_printer_ip=self.target_printer_ip,
  598. name=self.name,
  599. )
  600. self._tasks.append(
  601. asyncio.create_task(
  602. run_with_logging(self._ssdp_proxy.start(), "SSDP Proxy"),
  603. name=f"vp_{self.id}_ssdp_proxy",
  604. )
  605. )
  606. else:
  607. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  608. else:
  609. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  610. self._tasks.append(
  611. asyncio.create_task(
  612. run_with_logging(self._proxy.start(), "Proxy"),
  613. name=f"vp_{self.id}_proxy",
  614. )
  615. )
  616. def _start_fallback_ssdp(self, proxy_serial: str, run_with_logging) -> None:
  617. """Start single-interface SSDP server as fallback for proxy mode."""
  618. self._ssdp = VirtualPrinterSSDPServer(
  619. name=f"{self.name} (Proxy)",
  620. serial=proxy_serial,
  621. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  622. advertise_ip=self.bind_ip or "",
  623. bind_ip=self.bind_ip or "",
  624. )
  625. self._tasks.append(
  626. asyncio.create_task(
  627. run_with_logging(self._ssdp.start(), "SSDP"),
  628. name=f"vp_{self.id}_ssdp",
  629. )
  630. )
  631. async def stop_proxy(self) -> None:
  632. """Stop proxy mode services for this instance."""
  633. if self._proxy:
  634. await self._proxy.stop()
  635. self._proxy = None
  636. if self._ssdp:
  637. await self._ssdp.stop()
  638. self._ssdp = None
  639. if self._ssdp_proxy:
  640. await self._ssdp_proxy.stop()
  641. self._ssdp_proxy = None
  642. await self._cancel_tasks()
  643. async def _cancel_tasks(self) -> None:
  644. """Cancel all running tasks and wait for cleanup."""
  645. for task in self._tasks:
  646. task.cancel()
  647. if self._tasks:
  648. try:
  649. await asyncio.wait_for(asyncio.gather(*self._tasks, return_exceptions=True), timeout=1.0)
  650. except TimeoutError:
  651. pass
  652. self._tasks = []
  653. def get_status(self) -> dict:
  654. """Get status for this instance."""
  655. status: dict = {
  656. "running": self.is_running,
  657. "pending_files": len(self._pending_files),
  658. }
  659. if self.is_proxy and self._proxy:
  660. status["proxy"] = self._proxy.get_status()
  661. return status
  662. class VirtualPrinterManager:
  663. """Multi-instance virtual printer registry and orchestrator.
  664. Every VP runs its own independent services on a dedicated bind IP.
  665. """
  666. def __init__(self):
  667. self._session_factory: Callable | None = None
  668. self._printer_manager: PrinterManager | None = None
  669. self._instances: dict[int, VirtualPrinterInstance] = {}
  670. # Directories
  671. self._base_dir = app_settings.base_dir / "virtual_printer"
  672. # Ensure base directories exist
  673. self._ensure_base_directories()
  674. def _ensure_base_directories(self) -> None:
  675. """Create base directories at startup."""
  676. for dir_path in [self._base_dir, self._base_dir / "uploads", self._base_dir / "certs"]:
  677. try:
  678. dir_path.mkdir(parents=True, exist_ok=True)
  679. except PermissionError:
  680. logger.error(
  681. f"Cannot create directory {dir_path}: Permission denied. "
  682. f"For Docker: ensure the data volume is writable by the container user. "
  683. f"For bare metal: run 'sudo chown -R $(whoami) {self._base_dir}'"
  684. )
  685. def set_session_factory(self, session_factory: Callable) -> None:
  686. """Set the database session factory."""
  687. self._session_factory = session_factory
  688. def set_printer_manager(self, printer_manager: "PrinterManager") -> None:
  689. """Inject the global printer_manager so non-proxy VPs can mirror their target's MQTT stream."""
  690. self._printer_manager = printer_manager
  691. @property
  692. def is_enabled(self) -> bool:
  693. """Check if any virtual printer is running."""
  694. return len(self._instances) > 0
  695. async def sync_from_db(self) -> None:
  696. """Load all VPs from DB, reconcile running state."""
  697. if not self._session_factory:
  698. logger.warning("Cannot sync virtual printers: no session factory")
  699. return
  700. from sqlalchemy import select
  701. from backend.app.models.printer import Printer
  702. from backend.app.models.virtual_printer import VirtualPrinter
  703. async with self._session_factory() as db:
  704. result = await db.execute(
  705. select(VirtualPrinter).where(VirtualPrinter.enabled == True).order_by(VirtualPrinter.position) # noqa: E712
  706. )
  707. enabled_vps = result.scalars().all()
  708. # Stop instances that are no longer enabled or changed mode
  709. enabled_ids = {vp.id for vp in enabled_vps}
  710. for vp_id in list(self._instances.keys()):
  711. if vp_id not in enabled_ids:
  712. await self.remove_instance(vp_id)
  713. # Look up printer IPs for proxy VPs
  714. proxy_vps = [vp for vp in enabled_vps if vp.mode == "proxy"]
  715. proxy_ips: dict[int, tuple[str, str]] = {}
  716. if proxy_vps:
  717. async with self._session_factory() as db:
  718. for pvp in proxy_vps:
  719. if pvp.target_printer_id:
  720. result = await db.execute(select(Printer).where(Printer.id == pvp.target_printer_id))
  721. printer = result.scalar_one_or_none()
  722. if printer:
  723. proxy_ips[pvp.id] = (printer.ip_address, printer.serial_number)
  724. # Detect config changes on running instances and restart if needed
  725. for vp in enabled_vps:
  726. instance = self._instances.get(vp.id)
  727. if not instance:
  728. continue
  729. changed = (
  730. instance.mode != vp.mode
  731. or instance.model != (vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL)
  732. or instance.access_code != (vp.access_code or "")
  733. or instance.bind_ip != (vp.bind_ip or "")
  734. or instance.remote_interface_ip != (vp.remote_interface_ip or "")
  735. or instance.target_printer_id != vp.target_printer_id
  736. or instance.auto_dispatch != vp.auto_dispatch
  737. )
  738. if changed:
  739. logger.info(
  740. "VP %s config changed (mode: %s→%s), restarting",
  741. instance.name,
  742. instance.mode,
  743. vp.mode,
  744. )
  745. await self.remove_instance(vp.id)
  746. # Start instances for all enabled VPs (skip already running)
  747. for vp in enabled_vps:
  748. if vp.id in self._instances:
  749. continue
  750. if vp.mode == "proxy":
  751. ip_info = proxy_ips.get(vp.id)
  752. if not ip_info:
  753. logger.warning("Proxy VP %s: target printer not found, skipping", vp.name)
  754. continue
  755. target_ip, target_serial = ip_info
  756. instance = VirtualPrinterInstance(
  757. vp_id=vp.id,
  758. name=vp.name,
  759. mode=vp.mode,
  760. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  761. access_code=vp.access_code or "",
  762. serial_suffix=vp.serial_suffix,
  763. target_printer_ip=target_ip,
  764. target_printer_serial=target_serial,
  765. auto_dispatch=vp.auto_dispatch,
  766. bind_ip=vp.bind_ip or "",
  767. remote_interface_ip=vp.remote_interface_ip or "",
  768. tailscale_disabled=vp.tailscale_disabled,
  769. base_dir=self._base_dir,
  770. session_factory=self._session_factory,
  771. )
  772. self._instances[vp.id] = instance
  773. await instance.start_proxy()
  774. logger.info("Started proxy VP: %s → %s (bind=%s)", instance.name, target_ip, instance.bind_ip)
  775. else:
  776. instance = VirtualPrinterInstance(
  777. vp_id=vp.id,
  778. name=vp.name,
  779. mode=vp.mode,
  780. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  781. access_code=vp.access_code or "",
  782. serial_suffix=vp.serial_suffix,
  783. target_printer_id=vp.target_printer_id,
  784. auto_dispatch=vp.auto_dispatch,
  785. queue_force_color_match=vp.queue_force_color_match,
  786. bind_ip=vp.bind_ip or "",
  787. remote_interface_ip=vp.remote_interface_ip or "",
  788. tailscale_disabled=vp.tailscale_disabled,
  789. base_dir=self._base_dir,
  790. session_factory=self._session_factory,
  791. printer_manager=self._printer_manager,
  792. )
  793. self._instances[vp.id] = instance
  794. await instance.start_server()
  795. logger.info("Started server-mode VP: %s on %s", instance.name, vp.bind_ip)
  796. async def remove_instance(self, vp_id: int) -> None:
  797. """Stop and remove a single VP instance."""
  798. instance = self._instances.pop(vp_id, None)
  799. if instance:
  800. if instance.is_proxy:
  801. await instance.stop_proxy()
  802. else:
  803. await instance.stop_server()
  804. logger.info("Removed VP instance: %s", instance.name)
  805. async def stop_all(self) -> None:
  806. """Shutdown all virtual printer services."""
  807. logger.info("Stopping all virtual printer services...")
  808. for vp_id in list(self._instances.keys()):
  809. await self.remove_instance(vp_id)
  810. logger.info("All virtual printer services stopped")
  811. def get_instance(self, vp_id: int) -> VirtualPrinterInstance | None:
  812. """Get a running instance by ID."""
  813. return self._instances.get(vp_id)
  814. def get_all_status(self) -> list[dict]:
  815. """Get status for all running instances."""
  816. return [
  817. {
  818. "id": inst.id,
  819. "name": inst.name,
  820. "mode": inst.mode,
  821. **inst.get_status(),
  822. }
  823. for inst in self._instances.values()
  824. ]
  825. # -- Legacy single-printer compat --
  826. def get_status(self) -> dict:
  827. """Get status for first virtual printer (backward compat)."""
  828. if self._instances:
  829. first = next(iter(self._instances.values()))
  830. return {
  831. "enabled": True,
  832. "running": first.is_running,
  833. "mode": first.mode,
  834. "name": first.name,
  835. "serial": first.serial,
  836. "model": first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  837. "model_name": VIRTUAL_PRINTER_MODELS.get(
  838. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  839. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  840. ),
  841. "pending_files": first.get_status().get("pending_files", 0),
  842. **({"target_printer_ip": first.target_printer_ip} if first.is_proxy else {}),
  843. **({"proxy": first.get_status().get("proxy", {})} if first.is_proxy else {}),
  844. }
  845. return {
  846. "enabled": False,
  847. "running": False,
  848. "mode": "immediate",
  849. "name": "Bambuddy",
  850. "serial": "",
  851. "model": DEFAULT_VIRTUAL_PRINTER_MODEL,
  852. "model_name": VIRTUAL_PRINTER_MODELS[DEFAULT_VIRTUAL_PRINTER_MODEL],
  853. "pending_files": 0,
  854. }
  855. async def configure(
  856. self,
  857. enabled: bool,
  858. access_code: str = "",
  859. mode: str = "immediate",
  860. model: str = "",
  861. target_printer_ip: str = "",
  862. target_printer_serial: str = "",
  863. remote_interface_ip: str = "",
  864. ) -> None:
  865. """Legacy single-printer configure. Delegates to sync_from_db()."""
  866. # This method is kept for backward compat with the settings endpoint.
  867. # The actual work is done by sync_from_db() which reads from the DB.
  868. await self.sync_from_db()
  869. # Global instance
  870. virtual_printer_manager = VirtualPrinterManager()