support.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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.INFO)
  86. logging.getLogger("httpcore").setLevel(logging.DEBUG)
  87. logging.getLogger("httpx").setLevel(logging.DEBUG)
  88. else:
  89. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  90. logging.getLogger("httpcore").setLevel(logging.WARNING)
  91. logging.getLogger("httpx").setLevel(logging.WARNING)
  92. logger.info("Log level changed to %s", "DEBUG" if debug else "INFO")
  93. @router.get("/debug-logging", response_model=DebugLoggingState)
  94. async def get_debug_logging_state(
  95. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  96. ):
  97. """Get current debug logging state."""
  98. async with async_session() as db:
  99. enabled, enabled_at = await _get_debug_setting(db)
  100. duration = None
  101. if enabled and enabled_at:
  102. duration = int((datetime.now() - enabled_at).total_seconds())
  103. return DebugLoggingState(
  104. enabled=enabled,
  105. enabled_at=enabled_at.isoformat() if enabled_at else None,
  106. duration_seconds=duration,
  107. )
  108. @router.post("/debug-logging", response_model=DebugLoggingState)
  109. async def toggle_debug_logging(
  110. toggle: DebugLoggingToggle,
  111. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  112. ):
  113. """Enable or disable debug logging."""
  114. async with async_session() as db:
  115. enabled_at = await _set_debug_setting(db, toggle.enabled)
  116. _apply_log_level(toggle.enabled)
  117. duration = None
  118. if toggle.enabled and enabled_at:
  119. duration = int((datetime.now() - enabled_at).total_seconds())
  120. return DebugLoggingState(
  121. enabled=toggle.enabled,
  122. enabled_at=enabled_at.isoformat() if enabled_at else None,
  123. duration_seconds=duration,
  124. )
  125. class LogEntry(BaseModel):
  126. """A single log entry."""
  127. timestamp: str
  128. level: str
  129. logger_name: str
  130. message: str
  131. class LogsResponse(BaseModel):
  132. """Response containing log entries."""
  133. entries: list[LogEntry]
  134. total_in_file: int
  135. filtered_count: int
  136. # Log line regex pattern: "2024-01-15 10:30:45,123 INFO [module.name] Message here"
  137. 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+(.*)$")
  138. def _parse_log_line(line: str) -> LogEntry | None:
  139. """Parse a single log line into a LogEntry."""
  140. match = LOG_LINE_PATTERN.match(line.strip())
  141. if match:
  142. return LogEntry(
  143. timestamp=match.group(1),
  144. level=match.group(2),
  145. logger_name=match.group(3),
  146. message=match.group(4),
  147. )
  148. return None
  149. def _read_log_entries(
  150. limit: int = 200,
  151. level_filter: str | None = None,
  152. search: str | None = None,
  153. ) -> tuple[list[LogEntry], int]:
  154. """Read and parse log entries from file with optional filtering."""
  155. log_file = settings.log_dir / "bambuddy.log"
  156. if not log_file.exists():
  157. return [], 0
  158. entries: list[LogEntry] = []
  159. total_lines = 0
  160. try:
  161. with open(log_file, encoding="utf-8", errors="replace") as f:
  162. # Read all lines and process
  163. lines = f.readlines()
  164. total_lines = len(lines)
  165. # Parse lines in reverse order (newest first)
  166. current_entry: LogEntry | None = None
  167. multi_line_buffer: list[str] = []
  168. for line in reversed(lines):
  169. parsed = _parse_log_line(line)
  170. if parsed:
  171. # Found a new log entry start
  172. if current_entry:
  173. # Apply filters and add previous entry (without multi_line_buffer - it belongs to new entry)
  174. should_include = True
  175. # Level filter
  176. if level_filter and current_entry.level.upper() != level_filter.upper():
  177. should_include = False
  178. # Search filter (case-insensitive)
  179. if search and should_include:
  180. search_lower = search.lower()
  181. if not (
  182. search_lower in current_entry.message.lower()
  183. or search_lower in current_entry.logger_name.lower()
  184. ):
  185. should_include = False
  186. if should_include:
  187. entries.append(current_entry)
  188. if len(entries) >= limit:
  189. break
  190. # Set new entry and attach any accumulated multi-line content to it
  191. # (in reverse order, continuation lines come before their parent entry)
  192. current_entry = parsed
  193. if multi_line_buffer:
  194. current_entry.message += "\n" + "\n".join(reversed(multi_line_buffer))
  195. multi_line_buffer = []
  196. elif line.strip():
  197. # Continuation of multi-line log entry (will be attached to next parsed entry)
  198. multi_line_buffer.append(line.rstrip())
  199. # Don't forget the last (oldest) entry
  200. # Note: any remaining multi_line_buffer would be orphaned lines before the first entry
  201. if current_entry and len(entries) < limit:
  202. should_include = True
  203. if level_filter and current_entry.level.upper() != level_filter.upper():
  204. should_include = False
  205. if search and should_include:
  206. search_lower = search.lower()
  207. if not (
  208. search_lower in current_entry.message.lower()
  209. or search_lower in current_entry.logger_name.lower()
  210. ):
  211. should_include = False
  212. if should_include:
  213. entries.append(current_entry)
  214. except Exception as e:
  215. logger.error("Error reading log file: %s", e)
  216. return [], 0
  217. # Entries are already in newest-first order
  218. return entries, total_lines
  219. @router.get("/logs", response_model=LogsResponse)
  220. async def get_logs(
  221. limit: int = Query(200, ge=1, le=1000, description="Maximum number of entries to return"),
  222. level: str | None = Query(None, description="Filter by log level (DEBUG, INFO, WARNING, ERROR)"),
  223. search: str | None = Query(None, description="Search in message or logger name"),
  224. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  225. ):
  226. """Get recent application log entries with optional filtering."""
  227. entries, total_lines = _read_log_entries(limit=limit, level_filter=level, search=search)
  228. return LogsResponse(
  229. entries=entries,
  230. total_in_file=total_lines,
  231. filtered_count=len(entries),
  232. )
  233. @router.delete("/logs")
  234. async def clear_logs(
  235. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  236. ):
  237. """Clear the application log file."""
  238. log_file = settings.log_dir / "bambuddy.log"
  239. if log_file.exists():
  240. try:
  241. # Truncate the file instead of deleting (keeps file handles valid)
  242. with open(log_file, "w", encoding="utf-8") as f:
  243. f.write("")
  244. logger.info("Log file cleared by user")
  245. return {"message": "Logs cleared successfully"}
  246. except Exception as e:
  247. logger.error("Error clearing log file: %s", e, exc_info=True)
  248. raise HTTPException(status_code=500, detail="Failed to clear logs. Check server logs for details.")
  249. return {"message": "Log file does not exist"}
  250. def _sanitize_path(path: str) -> str:
  251. """Remove username from paths for privacy."""
  252. # Replace /home/username/ or /Users/username/ with /home/[user]/
  253. path = re.sub(r"/home/[^/]+/", "/home/[user]/", path)
  254. path = re.sub(r"/Users/[^/]+/", "/Users/[user]/", path)
  255. # Replace /opt/username/ patterns
  256. path = re.sub(r"/opt/[^/]+/", "/opt/[user]/", path)
  257. return path
  258. def _anonymize_mqtt_broker(broker: str) -> str:
  259. """Anonymize MQTT broker address. IPs become [IP], hostnames become *.domain."""
  260. if not broker:
  261. return ""
  262. try:
  263. ipaddress.ip_address(broker)
  264. return "[IP]"
  265. except ValueError:
  266. # It's a hostname — show *.domain pattern
  267. parts = broker.split(".")
  268. if len(parts) >= 2:
  269. return "*." + ".".join(parts[-2:])
  270. return broker
  271. async def _check_port(ip: str, port: int, timeout: float = 2.0) -> bool:
  272. """Test TCP connectivity to ip:port. Returns True if reachable."""
  273. try:
  274. _reader, writer = await asyncio.wait_for(asyncio.open_connection(ip, port), timeout=timeout)
  275. writer.close()
  276. await writer.wait_closed()
  277. return True
  278. except Exception:
  279. return False
  280. def _get_container_memory_limit() -> int | None:
  281. """Read cgroup memory limit. Returns bytes or None."""
  282. # cgroup v2
  283. v2 = Path("/sys/fs/cgroup/memory.max")
  284. if v2.exists():
  285. try:
  286. val = v2.read_text().strip()
  287. if val != "max":
  288. return int(val)
  289. except Exception:
  290. pass
  291. # cgroup v1
  292. v1 = Path("/sys/fs/cgroup/memory/memory.limit_in_bytes")
  293. if v1.exists():
  294. try:
  295. val = int(v1.read_text().strip())
  296. # Values near page-aligned max (2^63-4096) mean unlimited
  297. if val < 2**62:
  298. return val
  299. except Exception:
  300. pass
  301. return None
  302. def _format_bytes(size_bytes: int) -> str:
  303. """Format bytes into human-readable string."""
  304. if size_bytes < 1024:
  305. return f"{size_bytes} B"
  306. if size_bytes < 1024 * 1024:
  307. return f"{size_bytes / 1024:.1f} KB"
  308. if size_bytes < 1024 * 1024 * 1024:
  309. return f"{size_bytes / (1024 * 1024):.1f} MB"
  310. return f"{size_bytes / (1024 * 1024 * 1024):.2f} GB"
  311. async def _collect_support_info() -> dict:
  312. """Collect all support information."""
  313. in_docker = is_running_in_docker()
  314. info = {
  315. "generated_at": datetime.now().isoformat(),
  316. "app": {
  317. "version": APP_VERSION,
  318. "debug_mode": settings.debug,
  319. },
  320. "system": {
  321. "platform": platform.system(),
  322. "platform_release": platform.release(),
  323. "platform_version": platform.version(),
  324. "architecture": platform.machine(),
  325. "python_version": platform.python_version(),
  326. },
  327. "environment": {
  328. "docker": in_docker,
  329. "data_dir": _sanitize_path(str(settings.base_dir)),
  330. "log_dir": _sanitize_path(str(settings.log_dir)),
  331. "timezone": os.environ.get("TZ", ""),
  332. },
  333. "database": {},
  334. "printers": [],
  335. "settings": {},
  336. }
  337. # Docker-specific info
  338. if in_docker:
  339. try:
  340. mem_limit = _get_container_memory_limit()
  341. interfaces = get_network_interfaces()
  342. info["docker"] = {
  343. "container_memory_limit_bytes": mem_limit,
  344. "container_memory_limit_formatted": _format_bytes(mem_limit) if mem_limit else None,
  345. "network_mode_hint": "host" if len(interfaces) > 2 else "bridge",
  346. }
  347. except Exception:
  348. logger.debug("Failed to collect Docker info", exc_info=True)
  349. async with async_session() as db:
  350. # Database stats
  351. result = await db.execute(select(func.count(PrintArchive.id)))
  352. info["database"]["archives_total"] = result.scalar() or 0
  353. result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "completed"))
  354. info["database"]["archives_completed"] = result.scalar() or 0
  355. result = await db.execute(select(func.count(Printer.id)))
  356. info["database"]["printers_total"] = result.scalar() or 0
  357. result = await db.execute(select(func.count(Filament.id)))
  358. info["database"]["filaments_total"] = result.scalar() or 0
  359. result = await db.execute(select(func.count(Project.id)))
  360. info["database"]["projects_total"] = result.scalar() or 0
  361. result = await db.execute(select(func.count(SmartPlug.id)))
  362. info["database"]["smart_plugs_total"] = result.scalar() or 0
  363. # Printer info (anonymized - no names, IPs, or serials)
  364. result = await db.execute(select(Printer))
  365. printers = result.scalars().all()
  366. statuses = printer_manager.get_all_statuses()
  367. # Check reachability in parallel
  368. reachability_tasks = [_check_port(p.ip_address, 8883) for p in printers]
  369. reachable_results = await asyncio.gather(*reachability_tasks, return_exceptions=True)
  370. for i, printer in enumerate(printers):
  371. state = statuses.get(printer.id)
  372. reachable = reachable_results[i] if not isinstance(reachable_results[i], Exception) else False
  373. # Count AMS units and trays from raw_data
  374. ams_unit_count = 0
  375. ams_tray_count = 0
  376. has_vt_tray = False
  377. if state:
  378. ams_data = state.raw_data.get("ams")
  379. if isinstance(ams_data, dict) and "ams" in ams_data:
  380. ams_units = ams_data["ams"]
  381. if isinstance(ams_units, list):
  382. ams_unit_count = len(ams_units)
  383. for unit in ams_units:
  384. trays = unit.get("tray", [])
  385. ams_tray_count += len([t for t in trays if t.get("tray_type")])
  386. has_vt_tray = state.raw_data.get("vt_tray") is not None
  387. info["printers"].append(
  388. {
  389. "index": i + 1,
  390. "model": printer.model or "Unknown",
  391. "nozzle_count": printer.nozzle_count,
  392. "is_active": printer.is_active,
  393. "mqtt_connected": state.connected if state else False,
  394. "state": state.state if state else "unknown",
  395. "firmware_version": state.firmware_version if state else None,
  396. "wifi_signal": state.wifi_signal if state else None,
  397. "reachable": bool(reachable),
  398. "ams_unit_count": ams_unit_count,
  399. "ams_tray_count": ams_tray_count,
  400. "has_vt_tray": has_vt_tray,
  401. "external_camera_configured": bool(printer.external_camera_url),
  402. "plate_detection_enabled": printer.plate_detection_enabled,
  403. "hms_error_count": len(state.hms_errors) if state else 0,
  404. "nozzle_rack_count": len(state.nozzle_rack) if state else 0,
  405. }
  406. )
  407. # Non-sensitive settings
  408. result = await db.execute(select(Settings))
  409. all_settings = result.scalars().all()
  410. sensitive_keys = {
  411. "access_code",
  412. "password",
  413. "token",
  414. "secret",
  415. "api_key",
  416. "installation_id",
  417. "cloud_token",
  418. "mqtt_password",
  419. "email",
  420. "vapid",
  421. "private_key",
  422. "public_key",
  423. "webhook",
  424. "url",
  425. "config", # URLs may contain IPs, configs may have embedded secrets
  426. }
  427. for s in all_settings:
  428. # Skip sensitive settings
  429. if any(sensitive in s.key.lower() for sensitive in sensitive_keys):
  430. continue
  431. info["settings"][s.key] = s.value
  432. # Notification providers (anonymized — type/enabled/error status only)
  433. try:
  434. result = await db.execute(select(NotificationProvider))
  435. providers = result.scalars().all()
  436. info["integrations"] = info.get("integrations", {})
  437. info["integrations"]["notification_providers"] = [
  438. {
  439. "type": p.provider_type,
  440. "enabled": p.enabled,
  441. "has_last_error": bool(p.last_error),
  442. }
  443. for p in providers
  444. ]
  445. except Exception:
  446. logger.debug("Failed to collect notification provider info", exc_info=True)
  447. # Database health
  448. try:
  449. result = await db.execute(text("PRAGMA journal_mode"))
  450. journal_mode = result.scalar()
  451. result = await db.execute(text("PRAGMA quick_check"))
  452. quick_check = result.scalar()
  453. db_path = settings.base_dir / "bambuddy.db"
  454. db_size = db_path.stat().st_size if db_path.exists() else 0
  455. wal_path = settings.base_dir / "bambuddy.db-wal"
  456. wal_size = wal_path.stat().st_size if wal_path.exists() else 0
  457. info["database_health"] = {
  458. "journal_mode": journal_mode,
  459. "quick_check": quick_check,
  460. "db_size_bytes": db_size,
  461. "wal_size_bytes": wal_size,
  462. }
  463. except Exception:
  464. logger.debug("Failed to collect database health info", exc_info=True)
  465. # Integrations (lazy imports to avoid circular dependencies)
  466. info.setdefault("integrations", {})
  467. # Spoolman
  468. try:
  469. from backend.app.services.spoolman import get_spoolman_client
  470. client = await get_spoolman_client()
  471. if client:
  472. reachable = await client.health_check()
  473. info["integrations"]["spoolman"] = {"enabled": True, "reachable": reachable}
  474. else:
  475. info["integrations"]["spoolman"] = {"enabled": False, "reachable": False}
  476. except Exception:
  477. logger.debug("Failed to collect Spoolman info", exc_info=True)
  478. # MQTT relay
  479. try:
  480. from backend.app.services.mqtt_relay import mqtt_relay
  481. status = mqtt_relay.get_status()
  482. info["integrations"]["mqtt_relay"] = {
  483. "enabled": status.get("enabled", False),
  484. "connected": status.get("connected", False),
  485. "broker": _anonymize_mqtt_broker(status.get("broker", "")),
  486. "port": status.get("port", 0),
  487. "topic_prefix": status.get("topic_prefix", ""),
  488. }
  489. except Exception:
  490. logger.debug("Failed to collect MQTT relay info", exc_info=True)
  491. # Home Assistant (check ha_enabled setting)
  492. try:
  493. info["integrations"]["homeassistant"] = {
  494. "enabled": info["settings"].get("ha_enabled", "false").lower() == "true",
  495. }
  496. except Exception:
  497. logger.debug("Failed to collect Home Assistant info", exc_info=True)
  498. # Dependencies
  499. try:
  500. dep_packages = [
  501. "fastapi",
  502. "uvicorn",
  503. "pydantic",
  504. "sqlalchemy",
  505. "paho-mqtt",
  506. "psutil",
  507. "httpx",
  508. "aiofiles",
  509. "cryptography",
  510. "opencv-python-headless",
  511. "numpy",
  512. ]
  513. info["dependencies"] = {}
  514. for pkg in dep_packages:
  515. try:
  516. info["dependencies"][pkg] = importlib.metadata.version(pkg)
  517. except importlib.metadata.PackageNotFoundError:
  518. info["dependencies"][pkg] = None
  519. except Exception:
  520. logger.debug("Failed to collect dependency info", exc_info=True)
  521. # Log file info
  522. try:
  523. log_file = settings.log_dir / "bambuddy.log"
  524. if log_file.exists():
  525. size = log_file.stat().st_size
  526. info["log_file"] = {
  527. "size_bytes": size,
  528. "size_formatted": _format_bytes(size),
  529. }
  530. else:
  531. info["log_file"] = {"size_bytes": 0, "size_formatted": "0 B"}
  532. except Exception:
  533. logger.debug("Failed to collect log file info", exc_info=True)
  534. # Network interfaces (subnets only — already anonymized)
  535. try:
  536. interfaces = get_network_interfaces()
  537. info["network"] = {
  538. "interface_count": len(interfaces),
  539. "interfaces": [{"name": iface["name"], "subnet": iface["subnet"]} for iface in interfaces],
  540. }
  541. except Exception:
  542. logger.debug("Failed to collect network info", exc_info=True)
  543. # WebSocket connections
  544. try:
  545. info["websockets"] = {
  546. "active_connections": len(ws_manager.active_connections),
  547. }
  548. except Exception:
  549. logger.debug("Failed to collect WebSocket info", exc_info=True)
  550. return info
  551. def _sanitize_log_content(content: str) -> str:
  552. """Remove sensitive data from log content."""
  553. # Replace IP addresses with [IP]
  554. content = re.sub(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", "[IP]", content)
  555. # Replace email addresses
  556. content = re.sub(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b", "[EMAIL]", content)
  557. # Replace Bambu Lab printer serial numbers (format: 00M/01D/01S/01P/03W + alphanumeric, 12-16 chars total)
  558. # These appear in logs as [SERIAL] or in messages
  559. content = re.sub(r"\b(0[0-3][A-Z0-9])[A-Z0-9]{9,13}\b", r"\1[SERIAL]", content)
  560. # Replace paths with usernames
  561. content = re.sub(r"/home/[^/\s]+/", "/home/[user]/", content)
  562. content = re.sub(r"/Users/[^/\s]+/", "/Users/[user]/", content)
  563. content = re.sub(r"/opt/[^/\s]+/", "/opt/[user]/", content)
  564. return content
  565. def _get_log_content(max_bytes: int = 10 * 1024 * 1024) -> bytes:
  566. """Get log file content, limited to max_bytes from the end."""
  567. log_file = settings.log_dir / "bambuddy.log"
  568. if not log_file.exists():
  569. return b"Log file not found"
  570. file_size = log_file.stat().st_size
  571. if file_size <= max_bytes:
  572. content = log_file.read_text(encoding="utf-8", errors="replace")
  573. else:
  574. # Read last max_bytes
  575. with open(log_file, "rb") as f:
  576. f.seek(file_size - max_bytes)
  577. # Skip partial line at start
  578. f.readline()
  579. content = f.read().decode("utf-8", errors="replace")
  580. # Sanitize sensitive data
  581. content = _sanitize_log_content(content)
  582. return content.encode("utf-8")
  583. @router.get("/bundle")
  584. async def generate_support_bundle(
  585. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  586. ):
  587. """Generate a support bundle ZIP file for issue reporting."""
  588. # Check if debug logging is enabled
  589. async with async_session() as db:
  590. enabled, _enabled_at = await _get_debug_setting(db)
  591. if not enabled:
  592. raise HTTPException(
  593. status_code=400,
  594. detail="Debug logging must be enabled before generating a support bundle. "
  595. "Please enable debug logging, reproduce the issue, then generate the bundle.",
  596. )
  597. # Collect support info
  598. support_info = await _collect_support_info()
  599. # Create ZIP in memory
  600. zip_buffer = io.BytesIO()
  601. timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
  602. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  603. # Add support info JSON
  604. zf.writestr("support-info.json", json.dumps(support_info, indent=2, default=str))
  605. # Add log file
  606. log_content = _get_log_content()
  607. zf.writestr("bambuddy.log", log_content)
  608. zip_buffer.seek(0)
  609. filename = f"bambuddy-support-{timestamp}.zip"
  610. logger.info("Generated support bundle: %s", filename)
  611. return StreamingResponse(
  612. zip_buffer, media_type="application/zip", headers={"Content-Disposition": f"attachment; filename={filename}"}
  613. )
  614. async def init_debug_logging():
  615. """Initialize debug logging state from database on startup."""
  616. try:
  617. async with async_session() as db:
  618. enabled, _ = await _get_debug_setting(db)
  619. if enabled:
  620. _apply_log_level(True)
  621. logger.info("Debug logging restored from previous session")
  622. except Exception as e:
  623. logger.warning("Could not restore debug logging state: %s", e)