support.py 27 KB

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