Enhancing trace logging by switching to dev api service.

This commit is contained in:
Roland 2025-12-19 16:42:36 -07:00
parent a02c47cfa1
commit 35853f2a59
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
12 changed files with 173 additions and 18 deletions

View file

@ -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() {
<Header as='h1'>Browser Settings</Header>
<APIButton onClick={clearAll}>Show All Hints</APIButton>
</Segment>
{/* Trace Level Modal - shown when user selects trace level in native mode */}
<Modal
open={traceModalOpen}
onClose={() => !traceSwitching && handleTraceModalCancel()}
size='small'
>
<Modal.Header>
<Icon name='bug'/> Enable Debug Mode for Trace Logging
</Modal.Header>
<Modal.Content>
{traceSwitching ? (
<>
<p>
<Icon name='spinner' loading/>
{traceCountdown > 0
? `Switching to debug mode in ${traceCountdown} seconds...`
: 'Switching API services...'}
</p>
<p style={{color: '#888', fontSize: '0.9em'}}>
The API will restart. This page may temporarily lose connection.
</p>
</>
) : (
<>
<p>
Trace logging requires running the API in debug mode, which has slightly reduced
performance (2 workers instead of 5).
</p>
<p>
This will save your settings and restart the API service. The page may temporarily
lose connection during the switch.
</p>
<p style={{color: '#888', fontSize: '0.9em'}}>
You can switch back to production mode later from the Controller page.
</p>
</>
)}
</Modal.Content>
<Modal.Actions>
<Button
color='grey'
onClick={handleTraceModalCancel}
disabled={traceSwitching}
>
Cancel
</Button>
<Button
color='green'
onClick={handleTraceModalConfirm}
disabled={traceSwitching}
>
<Icon name='check'/> Enable Debug Mode
</Button>
</Modal.Actions>
</Modal>
</Container>;
}

View file

@ -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"]

View file

@ -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

View file

@ -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

View file

@ -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:

View file

@ -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:

View file

@ -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(

View file

@ -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():

View file

@ -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=}')

View file

@ -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.

View file

@ -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

View file

@ -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)