ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(wordpress): per-site PHP-fatals analytics from the WP_DEBUG log (#25)
Juan Denis733f866f1c14
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.pyindex 2dcfb876..c25e69d1 100644--- a/backend/app/api/wordpress.py+++ b/backend/app/api/wordpress.py@@ -566,6 +566,8 @@ def get_site_analytics(app_id):if user.role != 'admin' and app.user_id != current_user_id:return jsonify({'error': 'Access denied'}), 403result = WpAnalyticsService.get_traffic(app.name, request.args.get('hours', 24))+ # PHP fatals/warnings from the WP_DEBUG log (#25 fatals; populated by #30's toggle).+ result['php_errors'] = WpAnalyticsService.get_php_errors(app.name)return jsonify(result), 200diff --git a/backend/app/services/wp_analytics_service.py b/backend/app/services/wp_analytics_service.pyindex 1c1427a3..3e89ebdf 100644--- a/backend/app/services/wp_analytics_service.py+++ b/backend/app/services/wp_analytics_service.py@@ -8,9 +8,11 @@ symlink to stdout — exec-cat'ing it yields nothing). Analytics is computedbounded by the container's retained log (it resets when the container isrecreated, e.g. on a PHP-version switch — see #24).-Intentionally NOT derived from the default access log (deferred):-- PHP fatals — need ``wp-content/debug.log``, which only exists once WP_DEBUG_LOG- is enabled (the per-site WP_DEBUG toggle is #30).+PHP fatals/warnings are sourced separately from the WP_DEBUG log+(``/tmp/wp-debug.log``), populated only once the per-site WP_DEBUG toggle (#30)+is on — see ``get_php_errors`` (they are not in the access log).++Still NOT derived (deferred):- per-request response time / slow pages — need a ``%D`` LogFormat the officialimage does not emit.- cache hit ratio — a cache-plugin concern surfaced by #22/#23, not the access log.@@ -151,6 +153,86 @@ class WpAnalyticsService:})return result+ # --- PHP errors (#25 fatals) -------------------------------------------+ # Sourced from the WP_DEBUG log, NOT the access log. The log only exists once+ # the per-site WP_DEBUG toggle (#30) is on; its path is owned by WpSecurityService.+ DEBUG_LOG = '/tmp/wp-debug.log'+ PHP_ERR_TAIL = 200000 # bytes; bound the debug-log read so a noisy site can't blow up memory+ RECENT_CAP = 25 # most-recent entries returned++ # WP debug.log line: "[15-Jun-2026 12:34:56 UTC] PHP Fatal error: <message>"+ _PHP_ERR_RE = re.compile(r'^\[(?P<time>[^\]]+)\]\s+PHP\s+(?P<level>[A-Za-z][A-Za-z ]*?):\s+(?P<msg>.*)$')++ @staticmethod+ def _classify_php(level):+ l = level.lower()+ if 'fatal' in l or 'parse error' in l:+ return 'fatal'+ if 'warning' in l:+ return 'warning'+ if 'deprecated' in l:+ return 'deprecated'+ if 'notice' in l:+ return 'notice'+ return 'other'++ @classmethod+ def get_php_errors(cls, container_name):+ """Parse PHP fatals/warnings/notices from the container's WP_DEBUG log+ (``/tmp/wp-debug.log``, written only once the #30 WP_DEBUG toggle is on).+ On-demand like get_traffic, with a bounded read + hard timeout so the+ single worker never blocks. Never raises."""+ out = {'available': False, 'enabled': False, 'total': 0,+ 'counts': {'fatal': 0, 'warning': 0, 'notice': 0, 'deprecated': 0, 'other': 0},+ 'recent': [], 'note': None}+ if not container_name:+ out['note'] = 'No container is resolved for this site.'+ return out++ # One exec: print a marker IFF the log exists, then its (size-capped) tail.+ # Empty output => no log => WP_DEBUG logging not enabled (or never errored).+ marker = '__SK_WPDEBUG__'+ script = (f'if [ -f {cls.DEBUG_LOG} ]; then echo {marker}; '+ f'tail -c {cls.PHP_ERR_TAIL} {cls.DEBUG_LOG}; fi')+ try:+ proc = subprocess.run(+ ['docker', 'exec', container_name, 'sh', '-c', script],+ capture_output=True, text=True, timeout=cls.LOG_TIMEOUT,+ )+ except subprocess.TimeoutExpired:+ out['note'] = 'Debug log read timed out.'+ return out+ except (FileNotFoundError, OSError):+ out['note'] = 'Debug log is unavailable on this host (Docker is not reachable).'+ return out+ if proc.returncode != 0:+ out['note'] = 'Debug log is unavailable — the container may be stopped or on another host.'+ return out++ body = proc.stdout or ''+ if not body.startswith(marker):+ out['note'] = ('PHP error logging is off — enable WP_DEBUG logging on the '+ 'Security tab to collect PHP fatals and warnings.')+ return out+ out['available'] = True+ out['enabled'] = True+ content = body[len(marker):].lstrip('\n')++ recent = []+ for raw in content.splitlines():+ m = cls._PHP_ERR_RE.match(raw.strip())+ if not m:+ continue # stack-trace / continuation lines won't match+ sev = cls._classify_php(m.group('level'))+ out['counts'][sev] += 1+ out['total'] += 1+ recent.append({'time': m.group('time'), 'level': m.group('level').strip(),+ 'severity': sev, 'message': m.group('msg').strip()[:300]})+ out['recent'] = list(reversed(recent))[:cls.RECENT_CAP] # most-recent first+ if out['total'] == 0:+ out['note'] = 'WP_DEBUG logging is on; no PHP errors recorded yet.'+ return out+@classmethoddef _empty(cls, hours):now_hour = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)diff --git a/backend/tests/test_wp_php_errors.py b/backend/tests/test_wp_php_errors.pynew file mode 100644index 00000000..a326e8ac--- /dev/null+++ b/backend/tests/test_wp_php_errors.py@@ -0,0 +1,87 @@+"""Tests for #25 PHP-fatals ingest — parsing the WP_DEBUG log (docker exec mocked)."""++_SAMPLE = (+ '__SK_WPDEBUG__\n'+ '[15-Jun-2026 12:00:01 UTC] PHP Fatal error: Uncaught Error: Call to undefined '+ 'function foo() in /var/www/html/wp-content/plugins/x/x.php:12\n'+ 'Stack trace:\n'+ '#0 /var/www/html/index.php(17): require()\n'+ '#1 {main}\n'+ ' thrown in /var/www/html/wp-content/plugins/x/x.php on line 12\n'+ '[15-Jun-2026 12:05:00 UTC] PHP Warning: Undefined array key "k" in /t/functions.php on line 5\n'+ '[15-Jun-2026 12:06:00 UTC] PHP Deprecated: Function xyz() is deprecated in /x on line 1\n'+ '[15-Jun-2026 12:07:00 UTC] PHP Notice: Undefined variable $z in /x on line 2\n'+)+++class _Res:+ def __init__(self, rc, out):+ self.returncode = rc+ self.stdout = out+ self.stderr = ''+++def _mock_run(monkeypatch, rc, out):+ import app.services.wp_analytics_service as mod+ monkeypatch.setattr(mod.subprocess, 'run', lambda *a, **k: _Res(rc, out))+++def test_classify_php_levels():+ from app.services.wp_analytics_service import WpAnalyticsService as W+ assert W._classify_php('Fatal error') == 'fatal'+ assert W._classify_php('Parse error') == 'fatal'+ assert W._classify_php('Recoverable fatal error') == 'fatal'+ assert W._classify_php('Warning') == 'warning'+ assert W._classify_php('Deprecated') == 'deprecated'+ assert W._classify_php('Notice') == 'notice'+ assert W._classify_php('Strict standards') == 'other'+++def test_get_php_errors_parses_and_skips_stack_traces(monkeypatch):+ from app.services.wp_analytics_service import WpAnalyticsService+ _mock_run(monkeypatch, 0, _SAMPLE)+ out = WpAnalyticsService.get_php_errors('site')+ assert out['available'] is True and out['enabled'] is True+ assert out['total'] == 4 # stack-trace / "thrown in" lines are skipped+ assert out['counts'] == {'fatal': 1, 'warning': 1, 'notice': 1, 'deprecated': 1, 'other': 0}+ # Most-recent first: the Notice (12:07) leads.+ assert out['recent'][0]['severity'] == 'notice'+ assert 'Uncaught Error' in out['recent'][-1]['message']+++def test_get_php_errors_logging_off(monkeypatch):+ from app.services.wp_analytics_service import WpAnalyticsService+ _mock_run(monkeypatch, 0, '') # no marker => log file absent+ out = WpAnalyticsService.get_php_errors('site')+ assert out['available'] is False+ assert 'logging is off' in out['note']+++def test_get_php_errors_on_but_empty(monkeypatch):+ from app.services.wp_analytics_service import WpAnalyticsService+ _mock_run(monkeypatch, 0, '__SK_WPDEBUG__\n') # log exists, no entries+ out = WpAnalyticsService.get_php_errors('site')+ assert out['available'] is True and out['total'] == 0+ assert 'no PHP errors recorded' in out['note']+++def test_get_php_errors_container_unavailable(monkeypatch):+ from app.services.wp_analytics_service import WpAnalyticsService+ _mock_run(monkeypatch, 1, '') # docker exec non-zero (stopped / missing)+ out = WpAnalyticsService.get_php_errors('site')+ assert out['available'] is False and 'unavailable' in out['note']+++def test_get_php_errors_no_container():+ from app.services.wp_analytics_service import WpAnalyticsService+ out = WpAnalyticsService.get_php_errors(None)+ assert out['available'] is False and out['total'] == 0+++def test_message_truncation(monkeypatch):+ from app.services.wp_analytics_service import WpAnalyticsService+ long = 'x' * 500+ _mock_run(monkeypatch, 0, f'__SK_WPDEBUG__\n[1 UTC] PHP Fatal error: {long}\n')+ out = WpAnalyticsService.get_php_errors('site')+ assert out['counts']['fatal'] == 1+ assert len(out['recent'][0]['message']) == 300 # cappeddiff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.mdindex 08827e76..1b2b2a44 100644--- a/docs/WORDPRESS_ROADMAP.md+++ b/docs/WORDPRESS_ROADMAP.md@@ -231,12 +231,13 @@ The headline value of a managed platform, and the most net-new — but it leans- **Done when:** A site's PHP version and limits are editable per environment.- **Landed (limit-WRITE):** the deferred write side now ships, Docker-correct for the `wordpress:*-apache` (Apache + mod_php) model. New `WordPressService.set_php_limits(path, limits)` whitelists + **`re.fullmatch`-validates** each directive (`memory_limit`, `upload_max_filesize`, `post_max_size`, `max_execution_time`, `max_input_time`, `max_input_vars`) — fullmatch (not match) so a value like `"256M\nevil = 1"` can't smuggle a second ini line past the `$` anchor — then writes a host-side `php-conf/zz-serverkit.ini` and **bind-mounts that single file into `/usr/local/etc/php/conf.d/`** so it survives container recreate (a plain `docker exec` write would be lost on the next `compose up`). The host file is written **before** the mount is added (a single-file bind-mount needs its source to pre-exist, else Docker makes a directory); a newly-added mount applies via `compose up -d` (recreate), a content-only change via `compose_restart('wordpress')` so mod_php re-reads `php.ini`. Partial updates **merge** with the existing drop-in (no directive is dropped), and the mount is injected once (idempotent). Route `POST /sites/<id>/php/limits` (`@admin_required`), client `setPhpLimits`, and an **Edit PHP Limits** panel added to the PHP tab (per-directive inputs seeded from live values, partial-diff save). **Also fixed a latent #24 bug:** the `PhpTab` component (the read panel + version switch) was built but **never wired into `WordPressDetail`** — no tab button, no render branch — so the entire PHP panel was invisible; added `'php'` to `VALID_TABS` + a PHP tab + the render branch, so the read panel *and* the new limits editor actually render. Verified: backend `py_compile`, **7 new pytest tests** (unknown-directive + injection-value rejection, non-stack-site guard, ini-write + single-file-mount injection, partial-merge + no-duplicate-mount, unlimited/size-suffix acceptance, ini parsing), full suite **200 passed / 12 skipped**, frontend lint-clean (the `PhpTab`-unused warning is now gone) + production build. Not runtime-exercised on a real Docker host (Windows dev).-### #25 — Per-site traffic / error / cache analytics `[L]` ❌ — ✅ Done (Docker-correct: on-demand apache access-log analytics; PHP-fatals / response-time / cache-ratio deferred)+### #25 — Per-site traffic / error / cache analytics `[L]` ❌ — ✅ Done (Docker-correct: on-demand apache access-log analytics **+ PHP-fatals from the WP_DEBUG log**; response-time / cache-ratio deferred)- **Today:** All metrics are host/agent-keyed; API analytics covers only ServerKit's own API. No per-site visits/bandwidth/5xx/404/PHP-fatal.- **Do:** An nginx access/error + `wp-content/debug.log` ingest pipeline keyed to each WP vhost → visits, bandwidth, bot %, top URLs, 5xx/404, PHP fatals, slow pages, cache hit ratio.- **Reuse:** the existing log-tail / `metrics_history_service` aggregation patterns.- **Done when:** The site dashboard shows per-site traffic and error analytics.- **Landed:** **Architectural pivot** — managed WP sites are `wordpress:*-apache` containers on `localhost:PORT` with **no per-site nginx**, so the roadmap's "nginx access log" premise doesn't hold; the official image symlinks Apache's access log to the container's **stdout**, making `docker logs` the Docker-correct source. New `WpAnalyticsService.get_traffic(container_name, hours)` pulls `docker logs --tail 20000 --since <h>` (**hard 15s timeout**, reads only **stdout** to separate the access log from the stderr error_log, `returncode`-checked so stopped/missing/remote-agent containers degrade to an accurate note) and parses the Apache *combined* log **on-demand** — no store / collector / migration. It returns requests, unique visitors, bandwidth, status distribution (2xx/3xx/4xx/5xx), 404s, bot %, error rate, top URLs (grouped by route — query strings stripped so visitor tokens aren't surfaced), and a continuous hourly requests/errors series. Route `GET /sites/<id>/analytics?hours=` (owner/admin-guarded), client `getSiteAnalytics`, and a new **Analytics tab** on the site detail (stat cards + a recharts requests/errors AreaChart + status codes + Top URLs) with graceful empty/timeout/unavailable states. This also supplies the 5xx/error-rate signal **#27**'s "error spike" rule needs. *(Deferred — not derivable from the default access log: **PHP fatals** need `wp-content/debug.log` via a WP_DEBUG toggle (#30); **response time / slow pages** need a `%D` LogFormat the official image doesn't emit; **cache hit ratio** is a cache-plugin concern (#22/#23). History is point-in-time over the retained container log (resets on container recreate) — a persistent time-series collector on the `metrics_history` pattern is a clean follow-up.)* Verified: backend `py_compile`, frontend lint-clean + production build, a 3-lens adversarial review (major fixed: docker-logs timeout + memory cap; minor: accurate unavailable note via `returncode`; query-string token stripping). Not runtime-exercised on a real Docker host (Windows dev).+- **Landed (PHP fatals):** the deferred PHP-fatals signal now ships, sourced from the **WP_DEBUG log** (`/tmp/wp-debug.log`) that **#30**'s Security-tab toggle writes — *not* the access log (which can't carry it), exactly as the original deferral noted. New `WpAnalyticsService.get_php_errors(container)` does one bounded `docker exec` (a marker-guarded `tail -c 200000` with the same 15s single-worker timeout as `get_traffic`) to distinguish "WP_DEBUG logging off / no log" from "on but clean", then parses WP debug lines (`[time] PHP <Level>: <msg>`) into severity counts (**fatal**/warning/notice/deprecated — `Parse`/`Recoverable fatal` fold into fatal) + the 25 most-recent entries (messages capped at 300 chars; stack-trace continuation lines skipped). Merged into `GET /sites/<id>/analytics` as `php_errors`, and a **PHP errors** panel added to the Analytics tab (severity counts + recent list, with an explicit "enable WP_DEBUG logging on the Security tab" empty state). This also supplies the per-site **error signal #27**'s "error spike" rule wanted. Verified: backend `py_compile`, **7 new pytest tests** (level classification, parse-and-skip-stack-traces, logging-off vs on-but-empty vs container-unavailable, message truncation — docker mocked), full suite **218 passed / 12 skipped**, frontend lint-clean + production build. *(Still deferred: response-time/slow-pages — needs a `%D` LogFormat the official image doesn't emit — and cache hit-ratio, a #22/#23 plugin concern.)* The `docker exec` read is not runtime-exercised on a real host (Windows dev).### #26 — Per-site uptime + auto-incidents `[M]` 🟡 — ✅ Done (server-side health poller → bound status-page component with a real uptime % + auto-open/resolve incidents)- **Today:** Status pages / uptime have no FK to a WP site; components are hand-typed with arbitrary `check_target`; `EnvironmentHealthService` outages don't open incidents.diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsxindex 8eff71de..0b2a105f 100644--- a/frontend/src/pages/WordPressDetail.jsx+++ b/frontend/src/pages/WordPressDetail.jsx@@ -1336,7 +1336,9 @@ const AnalyticsTab = ({ siteId }) => {: d.toLocaleDateString([], { month: 'short', day: 'numeric' });};const clip = (p) => (p && p.length > 48 ? `${p.slice(0, 48)}…` : p);+ const clipMsg = (m) => (m && m.length > 80 ? `${m.slice(0, 80)}…` : m);const s = data?.status || {};+ const phpErr = data?.php_errors;return (<div className="app-overview-grid">@@ -1409,7 +1411,39 @@ const AnalyticsTab = ({ siteId }) => {</div>))}</div>- <p className="hint">Read live from the container access log; PHP fatals and response-time metrics are not captured by the default log.</p>+ <p className="hint">Read live from the container access log; response-time metrics are not captured by the default log.</p>+ </div>+ </div>+ )}++ {phpErr && (+ <div className="app-panel">+ <div className="app-panel-header">PHP errors</div>+ <div className="app-panel-body">+ {!phpErr.available ? (+ <p className="hint">{phpErr.note || 'PHP error logging is off.'}</p>+ ) : (+ <>+ <div className="app-info-grid">+ <div className="app-info-item"><span className="app-info-label">Fatal</span><span className="app-info-value">{(phpErr.counts?.fatal ?? 0).toLocaleString()}</span></div>+ <div className="app-info-item"><span className="app-info-label">Warning</span><span className="app-info-value">{(phpErr.counts?.warning ?? 0).toLocaleString()}</span></div>+ <div className="app-info-item"><span className="app-info-label">Notice</span><span className="app-info-value">{(phpErr.counts?.notice ?? 0).toLocaleString()}</span></div>+ <div className="app-info-item"><span className="app-info-label">Deprecated</span><span className="app-info-value">{(phpErr.counts?.deprecated ?? 0).toLocaleString()}</span></div>+ </div>+ {phpErr.recent?.length > 0 ? (+ <div className="app-info-grid">+ {phpErr.recent.map((e, i) => (+ <div className="app-info-item" key={i}>+ <span className="app-info-label" title={e.message}>{e.level}: {clipMsg(e.message)}</span>+ <span className="app-info-value">{e.time}</span>+ </div>+ ))}+ </div>+ ) : (+ <p className="hint">{phpErr.note || 'No PHP errors recorded.'}</p>+ )}+ </>+ )}</div></div>)}