manager.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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. # Reset MQTT status back to IDLE
  189. if self._mqtt and file_path.suffix.lower() == ".3mf":
  190. self._mqtt.set_gcode_state("IDLE")
  191. async def on_print_command(self, filename: str, data: dict) -> None:
  192. """Handle print command from MQTT."""
  193. logger.info("[VP %s] Print command for: %s", self.name, filename)
  194. async def _archive_file(self, file_path: Path, source_ip: str) -> None:
  195. """Archive file immediately."""
  196. if not self._session_factory:
  197. logger.error("Cannot archive: no database session factory configured")
  198. return
  199. if file_path.suffix.lower() != ".3mf":
  200. logger.debug("Skipping non-3MF file: %s", file_path.name)
  201. self._pending_files.pop(file_path.name, None)
  202. try:
  203. file_path.unlink()
  204. except OSError:
  205. pass
  206. return
  207. try:
  208. from backend.app.api.routes.settings import get_setting
  209. from backend.app.services.archive import ArchiveService
  210. async with self._session_factory() as db:
  211. name_source = await get_setting(db, "virtual_printer_archive_name_source")
  212. prefer_filename = name_source == "filename"
  213. service = ArchiveService(db)
  214. archive = await service.archive_print(
  215. printer_id=None,
  216. source_file=file_path,
  217. print_data={
  218. "status": "archived",
  219. "source": "virtual_printer",
  220. "source_ip": source_ip,
  221. },
  222. prefer_filename_for_name=prefer_filename,
  223. )
  224. if archive:
  225. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  226. try:
  227. file_path.unlink()
  228. except OSError:
  229. pass
  230. self._pending_files.pop(file_path.name, None)
  231. else:
  232. logger.error("Failed to archive file: %s", file_path.name)
  233. except Exception as e:
  234. logger.error("Error archiving file: %s", e)
  235. async def _queue_file(self, file_path: Path, source_ip: str) -> None:
  236. """Queue file for user review."""
  237. if not self._session_factory:
  238. logger.error("Cannot queue: no database session factory configured")
  239. return
  240. if file_path.suffix.lower() != ".3mf":
  241. self._pending_files.pop(file_path.name, None)
  242. try:
  243. file_path.unlink()
  244. except OSError:
  245. pass
  246. return
  247. # Peek at the 3MF for the embedded title BEFORE we hand it off to the
  248. # DB. Storing it now means the /pending-uploads/ list doesn't have to
  249. # reopen every 3MF on every render to keep the review card and the
  250. # eventual archive name in sync (#1152 follow-up). Failure to parse is
  251. # not fatal — the response model falls back to the filename stem.
  252. metadata_print_name: str | None = None
  253. try:
  254. from backend.app.services.archive import ThreeMFParser
  255. parsed = ThreeMFParser(file_path).parse()
  256. raw_name = parsed.get("print_name")
  257. if isinstance(raw_name, str) and raw_name.strip():
  258. metadata_print_name = raw_name.strip()[:255]
  259. except Exception as e:
  260. logger.debug("[VP %s] Metadata title peek failed for %s: %s", self.name, file_path.name, e)
  261. try:
  262. from backend.app.models.pending_upload import PendingUpload
  263. async with self._session_factory() as db:
  264. pending = PendingUpload(
  265. filename=file_path.name,
  266. file_path=str(file_path),
  267. file_size=file_path.stat().st_size,
  268. source_ip=source_ip,
  269. status="pending",
  270. uploaded_at=datetime.now(timezone.utc),
  271. metadata_print_name=metadata_print_name,
  272. )
  273. db.add(pending)
  274. await db.commit()
  275. logger.info("[VP %s] Queued: %s - %s", self.name, pending.id, file_path.name)
  276. self._pending_files.pop(file_path.name, None)
  277. except Exception as e:
  278. logger.error("Error queueing file: %s", e)
  279. async def _add_to_print_queue(self, file_path: Path, source_ip: str) -> None:
  280. """Archive file and add to print queue, assigned to target printer or model."""
  281. if not self._session_factory:
  282. logger.error("Cannot add to print queue: no database session factory configured")
  283. return
  284. if file_path.suffix.lower() != ".3mf":
  285. self._pending_files.pop(file_path.name, None)
  286. try:
  287. file_path.unlink()
  288. except OSError:
  289. pass
  290. return
  291. try:
  292. import json
  293. from backend.app.api.routes.settings import get_setting
  294. from backend.app.models.print_queue import PrintQueueItem
  295. from backend.app.services.archive import ArchiveService
  296. from backend.app.services.filament_requirements import extract_filament_requirements
  297. async with self._session_factory() as db:
  298. name_source = await get_setting(db, "virtual_printer_archive_name_source")
  299. prefer_filename = name_source == "filename"
  300. # Read workflow defaults from settings. Without this the
  301. # PrintQueueItem below would fall back to the column-level
  302. # defaults and ignore the user's workflow preferences (#1235).
  303. # Fallbacks match AppSettings defaults in schemas/settings.py.
  304. def _bool_setting(value: str | None, default: bool) -> bool:
  305. return value.lower() == "true" if value is not None else default
  306. bed_levelling = _bool_setting(await get_setting(db, "default_bed_levelling"), True)
  307. flow_cali = _bool_setting(await get_setting(db, "default_flow_cali"), False)
  308. vibration_cali = _bool_setting(await get_setting(db, "default_vibration_cali"), True)
  309. layer_inspect = _bool_setting(await get_setting(db, "default_layer_inspect"), False)
  310. timelapse = _bool_setting(await get_setting(db, "default_timelapse"), False)
  311. service = ArchiveService(db)
  312. archive = await service.archive_print(
  313. printer_id=None,
  314. source_file=file_path,
  315. print_data={
  316. "status": "archived",
  317. "source": "virtual_printer",
  318. "source_ip": source_ip,
  319. },
  320. prefer_filename_for_name=prefer_filename,
  321. )
  322. if archive:
  323. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  324. # Assign to specific printer if configured, otherwise use model for "Any X" scheduling
  325. target_model = None
  326. if not self.target_printer_id and self.model:
  327. target_model = VIRTUAL_PRINTER_MODELS.get(self.model)
  328. plate_id = self._extract_plate_id(file_path)
  329. # Parse the 3MF for per-slot filament requirements (#1188).
  330. # The manual /print-queue/ POST flow does this at queue-add
  331. # time; the VP path used to skip it, so the scheduler fell
  332. # through to model-only matching and dispatched onto whatever
  333. # printer happened to be free regardless of loaded colour.
  334. # required_filament_types is populated unconditionally — it's
  335. # cheap, lets the scheduler reject obvious mis-matches even
  336. # without force_color_match. filament_overrides only carries
  337. # force_color_match=True when the per-VP setting is on, so
  338. # upgraders keep the old behaviour by default.
  339. required_filament_types_json: str | None = None
  340. filament_overrides_json: str | None = None
  341. requirements = extract_filament_requirements(file_path, plate_id)
  342. if requirements:
  343. types = sorted({r["type"] for r in requirements if r.get("type")})
  344. if types:
  345. required_filament_types_json = json.dumps(types)
  346. if self.queue_force_color_match:
  347. overrides = [
  348. {
  349. "slot_id": r["slot_id"],
  350. "type": r.get("type", ""),
  351. "color": r.get("color", ""),
  352. "force_color_match": True,
  353. }
  354. for r in requirements
  355. if r.get("type") and r.get("color")
  356. ]
  357. if overrides:
  358. filament_overrides_json = json.dumps(overrides)
  359. queue_item = PrintQueueItem(
  360. printer_id=self.target_printer_id,
  361. target_model=target_model,
  362. archive_id=archive.id,
  363. plate_id=plate_id,
  364. position=1,
  365. status="pending",
  366. manual_start=not self.auto_dispatch,
  367. required_filament_types=required_filament_types_json,
  368. filament_overrides=filament_overrides_json,
  369. bed_levelling=bed_levelling,
  370. flow_cali=flow_cali,
  371. vibration_cali=vibration_cali,
  372. layer_inspect=layer_inspect,
  373. timelapse=timelapse,
  374. )
  375. db.add(queue_item)
  376. await db.commit()
  377. logger.info("[VP %s] Added to queue: %s", self.name, queue_item.id)
  378. try:
  379. file_path.unlink()
  380. except OSError:
  381. pass
  382. self._pending_files.pop(file_path.name, None)
  383. else:
  384. logger.error("Failed to archive file: %s", file_path.name)
  385. except Exception as e:
  386. logger.error("Error adding to print queue: %s", e)
  387. @staticmethod
  388. def _extract_plate_id(file_path: Path) -> int | None:
  389. """Extract plate index from 3MF slice_info.config."""
  390. try:
  391. import xml.etree.ElementTree as ET
  392. import zipfile
  393. with zipfile.ZipFile(file_path, "r") as zf:
  394. if "Metadata/slice_info.config" in zf.namelist():
  395. content = zf.read("Metadata/slice_info.config").decode()
  396. root = ET.fromstring(content) # noqa: S314 # nosec B314
  397. plate = root.find(".//plate")
  398. if plate is not None:
  399. for meta in plate.findall("metadata"):
  400. if meta.get("key") == "index" and meta.get("value"):
  401. return int(meta.get("value"))
  402. except Exception:
  403. return None
  404. return None
  405. # -- Service lifecycle --
  406. def _resolve_cert_and_advertise(self) -> tuple[Path, Path, str]:
  407. """Return (cert_path, key_path, advertise_address) for TLS services.
  408. Always uses the self-signed cert chain (signed by `bbl_ca`). The user
  409. imports `bbl_ca.crt` once into the slicer; per-VP certs validate from
  410. there. Tailscale exposure is handled by the user picking the Tailscale
  411. IP in the bind_ip dropdown.
  412. """
  413. cert_path, key_path = self.generate_certificates()
  414. advertise = self.remote_interface_ip or self.bind_ip or ""
  415. return cert_path, key_path, advertise
  416. async def start_server(self) -> None:
  417. """Start server-mode services (FTP, MQTT, SSDP, Bind) on this VP's bind_ip."""
  418. logger.info("[VP %s] Starting server-mode services on %s", self.name, self.bind_ip)
  419. cert_path, key_path, advertise_addr = self._resolve_cert_and_advertise()
  420. bind_addr = self.bind_ip or "0.0.0.0" # nosec B104
  421. async def run_with_logging(coro, svc_name):
  422. try:
  423. await coro
  424. except Exception as e:
  425. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  426. self._tasks = []
  427. # FTP server
  428. self._ftp = VirtualPrinterFTPServer(
  429. upload_dir=self.upload_dir,
  430. access_code=self.access_code,
  431. cert_path=cert_path,
  432. key_path=key_path,
  433. on_file_received=self.on_file_received,
  434. bind_address=bind_addr,
  435. vp_name=self.name,
  436. )
  437. self._tasks.append(
  438. asyncio.create_task(
  439. run_with_logging(self._ftp.start(), "FTP"),
  440. name=f"vp_{self.id}_ftp",
  441. )
  442. )
  443. # MQTT server
  444. self._mqtt = SimpleMQTTServer(
  445. serial=self.serial,
  446. access_code=self.access_code,
  447. cert_path=cert_path,
  448. key_path=key_path,
  449. on_print_command=self.on_print_command,
  450. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  451. bind_address=bind_addr,
  452. vp_name=self.name,
  453. )
  454. self._tasks.append(
  455. asyncio.create_task(
  456. run_with_logging(self._mqtt.start(), "MQTT"),
  457. name=f"vp_{self.id}_mqtt",
  458. )
  459. )
  460. # MQTT bridge — fans out the target printer's pushes to slicers connected
  461. # to this VP and forwards their commands back to the printer. Only meaningful
  462. # when a target printer is configured AND printer_manager was injected (it
  463. # always is at runtime; tests may omit it).
  464. if self.target_printer_id is not None and self._printer_manager is not None:
  465. self._mqtt_bridge = MQTTBridge(
  466. vp_id=self.id,
  467. vp_name=self.name,
  468. vp_serial=self.serial,
  469. target_printer_id=self.target_printer_id,
  470. mqtt_server=self._mqtt,
  471. printer_manager=self._printer_manager,
  472. )
  473. self._mqtt.set_bridge(self._mqtt_bridge)
  474. await self._mqtt_bridge.start()
  475. # RTSPS camera passthrough on port 322. BambuStudio's camera button
  476. # connects to the device IP it bound on (the VP), not the IP in
  477. # `ipcam.rtsp_url`. Without a listener on <bind_ip>:322 the slicer
  478. # gets connection refused → "LAN connection failed". Same raw TCP
  479. # pass-through used by SlicerProxyManager in proxy mode.
  480. target_client = self._printer_manager.get_client(self.target_printer_id)
  481. target_ip = getattr(target_client, "ip_address", None) if target_client else None
  482. if target_ip:
  483. self._rtsp_proxy = TCPProxy(
  484. name="RTSP",
  485. listen_port=322,
  486. target_host=target_ip,
  487. target_port=322,
  488. bind_address=bind_addr,
  489. )
  490. self._tasks.append(
  491. asyncio.create_task(
  492. run_with_logging(self._rtsp_proxy.start(), "RTSP"),
  493. name=f"vp_{self.id}_rtsp",
  494. )
  495. )
  496. # Bind server
  497. self._bind = BindServer(
  498. serial=self.serial,
  499. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  500. name=self.name,
  501. bind_address=bind_addr,
  502. cert_path=cert_path,
  503. key_path=key_path,
  504. )
  505. self._tasks.append(
  506. asyncio.create_task(
  507. run_with_logging(self._bind.start(), "Bind"),
  508. name=f"vp_{self.id}_bind",
  509. )
  510. )
  511. # SSDP server — advertise_addr is the Tailscale FQDN when available,
  512. # otherwise the bind/remote IP (existing behaviour)
  513. self._ssdp = VirtualPrinterSSDPServer(
  514. name=self.name,
  515. serial=self.serial,
  516. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  517. advertise_ip=advertise_addr,
  518. bind_ip=bind_addr,
  519. )
  520. self._tasks.append(
  521. asyncio.create_task(
  522. run_with_logging(self._ssdp.start(), "SSDP"),
  523. name=f"vp_{self.id}_ssdp",
  524. )
  525. )
  526. logger.info("[VP %s] Server-mode services started on %s", self.name, bind_addr)
  527. async def stop_server(self) -> None:
  528. """Stop server-mode services."""
  529. if self._mqtt_bridge:
  530. try:
  531. await self._mqtt_bridge.stop()
  532. except Exception:
  533. logger.exception("[VP %s] MQTT bridge stop failed", self.name)
  534. if self._mqtt:
  535. self._mqtt.set_bridge(None)
  536. self._mqtt_bridge = None
  537. if self._rtsp_proxy:
  538. try:
  539. await self._rtsp_proxy.stop()
  540. except Exception:
  541. logger.exception("[VP %s] RTSP proxy stop failed", self.name)
  542. self._rtsp_proxy = None
  543. if self._ftp:
  544. await self._ftp.stop()
  545. self._ftp = None
  546. if self._mqtt:
  547. await self._mqtt.stop()
  548. self._mqtt = None
  549. if self._bind:
  550. await self._bind.stop()
  551. self._bind = None
  552. if self._ssdp:
  553. await self._ssdp.stop()
  554. self._ssdp = None
  555. await self._cancel_tasks()
  556. async def start_proxy(self) -> None:
  557. """Start proxy mode services for this instance."""
  558. logger.info("[VP %s] Starting proxy mode to %s", self.name, self.target_printer_ip)
  559. cert_path, key_path, _ = self._resolve_cert_and_advertise()
  560. self._proxy = SlicerProxyManager(
  561. target_host=self.target_printer_ip,
  562. cert_path=cert_path,
  563. key_path=key_path,
  564. on_activity=lambda n, m: logger.info("[VP %s] Proxy %s: %s", self.name, n, m),
  565. bind_address=self.bind_ip or "0.0.0.0", # nosec B104
  566. bind_identity={
  567. "serial": self.target_printer_serial or self.serial,
  568. "model": self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  569. "name": self.name,
  570. "version": "01.00.00.00",
  571. },
  572. )
  573. async def run_with_logging(coro, svc_name):
  574. try:
  575. await coro
  576. except Exception as e:
  577. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  578. self._tasks = []
  579. # SSDP for proxy
  580. proxy_serial = self.target_printer_serial or self.serial
  581. if self.remote_interface_ip:
  582. from backend.app.services.network_utils import find_interface_for_ip
  583. local_iface = find_interface_for_ip(self.target_printer_ip)
  584. if local_iface:
  585. self._ssdp_proxy = SSDPProxy(
  586. local_interface_ip=local_iface["ip"],
  587. remote_interface_ip=self.remote_interface_ip,
  588. target_printer_ip=self.target_printer_ip,
  589. name=self.name,
  590. )
  591. self._tasks.append(
  592. asyncio.create_task(
  593. run_with_logging(self._ssdp_proxy.start(), "SSDP Proxy"),
  594. name=f"vp_{self.id}_ssdp_proxy",
  595. )
  596. )
  597. else:
  598. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  599. else:
  600. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  601. self._tasks.append(
  602. asyncio.create_task(
  603. run_with_logging(self._proxy.start(), "Proxy"),
  604. name=f"vp_{self.id}_proxy",
  605. )
  606. )
  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. if self._proxy:
  625. await self._proxy.stop()
  626. self._proxy = None
  627. if self._ssdp:
  628. await self._ssdp.stop()
  629. self._ssdp = None
  630. if self._ssdp_proxy:
  631. await self._ssdp_proxy.stop()
  632. self._ssdp_proxy = None
  633. await self._cancel_tasks()
  634. async def _cancel_tasks(self) -> None:
  635. """Cancel all running tasks and wait for cleanup."""
  636. for task in self._tasks:
  637. task.cancel()
  638. if self._tasks:
  639. try:
  640. await asyncio.wait_for(asyncio.gather(*self._tasks, return_exceptions=True), timeout=1.0)
  641. except TimeoutError:
  642. pass
  643. self._tasks = []
  644. def get_status(self) -> dict:
  645. """Get status for this instance."""
  646. status: dict = {
  647. "running": self.is_running,
  648. "pending_files": len(self._pending_files),
  649. }
  650. if self.is_proxy and self._proxy:
  651. status["proxy"] = self._proxy.get_status()
  652. return status
  653. class VirtualPrinterManager:
  654. """Multi-instance virtual printer registry and orchestrator.
  655. Every VP runs its own independent services on a dedicated bind IP.
  656. """
  657. def __init__(self):
  658. self._session_factory: Callable | None = None
  659. self._printer_manager: PrinterManager | None = None
  660. self._instances: dict[int, VirtualPrinterInstance] = {}
  661. # Directories
  662. self._base_dir = app_settings.base_dir / "virtual_printer"
  663. # Ensure base directories exist
  664. self._ensure_base_directories()
  665. def _ensure_base_directories(self) -> None:
  666. """Create base directories at startup."""
  667. for dir_path in [self._base_dir, self._base_dir / "uploads", self._base_dir / "certs"]:
  668. try:
  669. dir_path.mkdir(parents=True, exist_ok=True)
  670. except PermissionError:
  671. logger.error(
  672. f"Cannot create directory {dir_path}: Permission denied. "
  673. f"For Docker: ensure the data volume is writable by the container user. "
  674. f"For bare metal: run 'sudo chown -R $(whoami) {self._base_dir}'"
  675. )
  676. def set_session_factory(self, session_factory: Callable) -> None:
  677. """Set the database session factory."""
  678. self._session_factory = session_factory
  679. def set_printer_manager(self, printer_manager: "PrinterManager") -> None:
  680. """Inject the global printer_manager so non-proxy VPs can mirror their target's MQTT stream."""
  681. self._printer_manager = printer_manager
  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. )
  729. if changed:
  730. logger.info(
  731. "VP %s config changed (mode: %s→%s), restarting",
  732. instance.name,
  733. instance.mode,
  734. vp.mode,
  735. )
  736. await self.remove_instance(vp.id)
  737. # Start instances for all enabled VPs (skip already running)
  738. for vp in enabled_vps:
  739. if vp.id in self._instances:
  740. continue
  741. if vp.mode == "proxy":
  742. ip_info = proxy_ips.get(vp.id)
  743. if not ip_info:
  744. logger.warning("Proxy VP %s: target printer not found, skipping", vp.name)
  745. continue
  746. target_ip, target_serial = ip_info
  747. instance = VirtualPrinterInstance(
  748. vp_id=vp.id,
  749. name=vp.name,
  750. mode=vp.mode,
  751. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  752. access_code=vp.access_code or "",
  753. serial_suffix=vp.serial_suffix,
  754. target_printer_ip=target_ip,
  755. target_printer_serial=target_serial,
  756. auto_dispatch=vp.auto_dispatch,
  757. bind_ip=vp.bind_ip or "",
  758. remote_interface_ip=vp.remote_interface_ip or "",
  759. tailscale_disabled=vp.tailscale_disabled,
  760. base_dir=self._base_dir,
  761. session_factory=self._session_factory,
  762. )
  763. self._instances[vp.id] = instance
  764. await instance.start_proxy()
  765. logger.info("Started proxy VP: %s → %s (bind=%s)", instance.name, target_ip, instance.bind_ip)
  766. else:
  767. instance = VirtualPrinterInstance(
  768. vp_id=vp.id,
  769. name=vp.name,
  770. mode=vp.mode,
  771. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  772. access_code=vp.access_code or "",
  773. serial_suffix=vp.serial_suffix,
  774. target_printer_id=vp.target_printer_id,
  775. auto_dispatch=vp.auto_dispatch,
  776. queue_force_color_match=vp.queue_force_color_match,
  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. printer_manager=self._printer_manager,
  783. )
  784. self._instances[vp.id] = instance
  785. await instance.start_server()
  786. logger.info("Started server-mode VP: %s on %s", instance.name, vp.bind_ip)
  787. async def remove_instance(self, vp_id: int) -> None:
  788. """Stop and remove a single VP instance."""
  789. instance = self._instances.pop(vp_id, None)
  790. if instance:
  791. if instance.is_proxy:
  792. await instance.stop_proxy()
  793. else:
  794. await instance.stop_server()
  795. logger.info("Removed VP instance: %s", instance.name)
  796. async def stop_all(self) -> None:
  797. """Shutdown all virtual printer services."""
  798. logger.info("Stopping all virtual printer services...")
  799. for vp_id in list(self._instances.keys()):
  800. await self.remove_instance(vp_id)
  801. logger.info("All virtual printer services stopped")
  802. def get_instance(self, vp_id: int) -> VirtualPrinterInstance | None:
  803. """Get a running instance by ID."""
  804. return self._instances.get(vp_id)
  805. def get_all_status(self) -> list[dict]:
  806. """Get status for all running instances."""
  807. return [
  808. {
  809. "id": inst.id,
  810. "name": inst.name,
  811. "mode": inst.mode,
  812. **inst.get_status(),
  813. }
  814. for inst in self._instances.values()
  815. ]
  816. # -- Legacy single-printer compat --
  817. def get_status(self) -> dict:
  818. """Get status for first virtual printer (backward compat)."""
  819. if self._instances:
  820. first = next(iter(self._instances.values()))
  821. return {
  822. "enabled": True,
  823. "running": first.is_running,
  824. "mode": first.mode,
  825. "name": first.name,
  826. "serial": first.serial,
  827. "model": first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  828. "model_name": VIRTUAL_PRINTER_MODELS.get(
  829. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  830. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  831. ),
  832. "pending_files": first.get_status().get("pending_files", 0),
  833. **({"target_printer_ip": first.target_printer_ip} if first.is_proxy else {}),
  834. **({"proxy": first.get_status().get("proxy", {})} if first.is_proxy else {}),
  835. }
  836. return {
  837. "enabled": False,
  838. "running": False,
  839. "mode": "immediate",
  840. "name": "Bambuddy",
  841. "serial": "",
  842. "model": DEFAULT_VIRTUAL_PRINTER_MODEL,
  843. "model_name": VIRTUAL_PRINTER_MODELS[DEFAULT_VIRTUAL_PRINTER_MODEL],
  844. "pending_files": 0,
  845. }
  846. async def configure(
  847. self,
  848. enabled: bool,
  849. access_code: str = "",
  850. mode: str = "immediate",
  851. model: str = "",
  852. target_printer_ip: str = "",
  853. target_printer_serial: str = "",
  854. remote_interface_ip: str = "",
  855. ) -> None:
  856. """Legacy single-printer configure. Delegates to sync_from_db()."""
  857. # This method is kept for backward compat with the settings endpoint.
  858. # The actual work is done by sync_from_db() which reads from the DB.
  859. await self.sync_from_db()
  860. # Global instance
  861. virtual_printer_manager = VirtualPrinterManager()