support.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. """Support endpoints for debug logging and support bundle generation."""
  2. import asyncio
  3. import importlib.metadata
  4. import io
  5. import ipaddress
  6. import json
  7. import logging
  8. import os
  9. import platform
  10. import re
  11. import zipfile
  12. from datetime import datetime
  13. from pathlib import Path
  14. from fastapi import APIRouter, HTTPException, Query
  15. from fastapi.responses import StreamingResponse
  16. from pydantic import BaseModel
  17. from sqlalchemy import func, select, text
  18. from sqlalchemy.ext.asyncio import AsyncSession
  19. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  20. from backend.app.core.config import APP_VERSION, settings
  21. from backend.app.core.database import async_session
  22. from backend.app.core.permissions import Permission
  23. from backend.app.core.websocket import ws_manager
  24. from backend.app.models.archive import PrintArchive
  25. from backend.app.models.filament import Filament
  26. from backend.app.models.notification import NotificationProvider
  27. from backend.app.models.printer import Printer
  28. from backend.app.models.project import Project
  29. from backend.app.models.settings import Settings
  30. from backend.app.models.smart_plug import SmartPlug
  31. from backend.app.models.user import User
  32. from backend.app.services.discovery import is_running_in_docker
  33. from backend.app.services.network_utils import get_network_interfaces
  34. from backend.app.services.printer_manager import printer_manager
  35. router = APIRouter(prefix="/support", tags=["support"])
  36. logger = logging.getLogger(__name__)
  37. class DebugLoggingState(BaseModel):
  38. enabled: bool
  39. enabled_at: str | None = None
  40. duration_seconds: int | None = None
  41. class DebugLoggingToggle(BaseModel):
  42. enabled: bool
  43. async def _get_debug_setting(db: AsyncSession) -> tuple[bool, datetime | None]:
  44. """Get debug logging state from database."""
  45. result = await db.execute(select(Settings).where(Settings.key == "debug_logging_enabled"))
  46. enabled_setting = result.scalar_one_or_none()
  47. result = await db.execute(select(Settings).where(Settings.key == "debug_logging_enabled_at"))
  48. enabled_at_setting = result.scalar_one_or_none()
  49. enabled = enabled_setting.value.lower() == "true" if enabled_setting else False
  50. enabled_at = None
  51. if enabled_at_setting and enabled_at_setting.value:
  52. try:
  53. enabled_at = datetime.fromisoformat(enabled_at_setting.value)
  54. except ValueError:
  55. pass # Ignore malformed timestamp; enabled_at stays None
  56. return enabled, enabled_at
  57. async def _set_debug_setting(db: AsyncSession, enabled: bool) -> datetime | None:
  58. """Set debug logging state in database."""
  59. # Update or create enabled setting
  60. result = await db.execute(select(Settings).where(Settings.key == "debug_logging_enabled"))
  61. setting = result.scalar_one_or_none()
  62. if setting:
  63. setting.value = str(enabled).lower()
  64. else:
  65. db.add(Settings(key="debug_logging_enabled", value=str(enabled).lower()))
  66. # Update enabled_at timestamp
  67. enabled_at = datetime.now() if enabled else None
  68. result = await db.execute(select(Settings).where(Settings.key == "debug_logging_enabled_at"))
  69. at_setting = result.scalar_one_or_none()
  70. if at_setting:
  71. at_setting.value = enabled_at.isoformat() if enabled_at else ""
  72. else:
  73. db.add(Settings(key="debug_logging_enabled_at", value=enabled_at.isoformat() if enabled_at else ""))
  74. await db.commit()
  75. return enabled_at
  76. def _apply_log_level(debug: bool):
  77. """Apply log level change to root logger."""
  78. root_logger = logging.getLogger()
  79. new_level = logging.DEBUG if debug else logging.INFO
  80. root_logger.setLevel(new_level)
  81. for handler in root_logger.handlers:
  82. handler.setLevel(new_level)
  83. # Also adjust third-party loggers
  84. if debug:
  85. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  86. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  87. logging.getLogger("httpcore").setLevel(logging.DEBUG)
  88. logging.getLogger("httpx").setLevel(logging.DEBUG)
  89. logging.getLogger("paho.mqtt").setLevel(logging.DEBUG)
  90. else:
  91. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  92. logging.getLogger("httpcore").setLevel(logging.WARNING)
  93. logging.getLogger("httpx").setLevel(logging.WARNING)
  94. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  95. logger.info("Log level changed to %s", "DEBUG" if debug else "INFO")
  96. @router.get("/debug-logging", response_model=DebugLoggingState)
  97. async def get_debug_logging_state(
  98. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  99. ):
  100. """Get current debug logging state."""
  101. async with async_session() as db:
  102. enabled, enabled_at = await _get_debug_setting(db)
  103. duration = None
  104. if enabled and enabled_at:
  105. duration = int((datetime.now() - enabled_at).total_seconds())
  106. return DebugLoggingState(
  107. enabled=enabled,
  108. enabled_at=enabled_at.isoformat() if enabled_at else None,
  109. duration_seconds=duration,
  110. )
  111. @router.post("/debug-logging", response_model=DebugLoggingState)
  112. async def toggle_debug_logging(
  113. toggle: DebugLoggingToggle,
  114. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  115. ):
  116. """Enable or disable debug logging."""
  117. async with async_session() as db:
  118. enabled_at = await _set_debug_setting(db, toggle.enabled)
  119. _apply_log_level(toggle.enabled)
  120. duration = None
  121. if toggle.enabled and enabled_at:
  122. duration = int((datetime.now() - enabled_at).total_seconds())
  123. return DebugLoggingState(
  124. enabled=toggle.enabled,
  125. enabled_at=enabled_at.isoformat() if enabled_at else None,
  126. duration_seconds=duration,
  127. )
  128. class LogEntry(BaseModel):
  129. """A single log entry."""
  130. timestamp: str
  131. level: str
  132. logger_name: str
  133. message: str
  134. class LogsResponse(BaseModel):
  135. """Response containing log entries."""
  136. entries: list[LogEntry]
  137. total_in_file: int
  138. filtered_count: int
  139. # Log line regex pattern: "2024-01-15 10:30:45,123 INFO [module.name] Message here"
  140. LOG_LINE_PATTERN = re.compile(r"^(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2},\d{3})\s+(\w+)\s+\[([^\]]+)\]\s+(.*)$")
  141. def _parse_log_line(line: str) -> LogEntry | None:
  142. """Parse a single log line into a LogEntry."""
  143. match = LOG_LINE_PATTERN.match(line.strip())
  144. if match:
  145. return LogEntry(
  146. timestamp=match.group(1),
  147. level=match.group(2),
  148. logger_name=match.group(3),
  149. message=match.group(4),
  150. )
  151. return None
  152. def _read_log_entries(
  153. limit: int = 200,
  154. level_filter: str | None = None,
  155. search: str | None = None,
  156. ) -> tuple[list[LogEntry], int]:
  157. """Read and parse log entries from file with optional filtering."""
  158. log_file = settings.log_dir / "bambuddy.log"
  159. if not log_file.exists():
  160. return [], 0
  161. entries: list[LogEntry] = []
  162. total_lines = 0
  163. try:
  164. with open(log_file, encoding="utf-8", errors="replace") as f:
  165. # Read all lines and process
  166. lines = f.readlines()
  167. total_lines = len(lines)
  168. # Parse lines in reverse order (newest first)
  169. current_entry: LogEntry | None = None
  170. multi_line_buffer: list[str] = []
  171. for line in reversed(lines):
  172. parsed = _parse_log_line(line)
  173. if parsed:
  174. # Found a new log entry start
  175. if current_entry:
  176. # Apply filters and add previous entry (without multi_line_buffer - it belongs to new entry)
  177. should_include = True
  178. # Level filter
  179. if level_filter and current_entry.level.upper() != level_filter.upper():
  180. should_include = False
  181. # Search filter (case-insensitive)
  182. if search and should_include:
  183. search_lower = search.lower()
  184. if not (
  185. search_lower in current_entry.message.lower()
  186. or search_lower in current_entry.logger_name.lower()
  187. ):
  188. should_include = False
  189. if should_include:
  190. entries.append(current_entry)
  191. if len(entries) >= limit:
  192. break
  193. # Set new entry and attach any accumulated multi-line content to it
  194. # (in reverse order, continuation lines come before their parent entry)
  195. current_entry = parsed
  196. if multi_line_buffer:
  197. current_entry.message += "\n" + "\n".join(reversed(multi_line_buffer))
  198. multi_line_buffer = []
  199. elif line.strip():
  200. # Continuation of multi-line log entry (will be attached to next parsed entry)
  201. multi_line_buffer.append(line.rstrip())
  202. # Don't forget the last (oldest) entry
  203. # Note: any remaining multi_line_buffer would be orphaned lines before the first entry
  204. if current_entry and len(entries) < limit:
  205. should_include = True
  206. if level_filter and current_entry.level.upper() != level_filter.upper():
  207. should_include = False
  208. if search and should_include:
  209. search_lower = search.lower()
  210. if not (
  211. search_lower in current_entry.message.lower()
  212. or search_lower in current_entry.logger_name.lower()
  213. ):
  214. should_include = False
  215. if should_include:
  216. entries.append(current_entry)
  217. except Exception as e:
  218. logger.error("Error reading log file: %s", e)
  219. return [], 0
  220. # Entries are already in newest-first order
  221. return entries, total_lines
  222. @router.get("/logs", response_model=LogsResponse)
  223. async def get_logs(
  224. limit: int = Query(200, ge=1, le=1000, description="Maximum number of entries to return"),
  225. level: str | None = Query(None, description="Filter by log level (DEBUG, INFO, WARNING, ERROR)"),
  226. search: str | None = Query(None, description="Search in message or logger name"),
  227. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  228. ):
  229. """Get recent application log entries with optional filtering."""
  230. entries, total_lines = _read_log_entries(limit=limit, level_filter=level, search=search)
  231. return LogsResponse(
  232. entries=entries,
  233. total_in_file=total_lines,
  234. filtered_count=len(entries),
  235. )
  236. @router.delete("/logs")
  237. async def clear_logs(
  238. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  239. ):
  240. """Clear the application log file."""
  241. log_file = settings.log_dir / "bambuddy.log"
  242. if log_file.exists():
  243. try:
  244. # Truncate the file instead of deleting (keeps file handles valid)
  245. with open(log_file, "w", encoding="utf-8") as f:
  246. f.write("")
  247. logger.info("Log file cleared by user")
  248. return {"message": "Logs cleared successfully"}
  249. except Exception as e:
  250. logger.error("Error clearing log file: %s", e, exc_info=True)
  251. raise HTTPException(status_code=500, detail="Failed to clear logs. Check server logs for details.")
  252. return {"message": "Log file does not exist"}
  253. def _sanitize_path(path: str) -> str:
  254. """Remove username from paths for privacy."""
  255. # Replace /home/username/ or /Users/username/ with /home/[user]/
  256. path = re.sub(r"/home/[^/]+/", "/home/[user]/", path)
  257. path = re.sub(r"/Users/[^/]+/", "/Users/[user]/", path)
  258. # Replace /opt/username/ patterns
  259. path = re.sub(r"/opt/[^/]+/", "/opt/[user]/", path)
  260. return path
  261. def _detect_docker_network_mode() -> str:
  262. """Detect Docker network mode by checking for host-level interfaces.
  263. In host mode the container shares the host network namespace, so Docker
  264. infrastructure interfaces (docker0, br-*, veth*) are visible. In bridge
  265. mode the container is isolated and only sees its own veth (named eth0).
  266. """
  267. try:
  268. import socket
  269. for _idx, name in socket.if_nameindex():
  270. if name.startswith(("docker", "br-", "veth", "virbr")):
  271. return "host"
  272. except Exception:
  273. pass
  274. return "bridge"
  275. def _mask_subnet(subnet: str) -> str:
  276. """Mask the first two octets of a subnet string. e.g. '192.168.1.0/24' -> 'x.x.1.0/24'."""
  277. try:
  278. parts = subnet.split(".")
  279. if len(parts) >= 4:
  280. parts[0] = "x"
  281. parts[1] = "x"
  282. return ".".join(parts)
  283. except Exception:
  284. pass
  285. return subnet
  286. def _anonymize_mqtt_broker(broker: str) -> str:
  287. """Anonymize MQTT broker address. IPs become [IP], hostnames become *.domain."""
  288. if not broker:
  289. return ""
  290. try:
  291. ipaddress.ip_address(broker)
  292. return "[IP]"
  293. except ValueError:
  294. # It's a hostname — show *.domain pattern
  295. parts = broker.split(".")
  296. if len(parts) >= 2:
  297. return "*." + ".".join(parts[-2:])
  298. return broker
  299. async def _check_port(ip: str, port: int, timeout: float = 2.0) -> bool:
  300. """Test TCP connectivity to ip:port. Returns True if reachable."""
  301. try:
  302. _reader, writer = await asyncio.wait_for(asyncio.open_connection(ip, port), timeout=timeout)
  303. writer.close()
  304. await writer.wait_closed()
  305. return True
  306. except Exception:
  307. return False
  308. def _get_container_memory_limit() -> int | None:
  309. """Read cgroup memory limit. Returns bytes or None."""
  310. # cgroup v2
  311. v2 = Path("/sys/fs/cgroup/memory.max")
  312. if v2.exists():
  313. try:
  314. val = v2.read_text().strip()
  315. if val != "max":
  316. return int(val)
  317. except Exception:
  318. pass
  319. # cgroup v1
  320. v1 = Path("/sys/fs/cgroup/memory/memory.limit_in_bytes")
  321. if v1.exists():
  322. try:
  323. val = int(v1.read_text().strip())
  324. # Values near page-aligned max (2^63-4096) mean unlimited
  325. if val < 2**62:
  326. return val
  327. except Exception:
  328. pass
  329. return None
  330. def _format_bytes(size_bytes: int) -> str:
  331. """Format bytes into human-readable string."""
  332. if size_bytes < 1024:
  333. return f"{size_bytes} B"
  334. if size_bytes < 1024 * 1024:
  335. return f"{size_bytes / 1024:.1f} KB"
  336. if size_bytes < 1024 * 1024 * 1024:
  337. return f"{size_bytes / (1024 * 1024):.1f} MB"
  338. return f"{size_bytes / (1024 * 1024 * 1024):.2f} GB"
  339. async def _collect_support_info() -> dict:
  340. """Collect all support information."""
  341. in_docker = is_running_in_docker()
  342. info = {
  343. "generated_at": datetime.now().isoformat(),
  344. "app": {
  345. "version": APP_VERSION,
  346. "debug_mode": settings.debug,
  347. },
  348. "system": {
  349. "platform": platform.system(),
  350. "platform_release": platform.release(),
  351. "platform_version": platform.version(),
  352. "architecture": platform.machine(),
  353. "python_version": platform.python_version(),
  354. },
  355. "environment": {
  356. "docker": in_docker,
  357. "data_dir": _sanitize_path(str(settings.base_dir)),
  358. "log_dir": _sanitize_path(str(settings.log_dir)),
  359. "timezone": os.environ.get("TZ", ""),
  360. },
  361. "database": {},
  362. "printers": [],
  363. "settings": {},
  364. }
  365. # Docker-specific info
  366. if in_docker:
  367. try:
  368. mem_limit = _get_container_memory_limit()
  369. info["docker"] = {
  370. "container_memory_limit_bytes": mem_limit,
  371. "container_memory_limit_formatted": _format_bytes(mem_limit) if mem_limit else None,
  372. "network_mode_hint": _detect_docker_network_mode(),
  373. }
  374. except Exception:
  375. logger.debug("Failed to collect Docker info", exc_info=True)
  376. async with async_session() as db:
  377. # Database stats
  378. result = await db.execute(select(func.count(PrintArchive.id)))
  379. info["database"]["archives_total"] = result.scalar() or 0
  380. result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "completed"))
  381. info["database"]["archives_completed"] = result.scalar() or 0
  382. result = await db.execute(select(func.count(Printer.id)))
  383. info["database"]["printers_total"] = result.scalar() or 0
  384. result = await db.execute(select(func.count(Filament.id)))
  385. info["database"]["filaments_total"] = result.scalar() or 0
  386. result = await db.execute(select(func.count(Project.id)))
  387. info["database"]["projects_total"] = result.scalar() or 0
  388. result = await db.execute(select(func.count(SmartPlug.id)))
  389. info["database"]["smart_plugs_total"] = result.scalar() or 0
  390. # Printer info (anonymized - no names, IPs, or serials)
  391. result = await db.execute(select(Printer))
  392. printers = result.scalars().all()
  393. statuses = printer_manager.get_all_statuses()
  394. # Check reachability in parallel
  395. reachability_tasks = [_check_port(p.ip_address, 8883) for p in printers]
  396. reachable_results = await asyncio.gather(*reachability_tasks, return_exceptions=True)
  397. for i, printer in enumerate(printers):
  398. state = statuses.get(printer.id)
  399. reachable = reachable_results[i] if not isinstance(reachable_results[i], Exception) else False
  400. # Count AMS units and trays from raw_data
  401. ams_unit_count = 0
  402. ams_tray_count = 0
  403. has_vt_tray = False
  404. if state:
  405. ams_data = state.raw_data.get("ams")
  406. if isinstance(ams_data, list):
  407. ams_units = ams_data
  408. elif isinstance(ams_data, dict) and "ams" in ams_data:
  409. ams_units = ams_data["ams"] if isinstance(ams_data["ams"], list) else []
  410. else:
  411. ams_units = []
  412. ams_unit_count = len(ams_units)
  413. for unit in ams_units:
  414. trays = unit.get("tray", [])
  415. ams_tray_count += len([t for t in trays if t.get("tray_type")])
  416. has_vt_tray = bool(state.raw_data.get("vt_tray"))
  417. info["printers"].append(
  418. {
  419. "index": i + 1,
  420. "model": printer.model or "Unknown",
  421. "nozzle_count": printer.nozzle_count,
  422. "is_active": printer.is_active,
  423. "mqtt_connected": state.connected if state else False,
  424. "state": state.state if state else "unknown",
  425. "firmware_version": state.firmware_version if state else None,
  426. "wifi_signal": state.wifi_signal if state else None,
  427. "reachable": bool(reachable),
  428. "ams_unit_count": ams_unit_count,
  429. "ams_tray_count": ams_tray_count,
  430. "has_vt_tray": has_vt_tray,
  431. "external_camera_configured": bool(printer.external_camera_url),
  432. "plate_detection_enabled": printer.plate_detection_enabled,
  433. "hms_error_count": len(state.hms_errors) if state else 0,
  434. "developer_mode": state.developer_mode if state else None,
  435. "nozzle_rack_count": len(state.nozzle_rack) if state else 0,
  436. }
  437. )
  438. # Virtual printers
  439. try:
  440. from backend.app.models.virtual_printer import VirtualPrinter
  441. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS, virtual_printer_manager
  442. result = await db.execute(select(VirtualPrinter).order_by(VirtualPrinter.id))
  443. vps = result.scalars().all()
  444. info["virtual_printers"] = []
  445. for vp in vps:
  446. instance = virtual_printer_manager.get_instance(vp.id)
  447. status = instance.get_status() if instance else None
  448. model_code = vp.model or "C12"
  449. info["virtual_printers"].append(
  450. {
  451. "index": vp.id,
  452. "enabled": vp.enabled,
  453. "mode": vp.mode,
  454. "model": model_code,
  455. "model_name": VIRTUAL_PRINTER_MODELS.get(model_code, model_code),
  456. "has_target_printer": vp.target_printer_id is not None,
  457. "has_bind_ip": bool(vp.bind_ip),
  458. "running": status.get("running", False) if status else False,
  459. "pending_files": status.get("pending_files", 0) if status else 0,
  460. }
  461. )
  462. except Exception:
  463. logger.debug("Failed to collect virtual printer info", exc_info=True)
  464. # Non-sensitive settings
  465. result = await db.execute(select(Settings))
  466. all_settings = result.scalars().all()
  467. sensitive_keys = {
  468. "access_code",
  469. "password",
  470. "token",
  471. "secret",
  472. "api_key",
  473. "installation_id",
  474. "cloud_token",
  475. "mqtt_password",
  476. "email",
  477. "username",
  478. "vapid",
  479. "private_key",
  480. "public_key",
  481. "webhook",
  482. "url",
  483. "path", # Filesystem paths may contain usernames
  484. "config", # URLs may contain IPs, configs may have embedded secrets
  485. }
  486. for s in all_settings:
  487. # Skip sensitive settings
  488. if any(sensitive in s.key.lower() for sensitive in sensitive_keys):
  489. continue
  490. info["settings"][s.key] = s.value
  491. # Notification providers (anonymized — type/enabled/error status only)
  492. try:
  493. result = await db.execute(select(NotificationProvider))
  494. providers = result.scalars().all()
  495. info["integrations"] = info.get("integrations", {})
  496. info["integrations"]["notification_providers"] = [
  497. {
  498. "type": p.provider_type,
  499. "enabled": p.enabled,
  500. "has_last_error": bool(p.last_error),
  501. }
  502. for p in providers
  503. ]
  504. except Exception:
  505. logger.debug("Failed to collect notification provider info", exc_info=True)
  506. # Database health
  507. try:
  508. result = await db.execute(text("PRAGMA journal_mode"))
  509. journal_mode = result.scalar()
  510. result = await db.execute(text("PRAGMA quick_check"))
  511. quick_check = result.scalar()
  512. db_path = settings.base_dir / "bambuddy.db"
  513. db_size = db_path.stat().st_size if db_path.exists() else 0
  514. wal_path = settings.base_dir / "bambuddy.db-wal"
  515. wal_size = wal_path.stat().st_size if wal_path.exists() else 0
  516. info["database_health"] = {
  517. "journal_mode": journal_mode,
  518. "quick_check": quick_check,
  519. "db_size_bytes": db_size,
  520. "wal_size_bytes": wal_size,
  521. }
  522. except Exception:
  523. logger.debug("Failed to collect database health info", exc_info=True)
  524. # Integrations (lazy imports to avoid circular dependencies)
  525. info.setdefault("integrations", {})
  526. # Spoolman
  527. try:
  528. from backend.app.services.spoolman import get_spoolman_client
  529. client = await get_spoolman_client()
  530. if client:
  531. reachable = await client.health_check()
  532. info["integrations"]["spoolman"] = {"enabled": True, "reachable": reachable}
  533. else:
  534. info["integrations"]["spoolman"] = {"enabled": False, "reachable": False}
  535. except Exception:
  536. logger.debug("Failed to collect Spoolman info", exc_info=True)
  537. # MQTT relay
  538. try:
  539. from backend.app.services.mqtt_relay import mqtt_relay
  540. status = mqtt_relay.get_status()
  541. info["integrations"]["mqtt_relay"] = {
  542. "enabled": status.get("enabled", False),
  543. "connected": status.get("connected", False),
  544. "broker": _anonymize_mqtt_broker(status.get("broker", "")),
  545. "port": status.get("port", 0),
  546. "topic_prefix": status.get("topic_prefix", ""),
  547. }
  548. except Exception:
  549. logger.debug("Failed to collect MQTT relay info", exc_info=True)
  550. # Home Assistant (check ha_enabled setting)
  551. try:
  552. info["integrations"]["homeassistant"] = {
  553. "enabled": info["settings"].get("ha_enabled", "false").lower() == "true",
  554. }
  555. except Exception:
  556. logger.debug("Failed to collect Home Assistant info", exc_info=True)
  557. # Dependencies
  558. try:
  559. dep_packages = [
  560. "fastapi",
  561. "uvicorn",
  562. "pydantic",
  563. "sqlalchemy",
  564. "paho-mqtt",
  565. "psutil",
  566. "httpx",
  567. "aiofiles",
  568. "cryptography",
  569. "opencv-python-headless",
  570. "numpy",
  571. ]
  572. info["dependencies"] = {}
  573. for pkg in dep_packages:
  574. try:
  575. info["dependencies"][pkg] = importlib.metadata.version(pkg)
  576. except importlib.metadata.PackageNotFoundError:
  577. info["dependencies"][pkg] = None
  578. except Exception:
  579. logger.debug("Failed to collect dependency info", exc_info=True)
  580. # Log file info
  581. try:
  582. log_file = settings.log_dir / "bambuddy.log"
  583. if log_file.exists():
  584. size = log_file.stat().st_size
  585. info["log_file"] = {
  586. "size_bytes": size,
  587. "size_formatted": _format_bytes(size),
  588. }
  589. else:
  590. info["log_file"] = {"size_bytes": 0, "size_formatted": "0 B"}
  591. except Exception:
  592. logger.debug("Failed to collect log file info", exc_info=True)
  593. # Network interfaces (subnets with first two octets masked)
  594. try:
  595. interfaces = get_network_interfaces()
  596. info["network"] = {
  597. "interface_count": len(interfaces),
  598. "interfaces": [{"name": iface["name"], "subnet": _mask_subnet(iface["subnet"])} for iface in interfaces],
  599. }
  600. except Exception:
  601. logger.debug("Failed to collect network info", exc_info=True)
  602. # WebSocket connections
  603. try:
  604. info["websockets"] = {
  605. "active_connections": len(ws_manager.active_connections),
  606. }
  607. except Exception:
  608. logger.debug("Failed to collect WebSocket info", exc_info=True)
  609. return info
  610. def _sanitize_log_content(content: str, sensitive_strings: dict[str, str] | None = None) -> str:
  611. """Remove sensitive data from log content."""
  612. # First, replace known sensitive values (database-aware exact matching)
  613. # This catches printer names, usernames, and other arbitrary user-chosen strings
  614. # that regex patterns cannot detect
  615. if sensitive_strings:
  616. # Sort by length descending to avoid partial matches (e.g. "My Printer 1" before "My Printer")
  617. for value, label in sorted(sensitive_strings.items(), key=lambda x: len(x[0]), reverse=True):
  618. if len(value) < 3:
  619. continue # Skip very short strings to prevent over-redaction
  620. content = re.sub(re.escape(value), label, content)
  621. # Replace credentials in URLs (e.g. http://user:pass@host)
  622. content = re.sub(r"(https?://)[^/:@\s]+:[^/@\s]+@", r"\1[CREDENTIALS]@", content)
  623. # Replace email addresses
  624. content = re.sub(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b", "[EMAIL]", content)
  625. # Replace Bambu Lab printer serial numbers (format: 00M/01D/01S/01P/03W + alphanumeric, 12-16 chars total)
  626. content = re.sub(r"\b0[0-3][A-Z0-9][A-Z0-9]{9,13}\b", "[SERIAL]", content, flags=re.IGNORECASE)
  627. # Replace IPv4 addresses (skip firmware versions like 01.09.01.00 which have leading zeros)
  628. content = re.sub(
  629. r"\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\b",
  630. "[IP]",
  631. content,
  632. )
  633. # Replace paths with usernames
  634. content = re.sub(r"/home/[^/\s]+/", "/home/[user]/", content)
  635. content = re.sub(r"/Users/[^/\s]+/", "/Users/[user]/", content)
  636. content = re.sub(r"/opt/[^/\s]+/", "/opt/[user]/", content)
  637. return content
  638. def _get_log_content(max_bytes: int = 10 * 1024 * 1024, sensitive_strings: dict[str, str] | None = None) -> bytes:
  639. """Get log file content, limited to max_bytes from the end."""
  640. log_file = settings.log_dir / "bambuddy.log"
  641. if not log_file.exists():
  642. return b"Log file not found"
  643. file_size = log_file.stat().st_size
  644. if file_size <= max_bytes:
  645. content = log_file.read_text(encoding="utf-8", errors="replace")
  646. else:
  647. # Read last max_bytes
  648. with open(log_file, "rb") as f:
  649. f.seek(file_size - max_bytes)
  650. # Skip partial line at start
  651. f.readline()
  652. content = f.read().decode("utf-8", errors="replace")
  653. # Sanitize sensitive data
  654. content = _sanitize_log_content(content, sensitive_strings)
  655. return content.encode("utf-8")
  656. async def _get_recent_sanitized_logs(max_lines: int = 200) -> str:
  657. """Get recent log lines, sanitized for inclusion in bug reports."""
  658. # Collect sensitive strings from DB for redaction
  659. sensitive_strings: dict[str, str] = {}
  660. async with async_session() as db:
  661. result = await db.execute(select(Printer.name, Printer.serial_number, Printer.ip_address))
  662. for name, serial, ip_address in result.all():
  663. if name:
  664. sensitive_strings[name] = "[PRINTER]"
  665. if serial:
  666. sensitive_strings[serial] = "[SERIAL]"
  667. if ip_address:
  668. sensitive_strings[ip_address] = "[IP]"
  669. result = await db.execute(select(User.username))
  670. for (username,) in result.all():
  671. if username:
  672. sensitive_strings[username] = "[USER]"
  673. result = await db.execute(select(Settings.value).where(Settings.key == "bambu_cloud_email"))
  674. cloud_email = result.scalar_one_or_none()
  675. if cloud_email:
  676. sensitive_strings[cloud_email] = "[EMAIL]"
  677. log_file = settings.log_dir / "bambuddy.log"
  678. if not log_file.exists():
  679. return ""
  680. # Read last portion of log file
  681. try:
  682. content = log_file.read_text(encoding="utf-8", errors="replace")
  683. lines = content.splitlines()
  684. recent = "\n".join(lines[-max_lines:])
  685. return _sanitize_log_content(recent, sensitive_strings)
  686. except Exception:
  687. logger.debug("Failed to read logs for bug report", exc_info=True)
  688. return ""
  689. @router.get("/bundle")
  690. async def generate_support_bundle(
  691. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  692. ):
  693. """Generate a support bundle ZIP file for issue reporting."""
  694. # Check if debug logging is enabled and collect sensitive values for redaction
  695. async with async_session() as db:
  696. enabled, _enabled_at = await _get_debug_setting(db)
  697. if not enabled:
  698. raise HTTPException(
  699. status_code=400,
  700. detail="Debug logging must be enabled before generating a support bundle. "
  701. "Please enable debug logging, reproduce the issue, then generate the bundle.",
  702. )
  703. # Collect known sensitive values for log redaction
  704. sensitive_strings: dict[str, str] = {}
  705. # Printer names, serial numbers, and IP addresses
  706. result = await db.execute(select(Printer.name, Printer.serial_number, Printer.ip_address))
  707. for name, serial, ip_address in result.all():
  708. if name:
  709. sensitive_strings[name] = "[PRINTER]"
  710. if serial:
  711. sensitive_strings[serial] = "[SERIAL]"
  712. if ip_address:
  713. sensitive_strings[ip_address] = "[IP]"
  714. # Auth usernames
  715. result = await db.execute(select(User.username))
  716. for (username,) in result.all():
  717. if username:
  718. sensitive_strings[username] = "[USER]"
  719. # Bambu Cloud email
  720. result = await db.execute(select(Settings.value).where(Settings.key == "bambu_cloud_email"))
  721. cloud_email = result.scalar_one_or_none()
  722. if cloud_email:
  723. sensitive_strings[cloud_email] = "[EMAIL]"
  724. # Collect support info
  725. support_info = await _collect_support_info()
  726. # Create ZIP in memory
  727. zip_buffer = io.BytesIO()
  728. timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
  729. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  730. # Add support info JSON
  731. zf.writestr("support-info.json", json.dumps(support_info, indent=2, default=str))
  732. # Add log file
  733. log_content = _get_log_content(sensitive_strings=sensitive_strings)
  734. zf.writestr("bambuddy.log", log_content)
  735. zip_buffer.seek(0)
  736. filename = f"bambuddy-support-{timestamp}.zip"
  737. logger.info("Generated support bundle: %s", filename)
  738. return StreamingResponse(
  739. zip_buffer, media_type="application/zip", headers={"Content-Disposition": f"attachment; filename={filename}"}
  740. )
  741. async def init_debug_logging():
  742. """Initialize debug logging state from database on startup."""
  743. try:
  744. async with async_session() as db:
  745. enabled, _ = await _get_debug_setting(db)
  746. if enabled:
  747. _apply_log_level(True)
  748. logger.info("Debug logging restored from previous session")
  749. except Exception as e:
  750. logger.warning("Could not restore debug logging state: %s", e)