Skip to content

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.

feat(databases): live processlist with kill in the explorer

Juan Denis0a82873c832d
diff --git a/backend/app/api/databases.py b/backend/app/api/databases.py
index 9249acf3..dd7112ed 100644
--- a/backend/app/api/databases.py
+++ b/backend/app/api/databases.py
@@ -4,6 +4,7 @@ from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models import User, Application
from app.services.database_service import DatabaseService
+from app.services.db_process_service import DbProcessService
from app.services.managed_database_service import ManagedDatabaseService
from app.middleware.rbac import admin_required
from app.services.resource_grant_service import ResourceGrantService
@@ -919,6 +920,77 @@ def protect_managed_database(managed_id):
return jsonify({'policy': policy.to_dict()}), 201
+# ==================== PROCESSES ====================
+# Live SHOW PROCESSLIST / pg_stat_activity per server or container, with an
+# admin-only kill/terminate action. Targets mirror the explorer's connection
+# shapes (host engine vs docker container).
+
+def _process_error_response(result):
+ code = 400 if result['error'] == 'unsupported engine' else 502
+ return jsonify({'error': result['error']}), code
+
+
+@databases_bp.route('/mysql/processes', defaults={'engine': 'mysql'}, methods=['GET'])
+@databases_bp.route('/postgresql/processes', defaults={'engine': 'postgresql'}, methods=['GET'])
+@jwt_required()
+def list_host_db_processes(engine):
+ """List live server processes on a host engine."""
+ target = {'engine': engine, 'password': request.headers.get('X-DB-Password')}
+ result = DbProcessService.list_processes(target)
+ if 'error' in result:
+ return _process_error_response(result)
+ return jsonify(result), 200
+
+
+@databases_bp.route('/mysql/processes/<int:pid>/kill', defaults={'engine': 'mysql'}, methods=['POST'])
+@databases_bp.route('/postgresql/processes/<int:pid>/kill', defaults={'engine': 'postgresql'}, methods=['POST'])
+@jwt_required()
+@admin_required
+def kill_host_db_process(engine, pid):
+ """Kill/terminate a process on a host engine (admin only)."""
+ target = {'engine': engine, 'password': request.headers.get('X-DB-Password')}
+ result = DbProcessService.kill_process(target, pid)
+ if 'error' in result:
+ return _process_error_response(result)
+ return jsonify(result), 200
+
+
+@databases_bp.route('/docker/<container>/processes', methods=['GET'])
+@jwt_required()
+def list_docker_db_processes(container):
+ """List live server processes inside a Docker database container."""
+ target = {
+ 'engine': request.args.get('type', 'mysql'),
+ 'container': container,
+ 'user': request.args.get('user'),
+ 'password': request.headers.get('X-DB-Password'),
+ 'database': request.args.get('database'),
+ }
+ result = DbProcessService.list_processes(target)
+ if 'error' in result:
+ return _process_error_response(result)
+ return jsonify(result), 200
+
+
+@databases_bp.route('/docker/<container>/processes/<int:pid>/kill', methods=['POST'])
+@jwt_required()
+@admin_required
+def kill_docker_db_process(container, pid):
+ """Kill/terminate a process inside a Docker database container (admin only)."""
+ data = request.get_json(silent=True) or {}
+ target = {
+ 'engine': data.get('type') or request.args.get('type', 'mysql'),
+ 'container': container,
+ 'user': data.get('user'),
+ 'password': request.headers.get('X-DB-Password') or data.get('password'),
+ 'database': data.get('database'),
+ }
+ result = DbProcessService.kill_process(target, pid)
+ if 'error' in result:
+ return _process_error_response(result)
+ return jsonify(result), 200
+
+
# ==================== UTILITY ====================
@databases_bp.route('/generate-password', methods=['GET'])
diff --git a/backend/app/services/db_process_service.py b/backend/app/services/db_process_service.py
new file mode 100644
index 00000000..f59cc323
--- /dev/null
+++ b/backend/app/services/db_process_service.py
@@ -0,0 +1,205 @@
+"""Live database process inspection and termination.
+
+Surfaces ``SHOW FULL PROCESSLIST`` (MySQL/MariaDB) and ``pg_stat_activity``
+(PostgreSQL) for the Database Explorer, plus a kill/terminate action.
+
+A *target* mirrors the explorer's connection shapes:
+
+ {'engine': 'mysql'|'postgresql', # which SQL dialect / client to use
+ 'container': None | 'name', # set for Docker-hosted databases
+ 'user': ..., 'password': ..., # optional credentials
+ 'database': ...} # optional (docker postgres only)
+
+Every statement flows through the single :meth:`DbProcessService._exec_sql`
+choke-point (which reuses the exact exec pathways the explorer already uses in
+``DatabaseService``), so tests can stub one method to cover everything.
+"""
+import subprocess
+
+from app.services.database_service import DatabaseService
+
+SUPPORTED_ENGINES = ('mysql', 'postgresql')
+
+_MYSQL_PROCESSLIST = 'SHOW FULL PROCESSLIST;'
+
+# pid | usename | datname | state | time_s | query (query LAST so the
+# separator-based parse can never be broken by user SQL; newlines/tabs are
+# flattened server-side for the same reason).
+_PG_PROCESSLIST = (
+ "SELECT pid, usename, datname, state, "
+ "COALESCE(floor(extract(epoch FROM now() - query_start))::bigint, 0), "
+ "regexp_replace(COALESCE(query, ''), E'[\\n\\r\\t]+', ' ', 'g') "
+ "FROM pg_stat_activity "
+ "WHERE pid <> pg_backend_pid() "
+ "ORDER BY 5 DESC;"
+)
+
+
+class DbProcessService:
+ """List and kill live server processes for MySQL/MariaDB and PostgreSQL."""
+
+ # ------------------------------------------------------------------
+ # Single exec choke-point
+ # ------------------------------------------------------------------
+ @staticmethod
+ def _exec_sql(target, sql):
+ """Run ``sql`` against the target's engine.
+
+ Returns ``{'success': bool, 'output': str, 'error': str|None}`` —
+ the same shape the underlying ``DatabaseService`` helpers return.
+ """
+ engine = target.get('engine')
+ container = target.get('container')
+ try:
+ if container:
+ if engine == 'mysql':
+ return DatabaseService.docker_mysql_execute(
+ container, sql,
+ user=target.get('user') or 'root',
+ password=target.get('password'),
+ )
+ # Docker PostgreSQL — same docker-exec pathway, psql client.
+ cmd = ['docker', 'exec']
+ if target.get('password'):
+ cmd.extend(['-e', f"PGPASSWORD={target['password']}"])
+ cmd.extend([
+ container, 'psql',
+ '-U', target.get('user') or 'postgres',
+ '-d', target.get('database') or 'postgres',
+ '-t', '-A', '-c', sql,
+ ])
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
+ return {
+ 'success': result.returncode == 0,
+ 'output': result.stdout,
+ 'error': result.stderr if result.returncode != 0 else None,
+ }
+ if engine == 'mysql':
+ return DatabaseService.mysql_execute(sql, root_password=target.get('password'))
+ return DatabaseService.pg_execute(sql)
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'output': '', 'error': 'Query timed out'}
+ except Exception as e: # docker/client missing (e.g. Windows dev box)
+ return {'success': False, 'output': '', 'error': str(e)}
+
+ # ------------------------------------------------------------------
+ # Public API
+ # ------------------------------------------------------------------
+ @classmethod
+ def list_processes(cls, target):
+ """List live server processes, normalized across engines.
+
+ Returns ``{'processes': [{id, user, db, state, command, time_s,
+ query}, ...]}`` or ``{'error': msg}``.
+ """
+ engine = (target or {}).get('engine')
+ if engine not in SUPPORTED_ENGINES:
+ return {'error': 'unsupported engine'}
+
+ sql = _MYSQL_PROCESSLIST if engine == 'mysql' else _PG_PROCESSLIST
+ result = cls._exec_sql(target, sql)
+ if not result.get('success'):
+ return {'error': result.get('error') or 'failed to list processes'}
+
+ output = result.get('output') or ''
+ if engine == 'mysql':
+ return {'processes': cls._parse_mysql_processlist(output)}
+ return {'processes': cls._parse_pg_activity(output)}
+
+ @classmethod
+ def kill_process(cls, target, pid):
+ """Kill/terminate a server process by id.
+
+ MySQL: ``KILL <id>``; PostgreSQL: ``SELECT pg_terminate_backend(<pid>)``.
+ ``pid`` is validated as an integer before it goes anywhere near SQL.
+ """
+ engine = (target or {}).get('engine')
+ if engine not in SUPPORTED_ENGINES:
+ return {'error': 'unsupported engine'}
+ try:
+ pid = int(pid)
+ except (TypeError, ValueError):
+ return {'error': 'pid must be an integer'}
+
+ if engine == 'mysql':
+ sql = f'KILL {pid};'
+ else:
+ sql = f'SELECT pg_terminate_backend({pid});'
+
+ result = cls._exec_sql(target, sql)
+ if not result.get('success'):
+ return {'error': result.get('error') or 'failed to kill process'}
+ if engine == 'postgresql' and (result.get('output') or '').strip() == 'f':
+ return {'error': 'process not found or could not be terminated'}
+ return {'success': True, 'pid': pid}
+
+ # ------------------------------------------------------------------
+ # Output parsing / normalization
+ # ------------------------------------------------------------------
+ @staticmethod
+ def _parse_mysql_processlist(output):
+ """Parse tab-separated ``SHOW FULL PROCESSLIST`` batch output.
+
+ Columns: Id, User, Host, db, Command, Time, State, Info. ``Info``
+ (the query) is last, so a bounded split keeps embedded tabs safe —
+ the mysql client already escapes newlines in batch mode.
+ """
+ processes = []
+ lines = [ln for ln in output.split('\n') if ln.strip()]
+ for line in lines:
+ parts = line.split('\t', 7)
+ if len(parts) < 7:
+ continue
+ try:
+ proc_id = int(parts[0])
+ except ValueError:
+ continue # header row ("Id\tUser\t...") or noise
+ info = parts[7] if len(parts) > 7 else ''
+ try:
+ time_s = int(parts[5])
+ except ValueError:
+ time_s = 0
+ processes.append({
+ 'id': proc_id,
+ 'user': parts[1],
+ 'db': None if parts[3] == 'NULL' else parts[3],
+ 'command': parts[4],
+ 'time_s': time_s,
+ 'state': parts[6],
+ 'query': '' if info in ('NULL', '') else info,
+ })
+ return processes
+
+ @staticmethod
+ def _parse_pg_activity(output):
+ """Parse ``psql -t -A`` ('|'-separated, no header) activity rows.
+
+ The query column is selected last and split with a bound, so query
+ text containing '|' cannot shift fields.
+ """
+ processes = []
+ for line in output.split('\n'):
+ line = line.strip()
+ if not line:
+ continue
+ parts = line.split('|', 5)
+ if len(parts) < 6:
+ continue
+ try:
+ pid = int(parts[0])
+ except ValueError:
+ continue
+ try:
+ time_s = int(float(parts[4])) if parts[4] else 0
+ except ValueError:
+ time_s = 0
+ processes.append({
+ 'id': pid,
+ 'user': parts[1] or None,
+ 'db': parts[2] or None,
+ 'command': '',
+ 'time_s': time_s,
+ 'state': parts[3] or 'idle',
+ 'query': parts[5],
+ })
+ return processes
diff --git a/backend/tests/test_db_processes.py b/backend/tests/test_db_processes.py
new file mode 100644
index 00000000..29377a46
--- /dev/null
+++ b/backend/tests/test_db_processes.py
@@ -0,0 +1,342 @@
+"""Tests for the live processlist + kill feature (DbProcessService + API)."""
+import pytest
+
+from app.services.db_process_service import DbProcessService
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _stub_exec(monkeypatch, output='', success=True, error=None):
+ """Replace the single _exec_sql choke-point, recording calls."""
+ calls = []
+
+ def fake_exec(target, sql):
+ calls.append({'target': target, 'sql': sql})
+ return {'success': success, 'output': output, 'error': error}
+
+ monkeypatch.setattr(DbProcessService, '_exec_sql', staticmethod(fake_exec))
+ return calls
+
+
+MYSQL_OUTPUT = (
+ "Id\tUser\tHost\tdb\tCommand\tTime\tState\tInfo\n"
+ "5\troot\tlocalhost\tNULL\tSleep\t120\t\tNULL\n"
+ "12\tapp\t172.17.0.3:5544\tshop\tQuery\t3\texecuting\tSELECT * FROM orders WHERE id > 5\n"
+)
+
+PG_OUTPUT = (
+ "101|postgres|appdb|active|42|SELECT a || b FROM t WHERE x = 1\n"
+ "102|svc|appdb|idle|0|\n"
+)
+
+
+# ---------------------------------------------------------------------------
+# list_processes — parsing / normalization
+# ---------------------------------------------------------------------------
+
+class TestListProcessesMySQL:
+ def test_parses_and_normalizes_rows(self, monkeypatch):
+ calls = _stub_exec(monkeypatch, output=MYSQL_OUTPUT)
+ result = DbProcessService.list_processes({'engine': 'mysql'})
+
+ assert 'error' not in result
+ procs = result['processes']
+ assert len(procs) == 2 # header row skipped
+
+ sleep_row = procs[0]
+ assert sleep_row == {
+ 'id': 5, 'user': 'root', 'db': None, 'command': 'Sleep',
+ 'time_s': 120, 'state': '', 'query': '',
+ }
+
+ query_row = procs[1]
+ assert query_row['id'] == 12
+ assert query_row['db'] == 'shop'
+ assert query_row['command'] == 'Query'
+ assert query_row['time_s'] == 3
+ assert query_row['state'] == 'executing'
+ assert query_row['query'] == 'SELECT * FROM orders WHERE id > 5'
+
+ # Sent SHOW FULL PROCESSLIST through the choke-point
+ assert calls[0]['sql'] == 'SHOW FULL PROCESSLIST;'
+
+ def test_empty_output(self, monkeypatch):
+ _stub_exec(monkeypatch, output='')
+ result = DbProcessService.list_processes({'engine': 'mysql'})
+ assert result == {'processes': []}
+
+
+class TestListProcessesPostgres:
+ def test_parses_pipe_separated_rows(self, monkeypatch):
+ calls = _stub_exec(monkeypatch, output=PG_OUTPUT)
+ result = DbProcessService.list_processes({'engine': 'postgresql'})
+
+ procs = result['processes']
+ assert len(procs) == 2
+
+ active = procs[0]
+ assert active['id'] == 101
+ assert active['user'] == 'postgres'
+ assert active['db'] == 'appdb'
+ assert active['state'] == 'active'
+ assert active['time_s'] == 42
+ # Query containing '|' survives (bounded split, query column last)
+ assert active['query'] == 'SELECT a || b FROM t WHERE x = 1'
+
+ idle = procs[1]
+ assert idle['id'] == 102
+ assert idle['time_s'] == 0
+ assert idle['query'] == ''
+
+ assert 'pg_stat_activity' in calls[0]['sql']
+ assert 'pg_backend_pid()' in calls[0]['sql']
+
+ def test_skips_malformed_lines(self, monkeypatch):
+ _stub_exec(monkeypatch, output='garbage\nnot|enough|fields\n')
+ result = DbProcessService.list_processes({'engine': 'postgresql'})
+ assert result == {'processes': []}
+
+
+class TestListProcessesErrors:
+ @pytest.mark.parametrize('engine', ['sqlite', 'mongodb', 'redis', None, ''])
+ def test_unsupported_engine(self, engine):
+ result = DbProcessService.list_processes({'engine': engine})
+ assert result == {'error': 'unsupported engine'}
+
+ def test_exec_failure_surfaces_error(self, monkeypatch):
+ _stub_exec(monkeypatch, success=False, error='docker: command not found')
+ result = DbProcessService.list_processes({'engine': 'mysql', 'container': 'db1'})
+ assert result == {'error': 'docker: command not found'}
+
+ def test_exec_failure_without_message(self, monkeypatch):
+ _stub_exec(monkeypatch, success=False)
+ result = DbProcessService.list_processes({'engine': 'postgresql'})
+ assert result == {'error': 'failed to list processes'}
+
+
+# ---------------------------------------------------------------------------
+# kill_process — SQL generation + pid validation
+# ---------------------------------------------------------------------------
+
+class TestKillProcess:
+ def test_mysql_kill_sql(self, monkeypatch):
+ calls = _stub_exec(monkeypatch)
+ result = DbProcessService.kill_process({'engine': 'mysql'}, 42)
+ assert result == {'success': True, 'pid': 42}
+ assert calls[0]['sql'] == 'KILL 42;'
+
+ def test_pg_terminate_sql(self, monkeypatch):
+ calls = _stub_exec(monkeypatch, output='t\n')
+ result = DbProcessService.kill_process({'engine': 'postgresql'}, '77')
+ assert result == {'success': True, 'pid': 77}
+ assert calls[0]['sql'] == 'SELECT pg_terminate_backend(77);'
+
+ def test_pg_terminate_false_result(self, monkeypatch):
+ _stub_exec(monkeypatch, output='f\n')
+ result = DbProcessService.kill_process({'engine': 'postgresql'}, 77)
+ assert 'error' in result
+
+ @pytest.mark.parametrize('bad_pid', ['abc', '42; DROP TABLE x', None, '1 OR 1=1', ''])
+ def test_pid_must_be_integer(self, monkeypatch, bad_pid):
+ calls = _stub_exec(monkeypatch)
+ result = DbProcessService.kill_process({'engine': 'mysql'}, bad_pid)
+ assert result == {'error': 'pid must be an integer'}
+ assert calls == [] # never reached the exec pathway
+
+ def test_unsupported_engine(self, monkeypatch):
+ calls = _stub_exec(monkeypatch)
+ result = DbProcessService.kill_process({'engine': 'sqlite'}, 1)
+ assert result == {'error': 'unsupported engine'}
+ assert calls == []
+
+ def test_exec_failure(self, monkeypatch):
+ _stub_exec(monkeypatch, success=False, error='access denied')
+ result = DbProcessService.kill_process({'engine': 'mysql'}, 5)
+ assert result == {'error': 'access denied'}
+
+
+# ---------------------------------------------------------------------------
+# _exec_sql routing (host vs docker) — stub the DatabaseService pathways
+# ---------------------------------------------------------------------------
+
+class TestExecSqlRouting:
+ def test_host_mysql_routes_to_mysql_execute(self, monkeypatch):
+ seen = {}
+
+ def fake(query, database=None, root_password=None):
+ seen.update({'query': query, 'root_password': root_password})
+ return {'success': True, 'output': '', 'error': None}
+
+ from app.services import db_process_service
+ monkeypatch.setattr(db_process_service.DatabaseService, 'mysql_execute', staticmethod(fake))
+ result = DbProcessService._exec_sql({'engine': 'mysql', 'password': 's3c'}, 'SELECT 1;')
+ assert result['success'] is True
+ assert seen == {'query': 'SELECT 1;', 'root_password': 's3c'}
+
+ def test_host_pg_routes_to_pg_execute(self, monkeypatch):
+ seen = {}
+
+ def fake(query, database='postgres', user='postgres'):
+ seen['query'] = query
+ return {'success': True, 'output': '', 'error': None}
+
+ from app.services import db_process_service
+ monkeypatch.setattr(db_process_service.DatabaseService, 'pg_execute', staticmethod(fake))
+ result = DbProcessService._exec_sql({'engine': 'postgresql'}, 'SELECT 2;')
+ assert result['success'] is True
+ assert seen['query'] == 'SELECT 2;'
+
+ def test_docker_mysql_routes_to_docker_execute(self, monkeypatch):
+ seen = {}
+
+ def fake(container_name, query, database=None, user='root', password=None):
+ seen.update({'container': container_name, 'query': query, 'user': user, 'password': password})
+ return {'success': True, 'output': '', 'error': None}
+
+ from app.services import db_process_service
+ monkeypatch.setattr(db_process_service.DatabaseService, 'docker_mysql_execute', staticmethod(fake))
+ result = DbProcessService._exec_sql(
+ {'engine': 'mysql', 'container': 'wp-db', 'user': 'wp', 'password': 'pw'}, 'SHOW FULL PROCESSLIST;')
+ assert result['success'] is True
+ assert seen == {'container': 'wp-db', 'query': 'SHOW FULL PROCESSLIST;', 'user': 'wp', 'password': 'pw'}
+
+ def test_docker_pg_clean_error_when_docker_missing(self, monkeypatch):
+ def boom(*args, **kwargs):
+ raise FileNotFoundError('docker not found')
+
+ from app.services import db_process_service
+ monkeypatch.setattr(db_process_service.subprocess, 'run', boom)
+ result = DbProcessService._exec_sql({'engine': 'postgresql', 'container': 'pg1'}, 'SELECT 1;')
+ assert result['success'] is False
+ assert 'docker not found' in result['error']
+
+
+# ---------------------------------------------------------------------------
+# API endpoints — auth + wiring (service stubbed)
+# ---------------------------------------------------------------------------
+
+def user_headers(app):
+ """Headers for a non-admin user (kill must be forbidden)."""
+ from app import db
+ from app.models import User
+ from flask_jwt_extended import create_access_token
+ from werkzeug.security import generate_password_hash
+
+ with app.app_context():
+ user = User(
+ username='plainuser',
+ password_hash=generate_password_hash('testpass'),
+ role='user',
+ is_active=True,
+ )
+ db.session.add(user)
+ db.session.commit()
+ token = create_access_token(identity=user.id)
+ return {'Authorization': f'Bearer {token}'}
+
+
+class TestProcessAPI:
+ def test_list_requires_auth(self, client):
+ resp = client.get('/api/v1/databases/mysql/processes')
+ assert resp.status_code == 401
+
+ def test_list_host_processes(self, client, auth_headers, monkeypatch):
+ seen = {}
+
+ def fake(target):
+ seen.update(target)
+ return {'processes': [{'id': 1, 'user': 'root', 'db': None, 'state': '',
+ 'command': 'Sleep', 'time_s': 9, 'query': ''}]}
+
+ monkeypatch.setattr(DbProcessService, 'list_processes', staticmethod(fake))
+ resp = client.get('/api/v1/databases/postgresql/processes', headers=auth_headers)
+ assert resp.status_code == 200
+ assert resp.get_json()['processes'][0]['id'] == 1
+ assert seen['engine'] == 'postgresql'
+ assert seen.get('container') is None
+
+ def test_list_docker_processes_builds_target(self, client, auth_headers, monkeypatch):
+ seen = {}
+
+ def fake(target):
+ seen.update(target)
+ return {'processes': []}
+
+ monkeypatch.setattr(DbProcessService, 'list_processes', staticmethod(fake))
+ resp = client.get(
+ '/api/v1/databases/docker/wp-db/processes?type=mysql&user=wp',
+ headers={**auth_headers, 'X-DB-Password': 'pw'})
+ assert resp.status_code == 200
+ assert seen['engine'] == 'mysql'
+ assert seen['container'] == 'wp-db'
+ assert seen['user'] == 'wp'
+ assert seen['password'] == 'pw'
+
+ def test_list_unsupported_engine_is_400(self, client, auth_headers, monkeypatch):
+ monkeypatch.setattr(
+ DbProcessService, 'list_processes',
+ staticmethod(lambda target: {'error': 'unsupported engine'}))
+ resp = client.get('/api/v1/databases/docker/c1/processes?type=redis', headers=auth_headers)
+ assert resp.status_code == 400
+ assert resp.get_json() == {'error': 'unsupported engine'}
+
+ def test_list_exec_failure_is_502(self, client, auth_headers, monkeypatch):
+ monkeypatch.setattr(
+ DbProcessService, 'list_processes',
+ staticmethod(lambda target: {'error': 'connection refused'}))
+ resp = client.get('/api/v1/databases/mysql/processes', headers=auth_headers)
+ assert resp.status_code == 502
+ assert resp.get_json() == {'error': 'connection refused'}
+
+ def test_kill_requires_auth(self, client):
+ resp = client.post('/api/v1/databases/mysql/processes/5/kill')
+ assert resp.status_code == 401
+
+ def test_kill_requires_admin(self, client, user_headers, monkeypatch):
+ called = []
+ monkeypatch.setattr(
+ DbProcessService, 'kill_process',
+ staticmethod(lambda target, pid: called.append(pid) or {'success': True, 'pid': pid}))
+ resp = client.post('/api/v1/databases/mysql/processes/5/kill', headers=user_headers)
+ assert resp.status_code == 403
+ assert called == []
+
+ def test_kill_host_process_as_admin(self, client, auth_headers, monkeypatch):
+ seen = {}
+
+ def fake(target, pid):
+ seen.update({'target': target, 'pid': pid})
+ return {'success': True, 'pid': pid}
+
+ monkeypatch.setattr(DbProcessService, 'kill_process', staticmethod(fake))
+ resp = client.post('/api/v1/databases/mysql/processes/42/kill', headers=auth_headers)
+ assert resp.status_code == 200
+ assert resp.get_json() == {'success': True, 'pid': 42}
+ assert seen['target']['engine'] == 'mysql'
+ assert seen['pid'] == 42
+
+ def test_kill_docker_process_as_admin(self, client, auth_headers, monkeypatch):
+ seen = {}
+
+ def fake(target, pid):
+ seen.update({'target': target, 'pid': pid})
+ return {'success': True, 'pid': pid}
+
+ monkeypatch.setattr(DbProcessService, 'kill_process', staticmethod(fake))
+ resp = client.post(
+ '/api/v1/databases/docker/pg-db/processes/101/kill',
+ headers=auth_headers, json={'type': 'postgresql', 'user': 'svc'})
+ assert resp.status_code == 200
+ assert seen['target']['engine'] == 'postgresql'
+ assert seen['target']['container'] == 'pg-db'
+ assert seen['target']['user'] == 'svc'
+ assert seen['pid'] == 101
+
+ def test_kill_pid_must_be_int_in_url(self, client, auth_headers):
+ # <int:pid> converter rejects non-numeric pids at the routing layer
+ resp = client.post('/api/v1/databases/mysql/processes/abc/kill', headers=auth_headers)
+ assert resp.status_code in (404, 405)
diff --git a/frontend/src/components/databases/ProcessListPanel.jsx b/frontend/src/components/databases/ProcessListPanel.jsx
new file mode 100644
index 00000000..d78ed495
--- /dev/null
+++ b/frontend/src/components/databases/ProcessListPanel.jsx
@@ -0,0 +1,178 @@
+import { useState, useEffect, useCallback, useRef } from 'react';
+import { RefreshCw, Ban, Activity, TimerReset } from 'lucide-react';
+import api from '../../services/api';
+import { useToast } from '../../contexts/ToastContext';
+import { useConfirm } from '../../hooks/useConfirm';
+import EmptyState from '../EmptyState';
+
+const REFRESH_MS = 5000;
+const QUERY_PREVIEW_LEN = 120;
+
+function formatTime(s) {
+ if (s == null) return '—';
+ if (s < 60) return `${s}s`;
+ if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`;
+ return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`;
+}
+
+// Live processlist (SHOW FULL PROCESSLIST / pg_stat_activity) for the selected
+// engine or container, with an admin-only kill action and a 5s auto-refresh
+// toggle. `active` gates polling so hidden tabs don't keep hammering the API.
+export default function ProcessListPanel({ conn, engine, active, isAdmin }) {
+ const toast = useToast();
+ const { confirm } = useConfirm();
+
+ const [rows, setRows] = useState(null);
+ const [error, setError] = useState('');
+ const [loading, setLoading] = useState(false);
+ const [autoRefresh, setAutoRefresh] = useState(true);
+ const [killing, setKilling] = useState(null);
+ const inFlight = useRef(false);
+
+ const isDocker = conn?.dbType === 'docker';
+ const engineKind = isDocker ? (conn.dockerType || 'mysql') : (engine || conn?.dbType);
+
+ const load = useCallback(async (silent = false) => {
+ if (inFlight.current) return;
+ inFlight.current = true;
+ if (!silent) setLoading(true);
+ try {
+ const d = isDocker
+ ? await api.getDockerDbProcesses(conn.container, engineKind, conn.user, conn.password)
+ : await api.getHostDbProcesses(engineKind);
+ setRows(d.processes || []);
+ setError('');
+ } catch (err) {
+ setError(err.message || 'Failed to load processes');
+ } finally {
+ inFlight.current = false;
+ setLoading(false);
+ }
+ }, [isDocker, engineKind, conn]);
+
+ useEffect(() => { load(); }, [load]);
+
+ useEffect(() => {
+ if (!active || !autoRefresh) return undefined;
+ const t = setInterval(() => load(true), REFRESH_MS);
+ return () => clearInterval(t);
+ }, [active, autoRefresh, load]);
+
+ async function killProcess(proc) {
+ const verb = engineKind === 'postgresql' ? 'Terminate' : 'Kill';
+ const ok = await confirm({
+ title: `${verb} process ${proc.id}`,
+ message: `${verb} process ${proc.id}${proc.user ? ` (${proc.user}` : ''}${proc.user && proc.db ? ` on ${proc.db}` : ''}${proc.user ? ')' : ''}? Its running query will be aborted.`,
+ confirmText: `${verb} ${proc.id}`,
+ variant: 'danger',
+ });
+ if (!ok) return;
+ setKilling(proc.id);
+ try {
+ if (isDocker) {
+ await api.killDockerDbProcess(conn.container, proc.id, engineKind, conn.user, conn.password);
+ } else {
+ await api.killHostDbProcess(engineKind, proc.id);
+ }
+ toast.success(`Process ${proc.id} ${engineKind === 'postgresql' ? 'terminated' : 'killed'}`);
+ load(true);
+ } catch (err) {
+ toast.error(err.message || `Failed to ${verb.toLowerCase()} process ${proc.id}`);
+ } finally {
+ setKilling(null);
+ }
+ }
+
+ return (
+ <div className="dbp">
+ <div className="dbp-toolbar">
+ <span className="dbp-count">
+ <Activity size={14} aria-hidden="true" />
+ {rows ? `${rows.length} process${rows.length === 1 ? '' : 'es'}` : 'Processes'}
+ </span>
+ <div className="dbp-toolbar-right">
+ <label className="dbp-auto">
+ <input
+ type="checkbox"
+ checked={autoRefresh}
+ onChange={(e) => setAutoRefresh(e.target.checked)}
+ />
+ <TimerReset size={13} aria-hidden="true" /> Auto-refresh (5s)
+ </label>
+ <button
+ type="button"
+ className="dbx-icon-btn"
+ onClick={() => load()}
+ disabled={loading}
+ aria-label="Refresh processes"
+ title="Refresh"
+ >
+ <RefreshCw size={14} className={loading ? 'dbx-spin' : ''} aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+
+ {error ? (
+ <div className="dbp-error" role="alert">{error}</div>
+ ) : rows && rows.length === 0 ? (
+ <div className="dbp-empty">
+ <EmptyState
+ icon={Activity}
+ title="No processes"
+ description="No client sessions are currently connected to this server."
+ />
+ </div>
+ ) : (
+ <div className="dbp-scroll">
+ <table className="dbp-table">
+ <thead>
+ <tr>
+ <th>ID</th>
+ <th>User</th>
+ <th>Database</th>
+ <th>{engineKind === 'postgresql' ? 'State' : 'Command'}</th>
+ <th>Time</th>
+ <th>Query</th>
+ {isAdmin && <th aria-label="Actions" />}
+ </tr>
+ </thead>
+ <tbody>
+ {(rows || []).map((p) => (
+ <tr key={p.id}>
+ <td className="dbp-mono">{p.id}</td>
+ <td>{p.user || '—'}</td>
+ <td>{p.db || '—'}</td>
+ <td>
+ <span className="dbp-state">
+ {engineKind === 'postgresql' ? (p.state || '—') : (p.command || p.state || '—')}
+ </span>
+ </td>
+ <td className="dbp-mono">{formatTime(p.time_s)}</td>
+ <td className="dbp-query" title={p.query || ''}>
+ {p.query
+ ? (p.query.length > QUERY_PREVIEW_LEN ? `${p.query.slice(0, QUERY_PREVIEW_LEN)}…` : p.query)
+ : <span className="dbp-idle">idle</span>}
+ </td>
+ {isAdmin && (
+ <td className="dbp-actions">
+ <button
+ type="button"
+ className="dbx-icon-btn is-danger"
+ onClick={() => killProcess(p)}
+ disabled={killing === p.id}
+ aria-label={`Kill process ${p.id}`}
+ title={engineKind === 'postgresql' ? 'Terminate backend' : 'Kill process'}
+ >
+ <Ban size={14} aria-hidden="true" />
+ </button>
+ </td>
+ )}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/services/api/dbProcesses.js b/frontend/src/services/api/dbProcesses.js
new file mode 100644
index 00000000..62dd4eb0
--- /dev/null
+++ b/frontend/src/services/api/dbProcesses.js
@@ -0,0 +1,26 @@
+// Live database process inspection (SHOW PROCESSLIST / pg_stat_activity)
+// and kill/terminate, for the Database Explorer's Processes view.
+
+export async function getHostDbProcesses(engine) {
+ return this.request(`/databases/${engine}/processes`);
+}
+
+export async function killHostDbProcess(engine, pid) {
+ return this.request(`/databases/${engine}/processes/${pid}/kill`, { method: 'POST' });
+}
+
+export async function getDockerDbProcesses(container, type, user = null, password = null) {
+ const headers = password ? { 'X-DB-Password': password } : {};
+ const params = new URLSearchParams({ type: type || 'mysql' });
+ if (user) params.set('user', user);
+ return this.request(`/databases/docker/${container}/processes?${params.toString()}`, { headers });
+}
+
+export async function killDockerDbProcess(container, pid, type, user = null, password = null) {
+ const headers = password ? { 'X-DB-Password': password } : {};
+ return this.request(`/databases/docker/${container}/processes/${pid}/kill`, {
+ method: 'POST',
+ body: { type: type || 'mysql', user },
+ headers,
+ });
+}
diff --git a/frontend/src/styles/pages/_db-processes.scss b/frontend/src/styles/pages/_db-processes.scss
new file mode 100644
index 00000000..68c708b2
--- /dev/null
+++ b/frontend/src/styles/pages/_db-processes.scss
@@ -0,0 +1,131 @@
+// ============================================
+// DATABASE EXPLORER — PROCESSES PANEL
+// Live processlist / pg_stat_activity view with kill action.
+// ============================================
+
+.dbp {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ min-height: 0;
+ overflow: hidden;
+
+ .dbp-toolbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: $space-3;
+ padding: $space-2 $space-3;
+ border-bottom: 1px solid $border-color;
+ flex-shrink: 0;
+ }
+
+ .dbp-count {
+ display: inline-flex;
+ align-items: center;
+ gap: $space-2;
+ color: $text-secondary;
+ font-size: $font-size-sm;
+ font-weight: $font-weight-medium;
+ }
+
+ .dbp-toolbar-right {
+ display: inline-flex;
+ align-items: center;
+ gap: $space-3;
+ }
+
+ .dbp-auto {
+ display: inline-flex;
+ align-items: center;
+ gap: $space-2;
+ color: $text-secondary;
+ font-size: $font-size-sm;
+ cursor: pointer;
+ user-select: none;
+
+ input { accent-color: $primary-color; }
+ }
+
+ .dbp-error {
+ margin: $space-3;
+ padding: $space-2 $space-3;
+ background: $danger-bg;
+ border: 1px solid $danger-border;
+ border-radius: $radius-md;
+ color: $danger;
+ font-size: $font-size-sm;
+ }
+
+ .dbp-empty {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+
+ .dbp-scroll {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ }
+
+ .dbp-table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: $font-size-sm;
+
+ th {
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ background: $bg-tertiary;
+ color: $text-secondary;
+ font-weight: $font-weight-medium;
+ text-align: left;
+ padding: $space-2 $space-3;
+ border-bottom: 1px solid $border-color;
+ white-space: nowrap;
+ }
+
+ td {
+ padding: $space-2 $space-3;
+ border-bottom: 1px solid $border-color;
+ color: $text-primary;
+ vertical-align: top;
+ white-space: nowrap;
+ }
+
+ tbody tr:hover td { background: $bg-hover; }
+ }
+
+ .dbp-mono {
+ font-family: $font-family-mono;
+ font-size: $font-size-xs;
+ color: $text-secondary;
+ }
+
+ .dbp-state {
+ display: inline-block;
+ padding: 1px $space-2;
+ background: $bg-tertiary;
+ border-radius: $radius-sm;
+ color: $text-secondary;
+ font-size: $font-size-xs;
+ }
+
+ .dbp-query {
+ max-width: 480px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-family: $font-family-mono;
+ font-size: $font-size-xs;
+ }
+
+ .dbp-idle {
+ color: $text-muted;
+ font-style: italic;
+ }
+
+ .dbp-actions { text-align: right; }
+}