support.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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, timezone
  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. if enabled_at.tzinfo is None:
  55. enabled_at = enabled_at.replace(tzinfo=timezone.utc)
  56. except ValueError:
  57. pass # Ignore malformed timestamp; enabled_at stays None
  58. return enabled, enabled_at
  59. async def _set_debug_setting(db: AsyncSession, enabled: bool) -> datetime | None:
  60. """Set debug logging state in database."""
  61. # Update or create enabled setting
  62. result = await db.execute(select(Settings).where(Settings.key == "debug_logging_enabled"))
  63. setting = result.scalar_one_or_none()
  64. if setting:
  65. setting.value = str(enabled).lower()
  66. else:
  67. db.add(Settings(key="debug_logging_enabled", value=str(enabled).lower()))
  68. # Update enabled_at timestamp
  69. enabled_at = datetime.now(tz=timezone.utc) if enabled else None
  70. result = await db.execute(select(Settings).where(Settings.key == "debug_logging_enabled_at"))
  71. at_setting = result.scalar_one_or_none()
  72. if at_setting:
  73. at_setting.value = enabled_at.isoformat() if enabled_at else ""
  74. else:
  75. db.add(Settings(key="debug_logging_enabled_at", value=enabled_at.isoformat() if enabled_at else ""))
  76. await db.commit()
  77. return enabled_at
  78. def _apply_log_level(debug: bool):
  79. """Apply log level change to root logger."""
  80. root_logger = logging.getLogger()
  81. new_level = logging.DEBUG if debug else logging.INFO
  82. root_logger.setLevel(new_level)
  83. for handler in root_logger.handlers:
  84. handler.setLevel(new_level)
  85. # Also adjust third-party loggers. httpx/httpcore stay pinned to WARNING
  86. # even in debug mode — at INFO/DEBUG they log full request URLs, which
  87. # leaks secrets embedded in webhook URLs (Discord, generic webhooks, etc.).
  88. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  89. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  90. logging.getLogger("httpcore").setLevel(logging.WARNING)
  91. logging.getLogger("httpx").setLevel(logging.WARNING)
  92. logging.getLogger("paho.mqtt").setLevel(logging.DEBUG if debug else logging.WARNING)
  93. logger.info("Log level changed to %s", "DEBUG" if debug else "INFO")
  94. @router.get("/debug-logging", response_model=DebugLoggingState)
  95. async def get_debug_logging_state(
  96. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  97. ):
  98. """Get current debug logging state."""
  99. async with async_session() as db:
  100. enabled, enabled_at = await _get_debug_setting(db)
  101. duration = None
  102. if enabled and enabled_at:
  103. duration = int((datetime.now(tz=timezone.utc) - enabled_at).total_seconds())
  104. return DebugLoggingState(
  105. enabled=enabled,
  106. enabled_at=enabled_at.isoformat() if enabled_at else None,
  107. duration_seconds=duration,
  108. )
  109. @router.post("/debug-logging", response_model=DebugLoggingState)
  110. async def toggle_debug_logging(
  111. toggle: DebugLoggingToggle,
  112. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  113. ):
  114. """Enable or disable debug logging."""
  115. async with async_session() as db:
  116. enabled_at = await _set_debug_setting(db, toggle.enabled)
  117. _apply_log_level(toggle.enabled)
  118. duration = None
  119. if toggle.enabled and enabled_at:
  120. duration = int((datetime.now(tz=timezone.utc) - enabled_at).total_seconds())
  121. return DebugLoggingState(
  122. enabled=toggle.enabled,
  123. enabled_at=enabled_at.isoformat() if enabled_at else None,
  124. duration_seconds=duration,
  125. )
  126. class LogEntry(BaseModel):
  127. """A single log entry."""
  128. timestamp: str
  129. level: str
  130. logger_name: str
  131. message: str
  132. class LogsResponse(BaseModel):
  133. """Response containing log entries."""
  134. entries: list[LogEntry]
  135. total_in_file: int
  136. filtered_count: int
  137. # Log line regex pattern: "2024-01-15 10:30:45,123 INFO [module.name] Message here"
  138. 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+(.*)$")
  139. def _parse_log_line(line: str) -> LogEntry | None:
  140. """Parse a single log line into a LogEntry."""
  141. match = LOG_LINE_PATTERN.match(line.strip())
  142. if match:
  143. return LogEntry(
  144. timestamp=match.group(1),
  145. level=match.group(2),
  146. logger_name=match.group(3),
  147. message=match.group(4),
  148. )
  149. return None
  150. def _read_log_entries(
  151. limit: int = 200,
  152. level_filter: str | None = None,
  153. search: str | None = None,
  154. ) -> tuple[list[LogEntry], int]:
  155. """Read and parse log entries from file with optional filtering."""
  156. log_file = settings.log_dir / "bambuddy.log"
  157. if not log_file.exists():
  158. return [], 0
  159. entries: list[LogEntry] = []
  160. total_lines = 0
  161. try:
  162. with open(log_file, encoding="utf-8", errors="replace") as f:
  163. # Read all lines and process
  164. lines = f.readlines()
  165. total_lines = len(lines)
  166. # Parse lines in reverse order (newest first)
  167. current_entry: LogEntry | None = None
  168. multi_line_buffer: list[str] = []
  169. for line in reversed(lines):
  170. parsed = _parse_log_line(line)
  171. if parsed:
  172. # Found a new log entry start
  173. if current_entry:
  174. # Apply filters and add previous entry (without multi_line_buffer - it belongs to new entry)
  175. should_include = True
  176. # Level filter
  177. if level_filter and current_entry.level.upper() != level_filter.upper():
  178. should_include = False
  179. # Search filter (case-insensitive)
  180. if search and should_include:
  181. search_lower = search.lower()
  182. if not (
  183. search_lower in current_entry.message.lower()
  184. or search_lower in current_entry.logger_name.lower()
  185. ):
  186. should_include = False
  187. if should_include:
  188. entries.append(current_entry)
  189. if len(entries) >= limit:
  190. break
  191. # Set new entry and attach any accumulated multi-line content to it
  192. # (in reverse order, continuation lines come before their parent entry)
  193. current_entry = parsed
  194. if multi_line_buffer:
  195. current_entry.message += "\n" + "\n".join(reversed(multi_line_buffer))
  196. multi_line_buffer = []
  197. elif line.strip():
  198. # Continuation of multi-line log entry (will be attached to next parsed entry)
  199. multi_line_buffer.append(line.rstrip())
  200. # Don't forget the last (oldest) entry
  201. # Note: any remaining multi_line_buffer would be orphaned lines before the first entry
  202. if current_entry and len(entries) < limit:
  203. should_include = True
  204. if level_filter and current_entry.level.upper() != level_filter.upper():
  205. should_include = False
  206. if search and should_include:
  207. search_lower = search.lower()
  208. if not (
  209. search_lower in current_entry.message.lower()
  210. or search_lower in current_entry.logger_name.lower()
  211. ):
  212. should_include = False
  213. if should_include:
  214. entries.append(current_entry)
  215. except Exception as e:
  216. logger.error("Error reading log file: %s", e)
  217. return [], 0
  218. # Entries are already in newest-first order
  219. return entries, total_lines
  220. @router.get("/logs", response_model=LogsResponse)
  221. async def get_logs(
  222. limit: int = Query(200, ge=1, le=1000, description="Maximum number of entries to return"),
  223. level: str | None = Query(None, description="Filter by log level (DEBUG, INFO, WARNING, ERROR)"),
  224. search: str | None = Query(None, description="Search in message or logger name"),
  225. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  226. ):
  227. """Get recent application log entries with optional filtering."""
  228. entries, total_lines = _read_log_entries(limit=limit, level_filter=level, search=search)
  229. return LogsResponse(
  230. entries=entries,
  231. total_in_file=total_lines,
  232. filtered_count=len(entries),
  233. )
  234. @router.delete("/logs")
  235. async def clear_logs(
  236. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  237. ):
  238. """Clear the application log file."""
  239. log_file = settings.log_dir / "bambuddy.log"
  240. if log_file.exists():
  241. try:
  242. # Truncate the file instead of deleting (keeps file handles valid)
  243. with open(log_file, "w", encoding="utf-8") as f:
  244. f.write("")
  245. logger.info("Log file cleared by user")
  246. return {"message": "Logs cleared successfully"}
  247. except Exception as e:
  248. logger.error("Error clearing log file: %s", e, exc_info=True)
  249. raise HTTPException(status_code=500, detail="Failed to clear logs. Check server logs for details.")
  250. return {"message": "Log file does not exist"}
  251. def _sanitize_path(path: str) -> str:
  252. """Remove username from paths for privacy."""
  253. # Replace /home/username/ or /Users/username/ with /home/[user]/
  254. path = re.sub(r"/home/[^/]+/", "/home/[user]/", path)
  255. path = re.sub(r"/Users/[^/]+/", "/Users/[user]/", path)
  256. # Replace /opt/username/ patterns
  257. path = re.sub(r"/opt/[^/]+/", "/opt/[user]/", path)
  258. return path
  259. def _detect_docker_network_mode() -> str:
  260. """Detect Docker network mode by checking for host-level interfaces.
  261. In host mode the container shares the host network namespace, so Docker
  262. infrastructure interfaces (docker0, br-*, veth*) are visible. In bridge
  263. mode the container is isolated and only sees its own veth (named eth0).
  264. """
  265. try:
  266. import socket
  267. for _idx, name in socket.if_nameindex():
  268. if name.startswith(("docker", "br-", "veth", "virbr")):
  269. return "host"
  270. except Exception:
  271. pass
  272. return "bridge"
  273. def _mask_subnet(subnet: str) -> str:
  274. """Mask the first two octets of a subnet string. e.g. '192.168.1.0/24' -> 'x.x.1.0/24'."""
  275. try:
  276. parts = subnet.split(".")
  277. if len(parts) >= 4:
  278. parts[0] = "x"
  279. parts[1] = "x"
  280. return ".".join(parts)
  281. except Exception:
  282. pass
  283. return subnet
  284. def _anonymize_mqtt_broker(broker: str) -> str:
  285. """Anonymize MQTT broker address. IPs become [IP], hostnames become *.domain."""
  286. if not broker:
  287. return ""
  288. try:
  289. ipaddress.ip_address(broker)
  290. return "[IP]"
  291. except ValueError:
  292. # It's a hostname — show *.domain pattern
  293. parts = broker.split(".")
  294. if len(parts) >= 2:
  295. return "*." + ".".join(parts[-2:])
  296. return broker
  297. async def _check_port(ip: str, port: int, timeout: float = 2.0) -> bool:
  298. """Test TCP connectivity to ip:port. Returns True if reachable."""
  299. try:
  300. _reader, writer = await asyncio.wait_for(asyncio.open_connection(ip, port), timeout=timeout)
  301. writer.close()
  302. await writer.wait_closed()
  303. return True
  304. except Exception:
  305. return False
  306. def _get_container_memory_limit() -> int | None:
  307. """Read cgroup memory limit. Returns bytes or None."""
  308. # cgroup v2
  309. v2 = Path("/sys/fs/cgroup/memory.max")
  310. if v2.exists():
  311. try:
  312. val = v2.read_text().strip()
  313. if val != "max":
  314. return int(val)
  315. except Exception:
  316. pass
  317. # cgroup v1
  318. v1 = Path("/sys/fs/cgroup/memory/memory.limit_in_bytes")
  319. if v1.exists():
  320. try:
  321. val = int(v1.read_text().strip())
  322. # Values near page-aligned max (2^63-4096) mean unlimited
  323. if val < 2**62:
  324. return val
  325. except Exception:
  326. pass
  327. return None
  328. def _format_bytes(size_bytes: int) -> str:
  329. """Format bytes into human-readable string."""
  330. if size_bytes < 1024:
  331. return f"{size_bytes} B"
  332. if size_bytes < 1024 * 1024:
  333. return f"{size_bytes / 1024:.1f} KB"
  334. if size_bytes < 1024 * 1024 * 1024:
  335. return f"{size_bytes / (1024 * 1024):.1f} MB"
  336. return f"{size_bytes / (1024 * 1024 * 1024):.2f} GB"
  337. async def _collect_auth_info(db: AsyncSession) -> dict:
  338. """Auth-related configuration that's stored OUTSIDE the settings table.
  339. The settings-table passthrough already captures `ldap_*`, `advanced_auth_enabled`,
  340. etc. The blocks below come from dedicated tables that the support bundle did
  341. not previously surface — every recent SSO / 2FA / group bug needed this data
  342. to triage.
  343. """
  344. from backend.app.models.api_key import APIKey
  345. from backend.app.models.group import Group
  346. from backend.app.models.long_lived_token import LongLivedToken
  347. from backend.app.models.oidc_provider import OIDCProvider, UserOIDCLink
  348. from backend.app.models.user_otp_code import UserOTPCode
  349. from backend.app.models.user_totp import UserTOTP
  350. now = datetime.now(timezone.utc)
  351. auth: dict = {}
  352. # OIDC providers — names are public (login-button labels), no secrets.
  353. providers_result = await db.execute(select(OIDCProvider).order_by(OIDCProvider.id))
  354. providers = providers_result.scalars().all()
  355. oidc_list = []
  356. for p in providers:
  357. # Count linked users per provider — separate query so failure on one
  358. # provider doesn't blank the whole list.
  359. try:
  360. link_count = (
  361. await db.execute(select(func.count(UserOIDCLink.id)).where(UserOIDCLink.provider_id == p.id))
  362. ).scalar() or 0
  363. except Exception:
  364. link_count = None
  365. oidc_list.append(
  366. {
  367. "name": p.name,
  368. "is_enabled": p.is_enabled,
  369. "scopes": p.scopes,
  370. "email_claim": p.email_claim,
  371. "require_email_verified": p.require_email_verified,
  372. "auto_create_users": p.auto_create_users,
  373. "auto_link_existing_accounts": p.auto_link_existing_accounts,
  374. "has_default_group": p.default_group_id is not None,
  375. "has_icon": bool(p.icon_url),
  376. "linked_user_count": link_count,
  377. }
  378. )
  379. auth["oidc_providers"] = oidc_list
  380. # 2FA enrollment — counts only, no per-user data.
  381. totp_enabled = (
  382. await db.execute(select(func.count(UserTOTP.id)).where(UserTOTP.is_enabled.is_(True)))
  383. ).scalar() or 0
  384. auth["users_with_totp"] = totp_enabled
  385. # Active (not-yet-expired, not-yet-used) email OTP codes — bounded count;
  386. # spikes here would point at someone hammering the email OTP flow.
  387. email_otp_pending = (
  388. await db.execute(
  389. select(func.count(UserOTPCode.id)).where(
  390. UserOTPCode.used.is_(False),
  391. UserOTPCode.expires_at > now,
  392. )
  393. )
  394. ).scalar() or 0
  395. auth["email_otp_codes_pending"] = email_otp_pending
  396. # API keys
  397. api_keys_total = (await db.execute(select(func.count(APIKey.id)))).scalar() or 0
  398. api_keys_enabled = (await db.execute(select(func.count(APIKey.id)).where(APIKey.enabled.is_(True)))).scalar() or 0
  399. api_keys_expired = (
  400. await db.execute(
  401. select(func.count(APIKey.id)).where(
  402. APIKey.expires_at.is_not(None),
  403. APIKey.expires_at < now,
  404. )
  405. )
  406. ).scalar() or 0
  407. auth["api_keys_total"] = api_keys_total
  408. auth["api_keys_enabled"] = api_keys_enabled
  409. auth["api_keys_expired"] = api_keys_expired
  410. # Long-lived tokens (camera-stream tokens used by kiosks etc.)
  411. llt_total = (await db.execute(select(func.count(LongLivedToken.id)))).scalar() or 0
  412. llt_active = (
  413. await db.execute(
  414. select(func.count(LongLivedToken.id)).where(
  415. LongLivedToken.revoked_at.is_(None),
  416. LongLivedToken.expires_at > now,
  417. )
  418. )
  419. ).scalar() or 0
  420. auth["long_lived_tokens_total"] = llt_total
  421. auth["long_lived_tokens_active"] = llt_active
  422. # Groups — system vs custom split matters for permission triage.
  423. groups_system = (await db.execute(select(func.count(Group.id)).where(Group.is_system.is_(True)))).scalar() or 0
  424. groups_custom = (await db.execute(select(func.count(Group.id)).where(Group.is_system.is_(False)))).scalar() or 0
  425. auth["groups_system"] = groups_system
  426. auth["groups_custom"] = groups_custom
  427. return auth
  428. async def _collect_library_info(db: AsyncSession) -> dict:
  429. """Library file / folder totals, including external-link and trash counts."""
  430. from backend.app.models.external_link import ExternalLink
  431. from backend.app.models.library import LibraryFile, LibraryFolder
  432. info: dict = {}
  433. info["library_files_total"] = (
  434. await db.execute(select(func.count(LibraryFile.id)).where(LibraryFile.deleted_at.is_(None)))
  435. ).scalar() or 0
  436. info["library_files_in_trash"] = (
  437. await db.execute(select(func.count(LibraryFile.id)).where(LibraryFile.deleted_at.is_not(None)))
  438. ).scalar() or 0
  439. info["library_folders_total"] = (await db.execute(select(func.count(LibraryFolder.id)))).scalar() or 0
  440. info["external_folders_total"] = (
  441. await db.execute(select(func.count(LibraryFolder.id)).where(LibraryFolder.is_external.is_(True)))
  442. ).scalar() or 0
  443. info["external_links_total"] = (await db.execute(select(func.count(ExternalLink.id)))).scalar() or 0
  444. # MakerWorld imports — counted here because they're LibraryFile rows with
  445. # source_type='makerworld' (the import path doesn't have its own table).
  446. info["makerworld_imports_total"] = (
  447. await db.execute(
  448. select(func.count(LibraryFile.id)).where(
  449. LibraryFile.deleted_at.is_(None),
  450. LibraryFile.source_type == "makerworld",
  451. )
  452. )
  453. ).scalar() or 0
  454. return info
  455. async def _collect_inventory_info(db: AsyncSession) -> dict:
  456. """Spool / k-profile totals from the inventory feature."""
  457. from backend.app.models.spool import Spool
  458. from backend.app.models.spool_k_profile import SpoolKProfile
  459. from backend.app.models.spoolman_k_profile import SpoolmanKProfile
  460. info: dict = {}
  461. info["spools_internal"] = (await db.execute(select(func.count(Spool.id)))).scalar() or 0
  462. info["k_profiles_internal"] = (await db.execute(select(func.count(SpoolKProfile.id)))).scalar() or 0
  463. info["k_profiles_spoolman"] = (await db.execute(select(func.count(SpoolmanKProfile.id)))).scalar() or 0
  464. return info
  465. async def _collect_queue_info(db: AsyncSession) -> dict:
  466. """Print-queue health: pending count + oldest pending age."""
  467. from backend.app.models.print_queue import PrintQueueItem
  468. info: dict = {}
  469. info["pending_total"] = (
  470. await db.execute(select(func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending"))
  471. ).scalar() or 0
  472. info["manual_start_pending"] = (
  473. await db.execute(
  474. select(func.count(PrintQueueItem.id)).where(
  475. PrintQueueItem.status == "pending",
  476. PrintQueueItem.manual_start.is_(True),
  477. )
  478. )
  479. ).scalar() or 0
  480. # Oldest pending item — derived from created_at to detect items stuck in queue
  481. # (target printer offline, missing filament match, etc.).
  482. oldest_row = (
  483. await db.execute(
  484. select(PrintQueueItem.created_at)
  485. .where(PrintQueueItem.status == "pending")
  486. .order_by(PrintQueueItem.created_at)
  487. .limit(1)
  488. )
  489. ).scalar_one_or_none()
  490. if oldest_row is not None:
  491. # created_at is naive in this codebase (server_default=func.now()); compare
  492. # against naive utc-now to get the actual age without TZ-conversion surprises.
  493. age = (datetime.now() - oldest_row).total_seconds()
  494. info["oldest_pending_age_seconds"] = int(age)
  495. else:
  496. info["oldest_pending_age_seconds"] = None
  497. return info
  498. async def _collect_maintenance_info(db: AsyncSession) -> dict:
  499. """Maintenance schedule totals: enabled items count + last-serviced-never count."""
  500. from backend.app.models.maintenance import PrinterMaintenance
  501. info: dict = {}
  502. info["items_total"] = (await db.execute(select(func.count(PrinterMaintenance.id)))).scalar() or 0
  503. info["items_enabled"] = (
  504. await db.execute(select(func.count(PrinterMaintenance.id)).where(PrinterMaintenance.enabled.is_(True)))
  505. ).scalar() or 0
  506. return info
  507. async def _collect_github_backup_info(db: AsyncSession) -> dict:
  508. """GitHub-backup configs: count per provider + recent-failure indicator."""
  509. from backend.app.models.github_backup import GitHubBackupConfig
  510. rows = (await db.execute(select(GitHubBackupConfig))).scalars().all()
  511. providers_used: dict[str, int] = {}
  512. last_failure_count = 0
  513. schedule_enabled_count = 0
  514. for cfg in rows:
  515. providers_used[cfg.provider] = providers_used.get(cfg.provider, 0) + 1
  516. if cfg.last_backup_status == "failed":
  517. last_failure_count += 1
  518. if cfg.schedule_enabled:
  519. schedule_enabled_count += 1
  520. return {
  521. "configs_total": len(rows),
  522. "providers_used": providers_used,
  523. "schedule_enabled_count": schedule_enabled_count,
  524. "last_failure_count": last_failure_count,
  525. }
  526. async def _check_url_reachable(url: str, timeout: float = 2.0) -> bool | None:
  527. """Single HEAD/GET ping with a short timeout. Returns None if URL is empty."""
  528. if not url or not url.strip():
  529. return None
  530. try:
  531. import httpx
  532. async with httpx.AsyncClient(timeout=timeout, verify=False) as client: # noqa: S501 — local sidecars often use self-signed
  533. r = await client.get(url, follow_redirects=False)
  534. # Anything that returned a status code counts as reachable, even 404
  535. # (the API server is up, just the path was wrong) — separates network
  536. # failure from configuration mistakes for the user.
  537. return r.status_code is not None
  538. except Exception:
  539. return False
  540. async def _fetch_slicer_health(url: str, timeout: float = 2.0) -> dict | None:
  541. """Fetch ``/health`` from a slicer sidecar and extract the CLI version.
  542. Returns ``None`` when ``url`` is empty (so the caller can distinguish
  543. "not configured" from "unreachable"). On any failure to fetch or parse,
  544. returns ``{"reachable": False, "version": None}``. The slicer-API wrapper
  545. labels both sidecars' CLI under ``checks.orcaslicer`` regardless of which
  546. slicer is actually bundled (cosmetic wrapper bug), so we read the version
  547. from whichever non-``dataPath`` child key exists rather than hardcoding
  548. one. This lets the bundle reviewer answer "is the user running the image
  549. they think they are?" without a separate curl round-trip.
  550. """
  551. if not url or not url.strip():
  552. return None
  553. health_url = url.rstrip("/") + "/health"
  554. try:
  555. import httpx
  556. async with httpx.AsyncClient(timeout=timeout, verify=False) as client: # noqa: S501 — local sidecars often use self-signed
  557. r = await client.get(health_url, follow_redirects=False)
  558. if r.status_code != 200:
  559. return {"reachable": True, "version": None}
  560. try:
  561. data = r.json()
  562. except Exception:
  563. return {"reachable": True, "version": None}
  564. checks = data.get("checks") if isinstance(data, dict) else None
  565. if not isinstance(checks, dict):
  566. return {"reachable": True, "version": None}
  567. for key, value in checks.items():
  568. if key == "dataPath":
  569. continue
  570. if isinstance(value, dict) and "version" in value:
  571. return {"reachable": True, "version": value.get("version")}
  572. return {"reachable": True, "version": None}
  573. except Exception:
  574. return {"reachable": False, "version": None}
  575. async def _collect_slicer_api_info() -> dict:
  576. """Reachability check for configured slicer-API sidecars.
  577. Mirrors the URL-resolution precedence used by the real slicer routes
  578. (``archives.py:_slice_for_archive`` and ``library.py``) — DB setting first,
  579. falling back to ``app_settings.bambu_studio_api_url`` / ``slicer_api_url``
  580. which themselves respect the ``BAMBU_STUDIO_API_URL`` / ``SLICER_API_URL``
  581. env vars and default to ``http://localhost:3001`` / ``http://localhost:3003``.
  582. A bundle-time reachability check that only looked at the DB setting would
  583. return ``null`` for every user who runs the sidecar via env var or on the
  584. default port — i.e. most users.
  585. Also reads URLs directly from ``Settings.value`` rather than from
  586. ``info["settings"]``, which has already been redacted by the time the
  587. integrations block runs (``bambu_studio_api_url`` matches the ``url``
  588. keyword filter, so its value there is ``"[REDACTED]"`` and pinging that
  589. crashes httpx).
  590. """
  591. async with async_session() as db:
  592. keys_we_need = (
  593. "use_slicer_api",
  594. "preferred_slicer",
  595. "bambu_studio_api_url",
  596. "orcaslicer_api_url",
  597. )
  598. rows = (await db.execute(select(Settings).where(Settings.key.in_(keys_we_need)))).scalars().all()
  599. raw = {s.key: (s.value or "") for s in rows}
  600. # Resolve with the same DB-then-env-then-default precedence as the route
  601. # that the slicer-API client actually uses, so the bundle reflects what
  602. # the running app would resolve at request time.
  603. bs_db = raw.get("bambu_studio_api_url", "").strip()
  604. oc_db = raw.get("orcaslicer_api_url", "").strip()
  605. bs_url = bs_db or (settings.bambu_studio_api_url or "").strip()
  606. oc_url = oc_db or (settings.slicer_api_url or "").strip()
  607. info: dict = {
  608. "enabled": (raw.get("use_slicer_api", "false") or "false").lower() == "true",
  609. "preferred": raw.get("preferred_slicer", ""),
  610. # Layer accounting helps triage: was the URL set in the DB, or are
  611. # we falling through to the env-var / default? "Reachable but no
  612. # DB setting" is the env-var case.
  613. "bambu_studio_url_set_in_db": bool(bs_db),
  614. "orcaslicer_url_set_in_db": bool(oc_db),
  615. # Effective URL is the resolved one — kept as a host-portion-only
  616. # echo so we can confirm it's the expected sidecar without leaking
  617. # the full URL (which `url` keyword would have redacted anyway).
  618. "bambu_studio_url_source": ("db" if bs_db else ("env_or_default" if bs_url else "unset")),
  619. "orcaslicer_url_source": ("db" if oc_db else ("env_or_default" if oc_url else "unset")),
  620. }
  621. if info["enabled"]:
  622. bs_health, oc_health = await asyncio.gather(
  623. _fetch_slicer_health(bs_url),
  624. _fetch_slicer_health(oc_url),
  625. )
  626. info["bambu_studio_reachable"] = (bs_health or {}).get("reachable") if bs_health is not None else None
  627. info["bambu_studio_version"] = (bs_health or {}).get("version") if bs_health is not None else None
  628. info["orcaslicer_reachable"] = (oc_health or {}).get("reachable") if oc_health is not None else None
  629. info["orcaslicer_version"] = (oc_health or {}).get("version") if oc_health is not None else None
  630. return info
  631. def _parse_obico_enabled_printers(raw: str) -> set[int]:
  632. """Parse the comma-separated `obico_enabled_printers` setting. Same shape as
  633. obico_detection.py uses but tolerant of legacy formats."""
  634. if not raw or not raw.strip():
  635. return set()
  636. result: set[int] = set()
  637. for token in raw.split(","):
  638. token = token.strip()
  639. if not token:
  640. continue
  641. try:
  642. result.add(int(token))
  643. except ValueError:
  644. continue
  645. return result
  646. async def _collect_support_info() -> dict:
  647. """Collect all support information."""
  648. in_docker = is_running_in_docker()
  649. info = {
  650. "generated_at": datetime.now().isoformat(),
  651. "app": {
  652. "version": APP_VERSION,
  653. "debug_mode": settings.debug,
  654. },
  655. "system": {
  656. "platform": platform.system(),
  657. "platform_release": platform.release(),
  658. "platform_version": platform.version(),
  659. "architecture": platform.machine(),
  660. "python_version": platform.python_version(),
  661. },
  662. "environment": {
  663. "docker": in_docker,
  664. "data_dir": _sanitize_path(str(settings.base_dir)),
  665. "log_dir": _sanitize_path(str(settings.log_dir)),
  666. "timezone": os.environ.get("TZ", ""),
  667. },
  668. "database": {},
  669. "printers": [],
  670. "settings": {},
  671. }
  672. # Docker-specific info
  673. if in_docker:
  674. try:
  675. mem_limit = _get_container_memory_limit()
  676. info["docker"] = {
  677. "container_memory_limit_bytes": mem_limit,
  678. "container_memory_limit_formatted": _format_bytes(mem_limit) if mem_limit else None,
  679. "network_mode_hint": _detect_docker_network_mode(),
  680. }
  681. except Exception:
  682. logger.debug("Failed to collect Docker info", exc_info=True)
  683. async with async_session() as db:
  684. # Database stats
  685. result = await db.execute(select(func.count(PrintArchive.id)))
  686. info["database"]["archives_total"] = result.scalar() or 0
  687. result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "completed"))
  688. info["database"]["archives_completed"] = result.scalar() or 0
  689. result = await db.execute(select(func.count(Printer.id)))
  690. info["database"]["printers_total"] = result.scalar() or 0
  691. result = await db.execute(select(func.count(Filament.id)))
  692. info["database"]["filaments_total"] = result.scalar() or 0
  693. result = await db.execute(select(func.count(Project.id)))
  694. info["database"]["projects_total"] = result.scalar() or 0
  695. result = await db.execute(select(func.count(SmartPlug.id)))
  696. info["database"]["smart_plugs_total"] = result.scalar() or 0
  697. # Printer info (anonymized - no names, IPs, or serials)
  698. result = await db.execute(select(Printer))
  699. printers = result.scalars().all()
  700. statuses = printer_manager.get_all_statuses()
  701. # Pre-load the obico per-printer enabled-list. Settings are loaded later
  702. # in this function (and would overwrite this key in info["settings"]),
  703. # so do a targeted query here for the per-printer flag below.
  704. obico_enabled_set: set[int] = set()
  705. try:
  706. obico_row = (
  707. await db.execute(select(Settings).where(Settings.key == "obico_enabled_printers"))
  708. ).scalar_one_or_none()
  709. if obico_row is not None:
  710. obico_enabled_set = _parse_obico_enabled_printers(obico_row.value)
  711. except Exception:
  712. logger.debug("Failed to load obico_enabled_printers", exc_info=True)
  713. # Check reachability in parallel
  714. reachability_tasks = [_check_port(p.ip_address, 8883) for p in printers]
  715. reachable_results = await asyncio.gather(*reachability_tasks, return_exceptions=True)
  716. for i, printer in enumerate(printers):
  717. state = statuses.get(printer.id)
  718. reachable = reachable_results[i] if not isinstance(reachable_results[i], Exception) else False
  719. # Count AMS units and trays from raw_data
  720. ams_unit_count = 0
  721. ams_tray_count = 0
  722. has_vt_tray = False
  723. if state:
  724. ams_data = state.raw_data.get("ams")
  725. if isinstance(ams_data, list):
  726. ams_units = ams_data
  727. elif isinstance(ams_data, dict) and "ams" in ams_data:
  728. ams_units = ams_data["ams"] if isinstance(ams_data["ams"], list) else []
  729. else:
  730. ams_units = []
  731. ams_unit_count = len(ams_units)
  732. for unit in ams_units:
  733. trays = unit.get("tray", [])
  734. ams_tray_count += len([t for t in trays if t.get("tray_type")])
  735. has_vt_tray = bool(state.raw_data.get("vt_tray"))
  736. info["printers"].append(
  737. {
  738. "index": i + 1,
  739. "model": printer.model or "Unknown",
  740. "nozzle_count": printer.nozzle_count,
  741. "is_active": printer.is_active,
  742. "mqtt_connected": state.connected if state else False,
  743. "state": state.state if state else "unknown",
  744. "firmware_version": state.firmware_version if state else None,
  745. "wifi_signal": state.wifi_signal if state else None,
  746. "reachable": bool(reachable),
  747. "ams_unit_count": ams_unit_count,
  748. "ams_tray_count": ams_tray_count,
  749. "has_vt_tray": has_vt_tray,
  750. "external_camera_configured": bool(printer.external_camera_url),
  751. "plate_detection_enabled": printer.plate_detection_enabled,
  752. "obico_enabled": printer.id in obico_enabled_set,
  753. "hms_error_count": len(state.hms_errors) if state else 0,
  754. "developer_mode": state.developer_mode if state else None,
  755. "nozzle_rack_count": len(state.nozzle_rack) if state else 0,
  756. }
  757. )
  758. # Virtual printers
  759. try:
  760. from backend.app.models.virtual_printer import VirtualPrinter
  761. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS, virtual_printer_manager
  762. result = await db.execute(select(VirtualPrinter).order_by(VirtualPrinter.id))
  763. vps = result.scalars().all()
  764. info["virtual_printers"] = []
  765. for vp in vps:
  766. instance = virtual_printer_manager.get_instance(vp.id)
  767. status = instance.get_status() if instance else None
  768. model_code = vp.model or "C12"
  769. info["virtual_printers"].append(
  770. {
  771. "index": vp.id,
  772. "enabled": vp.enabled,
  773. "mode": vp.mode,
  774. "model": model_code,
  775. "model_name": VIRTUAL_PRINTER_MODELS.get(model_code, model_code),
  776. "has_target_printer": vp.target_printer_id is not None,
  777. "has_bind_ip": bool(vp.bind_ip),
  778. "running": status.get("running", False) if status else False,
  779. "pending_files": status.get("pending_files", 0) if status else 0,
  780. }
  781. )
  782. except Exception:
  783. logger.debug("Failed to collect virtual printer info", exc_info=True)
  784. # All settings — sensitive values are redacted rather than dropped so
  785. # new settings automatically show up in support bundles without a code
  786. # change. The value is replaced with "[REDACTED]" but the key is kept
  787. # so we can still see which integrations are configured.
  788. result = await db.execute(select(Settings))
  789. all_settings = result.scalars().all()
  790. sensitive_keys = {
  791. "access_code",
  792. "password",
  793. "token",
  794. "secret",
  795. "api_key",
  796. "auth_key", # Tailscale auth keys: virtual_printer_tailscale_auth_key
  797. "installation_id",
  798. "cloud_token",
  799. "mqtt_password",
  800. "email",
  801. "username",
  802. "vapid",
  803. "private_key",
  804. "public_key",
  805. "webhook",
  806. "url",
  807. "path", # Filesystem paths may contain usernames
  808. "config", # URLs may contain IPs, configs may have embedded secrets
  809. "_ip", # IP address fields (e.g. virtual_printer_remote_interface_ip)
  810. "host",
  811. "broker", # MQTT broker hostname / IP — network exposure
  812. "credential",
  813. }
  814. # Value-based safety net: redact anything whose value carries an
  815. # unambiguous secret prefix, even if the key name didn't match.
  816. # `tskey-` is the Tailscale auth-key prefix — future Tailscale settings
  817. # with unexpected names won't leak just because we forgot to add them.
  818. sensitive_value_prefixes = ("tskey-",)
  819. for s in all_settings:
  820. key_lower = s.key.lower()
  821. value = s.value or ""
  822. if any(sensitive in key_lower for sensitive in sensitive_keys) or any(
  823. value.startswith(prefix) for prefix in sensitive_value_prefixes
  824. ):
  825. # Preserve shape: mark presence without leaking the value
  826. info["settings"][s.key] = "[REDACTED]" if s.value else ""
  827. else:
  828. info["settings"][s.key] = s.value
  829. # Notification providers (anonymized — type/enabled/error status only)
  830. try:
  831. result = await db.execute(select(NotificationProvider))
  832. providers = result.scalars().all()
  833. info["integrations"] = info.get("integrations", {})
  834. info["integrations"]["notification_providers"] = [
  835. {
  836. "type": p.provider_type,
  837. "enabled": p.enabled,
  838. "has_last_error": bool(p.last_error),
  839. }
  840. for p in providers
  841. ]
  842. except Exception:
  843. logger.debug("Failed to collect notification provider info", exc_info=True)
  844. # Database health
  845. try:
  846. from backend.app.core.db_dialect import is_sqlite
  847. if is_sqlite():
  848. result = await db.execute(text("PRAGMA journal_mode"))
  849. journal_mode = result.scalar()
  850. result = await db.execute(text("PRAGMA quick_check"))
  851. quick_check = result.scalar()
  852. db_path = settings.base_dir / "bambuddy.db"
  853. db_size = db_path.stat().st_size if db_path.exists() else 0
  854. wal_path = settings.base_dir / "bambuddy.db-wal"
  855. wal_size = wal_path.stat().st_size if wal_path.exists() else 0
  856. info["database_health"] = {
  857. "backend": "sqlite",
  858. "journal_mode": journal_mode,
  859. "quick_check": quick_check,
  860. "db_size_bytes": db_size,
  861. "wal_size_bytes": wal_size,
  862. }
  863. else:
  864. result = await db.execute(text("SELECT version()"))
  865. pg_version = result.scalar()
  866. result = await db.execute(text("SELECT pg_database_size(current_database())"))
  867. db_size = result.scalar() or 0
  868. info["database_health"] = {
  869. "backend": "postgresql",
  870. "version": pg_version,
  871. "db_size_bytes": db_size,
  872. }
  873. except Exception:
  874. logger.debug("Failed to collect database health info", exc_info=True)
  875. # Auth section — OIDC, 2FA, API keys, long-lived tokens, groups.
  876. # Stored in dedicated tables that the settings-table passthrough doesn't see.
  877. try:
  878. async with async_session() as auth_db:
  879. info["auth"] = await _collect_auth_info(auth_db)
  880. except Exception:
  881. logger.debug("Failed to collect auth info", exc_info=True)
  882. # Library + folder + makerworld import totals
  883. try:
  884. async with async_session() as lib_db:
  885. info["library"] = await _collect_library_info(lib_db)
  886. except Exception:
  887. logger.debug("Failed to collect library info", exc_info=True)
  888. # Spool / k-profile totals (inventory feature)
  889. try:
  890. async with async_session() as inv_db:
  891. info["inventory"] = await _collect_inventory_info(inv_db)
  892. except Exception:
  893. logger.debug("Failed to collect inventory info", exc_info=True)
  894. # Print queue health
  895. try:
  896. async with async_session() as q_db:
  897. info["queue"] = await _collect_queue_info(q_db)
  898. except Exception:
  899. logger.debug("Failed to collect queue info", exc_info=True)
  900. # Maintenance schedules
  901. try:
  902. async with async_session() as m_db:
  903. info["maintenance"] = await _collect_maintenance_info(m_db)
  904. except Exception:
  905. logger.debug("Failed to collect maintenance info", exc_info=True)
  906. # Integrations (lazy imports to avoid circular dependencies)
  907. info.setdefault("integrations", {})
  908. # Spoolman
  909. try:
  910. from backend.app.services.spoolman import get_spoolman_client
  911. client = await get_spoolman_client()
  912. if client:
  913. reachable = await client.health_check()
  914. info["integrations"]["spoolman"] = {"enabled": True, "reachable": reachable}
  915. else:
  916. info["integrations"]["spoolman"] = {"enabled": False, "reachable": False}
  917. except Exception:
  918. logger.debug("Failed to collect Spoolman info", exc_info=True)
  919. # MQTT relay
  920. try:
  921. from backend.app.services.mqtt_relay import mqtt_relay
  922. status = mqtt_relay.get_status()
  923. info["integrations"]["mqtt_relay"] = {
  924. "enabled": status.get("enabled", False),
  925. "connected": status.get("connected", False),
  926. "broker": _anonymize_mqtt_broker(status.get("broker", "")),
  927. "port": status.get("port", 0),
  928. "topic_prefix": status.get("topic_prefix", ""),
  929. }
  930. except Exception:
  931. logger.debug("Failed to collect MQTT relay info", exc_info=True)
  932. # SpoolBuddy devices (anonymized — no hostnames, IPs or device IDs)
  933. try:
  934. async with async_session() as db:
  935. from backend.app.models.spoolbuddy_device import SpoolBuddyDevice
  936. result = await db.execute(select(SpoolBuddyDevice))
  937. devices = result.scalars().all()
  938. info["integrations"]["spoolbuddy"] = {
  939. "device_count": len(devices),
  940. "online_count": sum(
  941. 1
  942. for d in devices
  943. if d.last_seen
  944. and (datetime.now(tz=timezone.utc) - d.last_seen.replace(tzinfo=timezone.utc)).total_seconds() < 30
  945. ),
  946. "devices": [
  947. {
  948. "index": i + 1,
  949. "firmware_version": d.firmware_version,
  950. "has_nfc": d.has_nfc,
  951. "has_scale": d.has_scale,
  952. "nfc_reader_type": d.nfc_reader_type,
  953. "nfc_connection": d.nfc_connection,
  954. "has_backlight": d.has_backlight,
  955. "nfc_ok": d.nfc_ok,
  956. "scale_ok": d.scale_ok,
  957. "uptime_s": d.uptime_s,
  958. "calibration_factor": d.calibration_factor,
  959. "tare_offset": d.tare_offset,
  960. "last_calibrated_at": d.last_calibrated_at.isoformat() if d.last_calibrated_at else None,
  961. "update_status": d.update_status,
  962. }
  963. for i, d in enumerate(devices)
  964. ],
  965. }
  966. except Exception:
  967. logger.debug("Failed to collect SpoolBuddy info", exc_info=True)
  968. # Home Assistant (check ha_enabled setting)
  969. try:
  970. info["integrations"]["homeassistant"] = {
  971. "enabled": info["settings"].get("ha_enabled", "false").lower() == "true",
  972. }
  973. except Exception:
  974. logger.debug("Failed to collect Home Assistant info", exc_info=True)
  975. # GitHub backup — providers + recent-failure counts from github_backup_config.
  976. try:
  977. async with async_session() as gb_db:
  978. info["integrations"]["github_backup"] = await _collect_github_backup_info(gb_db)
  979. except Exception:
  980. logger.debug("Failed to collect GitHub backup info", exc_info=True)
  981. # Slicer-API sidecar reachability (#X1C-investigation-style triage)
  982. try:
  983. info["integrations"]["slicer_api"] = await _collect_slicer_api_info()
  984. except Exception:
  985. logger.debug("Failed to collect slicer-API info", exc_info=True)
  986. # Dependencies
  987. try:
  988. dep_packages = [
  989. "fastapi",
  990. "uvicorn",
  991. "pydantic",
  992. "sqlalchemy",
  993. "paho-mqtt",
  994. "psutil",
  995. "httpx",
  996. "aiofiles",
  997. "cryptography",
  998. "opencv-python-headless",
  999. "numpy",
  1000. ]
  1001. info["dependencies"] = {}
  1002. for pkg in dep_packages:
  1003. try:
  1004. info["dependencies"][pkg] = importlib.metadata.version(pkg)
  1005. except importlib.metadata.PackageNotFoundError:
  1006. info["dependencies"][pkg] = None
  1007. except Exception:
  1008. logger.debug("Failed to collect dependency info", exc_info=True)
  1009. # Log file info
  1010. try:
  1011. log_file = settings.log_dir / "bambuddy.log"
  1012. if log_file.exists():
  1013. size = log_file.stat().st_size
  1014. info["log_file"] = {
  1015. "size_bytes": size,
  1016. "size_formatted": _format_bytes(size),
  1017. }
  1018. else:
  1019. info["log_file"] = {"size_bytes": 0, "size_formatted": "0 B"}
  1020. except Exception:
  1021. logger.debug("Failed to collect log file info", exc_info=True)
  1022. # Network interfaces (subnets with first two octets masked)
  1023. try:
  1024. interfaces = get_network_interfaces()
  1025. info["network"] = {
  1026. "interface_count": len(interfaces),
  1027. "interfaces": [{"name": iface["name"], "subnet": _mask_subnet(iface["subnet"])} for iface in interfaces],
  1028. }
  1029. except Exception:
  1030. logger.debug("Failed to collect network info", exc_info=True)
  1031. # WebSocket connections
  1032. try:
  1033. info["websockets"] = {
  1034. "active_connections": len(ws_manager.active_connections),
  1035. }
  1036. except Exception:
  1037. logger.debug("Failed to collect WebSocket info", exc_info=True)
  1038. return info
  1039. def _sanitize_log_content(content: str, sensitive_strings: dict[str, str] | None = None) -> str:
  1040. """Remove sensitive data from log content."""
  1041. # First, replace known sensitive values (database-aware exact matching)
  1042. # This catches printer names, usernames, and other arbitrary user-chosen strings
  1043. # that regex patterns cannot detect
  1044. if sensitive_strings:
  1045. # Sort by length descending to avoid partial matches (e.g. "My Printer 1" before "My Printer")
  1046. for value, label in sorted(sensitive_strings.items(), key=lambda x: len(x[0]), reverse=True):
  1047. if len(value) < 3:
  1048. continue # Skip very short strings to prevent over-redaction
  1049. content = re.sub(re.escape(value), label, content)
  1050. # Replace credentials in URLs (e.g. http://user:pass@host, rtsps://bblp:code@host)
  1051. content = re.sub(r"((?:https?|rtsps?)://)[^/:@\s]+:[^/@\s]+@", r"\1[CREDENTIALS]@", content)
  1052. # Replace email addresses
  1053. content = re.sub(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b", "[EMAIL]", content)
  1054. # Replace Bambu Lab printer serial numbers (format: 00M/01D/01S/01P/03W + alphanumeric, 12-16 chars total)
  1055. content = re.sub(r"\b0[0-3][A-Z0-9][A-Z0-9]{9,13}\b", "[SERIAL]", content, flags=re.IGNORECASE)
  1056. # Replace IPv4 addresses (skip firmware versions like 01.09.01.00 which have leading zeros)
  1057. content = re.sub(
  1058. 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",
  1059. "[IP]",
  1060. content,
  1061. )
  1062. # Replace paths with usernames
  1063. content = re.sub(r"/home/[^/\s]+/", "/home/[user]/", content)
  1064. content = re.sub(r"/Users/[^/\s]+/", "/Users/[user]/", content)
  1065. content = re.sub(r"/opt/[^/\s]+/", "/opt/[user]/", content)
  1066. return content
  1067. def _get_log_content(max_bytes: int = 10 * 1024 * 1024, sensitive_strings: dict[str, str] | None = None) -> bytes:
  1068. """Get log file content, limited to max_bytes from the end."""
  1069. log_file = settings.log_dir / "bambuddy.log"
  1070. if not log_file.exists():
  1071. return b"Log file not found"
  1072. file_size = log_file.stat().st_size
  1073. if file_size <= max_bytes:
  1074. content = log_file.read_text(encoding="utf-8", errors="replace")
  1075. else:
  1076. # Read last max_bytes
  1077. with open(log_file, "rb") as f:
  1078. f.seek(file_size - max_bytes)
  1079. # Skip partial line at start
  1080. f.readline()
  1081. content = f.read().decode("utf-8", errors="replace")
  1082. # Sanitize sensitive data
  1083. content = _sanitize_log_content(content, sensitive_strings)
  1084. return content.encode("utf-8")
  1085. async def _get_recent_sanitized_logs(max_lines: int = 200) -> str:
  1086. """Get recent log lines, sanitized for inclusion in bug reports."""
  1087. # Collect sensitive strings from DB for redaction
  1088. sensitive_strings: dict[str, str] = {}
  1089. async with async_session() as db:
  1090. result = await db.execute(select(Printer.name, Printer.serial_number, Printer.ip_address, Printer.access_code))
  1091. for name, serial, ip_address, access_code in result.all():
  1092. if name:
  1093. sensitive_strings[name] = "[PRINTER]"
  1094. if serial:
  1095. sensitive_strings[serial] = "[SERIAL]"
  1096. if ip_address:
  1097. sensitive_strings[ip_address] = "[IP]"
  1098. if access_code:
  1099. sensitive_strings[access_code] = "[ACCESS_CODE]"
  1100. result = await db.execute(select(User.username))
  1101. for (username,) in result.all():
  1102. if username:
  1103. sensitive_strings[username] = "[USER]"
  1104. result = await db.execute(select(Settings.value).where(Settings.key == "bambu_cloud_email"))
  1105. cloud_email = result.scalar_one_or_none()
  1106. if cloud_email:
  1107. sensitive_strings[cloud_email] = "[EMAIL]"
  1108. log_file = settings.log_dir / "bambuddy.log"
  1109. if not log_file.exists():
  1110. return ""
  1111. # Read last portion of log file
  1112. try:
  1113. content = log_file.read_text(encoding="utf-8", errors="replace")
  1114. lines = content.splitlines()
  1115. recent = "\n".join(lines[-max_lines:])
  1116. return _sanitize_log_content(recent, sensitive_strings)
  1117. except Exception:
  1118. logger.debug("Failed to read logs for bug report", exc_info=True)
  1119. return ""
  1120. @router.get("/bundle")
  1121. async def generate_support_bundle(
  1122. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1123. ):
  1124. """Generate a support bundle ZIP file for issue reporting."""
  1125. # Check if debug logging is enabled and collect sensitive values for redaction
  1126. async with async_session() as db:
  1127. enabled, _enabled_at = await _get_debug_setting(db)
  1128. if not enabled:
  1129. raise HTTPException(
  1130. status_code=400,
  1131. detail="Debug logging must be enabled before generating a support bundle. "
  1132. "Please enable debug logging, reproduce the issue, then generate the bundle.",
  1133. )
  1134. # Collect known sensitive values for log redaction
  1135. sensitive_strings: dict[str, str] = {}
  1136. # Printer names, serial numbers, IP addresses, and access codes
  1137. result = await db.execute(select(Printer.name, Printer.serial_number, Printer.ip_address, Printer.access_code))
  1138. for name, serial, ip_address, access_code in result.all():
  1139. if name:
  1140. sensitive_strings[name] = "[PRINTER]"
  1141. if serial:
  1142. sensitive_strings[serial] = "[SERIAL]"
  1143. if ip_address:
  1144. sensitive_strings[ip_address] = "[IP]"
  1145. if access_code:
  1146. sensitive_strings[access_code] = "[ACCESS_CODE]"
  1147. # Auth usernames
  1148. result = await db.execute(select(User.username))
  1149. for (username,) in result.all():
  1150. if username:
  1151. sensitive_strings[username] = "[USER]"
  1152. # Bambu Cloud email
  1153. result = await db.execute(select(Settings.value).where(Settings.key == "bambu_cloud_email"))
  1154. cloud_email = result.scalar_one_or_none()
  1155. if cloud_email:
  1156. sensitive_strings[cloud_email] = "[EMAIL]"
  1157. # Collect support info
  1158. support_info = await _collect_support_info()
  1159. # Create ZIP in memory
  1160. zip_buffer = io.BytesIO()
  1161. timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
  1162. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  1163. # Add support info JSON
  1164. zf.writestr("support-info.json", json.dumps(support_info, indent=2, default=str))
  1165. # Add log file
  1166. log_content = _get_log_content(sensitive_strings=sensitive_strings)
  1167. zf.writestr("bambuddy.log", log_content)
  1168. zip_buffer.seek(0)
  1169. filename = f"bambuddy-support-{timestamp}.zip"
  1170. logger.info("Generated support bundle: %s", filename)
  1171. return StreamingResponse(
  1172. zip_buffer, media_type="application/zip", headers={"Content-Disposition": f"attachment; filename={filename}"}
  1173. )
  1174. async def init_debug_logging():
  1175. """Initialize debug logging state from database on startup."""
  1176. try:
  1177. async with async_session() as db:
  1178. enabled, _ = await _get_debug_setting(db)
  1179. if enabled:
  1180. _apply_log_level(True)
  1181. logger.info("Debug logging restored from previous session")
  1182. except Exception as e:
  1183. logger.warning("Could not restore debug logging state: %s", e)