diff --git a/AGENTS.md b/AGENTS.md index bd32cfc..c1a45f7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # RustProxy source and documentation maintenance -Current source version: **0.41.0**. The Cargo package and binary are named `rust-proxy`. +Current source version: **0.41.1**. The Cargo package and binary are named `rust-proxy`. Before editing, read [README.md](README.md), the relevant [documentation guide](docs/README.md) and the actual code and tests. Historical release experiments are not current specifications. Use the bundled `src/admin/openapi.json` for API routes and payloads; the source implementation is authoritative for runtime behavior. diff --git a/CHANGELOG.md b/CHANGELOG.md index 382f1b2..7b035c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ Release history focused on **features, settings, default behavior, compatibility and fixes**. Changes to internal code structure and preliminary performance experiments are intentionally omitted. Historical descriptions reflect their respective releases; consult the current documentation for the settings available in the latest release. +## 0.41.1 — Stored logs: rotation fix, per-host log files and rebuilt explorer + +- **Logging — rotation fix:** access logs (shared and per-Vhost) and the error log now notice external rotation (logrotate `create`, `mv`, `rm`) about once per second and reopen the configured path. Up to 0.41.0 RustProxy kept writing into the renamed file until a restart, so after `compress` those records were lost and the stored-log reader showed an old rotation (e.g. `.10.gz`) as the newest data. No `postrotate` or `copytruncate` is needed; a sample logrotate policy is in [Logs](docs/LOGS.md#per-site-files-and-rotation). +- **Logging — redirect and 404 hosts:** with per-Vhost access logs, requests answered by a redirect host go to `.redirect.jsonl` and requests answered by a local 404 host to `.host404.jsonl` instead of `_unmatched.jsonl`; their records carry `redirect_host` / `local_host` (omitted otherwise, also available as custom format fields). They are not counted as Vhost traffic. +- **Stored logs — rebuilt explorer:** sources are grouped per log (Vhosts, Redirect hosts, 404 hosts, Other traffic, shared access log, error log) with a separate **File** picker (current file, `.1`, `.2.gz`, …). Rotations are ordered by number instead of modification time and uncompressed rotations (`.1`) are included; a log is read newest-first so the newest records are always complete, and the status line shows the time range, the files read and how to reach older ones. New **Period** filter (`since_ms`, stops before older rotations), status/protocol-error chips, **← Newer / Older →** paging, an inline search-syntax panel with tap-to-use examples (the old popover opened off-screen on phones), source names instead of file ids, status-coloured cards on phones. API: `/api/file-logs` sources gain `rotation`, `scope` and `site`; queries accept `since_ms` and return `files`, `files_skipped`, `stopped_at_period`, `newest_ms` and `oldest_ms`; `consolidate_vhosts` now merges any log's rotations. +- **Panel CSS:** removed the styles of the old search-syntax popover, the *Merge rotations* switch and the old header-rule titles (and the unused `headerRule` text); shared rules keep their other selectors. +- **Upgrade note:** if logs are rotated externally, restart the service once after upgrading — a process older than 0.41.1 keeps writing into the rotated file until it restarts. +- **Compatibility:** configuration format unchanged. Access-log records gain `redirect_host` / `local_host` only for requests answered by redirect or local 404 hosts. Redirect/404 traffic moves from `_unmatched.jsonl` to its own files when per-Vhost logs are enabled. +- **Verification:** new unit tests for rotation detection (rename, delete, recreate, rate limit), per-site log names, rotation ordering independent of modification time, uncompressed `.1` rotations, newest-first reading, the period filter stopping before older rotations and single-file reads; full suite (1053 library tests, 7 CLI tests), `cargo clippy --all-targets` and `cargo fmt --check` clean. The real binary in headless mode wrote a Vhost, a redirect host, a 404 host and an unknown host to their own files, and after the current files were renamed (as logrotate does) new records went to newly created files within a second. The explorer was exercised in Chrome (desktop and a 390 px phone viewport) on eleven rotations whose oldest file had the newest modification time. Not tested: a real logrotate run and production traffic. + ## 0.41.0 — Conditional routing: request conditions and whole-host rules - **Location conditions (HAProxy `use_backend … if ` style):** a custom location accepts `conditions` — up to 16 tests on `header`, `cookie`, `query` (parameter), `method`, `ip` (client address after trusted forwarding/Cloudflare, `cidr` with IPs or networks), `host` or `country` (GeoIP/Cloudflare), with the operators `equals`, `exists`, `prefix`, `suffix`, `contains`, `regex` and `cidr`, `negate` and `ignore_case`. All conditions must hold (AND); a condition matches when any of its values matches (OR). A location whose conditions fail is skipped and the next candidate is used, so `/api/` + `X-Beta: 1` → beta backends can sit next to a plain `/api/`. For exact paths and prefixes of equal length the conditional location wins; regular expressions are tried in list order, and a conditional regex placed after an identical unconditional one is rejected as unreachable. See [Request conditions](docs/CUSTOM_LOCATIONS.md#request-conditions-routing-by-header-cookie-ip). diff --git a/Cargo.lock b/Cargo.lock index bec3ec4..6d3c362 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,7 +1914,7 @@ dependencies = [ [[package]] name = "rust-proxy" -version = "0.41.0" +version = "0.41.1" dependencies = [ "anyhow", "arc-swap", diff --git a/Cargo.toml b/Cargo.toml index 251f4e0..6b2e0e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-proxy" -version = "0.41.0" +version = "0.41.1" edition = "2021" rust-version = "1.99.1" description = "RustProxy - independent reverse proxy with local administration" diff --git a/docs/LOGS.md b/docs/LOGS.md index c9bea8f..d849711 100644 --- a/docs/LOGS.md +++ b/docs/LOGS.md @@ -22,6 +22,43 @@ Live viewing is **bounded in memory**. Slow consumers may receive a gap/loss ind The authenticated **Logs → Stored logs** page reads the configured structured JSON/JSONL access logs, optional per-Vhost files and optional error log. These files can remain readable even when their current writer is disabled. The explorer supports paging, dynamic columns, sorting, record expansion/Raw JSON and repeated-value analysis. +How to use it (0.41.1): + +- **Source** lists one entry per log, grouped as *Vhosts*, *Redirect hosts*, *404 hosts*, *Other traffic* (`_unmatched`), *Shared access log* and *Error log*. A log includes all its rotations. +- **File** narrows a log to one file: the current file, `.1`, `.2.gz`, … Rotations are always ordered by their number (newest data first), not by file modification time, so a touched or copied `.10.gz` no longer appears first. Uncompressed rotations (`.1` with logrotate `delaycompress`) are included. +- A log is read **newest first**: the current file may use the whole scan budget, and older rotations are read only while budget remains. The status line shows the range of matching records, which files were read and, if older files were left out, how to browse them (choose the file). +- **Period** (15 minutes … 7 days) filters by record time and stops before rotations that are entirely older. **Status chips** filter 2xx/3xx/4xx/5xx or protocol errors on the server. +- **Search syntax** opens as a panel under the search field (also on phones); tap an example to use it. **← Newer / Older →** page through the results. + +### Per-site files and rotation + +With **per-Vhost access logs** enabled, every site has its own file in the configured directory: + +| File | Traffic | +|---|---| +| `.jsonl` | requests handled by a Vhost | +| `.redirect.jsonl` | requests answered by a redirect host (records carry `redirect_host`) | +| `.host404.jsonl` | requests answered by a local 404 host (records carry `local_host`) | +| `_unmatched.jsonl` | requests for hosts that match nothing | + +Before 0.41.1 redirect and 404 hosts were logged to `_unmatched.jsonl` (or the shared file). The extra fields are omitted for other records, so existing parsers are unaffected. + +RustProxy now notices external rotation: about once per second it checks whether the configured path still names the open file and reopens it after `logrotate` (`create` mode), `mv` or deletion. A standard policy is enough — no `postrotate` signal and no `copytruncate` is needed: + +```text +/var/log/rustproxy/*.jsonl /var/log/rustproxy/vhosts/*.jsonl /var/log/rustproxy/error.log { + daily + rotate 14 + compress + delaycompress + missingok + notifempty + create 0600 rustproxy rustproxy +} +``` + +`delaycompress` keeps the last rotation uncompressed for the second during which RustProxy may still finish a write to it. Earlier versions kept writing into the renamed (and, after compression, deleted) file until a restart, so records written after a rotation could be missing from disk; restart the service once after upgrading if you rotate logs externally. + Search uses a restricted case-insensitive query syntax, for example: ```text @@ -48,7 +85,7 @@ For common symptoms: - **502/503/504:** correlate request ID, Vhost and backend health with upstream timeout/connect/TLS errors. - **403/405/429:** inspect ACL, method rule, country or rate limiting. - **Unexpected cache result:** inspect optional `X-Cache` diagnostics and Cache dashboard alongside request logs. -- **Files empty:** enable the correct sink and check permissions, path and rotation state. +- **Files empty:** enable the correct sink and check permissions, path and rotation state. If only old rotations hold data (e.g. the newest records are in `.10.gz` and the current file stays empty), the service was running a version older than 0.41.1 during a rotation; restart it once. - **Protocol failures missing from Live Logs:** inspect configured persistent error/protocol logs instead. Also see [Monitoring](MONITORING.md) and [Troubleshooting](TROUBLESHOOTING.md). diff --git a/langs/en_US.json b/langs/en_US.json index bbef09e..c2f92f4 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -1475,7 +1475,6 @@ "headersDocsProtected": "Protected transport/identity headers (Host, Connection, Content-Length, Forwarded/X-Forwarded-*, WebSocket proof headers and similar) cannot be overridden here.", "headersDocsOrder": "Values are literal; nginx variables are not interpreted. Request rules run before canonical forwarding metadata is applied, and response rules run before final RustProxy security/diagnostic policy.", "cacheColdPolicyTitle": "Hot → cold policy", - "headerRule": "Header rule", "headerRulesEmpty": "No rules yet. Add a rule below.", "headerRuleHelp": "Choose Set, Append or Remove. Transport, forwarding identity and WebSocket protocol headers remain protected.", "locationPreviewTitle": "Effective behavior preview", @@ -2416,21 +2415,12 @@ "openLogs": "Open Logs", "fileLogsSource": "Source", "fileLogsAllSources": "All configured files", - "fileLogsNoSources": "No configured log files are available.", "fileLogsEvent": "Event", "fileLogsPageSize": "Page size", "fileLogsRecord": "Request / reason", "fileLogsEmpty": "No records match the current filters.", - "fileLogsDetails": "Record details", - "fileLogsSelectRecord": "Select a record to inspect its JSON.", "fileLogsSearchPlaceholder": "req: GET AND !country: Poland", - "fileLogsTruncated": "scan limit reached", - "fileLogsSummary": "{from}–{to} of {total} matches · scanned {bytes} / {lines} lines", - "fileLogsMatchedBy": "Matched by", - "fileLogsSni": "SNI", - "fileLogsAuthority": "Authority / Host", "fileLogsColumnsRequired": "At least one Stored Logs column must remain visible.", - "fileLogsSourcesRead": "Configured files", "search": "Search", "all": "All", "clientIp": "Client IP", @@ -2727,7 +2717,6 @@ "vhUaBlockEnabled": "Block User-Agent patterns", "vhUaBlockPatterns": "Blocked User-Agent patterns", "vhUaBlockHelp": "Vhost blocklist. Plain text matches a case-insensitive substring; * is a wildcard. It is enforced in addition to the global blocklist.", - "fileLogsConsolidateVhosts": "Consolidate rotated logs per vhost", "fileLogsAdvancedParser": "Advanced parser · repeated values", "fileLogsAggregateField": "Field to count", "fileLogsAggregateMin": "Minimum repetitions", @@ -2741,7 +2730,6 @@ "fileLogsFiles": "files", "copied": "Copied", "copyValue": "Copy value", - "fileLogsConsolidateShort": "Merge rotations", "fileLogsEntriesTab": "Log entries", "fileLogsCountsTab": "Repeated values", "streamWidgetOverviewDescription": "Configured and running TCP/UDP listeners, including those requiring attention.", @@ -4068,6 +4056,36 @@ "hdrCardTimingHelp": "Timing metrics for browser DevTools; appended to the application's own Server-Timing.", "hdrCardBackendHelp": "Which backend served the request; absent on a cache hit.", "hdrCardBackendTimeHelp": "Time from sending the request to receiving the backend's response headers.", - "hdrPreviewHitNoRequest": "Cache HIT: the request does not reach any backend" + "hdrPreviewHitNoRequest": "Cache HIT: the request does not reach any backend", + "fileLogsFile": "File", + "fileLogsAllFiles": "All rotations, newest first", + "fileLogsCurrentFile": "current file", + "fileLogsPeriod": "Period", + "fileLogsPeriodAll": "Everything read", + "fileLogsPeriod15m": "Last 15 minutes", + "fileLogsPeriod1h": "Last hour", + "fileLogsPeriod24h": "Last 24 hours", + "fileLogsPeriod7d": "Last 7 days", + "fileLogsSyntaxTryHint": "Tap an example to use it:", + "fileLogsChipAll": "All", + "fileLogsChipProtocol": "Protocol errors", + "fileLogsNewer": "← Newer", + "fileLogsOlder": "Older →", + "fileLogsAccessLog": "Access log", + "fileLogsErrorLog": "Error log", + "fileLogsUnmatched": "Unmatched hosts", + "fileLogsScope_vhost": "Vhosts", + "fileLogsScope_redirect": "Redirect hosts", + "fileLogsScope_host404": "404 hosts", + "fileLogsScope_unmatched": "Other traffic", + "fileLogsScope_access": "Shared access log", + "fileLogsScope_error": "Error log", + "fileLogsSummaryShown": "{from}–{to} of {total}", + "fileLogsSummaryRange": "from {from} to {to}", + "fileLogsSummaryFiles": "read: {files}", + "fileLogsSummaryScanned": "{lines} lines / {bytes}", + "fileLogsSummarySkipped": "The newest records are complete; {count} older file(s) were not read within the scan limit. Choose one in “File” to browse it.", + "fileLogsSummaryTruncated": "Scan limit reached: older records in these files were not read. Narrow the period or choose a single file.", + "fileLogsSummaryPeriod": "{count} older file(s) skipped: they are entirely before the selected period." } } diff --git a/langs/pl_pl.json b/langs/pl_pl.json index cff31b7..dc057c3 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -1475,7 +1475,6 @@ "headersDocsProtected": "Chronionych nagłówków transportu/tożsamości (Host, Connection, Content-Length, Forwarded/X-Forwarded-*, nagłówki dowodu WebSocket itd.) nie można tu nadpisywać.", "headersDocsOrder": "Wartości są dosłowne; zmienne nginx nie są interpretowane. Reguły request działają przed nałożeniem kanonicznych danych forwardingu, a response przed końcową polityką bezpieczeństwa/diagnostyki RustProxy.", "cacheColdPolicyTitle": "Polityka hot → cold", - "headerRule": "Reguła nagłówka", "headerRulesEmpty": "Brak reguł. Dodaj regułę poniżej.", "headerRuleHelp": "Wybierz Ustaw, Dodaj lub Usuń. Nagłówki transportowe, tożsamości forwardingu i protokołu WebSocket pozostają chronione.", "locationPreviewTitle": "Podgląd efektywnego działania", @@ -2416,21 +2415,12 @@ "openLogs": "Otwórz Logs", "fileLogsSource": "Źródło", "fileLogsAllSources": "Wszystkie skonfigurowane pliki", - "fileLogsNoSources": "Brak dostępnych skonfigurowanych plików logów.", "fileLogsEvent": "Zdarzenie", "fileLogsPageSize": "Rozmiar strony", "fileLogsRecord": "Żądanie / przyczyna", "fileLogsEmpty": "Brak rekordów pasujących do filtrów.", - "fileLogsDetails": "Szczegóły rekordu", - "fileLogsSelectRecord": "Wybierz rekord, aby zobaczyć jego JSON.", "fileLogsSearchPlaceholder": "req: GET AND !country: Poland", - "fileLogsTruncated": "osiągnięto limit skanowania", - "fileLogsSummary": "{from}–{to} z {total} wyników · przeskanowano {bytes} / {lines} linii", - "fileLogsMatchedBy": "Dopasowanie przez", - "fileLogsSni": "SNI", - "fileLogsAuthority": "Authority / Host", "fileLogsColumnsRequired": "Co najmniej jedna kolumna zapisanych logów musi pozostać widoczna.", - "fileLogsSourcesRead": "Skonfigurowane pliki", "search": "Szukaj", "all": "Wszystkie", "clientIp": "IP klienta", @@ -2727,7 +2717,6 @@ "vhUaBlockEnabled": "Blokuj wzorce User-Agent", "vhUaBlockPatterns": "Blokowane wzorce User-Agent", "vhUaBlockHelp": "Lista blokad dla vhosta. Zwykły tekst dopasowuje fragment bez rozróżniania wielkości liter, a * jest wildcardem. Działa dodatkowo do listy globalnej.", - "fileLogsConsolidateVhosts": "Konsoliduj rotowane logi per vhost", "fileLogsAdvancedParser": "Zaawansowany parser · powtarzające się wartości", "fileLogsAggregateField": "Pole do zliczania", "fileLogsAggregateMin": "Minimalna liczba powtórzeń", @@ -2741,7 +2730,6 @@ "fileLogsFiles": "plików", "copied": "Skopiowano", "copyValue": "Kopiuj wartość", - "fileLogsConsolidateShort": "Scal rotacje", "fileLogsEntriesTab": "Wpisy logów", "fileLogsCountsTab": "Powtarzające się wartości", "streamWidgetOverviewDescription": "Liczba skonfigurowanych i uruchomionych listenerów TCP/UDP oraz wymagających uwagi.", @@ -4068,6 +4056,36 @@ "hdrCardTimingHelp": "Metryki czasu dla DevTools w przeglądarce; dopisywane do własnego Server-Timing aplikacji.", "hdrCardBackendHelp": "Który backend obsłużył żądanie; brak przy trafieniu w cache.", "hdrCardBackendTimeHelp": "Czas od wysłania żądania do otrzymania nagłówków odpowiedzi backendu.", - "hdrPreviewHitNoRequest": "Trafienie w cache: żądanie nie trafia do żadnego backendu" + "hdrPreviewHitNoRequest": "Trafienie w cache: żądanie nie trafia do żadnego backendu", + "fileLogsFile": "Plik", + "fileLogsAllFiles": "Wszystkie rotacje, od najnowszych", + "fileLogsCurrentFile": "bieżący plik", + "fileLogsPeriod": "Okres", + "fileLogsPeriodAll": "Wszystko, co przeczytano", + "fileLogsPeriod15m": "Ostatnie 15 minut", + "fileLogsPeriod1h": "Ostatnia godzina", + "fileLogsPeriod24h": "Ostatnie 24 godziny", + "fileLogsPeriod7d": "Ostatnie 7 dni", + "fileLogsSyntaxTryHint": "Dotknij przykładu, aby go użyć:", + "fileLogsChipAll": "Wszystkie", + "fileLogsChipProtocol": "Błędy protokołu", + "fileLogsNewer": "← Nowsze", + "fileLogsOlder": "Starsze →", + "fileLogsAccessLog": "Log dostępu", + "fileLogsErrorLog": "Log błędów", + "fileLogsUnmatched": "Niedopasowane hosty", + "fileLogsScope_vhost": "Vhosty", + "fileLogsScope_redirect": "Hosty przekierowań", + "fileLogsScope_host404": "Hosty 404", + "fileLogsScope_unmatched": "Pozostały ruch", + "fileLogsScope_access": "Wspólny log dostępu", + "fileLogsScope_error": "Log błędów", + "fileLogsSummaryShown": "{from}–{to} z {total}", + "fileLogsSummaryRange": "od {from} do {to}", + "fileLogsSummaryFiles": "przeczytane: {files}", + "fileLogsSummaryScanned": "{lines} linii / {bytes}", + "fileLogsSummarySkipped": "Najnowsze wpisy są kompletne; {count} starszych plików nie przeczytano w limicie skanowania. Wybierz plik w polu „Plik”, aby go przejrzeć.", + "fileLogsSummaryTruncated": "Osiągnięto limit skanowania: starsze wpisy z tych plików nie zostały przeczytane. Zawęź okres albo wybierz jeden plik.", + "fileLogsSummaryPeriod": "Pominięto {count} starszych plików: w całości są sprzed wybranego okresu." } } diff --git a/src/admin/file_logs.rs b/src/admin/file_logs.rs index 065cb6a..dd12e42 100644 --- a/src/admin/file_logs.rs +++ b/src/admin/file_logs.rs @@ -21,6 +21,42 @@ struct FileLogSource { size: u64, modified_ms: u64, compressed: bool, + /// 0 = file being written; N = rotation `.N` / `.N.gz` (higher is older). + rotation: u32, + /// vhost, redirect, host404, unmatched, access or error. + scope: &'static str, + /// Site id for per-site logs (vhost, redirect or 404 host id). + site: String, +} +/// Splits `.jsonl[.][.gz]` (or `[.][.gz]` for the global logs) +/// into the rotation index; `None` for files that are not part of the set. +fn rotation_suffix(rest: &str) -> Option<(u32, bool)> { + if rest.is_empty() { + return Some((0, false)); + } + let rest = rest.strip_prefix('.')?; + let (number, compressed) = match rest.strip_suffix(".gz") { + Some(number) => (number, true), + None => (rest, false), + }; + if !number.is_empty() && number.len() <= 6 && number.bytes().all(|b| b.is_ascii_digit()) { + return number.parse().ok().map(|n: u32| (n.max(1), compressed)); + } + // Other compressed rotations (e.g. `.old.gz`) sort after numbered ones. + compressed.then_some((u32::MAX, true)) +} +/// Scope and site of a per-site log base name (`app`, `old.redirect`, `park.host404`). +fn site_scope(base: &str) -> (&'static str, String) { + if base == "_unmatched" { + return ("unmatched", String::new()); + } + if let Some(id) = base.strip_suffix(".redirect") { + return ("redirect", id.to_owned()); + } + if let Some(id) = base.strip_suffix(".host404") { + return ("host404", id.to_owned()); + } + ("vhost", base.to_owned()) } #[derive(Default, Deserialize)] #[serde(default, deny_unknown_fields)] @@ -32,6 +68,8 @@ struct FileLogQuery { client_ip: Option, vhost: Option, consolidate_vhosts: Option, + /// Only records at or after this time (ms since the epoch). + since_ms: Option, aggregate_field: Option, aggregate_limit: Option, aggregate_min_count: Option, @@ -83,6 +121,9 @@ fn source_from_path( .filter(|_| safe_regular) .map_or(0, file_modified_ms), compressed, + rotation: 0, + scope: kind, + site: String::new(), } } include!("file_logs_io.rs"); @@ -103,11 +144,11 @@ fn configured_file_log_sources(config: &crate::config::Config) -> Vec 180 { + let (base, rest) = name.split_once(".jsonl")?; + if base.is_empty() || name.len() > 180 { return None; } + rotation_suffix(rest)?; let file_type = entry.file_type().ok()?; if !file_type.is_file() || file_type.is_symlink() { return None; @@ -118,25 +159,40 @@ fn configured_file_log_sources(config: &crate::config::Config) -> Vec Value { "size": source.size, "modified_ms": source.modified_ms, "compressed": source.compressed, + "rotation": source.rotation, + "scope": source.scope, + "site": source.site, }) }) .collect(), diff --git a/src/admin/file_logs_io.rs b/src/admin/file_logs_io.rs index 29b64d5..8db82b2 100644 --- a/src/admin/file_logs_io.rs +++ b/src/admin/file_logs_io.rs @@ -24,6 +24,8 @@ fn newest_log_files( result } +/// Rotated copies of a global log: `.N`, `.N.gz` (logrotate with or +/// without `delaycompress`) and other `.*.gz`, newest rotation first. fn rotated_gzip_sources( active: &std::path::Path, id_prefix: &str, @@ -44,7 +46,6 @@ fn rotated_gzip_sources( if !safe { return Vec::new(); } - let prefix = format!("{base}."); let entries = newest_log_files( std::fs::read_dir(parent) .ok() @@ -52,7 +53,8 @@ fn rotated_gzip_sources( .flat_map(|iter| iter.filter_map(|entry| entry.ok())) .filter_map(|entry| { let name = entry.file_name().to_string_lossy().into_owned(); - if name.len() > 180 || !name.starts_with(&prefix) || !name.ends_with(".gz") { + let rest = name.strip_prefix(base)?; + if name.len() > 180 || rest.is_empty() || rotation_suffix(rest).is_none() { return None; } let file_type = entry.file_type().ok()?; @@ -64,20 +66,38 @@ fn rotated_gzip_sources( }), 64, ); - entries + let mut sources: Vec = entries .into_iter() - .map(|(name, path, _)| { - source_from_path( - format!("{id_prefix}:gz:{name}"), + .filter_map(|(name, path, _)| { + let (rotation, compressed) = rotation_suffix(&name[base.len()..])?; + let mut source = source_from_path( + if compressed { + format!("{id_prefix}:gz:{name}") + } else { + format!("{id_prefix}:file:{name}") + }, format!("{label_prefix} · {name}"), id_prefix.to_owned(), kind, path, enabled, format, - ) + ); + source.rotation = rotation; + Some(source) }) - .collect() + .collect(); + sort_by_rotation(&mut sources); + sources +} +/// Newest data first: the file being written, then `.1`, `.2`, … (ties by mtime). +fn sort_by_rotation(sources: &mut [FileLogSource]) { + sources.sort_by(|a, b| { + a.rotation + .cmp(&b.rotation) + .then_with(|| b.modified_ms.cmp(&a.modified_ms)) + .then_with(|| a.id.cmp(&b.id)) + }); } fn open_file_log(path: &std::path::Path) -> std::io::Result { diff --git a/src/admin/file_logs_query.rs b/src/admin/file_logs_query.rs index 8da6401..c52b731 100644 --- a/src/admin/file_logs_query.rs +++ b/src/admin/file_logs_query.rs @@ -208,6 +208,197 @@ fn validate_file_log_query(query: &FileLogQuery) -> Result<(), ApiError> { Ok(()) } +/// Runs a stored-log query (blocking file I/O). +fn file_log_query_blocking( + config: &crate::config::Config, + query: &FileLogQuery, + search: &[FileLogSearchClause], +) -> Result, ApiError> { + let mut sources = configured_file_log_sources(config); + let log_format = config.logging.format.clone(); + let requested = query.source.as_deref().unwrap_or("all"); + let mut truncated = false; + let mut files_skipped = 0usize; + // One site/log (all its rotations) or one file is read newest-first: each file + // may use the whole remaining budget, so the newest records are always + // complete and older rotations are read only while budget remains. "All" + // spreads the budget over the newest file of every log first. + let sequential = requested != "all"; + if requested != "all" { + let consolidate = query.consolidate_vhosts.unwrap_or(false); + sources.retain(|source| { + source.id == requested || (consolidate && source.group_id == requested) + }); + if sources.is_empty() { + return Err(ApiError( + StatusCode::BAD_REQUEST, + "unknown file log source".into(), + )); + } + sort_by_rotation(&mut sources); + } else { + sort_by_rotation(&mut sources); + } + if sources.len() > FILE_LOG_MAX_SOURCES { + truncated = true; + files_skipped += sources.len() - FILE_LOG_MAX_SOURCES; + sources.truncate(FILE_LOG_MAX_SOURCES); + } + let since_ms = query.since_ms.filter(|value| *value > 0); + let mut files = Vec::new(); + let mut newest_ms: Option = None; + let mut oldest_ms: Option = None; + let offset = query.offset.unwrap_or(0); + let limit = query.limit.unwrap_or(100).clamp(1, FILE_LOG_MAX_LIMIT); + let mut remaining_bytes = FILE_LOG_SCAN_BYTES_TOTAL; + let mut scanned_bytes = 0u64; + let mut remaining_lines = FILE_LOG_SCAN_LINES; + let mut scanned_lines = 0usize; + let mut records = Vec::new(); + let mut fields = std::collections::BTreeSet::new(); + let aggregate_field = query + .aggregate_field + .as_deref() + .map(str::to_ascii_lowercase); + let aggregate_min_count = query.aggregate_min_count.unwrap_or(2); + let aggregate_limit = query + .aggregate_limit + .unwrap_or(50) + .clamp(1, FILE_LOG_MAX_AGGREGATE_RESULTS); + let mut aggregate_counts = std::collections::HashMap::::new(); + let mut aggregate_truncated = false; + let mut reached_since = false; + for (index, source) in sources.iter().enumerate() { + if remaining_bytes == 0 || remaining_lines == 0 || reached_since { + truncated |= !reached_since; + files_skipped += sources.len() - index; + break; + } + let sources_left = sources.len().saturating_sub(index).max(1); + let line_budget = if sequential { + remaining_lines + } else { + (remaining_lines / sources_left).max(1) + }; + match read_tail(source, remaining_bytes, line_budget) { + Ok((lines, bytes, source_truncated)) => { + remaining_bytes = remaining_bytes.saturating_sub(bytes); + remaining_lines = remaining_lines.saturating_sub(lines.len()); + scanned_bytes += bytes; + scanned_lines += lines.len(); + truncated |= source_truncated; + files.push(json!({ + "id": source.id, + "rotation": source.rotation, + "lines": lines.len(), + "partial": source_truncated, + })); + let mut file_newest: Option = None; + for line in lines { + if line.is_empty() { + continue; + } + let value = normalized_record(source, &line, &log_format); + let time = value.get("time_ms").and_then(Value::as_u64); + if let Some(time) = time { + file_newest = Some(file_newest.map_or(time, |n: u64| n.max(time))); + } + if since_ms.is_some_and(|since| time.is_some_and(|time| time < since)) { + continue; + } + if record_matches(&value, query, search) { + if let Some(time) = time { + newest_ms = Some(newest_ms.map_or(time, |n| n.max(time))); + oldest_ms = Some(oldest_ms.map_or(time, |o| o.min(time))); + } + collect_file_log_fields(&value, &mut fields); + if let Some(field) = aggregate_field.as_deref() { + if let Some(field_value) = file_log_field(&value, field) { + let mut values = Vec::new(); + file_log_aggregate_values(field_value, &mut values); + for aggregate_value in values { + if aggregate_counts.contains_key(&aggregate_value) + || aggregate_counts.len() + < FILE_LOG_MAX_AGGREGATE_VALUES + { + *aggregate_counts + .entry(aggregate_value) + .or_insert(0) += 1; + } else { + aggregate_truncated = true; + } + } + } + } + records.push(value); + } + } + // Older rotations only hold older records: stop once a whole file + // is before the requested period. + if sequential + && since_ms.is_some_and(|since| file_newest.is_some_and(|n| n < since)) + { + reached_since = true; + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => truncated = true, + } + } + sort_file_log_records( + &mut records, + query.sort_by.as_deref().unwrap_or("time"), + query.sort_descending.unwrap_or(true), + ); + let mut aggregation = aggregate_counts + .into_iter() + .filter(|(_, count)| *count >= aggregate_min_count) + .map(|(value, count)| json!({"value": value, "count": count})) + .collect::>(); + aggregation.sort_by(|left, right| { + let left_count = left.get("count").and_then(Value::as_u64).unwrap_or(0); + let right_count = right.get("count").and_then(Value::as_u64).unwrap_or(0); + right_count.cmp(&left_count).then_with(|| { + left.get("value") + .and_then(Value::as_str) + .unwrap_or("") + .cmp(right.get("value").and_then(Value::as_str).unwrap_or("")) + }) + }); + if aggregation.len() > aggregate_limit { + aggregation.truncate(aggregate_limit); + aggregate_truncated = true; + } + let total = records.len(); + let page = records + .into_iter() + .skip(offset) + .take(limit) + .collect::>(); + Ok(Json(json!({ + "entries": page, + "total": total, + "offset": offset, + "limit": limit, + "truncated": truncated, + "scanned_bytes": scanned_bytes, + "scanned_lines": scanned_lines, + "files": files, + "files_skipped": files_skipped, + "stopped_at_period": reached_since, + "newest_ms": newest_ms, + "oldest_ms": oldest_ms, + "fields": fields, + "sources": file_log_sources_json(&sources), + "aggregation": aggregate_field.map(|field| json!({ + "field": field, + "min_count": aggregate_min_count, + "entries": aggregation, + "truncated": aggregate_truncated, + })), + }))) +} + async fn file_logs_query( State(state): State>, Query(query): Query, @@ -215,144 +406,7 @@ async fn file_logs_query( validate_file_log_query(&query)?; let search = parse_file_log_search(query.q.as_deref().unwrap_or(""))?; let config = state.config.load().envelope.config.clone(); - tokio::task::spawn_blocking(move || { - let mut sources = configured_file_log_sources(&config); - let log_format = config.logging.format.clone(); - let requested = query.source.as_deref().unwrap_or("all"); - let mut truncated = false; - if requested != "all" { - let consolidate_vhosts = - query.consolidate_vhosts.unwrap_or(false) && requested.starts_with("vhost:"); - sources.retain(|source| { - source.id == requested || (consolidate_vhosts && source.group_id == requested) - }); - if sources.is_empty() { - return Err(ApiError( - StatusCode::BAD_REQUEST, - "unknown file log source".into(), - )); - } - } else { - sources.sort_by_key(|source| std::cmp::Reverse(source.modified_ms)); - if sources.len() > FILE_LOG_MAX_SOURCES { - truncated = true; - sources.truncate(FILE_LOG_MAX_SOURCES); - } - } - let offset = query.offset.unwrap_or(0); - let limit = query.limit.unwrap_or(100).clamp(1, FILE_LOG_MAX_LIMIT); - let mut remaining_bytes = FILE_LOG_SCAN_BYTES_TOTAL; - let mut scanned_bytes = 0u64; - let mut remaining_lines = FILE_LOG_SCAN_LINES; - let mut scanned_lines = 0usize; - let mut records = Vec::new(); - let mut fields = std::collections::BTreeSet::new(); - let aggregate_field = query - .aggregate_field - .as_deref() - .map(str::to_ascii_lowercase); - let aggregate_min_count = query.aggregate_min_count.unwrap_or(2); - let aggregate_limit = query - .aggregate_limit - .unwrap_or(50) - .clamp(1, FILE_LOG_MAX_AGGREGATE_RESULTS); - let mut aggregate_counts = std::collections::HashMap::::new(); - let mut aggregate_truncated = false; - for (index, source) in sources.iter().enumerate() { - if remaining_bytes == 0 || remaining_lines == 0 { - truncated = true; - break; - } - let sources_left = sources.len().saturating_sub(index).max(1); - let line_budget = (remaining_lines / sources_left).max(1); - match read_tail(source, remaining_bytes, line_budget) { - Ok((lines, bytes, source_truncated)) => { - remaining_bytes = remaining_bytes.saturating_sub(bytes); - remaining_lines = remaining_lines.saturating_sub(lines.len()); - scanned_bytes += bytes; - scanned_lines += lines.len(); - truncated |= source_truncated; - for line in lines { - if line.is_empty() { - continue; - } - let value = normalized_record(source, &line, &log_format); - if record_matches(&value, &query, &search) { - collect_file_log_fields(&value, &mut fields); - if let Some(field) = aggregate_field.as_deref() { - if let Some(field_value) = file_log_field(&value, field) { - let mut values = Vec::new(); - file_log_aggregate_values(field_value, &mut values); - for aggregate_value in values { - if aggregate_counts.contains_key(&aggregate_value) - || aggregate_counts.len() - < FILE_LOG_MAX_AGGREGATE_VALUES - { - *aggregate_counts - .entry(aggregate_value) - .or_insert(0) += 1; - } else { - aggregate_truncated = true; - } - } - } - } - records.push(value); - } - } - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(_) => truncated = true, - } - } - sort_file_log_records( - &mut records, - query.sort_by.as_deref().unwrap_or("time"), - query.sort_descending.unwrap_or(true), - ); - let mut aggregation = aggregate_counts - .into_iter() - .filter(|(_, count)| *count >= aggregate_min_count) - .map(|(value, count)| json!({"value": value, "count": count})) - .collect::>(); - aggregation.sort_by(|left, right| { - let left_count = left.get("count").and_then(Value::as_u64).unwrap_or(0); - let right_count = right.get("count").and_then(Value::as_u64).unwrap_or(0); - right_count.cmp(&left_count).then_with(|| { - left.get("value") - .and_then(Value::as_str) - .unwrap_or("") - .cmp(right.get("value").and_then(Value::as_str).unwrap_or("")) - }) - }); - if aggregation.len() > aggregate_limit { - aggregation.truncate(aggregate_limit); - aggregate_truncated = true; - } - let total = records.len(); - let page = records - .into_iter() - .skip(offset) - .take(limit) - .collect::>(); - Ok(Json(json!({ - "entries": page, - "total": total, - "offset": offset, - "limit": limit, - "truncated": truncated, - "scanned_bytes": scanned_bytes, - "scanned_lines": scanned_lines, - "fields": fields, - "sources": file_log_sources_json(&sources), - "aggregation": aggregate_field.map(|field| json!({ - "field": field, - "min_count": aggregate_min_count, - "entries": aggregation, - "truncated": aggregate_truncated, - })), - }))) - }) + tokio::task::spawn_blocking(move || file_log_query_blocking(&config, &query, &search)) .await .map_err(|_| { ApiError( diff --git a/src/admin/openapi.json b/src/admin/openapi.json index ec9c82e..afa331c 100644 --- a/src/admin/openapi.json +++ b/src/admin/openapi.json @@ -14809,7 +14809,7 @@ "/api/file-logs": { "get": { "summary": "Configured on-disk log sources", - "description": "Lists only RustProxy log paths from the active configuration. This endpoint is independent from the Live Logs memory buffer and does not accept a filesystem path.", + "description": "Lists only RustProxy log paths from the active configuration. This endpoint is independent from the Live Logs memory buffer and does not accept a filesystem path. Each source reports rotation (0 = file being written, N = .N/.N.gz), scope (vhost, redirect, host404, unmatched, access, error) and site (the vhost, redirect or 404 host id for per-site logs).", "tags": [ "Monitoring" ], @@ -14879,7 +14879,7 @@ "/api/file-logs/query": { "get": { "summary": "Query configured on-disk logs", - "description": "Reads bounded tails of configured RustProxy access/error log files using server-side source IDs only. The query never accepts arbitrary paths, follows no symlink on Unix, and is separate from /api/logs and /api/live-logs.", + "description": "Reads bounded tails of configured RustProxy access/error log files using server-side source IDs only. The query never accepts arbitrary paths, follows no symlink on Unix, and is separate from /api/logs and /api/live-logs. A log (group) is read newest rotation first; each file may use the remaining scan budget. The response adds files (id, rotation, lines, partial), files_skipped, stopped_at_period, newest_ms and oldest_ms.", "tags": [ "Monitoring" ], @@ -14889,7 +14889,7 @@ "name": "source", "in": "query", "required": false, - "description": "Source ID returned by /api/file-logs, or all. Never a filesystem path.", + "description": "Source or group ID returned by /api/file-logs, or all. Never a filesystem path. A single source (e.g. vhost-gz:app.jsonl.3.gz) reads only that file.", "schema": { "type": "string" } @@ -14898,12 +14898,22 @@ "name": "consolidate_vhosts", "in": "query", "required": false, - "description": "When true and source is vhost:, scan the active JSONL plus all discovered rotated .gz members that share that vhost group.", + "description": "When true and source is a group ID (vhost:, access or error), scan the current file and all rotations of that log (.N and .N.gz), newest rotation first.", "schema": { "type": "boolean", "default": false } }, + { + "name": "since_ms", + "in": "query", + "required": false, + "description": "Only records with time_ms at or after this value (ms since the Unix epoch). For a log read newest-first, reading stops at the first rotation that is entirely older.", + "schema": { + "type": "integer", + "minimum": 0 + } + }, { "name": "q", "in": "query", diff --git a/src/admin/tests.rs b/src/admin/tests.rs index 919c984..2d75df5 100644 --- a/src/admin/tests.rs +++ b/src/admin/tests.rs @@ -3219,6 +3219,150 @@ mod tests { assert!(app.iter().any(|source| source.compressed)); } + fn write_gz(path: &std::path::Path, lines: &[String]) { + use std::io::Write; + let file = std::fs::File::create(path).unwrap(); + let mut encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default()); + for line in lines { + writeln!(encoder, "{line}").unwrap(); + } + encoder.finish().unwrap(); + } + fn records(from: u64, to: u64) -> Vec { + (from..to) + .map(|time| format!(r#"{{"event":"request","time_ms":{time},"status":200,"path":"/p{time}"}}"#)) + .collect() + } + + #[test] + fn stored_log_rotations_are_read_newest_first_regardless_of_mtime() { + let dir = tempfile::tempdir().unwrap(); + // logrotate numbering: .jsonl newest, .1 (delaycompress, plain), .2.gz, .10.gz oldest. + std::fs::write(dir.path().join("mail.jsonl"), records(400, 410).join("\n") + "\n").unwrap(); + std::fs::write(dir.path().join("mail.jsonl.1"), records(300, 310).join("\n") + "\n").unwrap(); + write_gz(&dir.path().join("mail.jsonl.2.gz"), &records(200, 210)); + write_gz(&dir.path().join("mail.jsonl.10.gz"), &records(100, 110)); + // The oldest rotation has the newest mtime (copied or touched files). + std::fs::File::options() + .append(true) + .open(dir.path().join("mail.jsonl.10.gz")) + .unwrap() + .set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(3600)) + .unwrap(); + std::fs::write(dir.path().join("old.redirect.jsonl"), records(1, 2).join("\n")).unwrap(); + std::fs::write(dir.path().join("park.host404.jsonl"), records(1, 2).join("\n")).unwrap(); + std::fs::write(dir.path().join("_unmatched.jsonl"), records(1, 2).join("\n")).unwrap(); + std::fs::write(dir.path().join("mail.jsonl-20261113.gz"), b"ignored").unwrap(); + + let mut config = Config::default(); + config.logging.file.per_vhost = true; + config.logging.file.directory = dir.path().to_string_lossy().into_owned(); + config.error_log.path = dir.path().join("none/error.log").to_string_lossy().into_owned(); + let sources = configured_file_log_sources(&config); + let mail: Vec<_> = sources.iter().filter(|s| s.group_id == "vhost:mail").collect(); + assert_eq!( + mail.iter().map(|s| (s.id.as_str(), s.rotation)).collect::>(), + vec![ + ("vhost:mail", 0), + ("vhost-file:mail.jsonl.1", 1), + ("vhost-gz:mail.jsonl.2.gz", 2), + ("vhost-gz:mail.jsonl.10.gz", 10) + ] + ); + let scope = |id: &str| sources.iter().find(|s| s.id == id).map(|s| (s.scope, s.site.clone())); + assert_eq!(scope("vhost:old.redirect"), Some(("redirect", "old".into()))); + assert_eq!(scope("vhost:park.host404"), Some(("host404", "park".into()))); + assert_eq!(scope("vhost:_unmatched"), Some(("unmatched", String::new()))); + assert_eq!(scope("vhost:mail"), Some(("vhost", "mail".into()))); + + let query = |extra: FileLogQuery| { + let query = FileLogQuery { + source: Some("vhost:mail".into()), + consolidate_vhosts: Some(true), + limit: Some(5), + ..extra + }; + file_log_query_blocking(&config, &query, &[]).unwrap().0 + }; + let value = query(FileLogQuery::default()); + let times: Vec = value["entries"] + .as_array() + .unwrap() + .iter() + .map(|e| e["time_ms"].as_u64().unwrap()) + .collect(); + assert_eq!(times, vec![409, 408, 407, 406, 405]); + assert_eq!(value["total"], 40); + assert_eq!(value["newest_ms"], 409); + assert_eq!(value["oldest_ms"], 100); + let files: Vec<_> = value["files"].as_array().unwrap().iter().map(|f| f["rotation"].as_u64().unwrap()).collect(); + assert_eq!(files, vec![0, 1, 2, 10]); + + // A period stops before older rotations. + let value = query(FileLogQuery { + since_ms: Some(305), + ..FileLogQuery::default() + }); + assert_eq!(value["total"], 15); + assert_eq!(value["oldest_ms"], 305); + // .2.gz is read to learn that it is entirely older; .10.gz is skipped. + assert_eq!(value["files"].as_array().unwrap().len(), 3); + assert_eq!(value["files_skipped"], 1); + + // A single rotated file is its own source. + let value = file_log_query_blocking( + &config, + &FileLogQuery { + source: Some("vhost-gz:mail.jsonl.10.gz".into()), + ..FileLogQuery::default() + }, + &[], + ) + .unwrap() + .0; + assert_eq!(value["newest_ms"], 109); + assert_eq!(value["total"], 10); + } + + #[test] + fn stored_log_global_rotations_include_uncompressed_copies() { + let dir = tempfile::tempdir().unwrap(); + let active = dir.path().join("access.jsonl"); + std::fs::write(&active, records(30, 31).join("\n")).unwrap(); + std::fs::write(dir.path().join("access.jsonl.1"), records(20, 21).join("\n")).unwrap(); + write_gz(&dir.path().join("access.jsonl.2.gz"), &records(10, 11)); + let mut config = Config::default(); + config.logging.file.per_vhost = false; + config.logging.file.path = active.to_string_lossy().into_owned(); + let sources = configured_file_log_sources(&config); + let access: Vec<_> = sources + .iter() + .filter(|s| s.group_id == "access") + .map(|s| (s.id.clone(), s.rotation)) + .collect(); + assert_eq!( + access, + vec![ + ("access".to_string(), 0), + ("access:file:access.jsonl.1".to_string(), 1), + ("access:gz:access.jsonl.2.gz".to_string(), 2) + ] + ); + let value = file_log_query_blocking( + &config, + &FileLogQuery { + source: Some("access".into()), + consolidate_vhosts: Some(true), + ..FileLogQuery::default() + }, + &[], + ) + .unwrap() + .0; + assert_eq!(value["total"], 3); + assert_eq!(value["entries"][0]["time_ms"], 30); + } + #[test] fn stored_log_aggregate_values_support_scalars_and_bounded_arrays() { let value = json!(["BadBot/1", "BadBot/1", 503, true, {"ignored":"object"}]); diff --git a/src/admin/web/css/10-base.css b/src/admin/web/css/10-base.css index 51c09aa..a2133ca 100644 --- a/src/admin/web/css/10-base.css +++ b/src/admin/web/css/10-base.css @@ -204,8 +204,7 @@ button:focus-visible { } .quiet:hover, -.top-log-menu[open]>summary, -.file-log-search-help[open]>summary { +.top-log-menu[open]>summary { color: var(--text); border-color: var(--border-hover); } @@ -1348,8 +1347,7 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon { .metric-info, .top-log-menu, -.backend-column-picker, -.file-log-search-help { +.backend-column-picker { position: relative; } @@ -1372,8 +1370,7 @@ html[data-interface-icons="true"] .network-interface-hidden .quiet>svg.ui-icon { .top-log-menu>summary::-webkit-details-marker, .function-live-chart-summary::-webkit-details-marker, .backend-column-picker>summary::-webkit-details-marker, -.log-column-picker>summary::-webkit-details-marker, -.file-log-search-help>summary::-webkit-details-marker { +.log-column-picker>summary::-webkit-details-marker { display: none; } diff --git a/src/admin/web/css/20-shell.css b/src/admin/web/css/20-shell.css index a337a60..de5f714 100644 --- a/src/admin/web/css/20-shell.css +++ b/src/admin/web/css/20-shell.css @@ -607,8 +607,7 @@ main { } .top-log-menu>summary, -.backend-column-picker>summary, -.file-log-search-help>summary { +.backend-column-picker>summary { list-style: none; cursor: pointer; user-select: none; diff --git a/src/admin/web/css/30-overview.css b/src/admin/web/css/30-overview.css index 244685c..ed26e5c 100644 --- a/src/admin/web/css/30-overview.css +++ b/src/admin/web/css/30-overview.css @@ -2108,8 +2108,7 @@ html:is([data-corner-style=square], [data-corner-style=subtle], [data-corner-sty border-radius: var(--rp-progress-radius); } -#panel-overview .stat-meter>small, -.file-log-search-help-popover code { +#panel-overview .stat-meter>small { display: block; overflow-wrap: anywhere; } diff --git a/src/admin/web/css/40-editors.css b/src/admin/web/css/40-editors.css index 978f593..74239ed 100644 --- a/src/admin/web/css/40-editors.css +++ b/src/admin/web/css/40-editors.css @@ -597,7 +597,6 @@ p, #panel-tls .certificate-subheading h3, #panel-tls .certificate-library-footer p, .cache-operation-dialog .card, -.file-log-search-help-popover p, .file-logs-table-toolbar .fine, .cache-maintenance-help .subheading, .path-permissions p { @@ -622,21 +621,6 @@ p, gap: 8px; } -.vh-header-rule-head { - display: flex; - align-items: center; - justify-content: space-between; - gap: 8px; - margin-bottom: 8px; -} - -.vh-header-rule-title { - font: 600 10px var(--mono); - color: var(--muted); - text-transform: uppercase; - letter-spacing: .45px; -} - .vh-header-rule-fields { display: grid; align-items: end; @@ -1468,11 +1452,6 @@ html[data-dashboard-density=ultra] #panel-overview .dashboard-overview-grid>.car color: var(--muted); } -.location-header-editor .vh-header-rule-head>button { - margin-left: auto; - flex: 0 0 auto; -} - .listener-protocol-settings-actions { display: flex; gap: 14px; diff --git a/src/admin/web/css/60-monitoring.css b/src/admin/web/css/60-monitoring.css index f728277..d7d3b03 100644 --- a/src/admin/web/css/60-monitoring.css +++ b/src/admin/web/css/60-monitoring.css @@ -775,23 +775,9 @@ button.config-history-day.is-selected, min-height: 32px; } -.file-log-search-help-popover { - position: absolute; - z-index: 90; - top: calc(100% + 6px); - inset-inline-end: 0; - display: grid; - gap: 7px; - width: calc(min(420px, calc(100 * var(--rp-vw)) - 36px)); - padding: 12px; - border: 1px solid var(--line); - background: var(--panel2); - box-shadow: 0 12px 28px var(--shadow-strong); -} - .file-logs-filter { display: grid; - grid-template-columns: minmax(180px, 260px) minmax(260px, 1fr) minmax(110px, 150px); + grid-template-columns: minmax(200px, 1.4fr) minmax(200px, 1.4fr) minmax(150px, 1fr) minmax(100px, 130px); gap: 10px; align-items: end; --toolbar-control-height: min(var(--button-min-height), var(--ui-field-min-height)); @@ -799,6 +785,106 @@ button.config-history-day.is-selected, .file-logs-filter .file-log-search { grid-column: auto; + min-width: 0; +} + +.file-logs-filter .is-disabled { + opacity: .55; +} + +.file-log-search-row { + display: grid; + grid-column: 1/-1; + grid-template-columns: minmax(0, 1fr) auto; + align-items: end; + gap: 8px; +} + +.file-log-syntax-toggle.active { + border-color: var(--accent); + color: var(--accent); +} + +/* Search syntax help: an inline panel inside the workspace (never off-screen). */ +.file-log-syntax { + display: grid; + grid-column: 1/-1; + gap: 6px; + padding: 10px 12px; + border: 1px solid var(--line); + border-left: 2px solid var(--accent); + background: var(--panel2); +} + +.file-log-syntax[hidden] { + display: none; +} + +.file-log-syntax p { + margin: 0; +} + +.file-log-syntax-examples { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.file-log-syntax-examples button { + font: 11px var(--mono); + border-radius: 999px; + padding: 3px 10px; +} + +.file-log-chips { + display: flex; + flex-wrap: wrap; + grid-column: 1/-1; + gap: 6px; +} + +.file-log-chip { + border: 1px solid var(--line); + border-radius: 999px; + background: transparent; + color: var(--muted); + padding: 3px 12px; + font: 600 11px var(--mono); + cursor: pointer; +} + +.file-log-chip.active { + border-color: var(--accent); + color: var(--text); + background: var(--panel2); +} + +.file-log-chip.is-2xx.active { border-color: var(--green); } +.file-log-chip.is-4xx.active, +.file-log-chip.is-protocol.active { border-color: var(--notice-line); } +.file-log-chip.is-5xx.active { border-color: var(--red); } + +#file-log-summary strong { + color: var(--text); +} + +.file-log-summary-hint { + color: var(--notice-text); +} + +.file-log-summary-hint.is-info { + color: var(--muted); +} + +.file-logs-table tr[data-status-class="5xx"] td[data-mobile-column=status], +.file-logs-table tr[data-event] td[data-mobile-column=event] { + color: var(--red); + font-weight: 600; +} + +.file-logs-table tr[data-status-class="4xx"] td[data-mobile-column=status] { + color: var(--notice-text); + font-weight: 600; } .file-log-column-picker { @@ -937,29 +1023,8 @@ html[data-table-density=ultra] .file-log-inline-detail pre { line-height: 1.55; } -.file-logs-heading-actions .file-log-consolidate { - display: inline-flex; - align-items: center; - gap: .45rem; - padding: .35rem .55rem; - min-height: 0; - color: var(--muted); - font-size: .8rem; - font-weight: 400; - white-space: nowrap; - cursor: pointer; -} - -.file-log-consolidate input { - width: 14px; - height: 14px; - margin: 0; - accent-color: var(--accent); -} - .page-footer .footer-update:hover, .certificate-details summary:hover, -.file-log-consolidate:hover, .file-log-tab:hover, .config-history-change-values .diff-after { color: var(--text); diff --git a/src/admin/web/css/70-responsive.css b/src/admin/web/css/70-responsive.css index a998ea9..aa99185 100644 --- a/src/admin/web/css/70-responsive.css +++ b/src/admin/web/css/70-responsive.css @@ -440,11 +440,19 @@ #panel-tls .certificate-tabs, #panel-tls .renewal-meta, .file-log-column-picker .log-column-options, - .file-log-field, - .file-logs-filter { + .file-log-field { grid-template-columns: 1fr; } + .file-logs-filter { + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + } + + .file-logs-filter .file-log-source, + .file-logs-filter .file-log-file { + grid-column: 1/-1; + } + #panel-tls .renewal-actions { justify-content: stretch; } @@ -467,10 +475,6 @@ gap: 8px; } - .file-logs-heading-actions .file-log-consolidate { - margin-inline-end: auto; - } - .file-log-tab { padding: .6rem .7rem; } @@ -524,15 +528,6 @@ gap: 4px; } - #panel-filelogs .file-logs-heading-actions .file-log-consolidate { - margin-inline-end: auto; - white-space: normal; - } - - #panel-filelogs .file-log-search-help-popover { - width: calc(min(320px, calc(100 * var(--rp-vw)) - 54px)); - } - #panel-filelogs .file-log-aggregate-form, #panel-filelogs .file-logs-filter, #panel-filelogs .file-log-field { @@ -627,11 +622,43 @@ font-size: 11px; } - #panel-filelogs .file-logs-table td[data-mobile-column=time], - #panel-filelogs .file-logs-table td[data-mobile-column=vhost] { + #panel-filelogs .file-logs-table td[data-mobile-column=time] { color: var(--muted); font-size: 11px; - grid-column: 1/-1; + order: -2; + } + + #panel-filelogs .file-logs-table td[data-mobile-column=status] { + order: -1; + text-align: end; + } + + #panel-filelogs .file-logs-table td[data-mobile-column=time]:before, + #panel-filelogs .file-logs-table td[data-mobile-column=status]:before { + content: "" !important; + } + + #panel-filelogs .file-logs-table td[data-mobile-column=record] { + order: -1; + } + + #panel-filelogs .file-logs-table td[data-mobile-column=vhost], + #panel-filelogs .file-logs-table td[data-mobile-column=source] { + color: var(--muted); + font-size: 11px; + } + + #panel-filelogs .file-logs-table tbody tr[data-status-class="5xx"], + #panel-filelogs .file-logs-table tbody tr[data-event] { + border-left: 3px solid var(--red); + } + + #panel-filelogs .file-logs-table tbody tr[data-status-class="4xx"] { + border-left: 3px solid var(--notice-line); + } + + #panel-filelogs .file-logs-table tbody tr[data-status-class="2xx"] { + border-left: 3px solid var(--pill-live-line); } #panel-filelogs .file-logs-table tbody tr:not(.file-log-detail-row)>td:before { @@ -2073,4 +2100,10 @@ .docker-passive-health-editor>summary>span { flex: 0 0 190px; } -} \ No newline at end of file +} +@media (max-width: 760px) { + /* Plain request records do not need an "Event: request" line on phones. */ + #panel-filelogs .file-logs-table tbody tr:not([data-event]) td[data-mobile-column=event] { + display: none; + } +} diff --git a/src/admin/web/file-logs.js b/src/admin/web/file-logs.js index dec233c..d5af86d 100644 --- a/src/admin/web/file-logs.js +++ b/src/admin/web/file-logs.js @@ -13,14 +13,12 @@ let visibleColumns = new Set(defaultColumnIds); let sortBy = "time", sortDescending = true, pendingRefresh = false; - const CONSOLIDATION_STORAGE_KEY = "rp-file-logs-consolidate-vhosts"; - const consolidationToggle = $("file-log-consolidate-vhosts"); - try { - const saved = localStorage.getItem(CONSOLIDATION_STORAGE_KEY); - if (consolidationToggle && (saved === "1" || saved === "0")) consolidationToggle.checked = saved === "1"; - } catch { } - + // Sources are shown per log (a site with all its rotations); the File picker + // narrows to one rotation. Rotation 0 is the file being written. + let groups = new Map(), statusFilter = "", eventFilter = ""; + const SCOPE_ORDER = ["vhost", "redirect", "host404", "unmatched", "access", "error"]; const sourceSelect = () => $("file-log-source"); + const fileSelect = () => $("file-log-file"); function setView(view) { activeView = view === "counts" ? "counts" : "entries"; for (const name of ["entries", "counts"]) { @@ -32,41 +30,70 @@ } if (activeView === "counts" && aggregateField) void refresh(true); } - - function sourceOption(source) { - const grouped = Number(source.member_count) > 1 ? ` · ${fmt(source.member_count)} ${t("fileLogsFiles")}` : ""; - const label = `${source.label}${grouped} · ${source.format} · ${bytes(Number(source.size) || 0)}`; - const option = el("option", label); option.value = source.id; return option; + function scopeOf(source) { + if (source.scope) return source.scope; + return String(source.group_id || "").startsWith("vhost:") ? "vhost" : source.kind || "access"; } - function displaySources(sources) { - if (!$("file-log-consolidate-vhosts")?.checked) return sources; - const output = [], groups = new Map(); + function groupLabel(group) { + if (group.scope === "access") return t("fileLogsAccessLog"); + if (group.scope === "error") return t("fileLogsErrorLog"); + if (group.scope === "unmatched") return t("fileLogsUnmatched"); + return group.site || group.id.replace(/^vhost:/, ""); + } + function fileLabel(source) { + const rotation = Number(source.rotation) || 0; + const name = rotation === 0 ? t("fileLogsCurrentFile") : rotation >= 4294967295 ? source.label : `.${rotation}${source.compressed ? ".gz" : ""}`; + const when = Number(source.modified_ms) ? ` · ${formatDateTime(Number(source.modified_ms))}` : ""; + return `${name} · ${bytes(Number(source.size) || 0)}${when}`; + } + function buildGroups(sources) { + const result = new Map(); for (const source of sources) { - if (!String(source.group_id || "").startsWith("vhost:")) { output.push(source); continue; } - const id = source.group_id; - let group = groups.get(id); - if (!group) { - group = { ...source, id, label: id.slice("vhost:".length), size: 0, member_count: 0, compressed: false }; - groups.set(id, group); output.push(group); - } - group.size += Number(source.size) || 0; group.member_count += 1; - group.modified_ms = Math.max(Number(group.modified_ms) || 0, Number(source.modified_ms) || 0); + const id = source.group_id || source.id; + let group = result.get(id); + if (!group) { group = { id, scope: scopeOf(source), site: source.site || "", format: source.format, files: [], size: 0, modified_ms: 0 }; result.set(id, group); } + group.files.push(source); group.size += Number(source.size) || 0; + group.modified_ms = Math.max(group.modified_ms, Number(source.modified_ms) || 0); } - return output; + for (const group of result.values()) group.files.sort((a, b) => (Number(a.rotation) || 0) - (Number(b.rotation) || 0) || (Number(b.modified_ms) || 0) - (Number(a.modified_ms) || 0)); + return result; } function renderInventory(value) { inventory = value; - const select = sourceSelect(); - let selected = select.value || "all"; - const rawSources = Array.isArray(value?.sources) ? value.sources : []; - if ($("file-log-consolidate-vhosts")?.checked && selected !== "all") { - const member = rawSources.find(source => source.id === selected); - if (member?.group_id?.startsWith("vhost:")) selected = member.group_id; + const select = sourceSelect(), previous = select.value || "all", previousFile = fileSelect().value || "all"; + groups = buildGroups(Array.isArray(value?.sources) ? value.sources : []); + const options = [Object.assign(el("option", t("fileLogsAllSources")), { value: "all" })]; + for (const scope of SCOPE_ORDER) { + const items = [...groups.values()].filter(group => group.scope === scope).sort((a, b) => compareText(groupLabel(a), groupLabel(b), false)); + if (!items.length) continue; + const optgroup = document.createElement("optgroup"); optgroup.label = t(`fileLogsScope_${scope}`); + for (const group of items) { + const count = group.files.length > 1 ? ` · ${fmt(group.files.length)} ${t("fileLogsFiles")}` : ""; + const option = el("option", `${groupLabel(group)}${count} · ${bytes(group.size)}`); option.value = group.id; optgroup.append(option); + } + options.push(optgroup); } - const sources = displaySources(rawSources); - const options = [Object.assign(el("option", t("fileLogsAllSources")), { value: "all" }), ...sources.map(sourceOption)]; select.replaceChildren(...options); - select.value = sources.some(source => source.id === selected) ? selected : "all"; + // A file id (older bookmark) selects its group. + const owner = [...groups.values()].find(group => group.id === previous || group.files.some(file => file.id === previous)); + select.value = owner ? owner.id : "all"; + renderFiles(owner && owner.files.some(file => file.id === previousFile) ? previousFile : owner?.files.some(file => file.id === previous) ? previous : "all"); + } + function renderFiles(selected = "all") { + const group = groups.get(sourceSelect().value), files = fileSelect(); + const options = [Object.assign(el("option", t("fileLogsAllFiles")), { value: "all" })]; + if (group) for (const source of group.files) options.push(Object.assign(el("option", fileLabel(source)), { value: source.id })); + files.replaceChildren(...options); + files.value = group?.files.some(file => file.id === selected) ? selected : "all"; + files.disabled = !group || group.files.length < 2; + files.closest("label").classList.toggle("is-disabled", files.disabled); + } + function sourceName(id) { + for (const group of groups.values()) { + const file = group.files.find(item => item.id === id); + if (file) return (Number(file.rotation) || 0) === 0 ? groupLabel(group) : `${groupLabel(group)} · .${file.rotation}`; + } + return id || "—"; } async function loadInventory() { const value = await api("/api/file-logs"); @@ -112,7 +139,8 @@ function columnValue(entry, id) { if (id === "time") return entryTime(entry); if (id === "record") return entrySummary(entry); - if (id === "source") return entry._source || "—"; + if (id === "source") return sourceName(entry._source); + if (id === "vhost" && !entry.vhost && (entry.redirect_host || entry.local_host)) return entry.redirect_host ? `↪ ${entry.redirect_host}` : `404 · ${entry.local_host}`; return displayValue(nestedValue(entry, id)); } function columnLabel(id) { @@ -253,6 +281,8 @@ const nodes = []; entries.forEach((entry, index) => { const row = el("tr"); row.tabIndex = 0; row.classList.toggle("selected", selectedIndex === index); + const status = Number(entry.status) || 0; if (status >= 100) row.dataset.statusClass = `${Math.floor(status / 100)}xx`; + if (entry.event && entry.event !== "request") row.dataset.event = entry.event; row.setAttribute("aria-expanded", selectedIndex === index ? "true" : "false"); row.setAttribute("aria-label", entrySummary(entry)); for (const id of ids) { @@ -272,10 +302,16 @@ } function queryString() { const params = new URLSearchParams(); - const source = sourceSelect().value || "all"; - if (source !== "all") params.set("source", source); + const source = sourceSelect().value || "all", file = fileSelect().value || "all"; + if (source !== "all") { + if (file !== "all") params.set("source", file); + else { params.set("source", source); params.set("consolidate_vhosts", "true"); } + } const q = $("file-log-q").value.trim(); if (q) params.set("q", q); - if ($("file-log-consolidate-vhosts")?.checked) params.set("consolidate_vhosts", "true"); + const period = Number($("file-log-period").value) || 0; + if (period > 0) params.set("since_ms", String(Date.now() - period * 1000)); + if (statusFilter) params.set("status_class", statusFilter); + if (eventFilter) params.set("event", eventFilter); if (activeView === "counts" && aggregateField) { params.set("aggregate_field", aggregateField); params.set("aggregate_min_count", String(Math.max(2, Number($("file-log-aggregate-min")?.value) || 2))); @@ -297,22 +333,48 @@ applyFields(Array.isArray(value.fields) ? value.fields : []); renderRows(Array.isArray(value.entries) ? value.entries : []); renderAggregation(value.aggregation || null); - const from = lastTotal ? offset + 1 : 0, to = Math.min(offset + currentLimit(), lastTotal); - $("file-log-summary").textContent = t("fileLogsSummary") - .replace("{from}", fmt(from)).replace("{to}", fmt(to)).replace("{total}", fmt(lastTotal)) - .replace("{bytes}", bytes(Number(value.scanned_bytes) || 0)).replace("{lines}", fmt(Number(value.scanned_lines) || 0)) - + (value.truncated ? ` · ${t("fileLogsTruncated")}` : ""); + renderSummary(value); + const byTime = sortBy === "time" && sortDescending; + $("file-logs-prev").textContent = t(byTime ? "fileLogsNewer" : "previous"); + $("file-logs-next").textContent = t(byTime ? "fileLogsOlder" : "next"); $("file-logs-prev").disabled = offset === 0; $("file-logs-next").disabled = offset + currentLimit() >= lastTotal; } catch (error) { toast(error.message, true); } finally { busy = false; $("file-logs-refresh").disabled = false; if (pendingRefresh) { pendingRefresh = false; void refresh(); } } } + // Status line: what is shown, the time range and which files were read. + function renderSummary(value) { + const summary = $("file-log-summary"); summary.replaceChildren(); + const from = lastTotal ? offset + 1 : 0, to = Math.min(offset + currentLimit(), lastTotal); + const main = el("strong", t("fileLogsSummaryShown").replace("{from}", fmt(from)).replace("{to}", fmt(to)).replace("{total}", fmt(lastTotal))); + summary.append(main); + const parts = []; + if (value.newest_ms && value.oldest_ms) parts.push(t("fileLogsSummaryRange").replace("{from}", formatDateTime(Number(value.oldest_ms))).replace("{to}", formatDateTime(Number(value.newest_ms)))); + const files = Array.isArray(value.files) ? value.files : []; + const inGroup = groups.has(sourceSelect().value); + const fileName = file => inGroup ? ((Number(file.rotation) || 0) === 0 ? t("fileLogsCurrentFile") : `.${file.rotation}`) : sourceName(file.id); + if (files.length) parts.push(t("fileLogsSummaryFiles").replace("{files}", files.map(fileName).slice(0, 4).join(", ") + (files.length > 4 ? ` +${files.length - 4}` : ""))); + parts.push(t("fileLogsSummaryScanned").replace("{lines}", fmt(Number(value.scanned_lines) || 0)).replace("{bytes}", bytes(Number(value.scanned_bytes) || 0))); + summary.append(el("span", ` · ${parts.join(" · ")}`)); + const skipped = Number(value.files_skipped) || 0; + if (skipped > 0 || (value.truncated && !value.stopped_at_period)) { + const hint = el("span", "", "file-log-summary-hint"); + hint.textContent = value.stopped_at_period + ? t("fileLogsSummaryPeriod").replace("{count}", fmt(skipped)) + : skipped > 0 + ? t("fileLogsSummarySkipped").replace("{count}", fmt(skipped)) + : t("fileLogsSummaryTruncated"); + hint.classList.toggle("is-info", Boolean(value.stopped_at_period)); + summary.append(document.createElement("br"), hint); + } + } function reset() { inventory = null; offset = 0; lastTotal = 0; currentEntries = []; selectedIndex = null; aggregateField = ""; sortBy = "time"; sortDescending = true; pendingRefresh = false; preferencesLoaded = false; preferenceSaveRunning = false; preferenceSaveQueued = false; availableColumns = new Set(defaultColumnIds); visibleColumns = new Set(defaultColumnIds); - sourceSelect().replaceChildren(Object.assign(el("option", t("fileLogsAllSources")), { value: "all" })); + groups = new Map(); statusFilter = ""; eventFilter = ""; syncChips(); + sourceSelect().replaceChildren(Object.assign(el("option", t("fileLogsAllSources")), { value: "all" })); renderFiles(); $("file-log-rows").replaceChildren(); $("file-log-aggregate-rows")?.replaceChildren(); renderAggregation(null); syncColumnPicker(); syncHeaders(); } const fileLogTabs = [$("file-log-tab-entries"), $("file-log-tab-counts")]; @@ -333,12 +395,24 @@ $("file-logs-filter").addEventListener("submit", event => { event.preventDefault(); void refresh(true); }); $("file-log-q").addEventListener("input", () => { clearTimeout(searchTimer); searchTimer = setTimeout(() => void refresh(true), 250); }); $("file-log-limit").addEventListener("change", () => refresh(true)); - sourceSelect().addEventListener("change", () => refresh(true)); - consolidationToggle?.addEventListener("change", () => { - try { localStorage.setItem(CONSOLIDATION_STORAGE_KEY, consolidationToggle.checked ? "1" : "0"); } catch { } - if (inventory) renderInventory(inventory); - void refresh(true); - }); + sourceSelect().addEventListener("change", () => { renderFiles(); void refresh(true); }); + fileSelect().addEventListener("change", () => refresh(true)); + $("file-log-period").addEventListener("change", () => refresh(true)); + function syncChips() { + for (const chip of document.querySelectorAll("#file-log-chips .file-log-chip")) { + const active = (chip.dataset.status || "") === statusFilter && (chip.dataset.event || "") === eventFilter; + chip.setAttribute("aria-pressed", String(active)); chip.classList.toggle("active", active); + } + } + for (const chip of document.querySelectorAll("#file-log-chips .file-log-chip")) { + chip.addEventListener("click", () => { statusFilter = chip.dataset.status || ""; eventFilter = chip.dataset.event || ""; syncChips(); void refresh(true); }); + } + // Search syntax help opens inline under the search field (works on phones too). + const syntaxToggle = $("file-log-syntax-toggle"), syntax = $("file-log-syntax"); + syntaxToggle.addEventListener("click", () => { syntax.hidden = !syntax.hidden; syntaxToggle.setAttribute("aria-expanded", String(!syntax.hidden)); syntaxToggle.classList.toggle("active", !syntax.hidden); }); + for (const example of syntax.querySelectorAll(".file-log-syntax-examples button")) { + example.addEventListener("click", () => { $("file-log-q").value = example.textContent.trim(); syntax.hidden = true; syntaxToggle.setAttribute("aria-expanded", "false"); syntaxToggle.classList.remove("active"); void refresh(true); }); + } $("file-log-aggregate-form")?.addEventListener("submit", event => { event.preventDefault(); aggregateField = $("file-log-aggregate-field").value.trim().toLowerCase(); if (!aggregateField) { renderAggregation(null); return; } void refresh(true); }); $("file-logs-prev").addEventListener("click", () => { offset = Math.max(0, offset - currentLimit()); void refresh(); }); $("file-logs-next").addEventListener("click", () => { if (offset + currentLimit() < lastTotal) { offset += currentLimit(); void refresh(); } }); diff --git a/src/admin/web/index.html b/src/admin/web/index.html index 39ec1f0..b759a11 100644 --- a/src/admin/web/index.html +++ b/src/admin/web/index.html @@ -1906,21 +1906,6 @@

Stored log explorer

-
- Search syntax -
- Kibana-style field search -

Use field:value clauses. - Clauses are joined with AND; prefix a clause with ! to exclude it. Quotes - keep spaces together.

- req: GET AND !country: PL - status:>=500 AND path:/api/* - error:"connection reset" -
-
-
@@ -1932,9 +1917,18 @@ id="file-log-source"> - + + +
+ + +
+ +
+ + + + + + +
+
diff --git a/src/admin/web/vhosts/core.js b/src/admin/web/vhosts/core.js index 787de33..0c47225 100644 --- a/src/admin/web/vhosts/core.js +++ b/src/admin/web/vhosts/core.js @@ -100,10 +100,6 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha const holders = {}, adders = {}, emptyStates = {}; const renumber = direction => { const rows = holders[direction]; - [...rows.children].forEach((row, index) => { - const title = row.querySelector(".vh-header-rule-title"); - if (title) title.textContent = `${t("headerRule")} ${index + 1}`; - }); if (emptyStates[direction]) emptyStates[direction].hidden = rows.children.length > 0; }; const sync = () => { diff --git a/src/logging/error_runtime.rs b/src/logging/error_runtime.rs index 8e57b33..d5768d4 100644 --- a/src/logging/error_runtime.rs +++ b/src/logging/error_runtime.rs @@ -144,8 +144,8 @@ fn rfc3339_now() -> String { format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z") } -async fn open_error_file(path: PathBuf) -> Result { - let file = tokio::task::spawn_blocking(move || -> Result { +async fn open_error_file(path: PathBuf) -> Result<(File, RotationCheck)> { + let (file, identity) = tokio::task::spawn_blocking(move || -> Result<(std::fs::File, Option)> { let mut options = std::fs::OpenOptions::new(); options.create(true).append(true).write(true); #[cfg(unix)] @@ -161,11 +161,11 @@ async fn open_error_file(path: PathBuf) -> Result { use std::os::unix::fs::PermissionsExt; file.set_permissions(std::fs::Permissions::from_mode(0o600))?; } - Ok(file) + Ok((file, file_identity(&metadata))) }) .await .map_err(|_| anyhow::anyhow!("error log open worker failed"))??; - Ok(File::from_std(file)) + Ok((File::from_std(file), RotationCheck::new(identity))) } fn format_error_event(event: &ErrorEvent, format: ErrorLogFormat) -> Vec { @@ -230,7 +230,7 @@ async fn error_log_loop( errors: Arc, ) { let mut open_path: Option = None; - let mut file: Option = None; + let mut file: Option<(File, RotationCheck)> = None; let mut retry_after: Option = None; let mut last_warning: Option = None; loop { @@ -268,6 +268,12 @@ async fn error_log_loop( open_path = Some(path.clone()); retry_after = None; } + // Reopen after external rotation (logrotate `create`, mv, rm). + if let Some((_, rotation)) = file.as_mut() { + if rotation.rotated(&path).await { + file = None; + } + } if file.is_none() && retry_after.is_none_or(|until| Instant::now() >= until) { match open_error_file(path.clone()).await { Ok(opened) => { @@ -284,7 +290,7 @@ async fn error_log_loop( } } } - let Some(opened) = file.as_mut() else { + let Some((opened, _)) = file.as_mut() else { write_error_fallback(&event, config.format); continue; }; diff --git a/src/logging/format.rs b/src/logging/format.rs index 2c5456c..37be7d9 100644 --- a/src/logging/format.rs +++ b/src/logging/format.rs @@ -11,6 +11,12 @@ pub struct LogEntry { pub authority: Option, pub matched_by: Option<&'static str>, pub vhost: Option, + /// Redirect host that answered the request (its own per-site log file). + #[serde(skip_serializing_if = "Option::is_none")] + pub redirect_host: Option, + /// Local 404 host that answered the request (its own per-site log file). + #[serde(skip_serializing_if = "Option::is_none")] + pub local_host: Option, pub route: Option, pub cache_effective_enabled: Option, pub transform_effective_enabled: Option, @@ -263,6 +269,8 @@ impl Logs { authority, matched_by: Some(matched_by), vhost, + redirect_host: None, + local_host: None, route: None, cache_effective_enabled: None, transform_effective_enabled: None, @@ -368,6 +376,16 @@ fn value_for(entry: &LogEntry, name: &str) -> Value { .clone() .map(Value::String) .unwrap_or(Value::Null), + "redirect_host" => entry + .redirect_host + .clone() + .map(Value::String) + .unwrap_or(Value::Null), + "local_host" => entry + .local_host + .clone() + .map(Value::String) + .unwrap_or(Value::Null), "route" => entry .route .clone() diff --git a/src/logging/model.rs b/src/logging/model.rs index 034b8a6..16ede2a 100644 --- a/src/logging/model.rs +++ b/src/logging/model.rs @@ -261,6 +261,8 @@ fn source_value_name(name: &str) -> bool { | "outcome" | "cache" | "cache_reason" + | "redirect_host" + | "local_host" ) } diff --git a/src/logging/runtime.rs b/src/logging/runtime.rs index 50ad7ee..5d0e765 100644 --- a/src/logging/runtime.rs +++ b/src/logging/runtime.rs @@ -141,9 +141,74 @@ fn loki_client() -> Result { struct FileState { path: PathBuf, file: File, + rotation: RotationCheck, +} + +/// Identity of an open log file, used to notice external rotation (logrotate +/// `create`, mv, rm): the path then names a different file or none at all. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct FileIdentity { + device: u64, + inode: u64, +} +fn file_identity(metadata: &std::fs::Metadata) -> Option { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + Some(FileIdentity { + device: metadata.dev(), + inode: metadata.ino(), + }) + } + #[cfg(not(unix))] + { + let _ = metadata; + None + } +} +const ROTATION_CHECK_INTERVAL: Duration = Duration::from_secs(1); +#[derive(Debug)] +struct RotationCheck { + identity: Option, + checked: Instant, +} +impl RotationCheck { + fn new(identity: Option) -> Self { + Self { + identity, + checked: Instant::now(), + } + } + /// True when `path` no longer refers to the open file. Checked at most once per + /// second, so a busy log costs one `stat` per second. + async fn rotated(&mut self, path: &std::path::Path) -> bool { + let Some(identity) = self.identity else { + return false; + }; + if self.checked.elapsed() < ROTATION_CHECK_INTERVAL { + return false; + } + self.checked = Instant::now(); + match tokio::fs::symlink_metadata(path).await { + Ok(metadata) => file_identity(&metadata) != Some(identity), + Err(error) => error.kind() == std::io::ErrorKind::NotFound, + } + } } const PER_VHOST_OPEN_FILES: usize = 64; +/// File name (without `.jsonl`) of a per-site access log: the vhost id, or +/// `.redirect` / `.host404` for redirect and local 404 hosts (ids cannot +/// contain dots, so these never collide with a vhost), else `_unmatched`. +fn entry_log_name(entry: &LogEntry) -> String { + if let Some(id) = entry.redirect_host.as_deref().filter(|id| crate::config::valid_id(id)) { + return format!("{id}.redirect"); + } + if let Some(id) = entry.local_host.as_deref().filter(|id| crate::config::valid_id(id)) { + return format!("{id}.host404"); + } + vhost_log_name(entry.vhost.as_deref()) +} fn vhost_log_name(vhost: Option<&str>) -> String { vhost .filter(|value| crate::config::valid_id(value)) @@ -155,8 +220,8 @@ struct LogstashState { stream: TcpStream, } -async fn open_access_file(path: PathBuf) -> Result { - let file = tokio::task::spawn_blocking(move || -> Result { +async fn open_access_file(path: PathBuf) -> Result<(File, RotationCheck)> { + let (file, identity) = tokio::task::spawn_blocking(move || -> Result<(std::fs::File, Option)> { let mut options = std::fs::OpenOptions::new(); options.create(true).append(true).write(true); #[cfg(unix)] @@ -172,11 +237,11 @@ async fn open_access_file(path: PathBuf) -> Result { use std::os::unix::fs::PermissionsExt; file.set_permissions(std::fs::Permissions::from_mode(0o600))?; } - Ok(file) + Ok((file, file_identity(&metadata))) }) .await .map_err(|_| anyhow::anyhow!("access log open worker failed"))??; - Ok(File::from_std(file)) + Ok((File::from_std(file), RotationCheck::new(identity))) } async fn sink_loop( mut rx: mpsc::Receiver>, @@ -187,7 +252,7 @@ async fn sink_loop( ) { let client = loki_client().ok(); let mut file: Option = None; - let mut vhost_files: BTreeMap = BTreeMap::new(); + let mut vhost_files: BTreeMap = BTreeMap::new(); let mut vhost_directory: Option = None; let mut logstash: Option = None; let mut deferred_entry: Option> = None; @@ -210,11 +275,17 @@ async fn sink_loop( vhost_files.clear(); vhost_directory = None; let path = PathBuf::from(&config.file.path); + if let Some(state) = file.as_mut() { + if state.path == path && state.rotation.rotated(&path).await { + file = None; + } + } if file.as_ref().is_none_or(|state| state.path != path) { file = match open_access_file(path.clone()).await { - Ok(opened) => Some(FileState { + Ok((opened, rotation)) => Some(FileState { path: path.clone(), file: opened, + rotation, }), Err(error) => { tracing::warn!(%error, path=%path.display(), "access log file unavailable"); @@ -272,8 +343,12 @@ async fn sink_loop( if tokio::fs::create_dir_all(&directory).await.is_err() { failed = true; } else { - let path = - directory.join(format!("{}.jsonl", vhost_log_name(entry.vhost.as_deref()))); + let path = directory.join(format!("{}.jsonl", entry_log_name(&entry))); + if let Some((_, rotation)) = vhost_files.get_mut(&path) { + if rotation.rotated(&path).await { + vhost_files.remove(&path); + } + } if !vhost_files.contains_key(&path) { if vhost_files.len() >= PER_VHOST_OPEN_FILES { if let Some(path) = vhost_files.keys().next().cloned() { @@ -291,7 +366,7 @@ async fn sink_loop( } } let write_failed = match vhost_files.get_mut(&path) { - Some(opened) => opened.write_all(&jsonl_line).await.is_err(), + Some((opened, _)) => opened.write_all(&jsonl_line).await.is_err(), None => true, }; if write_failed { @@ -303,11 +378,17 @@ async fn sink_loop( vhost_files.clear(); vhost_directory = None; let path = PathBuf::from(&config.file.path); + if let Some(state) = file.as_mut() { + if state.path == path && state.rotation.rotated(&path).await { + file = None; + } + } if file.as_ref().is_none_or(|state| state.path != path) { file = match open_access_file(path.clone()).await { - Ok(opened) => Some(FileState { + Ok((opened, rotation)) => Some(FileState { path: path.clone(), file: opened, + rotation, }), Err(error) => { tracing::warn!(%error, path=%path.display(), "access log file unavailable"); diff --git a/src/logging/tests.rs b/src/logging/tests.rs index be60d12..632e73c 100644 --- a/src/logging/tests.rs +++ b/src/logging/tests.rs @@ -15,6 +15,8 @@ mod tests { authority: None, matched_by: None, vhost: Some("app".into()), + redirect_host: None, + local_host: None, route: Some("root".into()), cache_effective_enabled: Some(true), transform_effective_enabled: Some(false), @@ -654,4 +656,39 @@ mod tests { let jsonl = tokio::fs::read_to_string(path).await.unwrap(); assert_eq!(jsonl.lines().count(), 1); } + #[tokio::test] + async fn rotated_log_files_are_detected_for_reopening() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("app.jsonl"); + let (_file, mut check) = open_access_file(path.clone()).await.unwrap(); + check.checked -= ROTATION_CHECK_INTERVAL * 2; + assert!(!check.rotated(&path).await, "same file is not a rotation"); + // logrotate `create`: the old file is renamed and a new one created. + std::fs::rename(&path, dir.path().join("app.jsonl.1")).unwrap(); + check.checked -= ROTATION_CHECK_INTERVAL * 2; + assert!(check.rotated(&path).await, "missing path means rotated"); + std::fs::write(&path, b"").unwrap(); + check.checked -= ROTATION_CHECK_INTERVAL * 2; + assert!(check.rotated(&path).await, "new file means rotated"); + // Checks are rate-limited. + let (_file, mut fresh) = open_access_file(path.clone()).await.unwrap(); + std::fs::remove_file(&path).unwrap(); + assert!(!fresh.rotated(&path).await); + } + + #[test] + fn redirect_and_local_hosts_get_their_own_log_files() { + let mut item = entry(); + assert_eq!(entry_log_name(&item), "app"); + item.vhost = None; + item.redirect_host = Some("old-site".into()); + assert_eq!(entry_log_name(&item), "old-site.redirect"); + item.redirect_host = None; + item.local_host = Some("parking".into()); + assert_eq!(entry_log_name(&item), "parking.host404"); + item.local_host = Some("../bad".into()); + assert_eq!(entry_log_name(&item), "_unmatched"); + let json = serde_json::to_value(entry()).unwrap(); + assert!(json.get("redirect_host").is_none() && json.get("local_host").is_none()); + } } diff --git a/src/proxy/body/mod.rs b/src/proxy/body/mod.rs index f6d9b78..8ef49d5 100644 --- a/src/proxy/body/mod.rs +++ b/src/proxy/body/mod.rs @@ -49,6 +49,13 @@ fn read_effective(value: u8) -> Option { } } +/// Redirect or local 404 host that answered instead of a vhost; it gets its own +/// per-site access log file. +#[derive(Debug, Clone)] +pub enum LogSite { + Redirect(String), + LocalHost(String), +} pub struct Exchange { pub vhost_metrics: Option>, pub vhost: Option, @@ -58,6 +65,7 @@ pub struct Exchange { pub routed: Mutex>>, /// Request values for response header rules with `%[variables]`. pub header_vars: Mutex>>, + pub log_site: Mutex>, pub source: AtomicU8, pub cache_effective_enabled: AtomicU8, pub transform_effective_enabled: AtomicU8, @@ -232,7 +240,12 @@ impl Drop for Exchange { } else { "complete" }; - if let Some(vhost) = self.vhost.as_ref() { + let log_site = self + .log_site + .get_mut() + .unwrap_or_else(|e| e.into_inner()) + .take(); + if let Some(vhost) = self.vhost.as_ref().filter(|_| log_site.is_none()) { self.traffic.push_lazy(|| crate::traffic::Sample { vhost: vhost.clone(), route: route.clone(), @@ -261,7 +274,19 @@ impl Drop for Exchange { authority: None, matched_by: None, cache_reason, - vhost: self.vhost.take(), + vhost: if log_site.is_some() { + None + } else { + self.vhost.take() + }, + redirect_host: match &log_site { + Some(LogSite::Redirect(id)) => Some(id.clone()), + _ => None, + }, + local_host: match &log_site { + Some(LogSite::LocalHost(id)) => Some(id.clone()), + _ => None, + }, route, cache_effective_enabled, transform_effective_enabled, diff --git a/src/proxy/body/tests.rs b/src/proxy/body/tests.rs index 8e42f28..23c4826 100644 --- a/src/proxy/body/tests.rs +++ b/src/proxy/body/tests.rs @@ -13,6 +13,7 @@ mod tests { route: Mutex::new(None), routed: Mutex::new(None), header_vars: Mutex::new(None), + log_site: Mutex::new(None), source: AtomicU8::new(ExchangeSource::Unresolved as u8), cache_effective_enabled: AtomicU8::new(0), transform_effective_enabled: AtomicU8::new(0), diff --git a/src/proxy/forward_entry.rs b/src/proxy/forward_entry.rs index f21330e..cef512d 100644 --- a/src/proxy/forward_entry.rs +++ b/src/proxy/forward_entry.rs @@ -155,6 +155,17 @@ async fn forward_request( (Some(vhost), Some(local_host)) => local_host >= vhost, _ => true, }); + // Requests answered by a redirect or local 404 host are logged under that host. + if let Some(exchange) = request.extensions().get::>() { + let site = redirect + .map(|(redirect, _)| crate::proxy::body::LogSite::Redirect(redirect.id.clone())) + .or_else(|| { + local_host.map(|item| crate::proxy::body::LogSite::LocalHost(item.id.clone())) + }); + if site.is_some() { + *exchange.log_site.lock().unwrap_or_else(|e| e.into_inner()) = site; + } + } if request.version() == Version::HTTP_2 && (frontend.is_some_and(|frontend| !frontend.http2_enabled) || redirect.is_some_and(|(redirect, _)| !redirect.http2_enabled) diff --git a/src/proxy/upstream_helpers.rs b/src/proxy/upstream_helpers.rs index bd4e0a3..7978092 100644 --- a/src/proxy/upstream_helpers.rs +++ b/src/proxy/upstream_helpers.rs @@ -217,6 +217,7 @@ async fn observe(state: Arc, mut request: Request) -> Response { route: Mutex::new(None), routed: Mutex::new(None), header_vars: Mutex::new(None), + log_site: Mutex::new(None), source: AtomicU8::new(ExchangeSource::Unresolved as u8), cache_effective_enabled: AtomicU8::new(0), transform_effective_enabled: AtomicU8::new(0),