manager.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  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.models.virtual_printer import (
  13. VP_MODE_ARCHIVE,
  14. VP_MODE_PROXY,
  15. VP_MODE_QUEUE,
  16. normalize_vp_mode,
  17. )
  18. from backend.app.services.virtual_printer.bind_server import BindServer
  19. from backend.app.services.virtual_printer.certificate import CertificateService
  20. from backend.app.services.virtual_printer.ftp_server import VirtualPrinterFTPServer, compute_passive_port_slice
  21. from backend.app.services.virtual_printer.mqtt_bridge import MQTTBridge
  22. from backend.app.services.virtual_printer.mqtt_server import SimpleMQTTServer
  23. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy, VirtualPrinterSSDPServer
  24. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager, TCPProxy
  25. if TYPE_CHECKING:
  26. from backend.app.services.printer_manager import PrinterManager
  27. logger = logging.getLogger(__name__)
  28. # Mapping of SSDP model codes to display names
  29. # These are the codes that slicers expect during discovery
  30. # Sources:
  31. # - https://gist.github.com/Alex-Schaefer/72a9e2491a42da2ef99fb87601955cc3
  32. # - https://github.com/psychoticbeef/BambuLabOrcaSlicerDiscovery
  33. VIRTUAL_PRINTER_MODELS = {
  34. # X1 Series
  35. "BL-P001": "X1C", # X1 Carbon
  36. "BL-P002": "X1", # X1
  37. "C13": "X1E", # X1E
  38. # X2 Series
  39. "N6": "X2D", # X2D
  40. # A2 Series (single-FDM + integrated cutter/plotter)
  41. "N9": "A2L", # A2L
  42. # P Series
  43. "C11": "P1P", # P1P
  44. "C12": "P1S", # P1S
  45. "N7": "P2S", # P2S
  46. # A1 Series
  47. "N2S": "A1", # A1
  48. "N1": "A1 Mini", # A1 Mini
  49. # H2 Series
  50. "O1D": "H2D", # H2D
  51. "O1E": "H2D Pro", # H2D Pro
  52. "O2D": "H2D Pro", # H2D Pro
  53. "O1C": "H2C", # H2C
  54. "O1C2": "H2C", # H2C (dual nozzle variant)
  55. "O1S": "H2S", # H2S
  56. }
  57. # Serial number prefixes for each model (based on Bambu Lab serial number format)
  58. # Format: MMM??RYMDDUUUUU (15 chars total)
  59. # MMM = Model prefix (3 chars)
  60. # ?? = Unknown/revision code (2 chars)
  61. # R = Revision letter (1 char)
  62. # Y = Year digit (1 char)
  63. # M = Month (1 char, hex: 1-9, A=Oct, B=Nov, C=Dec)
  64. # DD = Day (2 chars)
  65. # UUUUU = Unit number (5 chars)
  66. MODEL_SERIAL_PREFIXES = {
  67. # X1 Series
  68. "BL-P001": "00M00A", # X1C
  69. "BL-P002": "00M00A", # X1
  70. "C13": "03W00A", # X1E
  71. # X2 Series
  72. "N6": "20P90A", # X2D (first 4 chars "20P9" match real serials)
  73. # A2 Series
  74. "N9": "26A19A", # A2L (first 5 chars "26A19" match real serials)
  75. # P Series
  76. "C11": "01S00A", # P1P
  77. "C12": "01P00A", # P1S
  78. "N7": "22E00A", # P2S
  79. # A1 Series
  80. "N2S": "03900A", # A1
  81. "N1": "03000A", # A1 Mini
  82. # H2 Series
  83. "O1D": "09400A", # H2D
  84. "O1E": "09400A", # H2D Pro (same prefix family as H2D)
  85. "O2D": "09400A", # H2D Pro
  86. "O1C": "09400A", # H2C
  87. "O1C2": "09400A", # H2C (dual nozzle variant)
  88. "O1S": "09400A", # H2S
  89. }
  90. # Reverse mapping: display name → SSDP model code (for auto-inheriting from printer model)
  91. DISPLAY_NAME_TO_MODEL_CODE = {v: k for k, v in VIRTUAL_PRINTER_MODELS.items()}
  92. # Default model
  93. DEFAULT_VIRTUAL_PRINTER_MODEL = "BL-P001" # X1C
  94. # Bound on per-instance ``_slicer_print_options`` cache size. The slicer's
  95. # project_file MQTT command stashes one dict per filename; the
  96. # corresponding ``_add_to_print_queue`` pop only fires when the file
  97. # upload completes. Failed / cancelled / non-3MF uploads orphan their
  98. # stash. The bound triggers FIFO eviction in ``on_print_command`` once
  99. # the dict fills, so a long-running VP can't leak unbounded state.
  100. _SLICER_OPTIONS_CACHE_LIMIT = 128
  101. def _get_serial_for_model(model: str, serial_suffix: str) -> str:
  102. """Get serial number for the given model and suffix."""
  103. prefix = MODEL_SERIAL_PREFIXES.get(model, "00M09A")
  104. return f"{prefix}{serial_suffix}"
  105. class VirtualPrinterInstance:
  106. """Per-printer state and file handling logic.
  107. Each instance represents one virtual printer with its own config,
  108. upload directory, certificates, and file handling mode.
  109. """
  110. def __init__(
  111. self,
  112. *,
  113. vp_id: int,
  114. name: str,
  115. mode: str,
  116. model: str,
  117. access_code: str,
  118. serial_suffix: str,
  119. target_printer_ip: str = "",
  120. target_printer_serial: str = "",
  121. target_printer_id: int | None = None,
  122. auto_dispatch: bool = True,
  123. queue_force_color_match: bool = False,
  124. gcode_injection: bool = False,
  125. bind_ip: str = "",
  126. remote_interface_ip: str = "",
  127. tailscale_disabled: bool = True,
  128. base_dir: Path,
  129. session_factory: Callable | None = None,
  130. printer_manager: "PrinterManager | None" = None,
  131. ):
  132. self.id = vp_id
  133. self.name = name
  134. # Normalize on construction so the rest of the code only compares
  135. # canonical values, even when a legacy DB row hasn't been migrated
  136. # yet (e.g. fresh-from-disk during the boot window before the
  137. # one-shot migration in `core/database.py` has executed).
  138. self.mode = normalize_vp_mode(mode) or VP_MODE_ARCHIVE
  139. self.model = model
  140. self.access_code = access_code
  141. self.serial_suffix = serial_suffix
  142. self.target_printer_ip = target_printer_ip
  143. self.target_printer_serial = target_printer_serial
  144. self.target_printer_id = target_printer_id
  145. self.auto_dispatch = auto_dispatch
  146. self.queue_force_color_match = queue_force_color_match
  147. self.gcode_injection = gcode_injection
  148. self.bind_ip = bind_ip
  149. self.remote_interface_ip = remote_interface_ip
  150. self.tailscale_disabled = tailscale_disabled
  151. self._session_factory = session_factory
  152. self._printer_manager = printer_manager
  153. # Directories
  154. self.upload_dir = base_dir / "uploads" / str(vp_id)
  155. self.cert_dir = base_dir / "certs" / str(vp_id)
  156. shared_ca_dir = base_dir / "certs"
  157. # Ensure directories exist
  158. self.upload_dir.mkdir(parents=True, exist_ok=True)
  159. (self.upload_dir / "cache").mkdir(exist_ok=True)
  160. self.cert_dir.mkdir(parents=True, exist_ok=True)
  161. # Certificate service (shared CA, per-instance printer cert)
  162. self._cert_service = CertificateService(
  163. cert_dir=self.cert_dir,
  164. serial=self.serial,
  165. shared_ca_dir=shared_ca_dir,
  166. )
  167. # Pending files for MQTT correlation
  168. self._pending_files: dict[str, Path] = {}
  169. # Slicer-side print options captured from the MQTT `project_file`
  170. # command, keyed by filename. Used by `_add_to_print_queue` so the
  171. # queue item inherits the user's slicer-chosen timelapse / bed_leveling
  172. # / flow_cali / vibration_cali / layer_inspect / use_ams toggles rather
  173. # than falling back to the global `default_*` settings (#1403). FTP
  174. # completes a few hundred ms before the slicer's MQTT `project_file`
  175. # arrives, so the queue-add path waits briefly on the event below
  176. # before reading the dict. Events are popped along with the options
  177. # so the dict stays bounded.
  178. self._slicer_print_options: dict[str, dict] = {}
  179. self._slicer_print_options_events: dict[str, asyncio.Event] = {}
  180. # Per-instance services
  181. self._proxy: SlicerProxyManager | None = None
  182. self._ftp: VirtualPrinterFTPServer | None = None
  183. self._mqtt: SimpleMQTTServer | None = None
  184. self._mqtt_bridge: MQTTBridge | None = None
  185. self._rtsp_proxy: TCPProxy | None = None
  186. self._bind: BindServer | None = None
  187. self._ssdp: VirtualPrinterSSDPServer | None = None
  188. self._ssdp_proxy: SSDPProxy | None = None
  189. self._tasks: list[asyncio.Task] = []
  190. # Pending timer that re-fires gcode_state=FINISH after a project_file
  191. # ack. See ``_schedule_finish_release`` for the #1658 rationale.
  192. self._finish_release_task: asyncio.Task | None = None
  193. @property
  194. def serial(self) -> str:
  195. """Full serial number for this virtual printer."""
  196. return _get_serial_for_model(self.model or DEFAULT_VIRTUAL_PRINTER_MODEL, self.serial_suffix)
  197. @property
  198. def cert_path(self) -> Path:
  199. return self._cert_service.cert_path
  200. @property
  201. def key_path(self) -> Path:
  202. return self._cert_service.key_path
  203. @property
  204. def is_proxy(self) -> bool:
  205. return self.mode == "proxy"
  206. @property
  207. def is_running(self) -> bool:
  208. return len(self._tasks) > 0 and all(not t.done() for t in self._tasks)
  209. def generate_certificates(self) -> tuple[Path, Path]:
  210. """Generate certificates for this instance."""
  211. self._cert_service.serial = self.serial if not self.is_proxy else (self.target_printer_serial or self.serial)
  212. additional_ips = [self.remote_interface_ip] if self.remote_interface_ip else None
  213. if self.bind_ip:
  214. additional_ips = additional_ips or []
  215. additional_ips.append(self.bind_ip)
  216. self._cert_service.delete_printer_certificate()
  217. return self._cert_service.generate_certificates(additional_ips=additional_ips)
  218. # -- File handling callbacks --
  219. async def on_file_received(self, file_path: Path, source_ip: str) -> None:
  220. """Handle file upload completion from FTP."""
  221. logger.info("[VP %s] Received file: %s from %s", self.name, file_path.name, source_ip)
  222. self._pending_files[file_path.name] = file_path
  223. # Accept both canonical (`archive`/`queue`) and legacy
  224. # (`immediate`/`print_queue`) wire values so a stale row that hasn't
  225. # been migrated yet still dispatches correctly. Migration in
  226. # `core/database.py` rewrites existing rows once at boot.
  227. mode = normalize_vp_mode(self.mode)
  228. if mode == VP_MODE_ARCHIVE:
  229. await self._archive_file(file_path, source_ip)
  230. elif mode == VP_MODE_QUEUE:
  231. await self._add_to_print_queue(file_path, source_ip)
  232. else:
  233. await self._queue_file(file_path, source_ip)
  234. # Signal job completion to the slicer. Send-flow slicers don't watch the
  235. # post-upload state and would be happy with anything; the Print flow
  236. # (intended for proxy-mode VPs, but users sometimes click it against
  237. # queue/immediate/review modes too — #1280) watches the gcode_state
  238. # cycle and only releases its in-flight-job lock when it sees FINISH.
  239. # Going PREPARE → IDLE wedges the slicer's UI at "Downloading...(0%)"
  240. # and blocks the next dispatch with "busy with another print job".
  241. # PREPARE → FINISH satisfies both flows. prepare_percent=100 also
  242. # unfreezes the slicer's "Downloading X%" progress bar which it ticks
  243. # against the same field during the upload window.
  244. if self._mqtt and file_path.suffix.lower() == ".3mf":
  245. self._mqtt.set_gcode_state("FINISH", filename=file_path.name, prepare_percent="100")
  246. # FINISH is the terminal state for the upload cycle per #1280
  247. # (commit 0d6171dc). The Print-flow slicer's in-flight-job lock
  248. # releases on FINISH; resetting to IDLE 2 s later would re-confuse
  249. # the slicer that just unwedged. Earlier audit suggesting the
  250. # IDLE reset was wrong — staying at FINISH is the designed
  251. # behaviour. The next upload's PREPARE→FINISH cycle starts fresh.
  252. async def on_print_command(self, filename: str, data: dict) -> None:
  253. """Handle print command from MQTT.
  254. Captures the slicer's project_file options (`timelapse`, `bed_leveling`,
  255. `flow_cali`, `vibration_cali`, `layer_inspect`, `use_ams`, plus the
  256. H2C rack-pick `nozzle_mapping`) so the VP-queue path can inherit them
  257. when adding the item to the queue, rather than falling back to the
  258. global default settings (#1403, #1780).
  259. Only queue mode consumes the capture; archive / review / proxy
  260. modes ignore the print command, so we skip the stash there to keep
  261. the dict from accumulating one entry per print over the VP's
  262. uptime.
  263. Also schedules the #1658 follow-up that re-fires gcode_state=FINISH a
  264. moment after the synthetic project_file ack — for every non-proxy
  265. mode — so the slicer's "Downloading" UI releases on the slicer's
  266. FTP-first-then-MQTT send order.
  267. ``filename`` is the slicer's ``subtask_name`` (bare model name, no
  268. extension) — used verbatim for `_schedule_finish_release` because
  269. push_status echoes it back to the slicer as gcode_file / subtask_name.
  270. The queue-side stash key is derived from ``data["file"]`` (the FTP
  271. filename with extension) so `_add_to_print_queue`'s
  272. ``file_path.name`` lookup matches; falls back to ``filename`` when
  273. ``data["file"]`` is absent (legacy slicers / non-3MF uploads).
  274. Stash/lookup mismatch was the #1780 root cause — every captured field
  275. silently fell back to settings defaults on every Bambu Studio "Send".
  276. """
  277. logger.info("[VP %s] Print command for: %s", self.name, filename)
  278. mode = normalize_vp_mode(self.mode)
  279. if mode != VP_MODE_PROXY and filename and self._mqtt is not None:
  280. self._schedule_finish_release(filename)
  281. if mode != VP_MODE_QUEUE:
  282. return
  283. # Stash key must match `_add_to_print_queue`'s lookup, which uses
  284. # `file_path.name` (FTP filename WITH extension). The slicer's
  285. # `subtask_name` (== this method's `filename` arg) is the bare model
  286. # name, no extension — using it as the stash key was the #1780 root
  287. # cause.
  288. stash_key = data.get("file") or filename
  289. # Drop the oldest stash if the cache is growing — happens when the
  290. # slicer sends project_file for a filename whose FTP upload was
  291. # rejected / cancelled / non-3MF, so _add_to_print_queue's pop
  292. # never fires. With no bound, a long-running VP accumulates one
  293. # dict per such mismatch.
  294. if len(self._slicer_print_options) >= _SLICER_OPTIONS_CACHE_LIMIT:
  295. try:
  296. stale_key = next(iter(self._slicer_print_options))
  297. self._slicer_print_options.pop(stale_key, None)
  298. self._slicer_print_options_events.pop(stale_key, None)
  299. logger.debug("[VP %s] Evicted stale slicer options for %s", self.name, stale_key)
  300. except StopIteration:
  301. pass
  302. self._slicer_print_options[stash_key] = dict(data)
  303. event = self._slicer_print_options_events.get(stash_key)
  304. if event:
  305. event.set()
  306. def _schedule_finish_release(self, filename: str, delay: float = 1.5) -> None:
  307. """Re-set gcode_state=FINISH on the VP after the project_file ack.
  308. #1280 set FINISH after the FTP upload completes — that was correct
  309. for the slicer flow at the time (MQTT project_file → FTP → done).
  310. Bambu Studio 2.7.x flipped the order to FTP → FTP → MQTT project_file,
  311. which means ``_send_print_response`` runs *after* the FINISH set in
  312. ``on_file_received`` and overwrites the state back to PREPARE. The
  313. slicer's 1 Hz status stream then carries PREPARE forever and the
  314. send modal sits at "Downloading" until the VP is restarted (#1658).
  315. Re-firing FINISH after a short delay closes the gap: the slicer sees
  316. the synthetic PREPARE in the project_file ack (and likely one PREPARE
  317. push on the 1 Hz cycle), then the next push carries FINISH and the
  318. modal releases. Proxy mode is exempt — there the real printer drives
  319. the state through the bridge and a synthetic FINISH would clobber a
  320. real PREPARE/RUNNING transition coming back from the printer.
  321. Cancels any in-flight timer before scheduling a new one so a slicer
  322. that fires project_file twice in quick succession only ends in one
  323. FINISH.
  324. """
  325. if self._mqtt is None:
  326. return
  327. if self._finish_release_task is not None and not self._finish_release_task.done():
  328. self._finish_release_task.cancel()
  329. self._finish_release_task = asyncio.create_task(
  330. self._delayed_finish_release(filename, delay),
  331. name=f"vp-{self.id}-finish-release",
  332. )
  333. async def _delayed_finish_release(self, filename: str, delay: float) -> None:
  334. """Sleep, then set gcode_state=FINISH. Used by ``_schedule_finish_release``."""
  335. try:
  336. await asyncio.sleep(delay)
  337. except asyncio.CancelledError:
  338. return
  339. if self._mqtt is None:
  340. return
  341. self._mqtt.set_gcode_state("FINISH", filename=filename, prepare_percent="100")
  342. logger.debug("[VP %s] Re-set gcode_state=FINISH after project_file ack (%s)", self.name, filename)
  343. async def _archive_file(self, file_path: Path, source_ip: str) -> None:
  344. """Archive file immediately."""
  345. if not self._session_factory:
  346. logger.error("Cannot archive: no database session factory configured")
  347. return
  348. if file_path.suffix.lower() != ".3mf":
  349. logger.debug("Skipping non-3MF file: %s", file_path.name)
  350. self._pending_files.pop(file_path.name, None)
  351. try:
  352. file_path.unlink()
  353. except OSError:
  354. pass
  355. return
  356. archived = False
  357. try:
  358. from backend.app.api.routes.settings import get_setting
  359. from backend.app.services.archive import ArchiveService
  360. async with self._session_factory() as db:
  361. name_source = await get_setting(db, "virtual_printer_archive_name_source")
  362. prefer_filename = name_source == "filename"
  363. service = ArchiveService(db)
  364. archive = await service.archive_print(
  365. printer_id=None,
  366. source_file=file_path,
  367. print_data={
  368. "status": "archived",
  369. "source": "virtual_printer",
  370. "source_ip": source_ip,
  371. },
  372. prefer_filename_for_name=prefer_filename,
  373. )
  374. if archive:
  375. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  376. await self._broadcast_archive_created(archive)
  377. archived = True
  378. else:
  379. logger.error("Failed to archive file: %s", file_path.name)
  380. except Exception as e:
  381. logger.error("Error archiving file: %s", e)
  382. finally:
  383. # Always release the in-flight marker and delete the temp file —
  384. # previously the failure paths only logged and the next upload of
  385. # the same name was silently rejected with "already uploading",
  386. # the upload_dir filled up indefinitely, and the slicer received
  387. # a clean 226 even though no archive existed (#audit-R2-1).
  388. self._pending_files.pop(file_path.name, None)
  389. if archived:
  390. try:
  391. file_path.unlink()
  392. except OSError:
  393. pass
  394. else:
  395. # Drop the failed temp file so it doesn't accumulate.
  396. try:
  397. file_path.unlink(missing_ok=True)
  398. except OSError:
  399. pass
  400. async def _queue_file(self, file_path: Path, source_ip: str) -> None:
  401. """Queue file for user review."""
  402. if not self._session_factory:
  403. logger.error("Cannot queue: no database session factory configured")
  404. return
  405. if file_path.suffix.lower() != ".3mf":
  406. self._pending_files.pop(file_path.name, None)
  407. try:
  408. file_path.unlink()
  409. except OSError:
  410. pass
  411. return
  412. # Peek at the 3MF for the embedded title BEFORE we hand it off to the
  413. # DB. Storing it now means the /pending-uploads/ list doesn't have to
  414. # reopen every 3MF on every render to keep the review card and the
  415. # eventual archive name in sync (#1152 follow-up). Failure to parse is
  416. # not fatal — the response model falls back to the filename stem.
  417. metadata_print_name: str | None = None
  418. try:
  419. from backend.app.services.archive import ThreeMFParser
  420. parsed = ThreeMFParser(file_path).parse()
  421. raw_name = parsed.get("print_name")
  422. if isinstance(raw_name, str) and raw_name.strip():
  423. metadata_print_name = raw_name.strip()[:255]
  424. except Exception as e:
  425. logger.debug("[VP %s] Metadata title peek failed for %s: %s", self.name, file_path.name, e)
  426. try:
  427. from backend.app.models.pending_upload import PendingUpload
  428. async with self._session_factory() as db:
  429. pending = PendingUpload(
  430. filename=file_path.name,
  431. file_path=str(file_path),
  432. file_size=file_path.stat().st_size,
  433. source_ip=source_ip,
  434. status="pending",
  435. uploaded_at=datetime.now(timezone.utc),
  436. metadata_print_name=metadata_print_name,
  437. )
  438. db.add(pending)
  439. await db.commit()
  440. logger.info("[VP %s] Queued: %s - %s", self.name, pending.id, file_path.name)
  441. except Exception as e:
  442. logger.error("Error queueing file: %s", e)
  443. # Queue insert failed — drop the temp file so it doesn't
  444. # accumulate. The file is unreachable without the DB row.
  445. try:
  446. file_path.unlink(missing_ok=True)
  447. except OSError:
  448. pass
  449. finally:
  450. # Always release the in-flight marker so concurrent uploads
  451. # with the same filename aren't spuriously rejected after
  452. # a queue failure.
  453. self._pending_files.pop(file_path.name, None)
  454. async def _add_to_print_queue(self, file_path: Path, source_ip: str) -> None:
  455. """Archive file and add to print queue, assigned to target printer or model."""
  456. if not self._session_factory:
  457. logger.error("Cannot add to print queue: no database session factory configured")
  458. return
  459. if file_path.suffix.lower() != ".3mf":
  460. self._pending_files.pop(file_path.name, None)
  461. try:
  462. file_path.unlink()
  463. except OSError:
  464. pass
  465. return
  466. # Wait briefly for the slicer's MQTT `project_file` command so the
  467. # queue item can inherit the slicer-side print options the user
  468. # picked (timelapse, bed_leveling, etc). Slicers send the FTP upload
  469. # first and the MQTT command immediately after, so the typical lag
  470. # is a few hundred ms; 2 s is conservative without making every
  471. # VP-queue add visibly slow. Falls back to the global default_*
  472. # settings if MQTT doesn't arrive in time (legacy behaviour for
  473. # users on a slicer that doesn't send a print command). #1403.
  474. # The wait is skipped when there's no MQTT server attached — covers
  475. # unit tests that invoke `_add_to_print_queue` directly without
  476. # going through `on_print_command`, so they don't pay the 2 s tax.
  477. slicer_opts = self._slicer_print_options.pop(file_path.name, None)
  478. if slicer_opts is None and self._mqtt is not None:
  479. event = asyncio.Event()
  480. self._slicer_print_options_events[file_path.name] = event
  481. try:
  482. await asyncio.wait_for(event.wait(), timeout=2.0)
  483. slicer_opts = self._slicer_print_options.pop(file_path.name, None)
  484. except asyncio.TimeoutError:
  485. slicer_opts = None
  486. finally:
  487. self._slicer_print_options_events.pop(file_path.name, None)
  488. # If the cache still misses, queued workflow flags / nozzle pick will
  489. # silently fall back to settings defaults. Surface the missed key so a
  490. # future stash/lookup mismatch (the #1780 root cause) is obvious in
  491. # the log instead of needing a wire capture to diagnose.
  492. if slicer_opts is None:
  493. logger.debug(
  494. "[VP %s] No slicer options cached for %r (cache keys: %s); "
  495. "workflow flags + nozzle pick will fall back to settings defaults.",
  496. self.name,
  497. file_path.name,
  498. sorted(self._slicer_print_options.keys()),
  499. )
  500. try:
  501. import json
  502. from backend.app.api.routes.settings import get_setting
  503. from backend.app.models.print_queue import PrintQueueItem
  504. from backend.app.services.archive import ArchiveService
  505. from backend.app.services.filament_requirements import extract_filament_requirements
  506. async with self._session_factory() as db:
  507. name_source = await get_setting(db, "virtual_printer_archive_name_source")
  508. prefer_filename = name_source == "filename"
  509. # Read workflow defaults from settings. Without this the
  510. # PrintQueueItem below would fall back to the column-level
  511. # defaults and ignore the user's workflow preferences (#1235).
  512. # Fallbacks match AppSettings defaults in schemas/settings.py.
  513. # The slicer-side options captured above (if any) take
  514. # precedence per-field over these defaults.
  515. def _bool_setting(value: str | None, default: bool) -> bool:
  516. return value.lower() == "true" if value is not None else default
  517. def _slicer_or(field_mqtt: str, settings_default: bool) -> bool:
  518. """Slicer's MQTT value if present, else the settings default.
  519. Slicer payloads carry both bool and int (0/1) shapes
  520. depending on firmware family — coerce via bool() so
  521. `0`/`False` and `1`/`True` both work.
  522. """
  523. if slicer_opts is not None and field_mqtt in slicer_opts:
  524. return bool(slicer_opts[field_mqtt])
  525. return settings_default
  526. # Note the MQTT field names differ from Bambuddy's column
  527. # names: MQTT uses `bed_leveling` (single L) while the
  528. # column / settings key use `bed_levelling` (double L).
  529. bed_levelling = _slicer_or(
  530. "bed_leveling", _bool_setting(await get_setting(db, "default_bed_levelling"), True)
  531. )
  532. flow_cali = _slicer_or("flow_cali", _bool_setting(await get_setting(db, "default_flow_cali"), False))
  533. vibration_cali = _slicer_or(
  534. "vibration_cali", _bool_setting(await get_setting(db, "default_vibration_cali"), True)
  535. )
  536. layer_inspect = _slicer_or(
  537. "layer_inspect", _bool_setting(await get_setting(db, "default_layer_inspect"), False)
  538. )
  539. timelapse = _slicer_or("timelapse", _bool_setting(await get_setting(db, "default_timelapse"), False))
  540. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  541. # BambuStudio's project_file MQTT command for rack-swap models
  542. # (O1C2 today) carries `nozzle_mapping` — a per-filament array
  543. # of physical nozzle position IDs (`list[int]`). Forward it
  544. # verbatim onto the queue item so the dispatcher can replay it
  545. # in its own project_file command. Without this the H2C
  546. # firmware falls back to "last matching nozzle" auto-pick and
  547. # ignores the user's Bambu Studio choice. Every other model
  548. # has it absent from slicer_opts, so the capture is a
  549. # transparent no-op there. (`nozzles_info` was also captured
  550. # in the original fix but BambuStudio never actually sends it
  551. # — verified via wire capture on H2C — so only `nozzle_mapping`
  552. # is forwarded now.)
  553. nozzle_mapping_json: str | None = None
  554. if slicer_opts is not None:
  555. raw = slicer_opts.get("nozzle_mapping")
  556. if raw is not None:
  557. # BambuStudio's NetworkAgent embeds this as parsed
  558. # JSON in the project_file body (matching the
  559. # ams_mapping shape Bambuddy already consumes as
  560. # list[int]). Accept a JSON-encoded string defensively
  561. # in case any path arrives stringified.
  562. if isinstance(raw, str):
  563. try:
  564. raw = json.loads(raw)
  565. except json.JSONDecodeError:
  566. logger.warning(
  567. "[VP %s] Slicer nozzle_mapping is unparseable JSON, dropping: %r",
  568. self.name,
  569. raw,
  570. )
  571. raw = None
  572. if raw is not None:
  573. nozzle_mapping_json = json.dumps(raw)
  574. service = ArchiveService(db)
  575. archive = await service.archive_print(
  576. printer_id=None,
  577. source_file=file_path,
  578. print_data={
  579. "status": "archived",
  580. "source": "virtual_printer",
  581. "source_ip": source_ip,
  582. },
  583. prefer_filename_for_name=prefer_filename,
  584. )
  585. if archive:
  586. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  587. # Assign to specific printer if configured, otherwise use model for "Any X" scheduling
  588. target_model = None
  589. if not self.target_printer_id and self.model:
  590. target_model = VIRTUAL_PRINTER_MODELS.get(self.model)
  591. # #1733: multi-plate "Send All" uploads ship every plate in
  592. # one 3MF — `slice_info.config` lists each `<plate>` with
  593. # its own index. Enqueue one PrintQueueItem per plate so
  594. # the scheduler runs each separately. Single-plate "Send"
  595. # comes through as `[N]` (one plate index) so the loop
  596. # below runs once and the existing behaviour is preserved.
  597. plate_ids = self._extract_plate_ids(file_path)
  598. # Pick a base position the same way the manual /print-queue/
  599. # POST does, then hand consecutive positions to each plate
  600. # so a Send All keeps plate-order execution inside the
  601. # queue (#1733). Previously hardcoded to 1, which created
  602. # duplicate position=1 rows on every VP upload and made
  603. # queue execution order non-deterministic for any non-
  604. # empty queue.
  605. from sqlalchemy import func, select as _sql_select
  606. queue_scope = _sql_select(func.max(PrintQueueItem.position)).where(
  607. PrintQueueItem.status == "pending"
  608. )
  609. if self.target_printer_id is not None:
  610. queue_scope = queue_scope.where(PrintQueueItem.printer_id == self.target_printer_id)
  611. else:
  612. queue_scope = queue_scope.where(PrintQueueItem.printer_id.is_(None))
  613. try:
  614. max_pos_raw = (await db.execute(queue_scope)).scalar()
  615. max_pos = int(max_pos_raw) if max_pos_raw is not None else 0
  616. except (TypeError, ValueError):
  617. max_pos = 0
  618. # Parse per-plate filament requirements (#1188). Each plate
  619. # has its own filament set in `slice_info.config`, so the
  620. # `required_filament_types` / `filament_overrides` columns
  621. # on each queue item reflect THAT plate, not the file's
  622. # first plate. Scoping was already plate-aware via #1697 —
  623. # the `extract_filament_requirements(path, plate_id)` filter
  624. # returns just the plate's filaments. required_filament_types
  625. # is populated unconditionally — it's cheap, lets the
  626. # scheduler reject obvious mis-matches even without
  627. # force_color_match. filament_overrides only carries
  628. # force_color_match=True when the per-VP setting is on, so
  629. # upgraders keep the old behaviour by default.
  630. queue_item_ids: list[int] = []
  631. for offset, plate_id in enumerate(plate_ids, start=1):
  632. required_filament_types_json: str | None = None
  633. filament_overrides_json: str | None = None
  634. requirements = extract_filament_requirements(file_path, plate_id)
  635. if requirements:
  636. types = sorted({r["type"] for r in requirements if r.get("type")})
  637. if types:
  638. required_filament_types_json = json.dumps(types)
  639. if self.queue_force_color_match:
  640. overrides = [
  641. {
  642. "slot_id": r["slot_id"],
  643. "type": r.get("type", ""),
  644. "color": r.get("color", ""),
  645. "force_color_match": True,
  646. }
  647. for r in requirements
  648. if r.get("type") and r.get("color")
  649. ]
  650. if overrides:
  651. filament_overrides_json = json.dumps(overrides)
  652. queue_item = PrintQueueItem(
  653. printer_id=self.target_printer_id,
  654. target_model=target_model,
  655. archive_id=archive.id,
  656. plate_id=plate_id,
  657. position=max_pos + offset,
  658. status="pending",
  659. manual_start=not self.auto_dispatch,
  660. required_filament_types=required_filament_types_json,
  661. filament_overrides=filament_overrides_json,
  662. bed_levelling=bed_levelling,
  663. flow_cali=flow_cali,
  664. vibration_cali=vibration_cali,
  665. layer_inspect=layer_inspect,
  666. timelapse=timelapse,
  667. # Per-VP opt-in for auto-print G-code injection (#1516).
  668. # Default off; when on, the scheduler still no-ops unless
  669. # gcode_snippets are configured for the target model, so it's
  670. # effectively "inject when enabled AND snippets exist".
  671. gcode_injection=self.gcode_injection,
  672. # H2C rack-swap slicer pick (#1780). Captured above;
  673. # stamped on every plate so a multi-plate Send All keeps
  674. # the same nozzle pick across plates rather than only the
  675. # first one (mirrors the #1697 / #1188 per-plate loop fix).
  676. nozzle_mapping=nozzle_mapping_json,
  677. )
  678. db.add(queue_item)
  679. await db.flush() # populate queue_item.id before logging
  680. queue_item_ids.append(queue_item.id)
  681. await db.commit()
  682. if len(queue_item_ids) == 1:
  683. logger.info("[VP %s] Added to queue: %s", self.name, queue_item_ids[0])
  684. else:
  685. logger.info(
  686. "[VP %s] Added %d queue items for multi-plate upload (plates %s): %s",
  687. self.name,
  688. len(queue_item_ids),
  689. plate_ids,
  690. queue_item_ids,
  691. )
  692. await self._broadcast_archive_created(archive)
  693. else:
  694. logger.error("Failed to archive file: %s", file_path.name)
  695. except Exception as e:
  696. logger.error("Error adding to print queue: %s", e)
  697. finally:
  698. # Always release the marker and clean the temp file. Without this
  699. # the same-name STOR guard would block the next upload and the
  700. # upload_dir would accumulate failed temp files forever
  701. # (#audit-R2-1).
  702. self._pending_files.pop(file_path.name, None)
  703. try:
  704. file_path.unlink(missing_ok=True)
  705. except OSError:
  706. pass
  707. async def _broadcast_archive_created(self, archive) -> None:
  708. """Notify connected clients that a new archive exists.
  709. Real-printer prints get this from main.py's MQTT print_start handler;
  710. VP-uploaded prints need their own broadcast or the Archives page stays
  711. stale until the user switches tabs (#1282).
  712. """
  713. try:
  714. from backend.app.core.websocket import ws_manager
  715. await ws_manager.send_archive_created(
  716. {
  717. "id": archive.id,
  718. "printer_id": archive.printer_id,
  719. "filename": archive.filename,
  720. "print_name": archive.print_name,
  721. "status": archive.status,
  722. }
  723. )
  724. except Exception as e:
  725. logger.debug("[VP %s] archive_created broadcast failed: %s", self.name, e)
  726. @staticmethod
  727. def _extract_plate_ids(file_path: Path) -> list[int]:
  728. """Extract every plate index from a 3MF's slice_info.config.
  729. A multi-plate "Send All" from BambuStudio / OrcaSlicer uploads a
  730. single 3MF containing every plate the user selected. Each plate
  731. has its own ``<plate>`` block with a ``<metadata key="index"
  732. value="N"/>`` child and its own ``Metadata/plate_N.gcode`` payload
  733. inside the same zip. Returning the full ordered list lets the VP
  734. queue path create one queue item per plate (`_add_to_print_queue`
  735. loops over the result), so "Send All" of a 3-plate file produces
  736. 3 queue items sharing the same archive — one per plate to print.
  737. Single-plate "Send" hits the same code path and returns ``[N]``
  738. for whichever plate the user selected; the loop runs once and the
  739. existing single-plate behaviour is preserved.
  740. Returns ``[1]`` when the 3MF is missing ``slice_info.config``,
  741. unparseable, or contains no plate-index metadata — the original
  742. single-plate fallback. Production logs at debug so a non-3MF
  743. upload doesn't spam, but the trail survives for support bundles.
  744. """
  745. try:
  746. import xml.etree.ElementTree as ET
  747. import zipfile
  748. with zipfile.ZipFile(file_path, "r") as zf:
  749. if "Metadata/slice_info.config" in zf.namelist():
  750. content = zf.read("Metadata/slice_info.config").decode()
  751. root = ET.fromstring(content) # noqa: S314 # nosec B314
  752. plate_ids: list[int] = []
  753. for plate in root.findall(".//plate"):
  754. for meta in plate.findall("metadata"):
  755. if meta.get("key") == "index" and meta.get("value"):
  756. try:
  757. plate_ids.append(int(meta.get("value")))
  758. except ValueError:
  759. continue
  760. break
  761. if plate_ids:
  762. return plate_ids
  763. except Exception as e:
  764. logger.debug("[VP] _extract_plate_ids failed for %s: %s", file_path.name, e)
  765. return [1]
  766. # -- Service lifecycle --
  767. def _resolve_cert_and_advertise(self) -> tuple[Path, Path, str]:
  768. """Return (cert_path, key_path, advertise_address) for TLS services.
  769. Always uses the self-signed cert chain (signed by `bbl_ca`). The user
  770. imports `bbl_ca.crt` once into the slicer; per-VP certs validate from
  771. there. Tailscale exposure is handled by the user picking the Tailscale
  772. IP in the bind_ip dropdown.
  773. """
  774. cert_path, key_path = self.generate_certificates()
  775. advertise = self.remote_interface_ip or self.bind_ip or ""
  776. return cert_path, key_path, advertise
  777. async def start_server(self) -> None:
  778. """Start server-mode services (FTP, MQTT, SSDP, Bind) on this VP's bind_ip."""
  779. logger.info("[VP %s] Starting server-mode services on %s", self.name, self.bind_ip)
  780. cert_path, key_path, advertise_addr = self._resolve_cert_and_advertise()
  781. bind_addr = self.bind_ip or "0.0.0.0" # nosec B104
  782. async def run_with_logging(coro, svc_name):
  783. try:
  784. await coro
  785. except Exception as e:
  786. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  787. self._tasks = []
  788. # FTP server. Each VP gets a non-overlapping passive-mode port slice
  789. # derived from its DB id so bridge-mode Docker users only have to
  790. # expose a narrow range (#1646). Default slice is 10 ports per VP;
  791. # see ftp_server.compute_passive_port_slice for the wrap-around
  792. # behaviour on installs with very high VP ids.
  793. passive_port_min, passive_port_max = compute_passive_port_slice(self.id)
  794. self._ftp = VirtualPrinterFTPServer(
  795. upload_dir=self.upload_dir,
  796. access_code=self.access_code,
  797. cert_path=cert_path,
  798. key_path=key_path,
  799. on_file_received=self.on_file_received,
  800. bind_address=bind_addr,
  801. vp_name=self.name,
  802. passive_port_min=passive_port_min,
  803. passive_port_max=passive_port_max,
  804. )
  805. self._tasks.append(
  806. asyncio.create_task(
  807. run_with_logging(self._ftp.start(), "FTP"),
  808. name=f"vp_{self.id}_ftp",
  809. )
  810. )
  811. # MQTT server
  812. self._mqtt = SimpleMQTTServer(
  813. serial=self.serial,
  814. access_code=self.access_code,
  815. cert_path=cert_path,
  816. key_path=key_path,
  817. on_print_command=self.on_print_command,
  818. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  819. bind_address=bind_addr,
  820. vp_name=self.name,
  821. )
  822. self._tasks.append(
  823. asyncio.create_task(
  824. run_with_logging(self._mqtt.start(), "MQTT"),
  825. name=f"vp_{self.id}_mqtt",
  826. )
  827. )
  828. # MQTT bridge — fans out the target printer's pushes to slicers connected
  829. # to this VP and forwards their commands back to the printer. Only meaningful
  830. # when a target printer is configured AND printer_manager was injected (it
  831. # always is at runtime; tests may omit it).
  832. if self.target_printer_id is not None and self._printer_manager is not None:
  833. self._mqtt_bridge = MQTTBridge(
  834. vp_id=self.id,
  835. vp_name=self.name,
  836. vp_serial=self.serial,
  837. target_printer_id=self.target_printer_id,
  838. mqtt_server=self._mqtt,
  839. printer_manager=self._printer_manager,
  840. )
  841. self._mqtt.set_bridge(self._mqtt_bridge)
  842. await self._mqtt_bridge.start()
  843. # RTSPS camera passthrough on port 322. BambuStudio's camera button
  844. # connects to the device IP it bound on (the VP), not the IP in
  845. # `ipcam.rtsp_url`. Without a listener on <bind_ip>:322 the slicer
  846. # gets connection refused → "LAN connection failed". Same raw TCP
  847. # pass-through used by SlicerProxyManager in proxy mode.
  848. target_client = self._printer_manager.get_client(self.target_printer_id)
  849. target_ip = getattr(target_client, "ip_address", None) if target_client else None
  850. if target_ip:
  851. self._rtsp_proxy = TCPProxy(
  852. name="RTSP",
  853. listen_port=322,
  854. target_host=target_ip,
  855. target_port=322,
  856. bind_address=bind_addr,
  857. )
  858. self._tasks.append(
  859. asyncio.create_task(
  860. run_with_logging(self._rtsp_proxy.start(), "RTSP"),
  861. name=f"vp_{self.id}_rtsp",
  862. )
  863. )
  864. # Bind server
  865. self._bind = BindServer(
  866. serial=self.serial,
  867. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  868. name=self.name,
  869. bind_address=bind_addr,
  870. cert_path=cert_path,
  871. key_path=key_path,
  872. )
  873. self._tasks.append(
  874. asyncio.create_task(
  875. run_with_logging(self._bind.start(), "Bind"),
  876. name=f"vp_{self.id}_bind",
  877. )
  878. )
  879. # SSDP server — advertise_addr is the remote_interface_ip (Tailscale
  880. # IP, when chosen from the bind_ip dropdown) or the bind_ip. SSDP
  881. # Location accepts IPs only; FQDNs go in through bind_ip selection
  882. # at the printer-IP level and resolve before reaching the SSDP
  883. # advertisement.
  884. self._ssdp = VirtualPrinterSSDPServer(
  885. name=self.name,
  886. serial=self.serial,
  887. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  888. advertise_ip=advertise_addr,
  889. bind_ip=bind_addr,
  890. )
  891. self._tasks.append(
  892. asyncio.create_task(
  893. run_with_logging(self._ssdp.start(), "SSDP"),
  894. name=f"vp_{self.id}_ssdp",
  895. )
  896. )
  897. # Wait briefly for every child service to actually finish binding its
  898. # socket so ``is_running`` doesn't lie. Without this barrier a caller
  899. # racing the start (e.g. the diagnostic route) would see is_running=True
  900. # while ports were still in the gap between task creation and the
  901. # ``asyncio.start_server`` returning. Bounded timeout — if a child
  902. # hangs we log it and move on; the existing task tracking still
  903. # catches the failure on the next iteration.
  904. ready_targets = [
  905. ("FTP", self._ftp.ready),
  906. ("MQTT", self._mqtt.ready),
  907. ("Bind", self._bind.ready),
  908. ("SSDP", self._ssdp.ready),
  909. ]
  910. try:
  911. await asyncio.wait_for(
  912. asyncio.gather(*(e.wait() for _, e in ready_targets)),
  913. timeout=5.0,
  914. )
  915. except TimeoutError:
  916. not_ready = [name for name, e in ready_targets if not e.is_set()]
  917. logger.warning(
  918. "[VP %s] Sub-service(s) didn't bind within 5s: %s — continuing anyway",
  919. self.name,
  920. ", ".join(not_ready) or "(none)",
  921. )
  922. logger.info("[VP %s] Server-mode services started on %s", self.name, bind_addr)
  923. async def stop_server(self) -> None:
  924. """Stop server-mode services."""
  925. if self._finish_release_task is not None and not self._finish_release_task.done():
  926. self._finish_release_task.cancel()
  927. self._finish_release_task = None
  928. if self._mqtt_bridge:
  929. try:
  930. await self._mqtt_bridge.stop()
  931. except Exception:
  932. logger.exception("[VP %s] MQTT bridge stop failed", self.name)
  933. if self._mqtt:
  934. self._mqtt.set_bridge(None)
  935. self._mqtt_bridge = None
  936. if self._rtsp_proxy:
  937. try:
  938. await self._rtsp_proxy.stop()
  939. except Exception:
  940. logger.exception("[VP %s] RTSP proxy stop failed", self.name)
  941. self._rtsp_proxy = None
  942. if self._ftp:
  943. await self._ftp.stop()
  944. self._ftp = None
  945. if self._mqtt:
  946. await self._mqtt.stop()
  947. self._mqtt = None
  948. if self._bind:
  949. await self._bind.stop()
  950. self._bind = None
  951. if self._ssdp:
  952. await self._ssdp.stop()
  953. self._ssdp = None
  954. await self._cancel_tasks()
  955. async def start_proxy(self) -> None:
  956. """Start proxy mode services for this instance."""
  957. logger.info("[VP %s] Starting proxy mode to %s", self.name, self.target_printer_ip)
  958. cert_path, key_path, _ = self._resolve_cert_and_advertise()
  959. self._proxy = SlicerProxyManager(
  960. target_host=self.target_printer_ip,
  961. cert_path=cert_path,
  962. key_path=key_path,
  963. on_activity=lambda n, m: logger.info("[VP %s] Proxy %s: %s", self.name, n, m),
  964. bind_address=self.bind_ip or "0.0.0.0", # nosec B104
  965. bind_identity={
  966. "serial": self.target_printer_serial or self.serial,
  967. "model": self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  968. "name": self.name,
  969. "version": "01.00.00.00",
  970. },
  971. )
  972. async def run_with_logging(coro, svc_name):
  973. try:
  974. await coro
  975. except Exception as e:
  976. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  977. self._tasks = []
  978. # SSDP for proxy
  979. proxy_serial = self.target_printer_serial or self.serial
  980. if self.remote_interface_ip:
  981. from backend.app.services.network_utils import find_interface_for_ip
  982. local_iface = find_interface_for_ip(self.target_printer_ip)
  983. if local_iface:
  984. self._ssdp_proxy = SSDPProxy(
  985. local_interface_ip=local_iface["ip"],
  986. remote_interface_ip=self.remote_interface_ip,
  987. target_printer_ip=self.target_printer_ip,
  988. name=self.name,
  989. )
  990. self._tasks.append(
  991. asyncio.create_task(
  992. run_with_logging(self._ssdp_proxy.start(), "SSDP Proxy"),
  993. name=f"vp_{self.id}_ssdp_proxy",
  994. )
  995. )
  996. else:
  997. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  998. else:
  999. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  1000. self._tasks.append(
  1001. asyncio.create_task(
  1002. run_with_logging(self._proxy.start(), "Proxy"),
  1003. name=f"vp_{self.id}_proxy",
  1004. )
  1005. )
  1006. def _start_fallback_ssdp(self, proxy_serial: str, run_with_logging) -> None:
  1007. """Start single-interface SSDP server as fallback for proxy mode."""
  1008. self._ssdp = VirtualPrinterSSDPServer(
  1009. name=f"{self.name} (Proxy)",
  1010. serial=proxy_serial,
  1011. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1012. advertise_ip=self.bind_ip or "",
  1013. bind_ip=self.bind_ip or "",
  1014. )
  1015. self._tasks.append(
  1016. asyncio.create_task(
  1017. run_with_logging(self._ssdp.start(), "SSDP"),
  1018. name=f"vp_{self.id}_ssdp",
  1019. )
  1020. )
  1021. async def stop_proxy(self) -> None:
  1022. """Stop proxy mode services for this instance."""
  1023. if self._proxy:
  1024. await self._proxy.stop()
  1025. self._proxy = None
  1026. if self._ssdp:
  1027. await self._ssdp.stop()
  1028. self._ssdp = None
  1029. if self._ssdp_proxy:
  1030. await self._ssdp_proxy.stop()
  1031. self._ssdp_proxy = None
  1032. await self._cancel_tasks()
  1033. async def _cancel_tasks(self) -> None:
  1034. """Cancel all running tasks and wait for cleanup."""
  1035. for task in self._tasks:
  1036. task.cancel()
  1037. if self._tasks:
  1038. try:
  1039. await asyncio.wait_for(asyncio.gather(*self._tasks, return_exceptions=True), timeout=1.0)
  1040. except TimeoutError:
  1041. pass
  1042. self._tasks = []
  1043. def get_status(self) -> dict:
  1044. """Get status for this instance."""
  1045. status: dict = {
  1046. "running": self.is_running,
  1047. "pending_files": len(self._pending_files),
  1048. }
  1049. if self.is_proxy and self._proxy:
  1050. status["proxy"] = self._proxy.get_status()
  1051. return status
  1052. class VirtualPrinterManager:
  1053. """Multi-instance virtual printer registry and orchestrator.
  1054. Every VP runs its own independent services on a dedicated bind IP.
  1055. """
  1056. def __init__(self):
  1057. self._session_factory: Callable | None = None
  1058. self._printer_manager: PrinterManager | None = None
  1059. self._instances: dict[int, VirtualPrinterInstance] = {}
  1060. # Serialize sync_from_db so concurrent PUT /vp/{id} calls can't
  1061. # race the start/stop sequence and leave duplicate sub-services
  1062. # bound to the same port. The lock is fine-grained enough that
  1063. # a single VP update completes in well under a second; if the
  1064. # user holds the lock with a long-running start they intended
  1065. # to anyway.
  1066. self._sync_lock = asyncio.Lock()
  1067. # Directories
  1068. self._base_dir = app_settings.base_dir / "virtual_printer"
  1069. # Ensure base directories exist
  1070. self._ensure_base_directories()
  1071. def _ensure_base_directories(self) -> None:
  1072. """Create base directories at startup."""
  1073. for dir_path in [self._base_dir, self._base_dir / "uploads", self._base_dir / "certs"]:
  1074. try:
  1075. dir_path.mkdir(parents=True, exist_ok=True)
  1076. except PermissionError:
  1077. logger.error(
  1078. f"Cannot create directory {dir_path}: Permission denied. "
  1079. f"For Docker: ensure the data volume is writable by the container user. "
  1080. f"For bare metal: run 'sudo chown -R $(whoami) {self._base_dir}'"
  1081. )
  1082. def set_session_factory(self, session_factory: Callable) -> None:
  1083. """Set the database session factory."""
  1084. self._session_factory = session_factory
  1085. def set_printer_manager(self, printer_manager: "PrinterManager") -> None:
  1086. """Inject the global printer_manager so non-proxy VPs can mirror their target's MQTT stream."""
  1087. self._printer_manager = printer_manager
  1088. def get_ca_certificate_info(self) -> dict:
  1089. """Return the shared virtual-printer CA certificate for slicer-trust import.
  1090. The CA is shared by every VP (one import covers all of them). It is
  1091. generated on demand here if no VP has triggered cert generation yet,
  1092. so the "copy/download certificate" UI works even before the first VP
  1093. is enabled.
  1094. """
  1095. certs_dir = self._base_dir / "certs"
  1096. cert_service = CertificateService(cert_dir=certs_dir, shared_ca_dir=certs_dir)
  1097. return cert_service.get_ca_certificate_info()
  1098. @property
  1099. def is_enabled(self) -> bool:
  1100. """Check if any virtual printer is running."""
  1101. return len(self._instances) > 0
  1102. async def sync_from_db(self) -> None:
  1103. """Load all VPs from DB, reconcile running state.
  1104. Serialised by ``self._sync_lock`` — concurrent PUT /vp/{id} routes
  1105. all call into this method; without the lock the start / stop
  1106. sequence races and can leave duplicate sub-services bound to the
  1107. same port or orphan still-running tasks.
  1108. """
  1109. if not self._session_factory:
  1110. logger.warning("Cannot sync virtual printers: no session factory")
  1111. return
  1112. async with self._sync_lock:
  1113. await self._sync_from_db_locked()
  1114. async def _sync_from_db_locked(self) -> None:
  1115. """Inner sync body — caller holds ``self._sync_lock``."""
  1116. from sqlalchemy import select
  1117. from backend.app.models.printer import Printer
  1118. from backend.app.models.virtual_printer import VirtualPrinter
  1119. async with self._session_factory() as db:
  1120. result = await db.execute(
  1121. select(VirtualPrinter).where(VirtualPrinter.enabled == True).order_by(VirtualPrinter.position) # noqa: E712
  1122. )
  1123. enabled_vps = result.scalars().all()
  1124. # Stop instances that are no longer enabled or changed mode
  1125. enabled_ids = {vp.id for vp in enabled_vps}
  1126. for vp_id in list(self._instances.keys()):
  1127. if vp_id not in enabled_ids:
  1128. await self.remove_instance(vp_id)
  1129. # Look up printer IPs for proxy VPs
  1130. proxy_vps = [vp for vp in enabled_vps if vp.mode == "proxy"]
  1131. proxy_ips: dict[int, tuple[str, str]] = {}
  1132. if proxy_vps:
  1133. async with self._session_factory() as db:
  1134. for pvp in proxy_vps:
  1135. if pvp.target_printer_id:
  1136. result = await db.execute(select(Printer).where(Printer.id == pvp.target_printer_id))
  1137. printer = result.scalar_one_or_none()
  1138. if printer:
  1139. proxy_ips[pvp.id] = (printer.ip_address, printer.serial_number)
  1140. # Detect config changes on running instances and restart if needed
  1141. for vp in enabled_vps:
  1142. instance = self._instances.get(vp.id)
  1143. if not instance:
  1144. continue
  1145. # Proxy mode: detect target printer IP / serial changes from the
  1146. # DB lookup above. Without this branch a DHCP renewal that gives
  1147. # the target printer a new IP would leave the running proxy
  1148. # forwarding to the stale IP until the user manually toggles the
  1149. # VP. The same shape covers a target-side serial change.
  1150. proxy_target_changed = False
  1151. if vp.mode == "proxy":
  1152. fresh = proxy_ips.get(vp.id)
  1153. if fresh is not None:
  1154. fresh_ip, fresh_serial = fresh
  1155. if (
  1156. getattr(instance, "target_printer_ip", None) != fresh_ip
  1157. or getattr(instance, "target_printer_serial", None) != fresh_serial
  1158. ):
  1159. proxy_target_changed = True
  1160. # Normalize the DB value before comparing — a legacy `immediate`
  1161. # row read before the migration window finishes would otherwise
  1162. # trip the "changed" branch and bounce every VP at boot.
  1163. db_mode = normalize_vp_mode(vp.mode)
  1164. changed = (
  1165. instance.mode != db_mode
  1166. or instance.model != (vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL)
  1167. or instance.access_code != (vp.access_code or "")
  1168. or instance.bind_ip != (vp.bind_ip or "")
  1169. or instance.remote_interface_ip != (vp.remote_interface_ip or "")
  1170. or instance.target_printer_id != vp.target_printer_id
  1171. or instance.auto_dispatch != vp.auto_dispatch
  1172. # Queue-mode behaviour toggle — without it the running
  1173. # instance silently keeps the old value until process
  1174. # restart (#1552 follow-up family).
  1175. or instance.queue_force_color_match != vp.queue_force_color_match
  1176. or instance.gcode_injection != vp.gcode_injection
  1177. or proxy_target_changed
  1178. )
  1179. if changed:
  1180. logger.info(
  1181. "VP %s config changed (mode: %s→%s), restarting",
  1182. instance.name,
  1183. instance.mode,
  1184. vp.mode,
  1185. )
  1186. await self.remove_instance(vp.id)
  1187. # Start instances for all enabled VPs (skip already running)
  1188. for vp in enabled_vps:
  1189. if vp.id in self._instances:
  1190. continue
  1191. if vp.mode == "proxy":
  1192. ip_info = proxy_ips.get(vp.id)
  1193. if not ip_info:
  1194. logger.warning("Proxy VP %s: target printer not found, skipping", vp.name)
  1195. continue
  1196. target_ip, target_serial = ip_info
  1197. instance = VirtualPrinterInstance(
  1198. vp_id=vp.id,
  1199. name=vp.name,
  1200. mode=vp.mode,
  1201. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1202. access_code=vp.access_code or "",
  1203. serial_suffix=vp.serial_suffix,
  1204. target_printer_ip=target_ip,
  1205. target_printer_serial=target_serial,
  1206. auto_dispatch=vp.auto_dispatch,
  1207. bind_ip=vp.bind_ip or "",
  1208. remote_interface_ip=vp.remote_interface_ip or "",
  1209. tailscale_disabled=vp.tailscale_disabled,
  1210. base_dir=self._base_dir,
  1211. session_factory=self._session_factory,
  1212. )
  1213. self._instances[vp.id] = instance
  1214. await instance.start_proxy()
  1215. logger.info("Started proxy VP: %s → %s (bind=%s)", instance.name, target_ip, instance.bind_ip)
  1216. else:
  1217. instance = VirtualPrinterInstance(
  1218. vp_id=vp.id,
  1219. name=vp.name,
  1220. mode=vp.mode,
  1221. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1222. access_code=vp.access_code or "",
  1223. serial_suffix=vp.serial_suffix,
  1224. target_printer_id=vp.target_printer_id,
  1225. auto_dispatch=vp.auto_dispatch,
  1226. queue_force_color_match=vp.queue_force_color_match,
  1227. gcode_injection=vp.gcode_injection,
  1228. bind_ip=vp.bind_ip or "",
  1229. remote_interface_ip=vp.remote_interface_ip or "",
  1230. tailscale_disabled=vp.tailscale_disabled,
  1231. base_dir=self._base_dir,
  1232. session_factory=self._session_factory,
  1233. printer_manager=self._printer_manager,
  1234. )
  1235. self._instances[vp.id] = instance
  1236. await instance.start_server()
  1237. logger.info("Started server-mode VP: %s on %s", instance.name, vp.bind_ip)
  1238. async def remove_instance(self, vp_id: int) -> None:
  1239. """Stop and remove a single VP instance."""
  1240. instance = self._instances.pop(vp_id, None)
  1241. if instance:
  1242. if instance.is_proxy:
  1243. await instance.stop_proxy()
  1244. else:
  1245. await instance.stop_server()
  1246. logger.info("Removed VP instance: %s", instance.name)
  1247. async def stop_all(self) -> None:
  1248. """Shutdown all virtual printer services."""
  1249. logger.info("Stopping all virtual printer services...")
  1250. for vp_id in list(self._instances.keys()):
  1251. await self.remove_instance(vp_id)
  1252. logger.info("All virtual printer services stopped")
  1253. def get_instance(self, vp_id: int) -> VirtualPrinterInstance | None:
  1254. """Get a running instance by ID."""
  1255. return self._instances.get(vp_id)
  1256. def get_all_status(self) -> list[dict]:
  1257. """Get status for all running instances."""
  1258. return [
  1259. {
  1260. "id": inst.id,
  1261. "name": inst.name,
  1262. "mode": inst.mode,
  1263. **inst.get_status(),
  1264. }
  1265. for inst in self._instances.values()
  1266. ]
  1267. # -- Legacy single-printer compat --
  1268. def get_status(self) -> dict:
  1269. """Get status for first virtual printer (backward compat)."""
  1270. if self._instances:
  1271. first = next(iter(self._instances.values()))
  1272. return {
  1273. "enabled": True,
  1274. "running": first.is_running,
  1275. "mode": first.mode,
  1276. "name": first.name,
  1277. "serial": first.serial,
  1278. "model": first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1279. "model_name": VIRTUAL_PRINTER_MODELS.get(
  1280. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1281. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1282. ),
  1283. "pending_files": first.get_status().get("pending_files", 0),
  1284. **({"target_printer_ip": first.target_printer_ip} if first.is_proxy else {}),
  1285. **({"proxy": first.get_status().get("proxy", {})} if first.is_proxy else {}),
  1286. }
  1287. return {
  1288. "enabled": False,
  1289. "running": False,
  1290. "mode": VP_MODE_ARCHIVE,
  1291. "name": "Bambuddy",
  1292. "serial": "",
  1293. "model": DEFAULT_VIRTUAL_PRINTER_MODEL,
  1294. "model_name": VIRTUAL_PRINTER_MODELS[DEFAULT_VIRTUAL_PRINTER_MODEL],
  1295. "pending_files": 0,
  1296. }
  1297. async def configure(
  1298. self,
  1299. enabled: bool,
  1300. access_code: str = "",
  1301. mode: str = VP_MODE_ARCHIVE,
  1302. model: str = "",
  1303. target_printer_ip: str = "",
  1304. target_printer_serial: str = "",
  1305. remote_interface_ip: str = "",
  1306. ) -> None:
  1307. """Legacy single-printer configure. Delegates to sync_from_db()."""
  1308. # This method is kept for backward compat with the settings endpoint.
  1309. # The actual work is done by sync_from_db() which reads from the DB.
  1310. await self.sync_from_db()
  1311. # Global instance
  1312. virtual_printer_manager = VirtualPrinterManager()