diff --git a/app/src/components/admin/Settings.js b/app/src/components/admin/Settings.js index 1da952fd..b783c1d6 100644 --- a/app/src/components/admin/Settings.js +++ b/app/src/components/admin/Settings.js @@ -1,6 +1,7 @@ import React from "react"; import {SettingsContext, StatusContext} from "../../contexts/contexts"; import {checkUpgrade, postRestart, postShutdown, saveSettings as saveSettingsApi, triggerUpgrade} from "../../api"; +import {getServices, stopService, startService} from "../../api/controller"; import { Button, Divider, @@ -299,6 +300,12 @@ export function SettingsPage() { const {clearAll} = useMessageDismissal(); const dockerized = useDockerized(); + // Trace level modal state + const [traceModalOpen, setTraceModalOpen] = React.useState(false); + const [traceCountdown, setTraceCountdown] = React.useState(5); + const [traceSwitching, setTraceSwitching] = React.useState(false); + const [isDevMode, setIsDevMode] = React.useState(false); + // Get current settings from the API. const {settings, saveSettings, fetchSettings} = React.useContext(SettingsContext); // Used to track changes to the settings form between saves/loads. @@ -310,6 +317,22 @@ export function SettingsPage() { fetchConfigs(); }, []); + // Check if we're running in dev mode (wrolpi-api-dev service) + React.useEffect(() => { + if (!dockerized) { + const checkDevMode = async () => { + try { + const services = await getServices(); + const apiDevService = services.find(s => s.name === 'wrolpi-api-dev'); + setIsDevMode(apiDevService?.status === 'running'); + } catch (e) { + console.error('Failed to check dev mode status:', e); + } + }; + checkDevMode(); + } + }, [dockerized]); + const localFetchSettings = async () => { console.debug('fetching settings...'); try { @@ -322,6 +345,20 @@ export function SettingsPage() { } const localSaveSettings = async (newSettings) => { + // Check if trace level is selected (5 = trace in frontend) + const isTraceLevel = newSettings.log_level === 5; + + // In native mode, if trace is selected and not already in dev mode, show confirmation modal + if (isTraceLevel && !dockerized && !isDevMode) { + setTraceModalOpen(true); + return; + } + + // Otherwise, save normally + await doSaveSettings(newSettings); + } + + const doSaveSettings = async (newSettings) => { setDisabled(true); setPendingSave(true); newSettings.download_timeout = parseInt(newSettings.download_timeout); @@ -335,6 +372,68 @@ export function SettingsPage() { } } + const handleTraceModalConfirm = async () => { + setTraceSwitching(true); + setTraceCountdown(5); + + // Start countdown + const countdownInterval = setInterval(() => { + setTraceCountdown(prev => { + if (prev <= 1) { + clearInterval(countdownInterval); + return 0; + } + return prev - 1; + }); + }, 1000); + + // Wait for countdown + await new Promise(resolve => setTimeout(resolve, 5000)); + + try { + // Save settings first + await doSaveSettings({...state}); + + // Switch to dev mode: stop wrolpi-api, start wrolpi-api-dev + toast({ + type: 'info', + title: 'Switching to Debug Mode', + description: 'Stopping production API and starting debug API...', + time: 3000, + }); + + await stopService('wrolpi-api'); + await startService('wrolpi-api-dev'); + + toast({ + type: 'success', + title: 'Debug Mode Enabled', + description: 'API is now running in debug mode with trace logging enabled.', + time: 5000, + }); + + setIsDevMode(true); + } catch (e) { + console.error('Failed to switch to dev mode:', e); + toast({ + type: 'error', + title: 'Service Switch Failed', + description: `Failed to switch API services: ${e.message}. You may need to manually restart services.`, + time: 10000, + }); + } finally { + setTraceSwitching(false); + setTraceModalOpen(false); + setTraceCountdown(5); + } + } + + const handleTraceModalCancel = () => { + // Reset log level to previous value and close modal + setState({...state, log_level: fromApiLogLevel(settings.log_level)}); + setTraceModalOpen(false); + } + const handleHotspotChange = async () => { let {hotspot_ssid, hotspot_encryption, hotspot_password} = state; // Special string which allows a mobile device to connect to a specific Wi-Fi. @@ -655,6 +754,62 @@ export function SettingsPage() {
Browser Settings
Show All Hints + + {/* Trace Level Modal - shown when user selects trace level in native mode */} + !traceSwitching && handleTraceModalCancel()} + size='small' + > + + Enable Debug Mode for Trace Logging + + + {traceSwitching ? ( + <> +

+ + {traceCountdown > 0 + ? `Switching to debug mode in ${traceCountdown} seconds...` + : 'Switching API services...'} +

+

+ The API will restart. This page may temporarily lose connection. +

+ + ) : ( + <> +

+ Trace logging requires running the API in debug mode, which has slightly reduced + performance (2 workers instead of 5). +

+

+ This will save your settings and restart the API service. The page may temporarily + lose connection during the switch. +

+

+ You can switch back to production mode later from the Controller page. +

+ + )} +
+ + + + +
; } diff --git a/docker/api/Dockerfile b/docker/api/Dockerfile index 663d5fad..59084124 100644 --- a/docker/api/Dockerfile +++ b/docker/api/Dockerfile @@ -17,6 +17,6 @@ COPY main.py /opt/wrolpi/ COPY wrolpi /opt/wrolpi/wrolpi COPY modules /opt/wrolpi/modules -ENTRYPOINT [ "python3", "-OO", "/opt/wrolpi/main.py"] +ENTRYPOINT [ "python3", "/opt/wrolpi/main.py"] # Log level controlled by LOG_LEVEL env var or wrolpi.yaml config (default: info) CMD ["api", "--host", "0.0.0.0"] diff --git a/etc/raspberrypios/wrolpi-api-dev.service b/etc/raspberrypios/wrolpi-api-dev.service index 657bdb2f..c257cf76 100644 --- a/etc/raspberrypios/wrolpi-api-dev.service +++ b/etc/raspberrypios/wrolpi-api-dev.service @@ -6,7 +6,7 @@ Conflicts=wrolpi-api.service [Service] Environment=PYTHONUNBUFFERED=1 -ExecStart=/opt/wrolpi/venv/bin/python -m sanic main:api_app --host 0.0.0.0 --port 8081 -w 1 --reload --debug +ExecStart=/opt/wrolpi/venv/bin/python -m sanic main:api_app --host 0.0.0.0 --port 8081 -w 2 --reload --debug ExecReload=/bin/kill -HUP $MAINPID Group=wrolpi User=wrolpi diff --git a/modules/archive/__init__.py b/modules/archive/__init__.py index 0ac74f9e..56745684 100644 --- a/modules/archive/__init__.py +++ b/modules/archive/__init__.py @@ -301,7 +301,7 @@ async def archive_modeler(): if processed < 19: # Did not reach limit (enumerate is 0-indexed, so 19 = 20 items), do not query again. - if logger.isEnabledFor(TRACE_LEVEL): + if __debug__ and logger.isEnabledFor(TRACE_LEVEL): logger.trace(f'archive_modeler: DONE (processed {processed + 1} files)') break diff --git a/modules/archive/api.py b/modules/archive/api.py index 16b54107..cc59594c 100644 --- a/modules/archive/api.py +++ b/modules/archive/api.py @@ -88,7 +88,7 @@ async def singlefile_upload_switch_handler(url=None): q: multiprocessing.Queue = api_app.shared_ctx.archive_singlefiles - trace_enabled = logger.isEnabledFor(TRACE_LEVEL) + trace_enabled = __debug__ and logger.isEnabledFor(TRACE_LEVEL) if trace_enabled: logger.trace(f'singlefile_upload_switch_handler called for {url}') try: @@ -135,7 +135,7 @@ async def generate_screenshot_switch_handler(archive_id=None): """Used by `post_generate_screenshot` to generate screenshots in the background""" q: multiprocessing.Queue = api_app.shared_ctx.archive_screenshots - trace_enabled = logger.isEnabledFor(TRACE_LEVEL) + trace_enabled = __debug__ and logger.isEnabledFor(TRACE_LEVEL) if trace_enabled: logger.trace(f'generate_screenshot_switch_handler called for archive_id={archive_id}') try: diff --git a/wrolpi/api_utils.py b/wrolpi/api_utils.py index 2b0d80a0..0c7f5971 100644 --- a/wrolpi/api_utils.py +++ b/wrolpi/api_utils.py @@ -198,7 +198,7 @@ def perpetual_signal(event: str = None, sleep: int | float = 1, run_while_testin except Exception as e: logger.error(f'Perpetual worker {event_} had error', exc_info=e) finally: - if logger.isEnabledFor(TRACE_LEVEL): + if __debug__ and logger.isEnabledFor(TRACE_LEVEL): elapsed = int(time() - start) logger.trace(f'perpetual_signal {event_} took {elapsed} seconds') if not cancelled: diff --git a/wrolpi/cmd.py b/wrolpi/cmd.py index bad02dac..0bb74f96 100644 --- a/wrolpi/cmd.py +++ b/wrolpi/cmd.py @@ -130,7 +130,7 @@ async def run_command(cmd: tuple[str | pathlib.Path, ...], cwd: pathlib.Path | s cmd_str = ' '.join(shlex.quote(i) for i in cmd) if log_command: logger.info(f'run_command: running ({timeout=}): {cmd_str}') - elif logger.isEnabledFor(TRACE_LEVEL): + elif __debug__ and logger.isEnabledFor(TRACE_LEVEL): logger.trace(f'run_command: running ({timeout=}): {cmd_str}') proc = await asyncio.create_subprocess_exec( *cmd, @@ -171,7 +171,7 @@ async def run_command(cmd: tuple[str | pathlib.Path, ...], cwd: pathlib.Path | s if log_command: logger.debug( f'run_command: finished ({elapsed=}s) with stdout={len(stdout)} stderr={len(stderr)}: {cmd_str=}') - elif logger.isEnabledFor(TRACE_LEVEL): + elif __debug__ and logger.isEnabledFor(TRACE_LEVEL): logger.trace( f'run_command: finished ({elapsed=}s) with stdout={len(stdout)} stderr={len(stderr)}: {cmd_str=}') return CommandResult( diff --git a/wrolpi/downloader.py b/wrolpi/downloader.py index 5f16ee96..2455a984 100644 --- a/wrolpi/downloader.py +++ b/wrolpi/downloader.py @@ -323,7 +323,7 @@ class Downloader: coro = run_command(cmd, cwd=cwd, timeout=timeout, log_command=debug) result = await self.cancel_wrapper(coro, download) - if logger.isEnabledFor(TRACE_LEVEL): + if __debug__ and logger.isEnabledFor(TRACE_LEVEL): for line in result.stdout.decode().splitlines(): logger.trace(line) for line in result.stderr.decode().splitlines(): diff --git a/wrolpi/files/api.py b/wrolpi/files/api.py index 90d7ac16..0696a48c 100644 --- a/wrolpi/files/api.py +++ b/wrolpi/files/api.py @@ -149,14 +149,14 @@ async def post_search_directories(request, body: schema.DirectoriesSearchRequest session = request.ctx.session path = get_media_directory() / body.path - if logger.isEnabledFor(TRACE_LEVEL): + if __debug__ and logger.isEnabledFor(TRACE_LEVEL): logger.trace(f'post_search_directories: {path=}') try: matching_directories = lib.get_matching_directories(path) except FileNotFoundError: matching_directories = [] - if logger.isEnabledFor(TRACE_LEVEL): + if __debug__ and logger.isEnabledFor(TRACE_LEVEL): logger.trace(f'post_search_directories: {matching_directories=}') # Search Channels by name. @@ -164,7 +164,7 @@ async def post_search_directories(request, body: schema.DirectoriesSearchRequest channels = await search_channels_by_name(session, name=body.path) channel_directories = [dict(path=i.directory, name=i.name) for i in channels] channel_paths = [i['path'] for i in channel_directories] - if logger.isEnabledFor(TRACE_LEVEL): + if __debug__ and logger.isEnabledFor(TRACE_LEVEL): logger.trace(f'post_search_directories: {channel_paths=}') # Search Domains by name. @@ -173,7 +173,7 @@ async def post_search_directories(request, body: schema.DirectoriesSearchRequest # search_domains_by_name returns dicts with 'directory' and 'domain' keys domain_directories = [dict(path=i['directory'], domain=i['domain']) for i in domains] domain_paths = [i['path'] for i in domain_directories] - if logger.isEnabledFor(TRACE_LEVEL): + if __debug__ and logger.isEnabledFor(TRACE_LEVEL): logger.trace(f'post_search_directories: {domain_paths=}') # Get all Directory that match but do not contain the above directories. @@ -188,7 +188,7 @@ async def post_search_directories(request, body: schema.DirectoriesSearchRequest directories = unique_by_predicate(directories, lambda i: i['path']) directories = list(sorted(directories, key=lambda i: i['path']))[:20] - if logger.isEnabledFor(TRACE_LEVEL): + if __debug__ and logger.isEnabledFor(TRACE_LEVEL): logger.trace(f'post_search_directories: {excluded=}') logger.trace(f'post_search_directories: {directories=}') diff --git a/wrolpi/files/downloader.py b/wrolpi/files/downloader.py index 9138e675..c7d65758 100644 --- a/wrolpi/files/downloader.py +++ b/wrolpi/files/downloader.py @@ -36,7 +36,7 @@ class FileDownloader(Downloader, ABC): if not destination: raise UnrecoverableDownloadError(f'Cannot download the file without a destination') - if logger.isEnabledFor(TRACE_LEVEL): + if __debug__ and logger.isEnabledFor(TRACE_LEVEL): logger.trace(f'FileDownloader: downloading {download.url} to {destination}') # Create the destination only if it is within the media directory. diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index 118dab1d..f1782bf5 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -351,7 +351,7 @@ def get_unique_files_by_stem(files: List[pathlib.Path] | Tuple[pathlib.Path, ... -> List[pathlib.Path]: """Returns the first of each Path with a unique stem. Used to detect if a group of files share a stem.""" results = unique_by_predicate(files, lambda i: split_path_stem_and_suffix(i)[0]) - if logger.isEnabledFor(TRACE_LEVEL): + if __debug__ and logger.isEnabledFor(TRACE_LEVEL): logger.trace(f'get_unique_files_by_stem {files=}') logger.trace(f'get_unique_files_by_stem {results=}') return results diff --git a/wrolpi/status.py b/wrolpi/status.py index 5502607e..e7f80c4d 100755 --- a/wrolpi/status.py +++ b/wrolpi/status.py @@ -101,7 +101,7 @@ async def get_iostat_stats() -> IostatInfo: cpu_statuses, _ = partition(lambda i: i['type'] == 'cpu', iostat_stats) _, cpu_stats = cpu_statuses # Use the second status because the first is a lie. - if logger.isEnabledFor(TRACE_LEVEL): + if __debug__ and logger.isEnabledFor(TRACE_LEVEL): logger.trace( f'get_iostat_stats' f' percent_iowait={cpu_stats["percent_iowait"]}' @@ -116,7 +116,7 @@ async def get_iostat_stats() -> IostatInfo: percent_user=cpu_stats['percent_user'], ) except Exception as e: - if logger.isEnabledFor(TRACE_LEVEL): + if __debug__ and logger.isEnabledFor(TRACE_LEVEL): logger.trace(f'get_iostat_stats failed: {e}') warn_iostat_once(e)