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.

Add log fallbacks, privilege helpers, and checks

Juan Denis3491e8887774
diff --git a/backend/app/services/backup_service.py b/backend/app/services/backup_service.py
index 5104c9df..32f1d694 100644
--- a/backend/app/services/backup_service.py
+++ b/backend/app/services/backup_service.py
@@ -13,6 +13,7 @@ import uuid
import schedule
from app import paths
+from app.utils.system import is_command_available
class BackupService:
@@ -145,6 +146,8 @@ class BackupService:
try:
if db_type == 'mysql':
+ if not is_command_available('mysqldump'):
+ return {'success': False, 'error': 'mysqldump not installed'}
cmd = ['mysqldump']
if config.get('user'):
cmd.extend(['-u', config['user']])
@@ -161,6 +164,9 @@ class BackupService:
return {'success': False, 'error': result.stderr}
elif db_type == 'postgresql':
+ if not is_command_available('pg_dump'):
+ return {'success': False, 'error': 'pg_dump not installed'}
+
env = os.environ.copy()
if config.get('password'):
env['PGPASSWORD'] = config['password']
@@ -335,6 +341,8 @@ class BackupService:
try:
if db_type == 'mysql':
+ if not is_command_available('mysql'):
+ return {'success': False, 'error': 'mysql client not installed'}
cmd = ['mysql']
if user:
cmd.extend(['-u', user])
@@ -348,6 +356,9 @@ class BackupService:
result = subprocess.run(cmd, stdin=f, capture_output=True, text=True)
elif db_type == 'postgresql':
+ if not is_command_available('psql'):
+ return {'success': False, 'error': 'psql client not installed'}
+
env = os.environ.copy()
if password:
env['PGPASSWORD'] = password
diff --git a/backend/app/services/deployment_service.py b/backend/app/services/deployment_service.py
index 29b21d6d..4f9f69f2 100644
--- a/backend/app/services/deployment_service.py
+++ b/backend/app/services/deployment_service.py
@@ -9,6 +9,7 @@ Supports:
- Diff generation between deployments
"""
+import logging
import os
import subprocess
import json
@@ -26,6 +27,9 @@ from app.services.git_service import GitService
from app import paths
+logger = logging.getLogger(__name__)
+
+
class DeploymentService:
"""Service for orchestrating deployments."""
@@ -543,8 +547,8 @@ class DeploymentService:
db.session.add(diff)
db.session.commit()
- except Exception:
- pass
+ except Exception as e:
+ logger.warning('Failed to generate deployment diff: %s', e)
@classmethod
def get_deployments(cls, app_id: int, limit: int = 20, offset: int = 0) -> List[Dict]:
diff --git a/backend/app/services/ftp_service.py b/backend/app/services/ftp_service.py
index ac29575c..90df6251 100644
--- a/backend/app/services/ftp_service.py
+++ b/backend/app/services/ftp_service.py
@@ -4,7 +4,7 @@ import os
import subprocess
import re
-from app.utils.system import PackageManager, ServiceControl, run_privileged
+from app.utils.system import PackageManager, ServiceControl, run_privileged, privileged_cmd
try:
import pwd
except ImportError:
@@ -285,6 +285,9 @@ class FTPService:
@classmethod
def list_users(cls) -> Dict:
"""List FTP users."""
+ if pwd is None:
+ return {'success': False, 'error': 'User management requires Linux'}
+
try:
users = []
@@ -340,6 +343,9 @@ class FTPService:
@classmethod
def create_user(cls, username: str, password: str = None, home_dir: str = None) -> Dict:
"""Create a new FTP user."""
+ if pwd is None:
+ return {'success': False, 'error': 'User management requires Linux'}
+
# Validate username
if not re.match(r'^[a-z][a-z0-9_-]{2,31}$', username):
return {'success': False, 'error': 'Invalid username. Use lowercase letters, numbers, underscore, hyphen. 3-32 chars.'}
@@ -361,26 +367,29 @@ class FTPService:
try:
# Create user with restricted shell
- result = subprocess.run([
- 'sudo', 'useradd',
+ result = run_privileged([
+ 'useradd',
'-m', # Create home directory
'-d', home_dir,
'-s', '/usr/sbin/nologin', # No shell access
'-c', f'FTP User {username}',
username
- ], capture_output=True, text=True)
+ ])
if result.returncode != 0:
return {'success': False, 'error': result.stderr or 'Failed to create user'}
# Set password
proc = subprocess.Popen(
- ['sudo', 'chpasswd'],
+ privileged_cmd(['chpasswd']),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
- proc.communicate(input=f'{username}:{password}'.encode())
+ stdout, stderr = proc.communicate(input=f'{username}:{password}'.encode())
+
+ if proc.returncode != 0:
+ return {'success': False, 'error': stderr.decode() or 'Failed to set password'}
# Add to vsftpd userlist if it exists
if os.path.exists(cls.VSFTPD_USER_LIST):
@@ -388,7 +397,7 @@ class FTPService:
f.write(f'{username}\n')
# Set proper permissions on home directory
- subprocess.run(['sudo', 'chmod', '755', home_dir], capture_output=True)
+ run_privileged(['chmod', '755', home_dir])
return {
'success': True,
@@ -404,6 +413,9 @@ class FTPService:
@classmethod
def delete_user(cls, username: str, delete_home: bool = False) -> Dict:
"""Delete an FTP user."""
+ if pwd is None:
+ return {'success': False, 'error': 'User management requires Linux'}
+
try:
# Check if user exists
try:
@@ -412,12 +424,12 @@ class FTPService:
return {'success': False, 'error': 'User not found'}
# Delete user
- cmd = ['sudo', 'userdel']
+ cmd = ['userdel']
if delete_home:
cmd.append('-r')
cmd.append(username)
- result = subprocess.run(cmd, capture_output=True, text=True)
+ result = run_privileged(cmd)
if result.returncode != 0:
return {'success': False, 'error': result.stderr or 'Failed to delete user'}
@@ -437,6 +449,9 @@ class FTPService:
@classmethod
def change_password(cls, username: str, new_password: str = None) -> Dict:
"""Change FTP user password."""
+ if pwd is None:
+ return {'success': False, 'error': 'User management requires Linux'}
+
try:
# Check if user exists
try:
@@ -450,7 +465,7 @@ class FTPService:
# Set password
proc = subprocess.Popen(
- ['sudo', 'chpasswd'],
+ privileged_cmd(['chpasswd']),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
@@ -537,6 +552,9 @@ class FTPService:
@classmethod
def toggle_user(cls, username: str, enabled: bool) -> Dict:
"""Enable or disable an FTP user."""
+ if pwd is None:
+ return {'success': False, 'error': 'User management requires Linux'}
+
try:
# Check if user exists
try:
@@ -551,9 +569,8 @@ class FTPService:
# Change shell to /bin/false to disable
shell = '/bin/false'
- result = subprocess.run(
- ['sudo', 'usermod', '-s', shell, username],
- capture_output=True, text=True
+ result = run_privileged(
+ ['usermod', '-s', shell, username]
)
if result.returncode != 0:
@@ -573,9 +590,8 @@ class FTPService:
def disconnect_session(cls, pid: int) -> Dict:
"""Disconnect an active FTP session by PID."""
try:
- result = subprocess.run(
- ['sudo', 'kill', str(pid)],
- capture_output=True, text=True
+ result = run_privileged(
+ ['kill', str(pid)]
)
if result.returncode != 0:
diff --git a/backend/app/services/log_service.py b/backend/app/services/log_service.py
index 4d318415..43553fb8 100644
--- a/backend/app/services/log_service.py
+++ b/backend/app/services/log_service.py
@@ -7,7 +7,7 @@ import threading
import queue
from app import paths
-from app.utils.system import run_privileged, privileged_cmd, is_command_available
+from app.utils.system import run_privileged, privileged_cmd, is_command_available, sourced_result
class LogService:
@@ -74,65 +74,116 @@ class LogService:
@classmethod
def read_log(cls, filepath: str, lines: int = 100, from_end: bool = True) -> Dict:
- """Read lines from a log file."""
+ """Read lines from a log file. Falls back to Python I/O when tail/head are unavailable."""
if not cls.is_path_allowed(filepath):
return {'success': False, 'error': 'Access denied: path not in allowed directories'}
if not os.path.exists(filepath):
return {'success': False, 'error': 'Log file not found'}
+ tool = 'tail' if from_end else 'head'
+
+ if is_command_available(tool):
+ try:
+ result = run_privileged(
+ [tool, '-n', str(lines), filepath],
+ timeout=30
+ )
+
+ if result.returncode == 0:
+ log_lines = result.stdout.split('\n')
+ return {**sourced_result(log_lines, tool, tool), 'filepath': filepath}
+ else:
+ return {'success': False, 'error': result.stderr}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ # Fallback: Python file I/O
try:
- tool = 'tail' if from_end else 'head'
- result = run_privileged(
- [tool, '-n', str(lines), filepath],
- timeout=30
- )
+ with open(filepath, 'r', errors='replace') as f:
+ all_lines = f.readlines()
- if result.returncode == 0:
- log_lines = result.stdout.split('\n')
- return {
- 'success': True,
- 'lines': log_lines,
- 'count': len(log_lines),
- 'filepath': filepath
- }
+ if from_end:
+ log_lines = [l.rstrip('\n') for l in all_lines[-lines:]]
else:
- return {'success': False, 'error': result.stderr}
+ log_lines = [l.rstrip('\n') for l in all_lines[:lines]]
- except FileNotFoundError:
- return {'success': False, 'error': f'{tool} command not found'}
+ return {**sourced_result(log_lines, 'python', 'direct file read'), 'filepath': filepath}
+
+ except PermissionError:
+ return {'success': False, 'error': f'Permission denied reading {filepath}'}
except Exception as e:
return {'success': False, 'error': str(e)}
@classmethod
def search_log(cls, filepath: str, pattern: str, lines: int = 100) -> Dict:
- """Search log file for pattern."""
+ """Search log file for pattern. Falls back to Python regex when grep is unavailable."""
if not cls.is_path_allowed(filepath):
return {'success': False, 'error': 'Access denied: path not in allowed directories'}
if not os.path.exists(filepath):
return {'success': False, 'error': 'Log file not found'}
+ if is_command_available('grep'):
+ try:
+ result = run_privileged(
+ ['grep', '-i', '-m', str(lines), pattern, filepath],
+ timeout=60
+ )
+
+ # grep returns 1 if no matches (not an error)
+ if result.returncode in [0, 1]:
+ matches = result.stdout.split('\n') if result.stdout else []
+ return {
+ 'success': True,
+ 'matches': [m for m in matches if m],
+ 'count': len([m for m in matches if m]),
+ 'pattern': pattern
+ }
+ else:
+ return {'success': False, 'error': result.stderr}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ # Fallback: Python regex search
+ import re
try:
- result = run_privileged(
- ['grep', '-i', '-m', str(lines), pattern, filepath],
- timeout=60
- )
+ regex = re.compile(pattern, re.IGNORECASE)
+ matches = []
+ with open(filepath, 'r', errors='replace') as f:
+ for line in f:
+ if regex.search(line):
+ matches.append(line.rstrip('\n'))
+ if len(matches) >= lines:
+ break
- # grep returns 1 if no matches (not an error)
- if result.returncode in [0, 1]:
- matches = result.stdout.split('\n') if result.stdout else []
- return {
- 'success': True,
- 'matches': [m for m in matches if m],
- 'count': len([m for m in matches if m]),
- 'pattern': pattern
- }
- else:
- return {'success': False, 'error': result.stderr}
+ return {
+ 'success': True,
+ 'matches': matches,
+ 'count': len(matches),
+ 'pattern': pattern
+ }
- except FileNotFoundError:
- return {'success': False, 'error': 'grep command not found'}
+ except re.error:
+ # Pattern might be a plain string, not valid regex — use substring match
+ matches = []
+ with open(filepath, 'r', errors='replace') as f:
+ for line in f:
+ if pattern.lower() in line.lower():
+ matches.append(line.rstrip('\n'))
+ if len(matches) >= lines:
+ break
+
+ return {
+ 'success': True,
+ 'matches': matches,
+ 'count': len(matches),
+ 'pattern': pattern
+ }
+ except PermissionError:
+ return {'success': False, 'error': f'Permission denied reading {filepath}'}
except Exception as e:
return {'success': False, 'error': str(e)}
@@ -176,13 +227,7 @@ class LogService:
if result.returncode == 0:
log_lines = result.stdout.split('\n') if result.stdout else []
- return {
- 'success': True,
- 'lines': log_lines,
- 'count': len(log_lines),
- 'source': 'docker',
- 'app_dir': app_dir
- }
+ return {**sourced_result(log_lines, 'docker', 'Docker Compose'), 'app_dir': app_dir}
else:
# Try with docker-compose (older syntax) as fallback
result = subprocess.run(
@@ -194,13 +239,7 @@ class LogService:
)
if result.returncode == 0:
log_lines = result.stdout.split('\n') if result.stdout else []
- return {
- 'success': True,
- 'lines': log_lines,
- 'count': len(log_lines),
- 'source': 'docker',
- 'app_dir': app_dir
- }
+ return {**sourced_result(log_lines, 'docker', 'Docker Compose (legacy)'), 'app_dir': app_dir}
return {'success': False, 'error': result.stderr or 'Failed to get Docker logs'}
except FileNotFoundError:
@@ -213,10 +252,22 @@ class LogService:
@classmethod
def get_journalctl_logs(cls, unit: str = None, lines: int = 100,
since: str = None, priority: str = None) -> Dict:
- """Get logs from systemd journal."""
- if not is_command_available('journalctl'):
- return {'success': False, 'error': 'journalctl is not available on this system'}
+ """Get system logs, trying journalctl → syslog → Windows Event Log."""
+ if is_command_available('journalctl'):
+ return cls._read_journalctl(unit, lines, since, priority)
+
+ syslog_path = cls._find_syslog()
+ if syslog_path:
+ return cls._read_syslog(syslog_path, unit, lines)
+
+ if os.name == 'nt':
+ return cls._read_windows_eventlog(lines)
+ return {'success': False, 'error': 'No system log source available — journalctl, syslog, and Windows Event Log are all unavailable'}
+
+ @classmethod
+ def _read_journalctl(cls, unit: str, lines: int, since: str, priority: str) -> Dict:
+ """Read logs from systemd journal."""
try:
cmd = ['journalctl', '-n', str(lines), '--no-pager', '-o', 'short-iso']
@@ -231,11 +282,7 @@ class LogService:
if result.returncode == 0:
log_lines = result.stdout.split('\n')
- return {
- 'success': True,
- 'lines': log_lines,
- 'count': len(log_lines)
- }
+ return sourced_result(log_lines, 'journalctl', 'systemd journal')
else:
return {'success': False, 'error': result.stderr}
@@ -244,6 +291,62 @@ class LogService:
except Exception as e:
return {'success': False, 'error': str(e)}
+ @staticmethod
+ def _find_syslog() -> Optional[str]:
+ """Return the first existing syslog path, or None."""
+ for path in ['/var/log/syslog', '/var/log/messages']:
+ if os.path.exists(path):
+ return path
+ return None
+
+ @classmethod
+ def _read_syslog(cls, filepath: str, service: str, lines: int) -> Dict:
+ """Read system logs from a syslog file, optionally filtering by service."""
+ try:
+ if service:
+ result = run_privileged(
+ ['bash', '-c', f'grep -i {subprocess.list2cmdline([service])} {subprocess.list2cmdline([filepath])} | tail -n {int(lines)}'],
+ timeout=60,
+ )
+ else:
+ result = run_privileged(
+ ['tail', '-n', str(lines), filepath],
+ timeout=60,
+ )
+
+ if result.returncode == 0 or (service and result.returncode == 1):
+ log_lines = result.stdout.split('\n') if result.stdout else []
+ return sourced_result(log_lines, 'syslog', filepath)
+ else:
+ return {'success': False, 'error': result.stderr}
+
+ except FileNotFoundError:
+ return {'success': False, 'error': 'Required commands not found'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @staticmethod
+ def _read_windows_eventlog(lines: int) -> Dict:
+ """Read system logs from Windows Event Log via wevtutil."""
+ try:
+ result = subprocess.run(
+ ['wevtutil', 'qe', 'System', f'/c:{int(lines)}', '/f:text', '/rd:true'],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+
+ if result.returncode == 0:
+ log_lines = result.stdout.split('\n') if result.stdout else []
+ return sourced_result(log_lines, 'eventlog', 'Windows Event Log')
+ else:
+ return {'success': False, 'error': result.stderr}
+
+ except FileNotFoundError:
+ return {'success': False, 'error': 'wevtutil command not found'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
@classmethod
def clear_log(cls, filepath: str) -> Dict:
"""Clear/truncate a log file."""
diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.py
index 88b2bda0..3ec1aaa3 100644
--- a/backend/app/services/nginx_service.py
+++ b/backend/app/services/nginx_service.py
@@ -4,7 +4,7 @@ import re
from typing import Dict, List, Optional
from pathlib import Path
-from app.utils.system import ServiceControl, run_privileged
+from app.utils.system import ServiceControl, run_privileged, is_command_available
class NginxService:
@@ -293,6 +293,9 @@ server {{
@classmethod
def test_config(cls) -> Dict:
"""Test Nginx configuration syntax."""
+ if not is_command_available('nginx'):
+ return {'success': False, 'error': 'nginx is not installed'}
+
try:
result = run_privileged([cls.NGINX_BIN, '-t'], timeout=30)
return {
diff --git a/backend/app/services/php_service.py b/backend/app/services/php_service.py
index 1832335f..2351a30b 100644
--- a/backend/app/services/php_service.py
+++ b/backend/app/services/php_service.py
@@ -4,7 +4,7 @@ import re
from typing import Dict, List, Optional
from pathlib import Path
-from app.utils.system import PackageManager, ServiceControl, run_privileged
+from app.utils.system import PackageManager, ServiceControl, run_privileged, is_command_available
class PHPService:
@@ -77,7 +77,7 @@ env[TEMP] = /tmp
timeout=10
)
full_version = result.stdout.split('\n')[0] if result.returncode == 0 else version
- except:
+ except Exception:
full_version = version
# Check if FPM is installed
@@ -88,7 +88,7 @@ env[TEMP] = /tmp
if fpm_installed:
try:
fpm_running = ServiceControl.is_active(f'php{version}-fpm')
- except:
+ except Exception:
pass
versions.append({
@@ -116,7 +116,7 @@ env[TEMP] = /tmp
match = re.search(r'PHP (\d+\.\d+)', result.stdout)
if match:
return match.group(1)
- except:
+ except Exception:
pass
return None
@@ -150,13 +150,17 @@ env[TEMP] = /tmp
return {'success': False, 'error': f'Unsupported PHP version: {version}'}
try:
- # Add PHP repository if needed
- run_privileged(
- ['add-apt-repository', '-y', 'ppa:ondrej/php'],
- timeout=120,
- )
-
- run_privileged(['apt-get', 'update'], timeout=120)
+ # Add PHP repository if needed (Ubuntu/Debian only)
+ if is_command_available('add-apt-repository'):
+ run_privileged(
+ ['add-apt-repository', '-y', 'ppa:ondrej/php'],
+ timeout=120,
+ )
+
+ # Update package lists (apt-specific, safe to skip on non-apt)
+ manager = PackageManager.detect()
+ if manager == 'apt':
+ run_privileged(['apt-get', 'update'], timeout=120)
# Install PHP and common extensions
packages = [
@@ -177,10 +181,7 @@ env[TEMP] = /tmp
f'php{version}-bcmath',
]
- result = run_privileged(
- ['apt-get', 'install', '-y'] + packages,
- timeout=600,
- )
+ result = PackageManager.install(packages, timeout=600)
if result.returncode == 0:
# Start FPM service
@@ -216,7 +217,7 @@ env[TEMP] = /tmp
'name': ext,
'enabled': True
})
- except:
+ except Exception:
pass
return extensions
@@ -227,10 +228,7 @@ env[TEMP] = /tmp
package = f'php{version}-{extension}'
try:
- result = run_privileged(
- ['apt-get', 'install', '-y', package],
- timeout=120,
- )
+ result = PackageManager.install(package, timeout=120)
if result.returncode == 0:
# Restart FPM to load extension
@@ -263,7 +261,7 @@ env[TEMP] = /tmp
'pm': config.get('pm', 'dynamic'),
'max_children': config.get('pm.max_children', '5')
})
- except Exception as e:
+ except Exception:
pass
return pools
@@ -279,7 +277,7 @@ env[TEMP] = /tmp
if line and not line.startswith(';') and '=' in line:
key, value = line.split('=', 1)
config[key.strip()] = value.strip()
- except:
+ except Exception:
pass
return config
diff --git a/backend/app/services/process_service.py b/backend/app/services/process_service.py
index af1da4b3..7dfb9209 100644
--- a/backend/app/services/process_service.py
+++ b/backend/app/services/process_service.py
@@ -3,7 +3,7 @@ import subprocess
import platform
from typing import List, Dict, Optional
-from app.utils.system import run_privileged, is_command_available
+from app.utils.system import run_privileged
class ProcessService:
@@ -171,28 +171,6 @@ class ProcessService:
@classmethod
def get_service_logs(cls, service_name: str, lines: int = 100) -> Dict:
- """Get recent logs for a service."""
- system = platform.system()
-
- try:
- if system == 'Linux':
- if not is_command_available('journalctl'):
- return {'success': False, 'error': 'journalctl is not available on this system'}
-
- result = run_privileged(
- ['journalctl', '-u', service_name, '-n', str(lines), '--no-pager'],
- timeout=30
- )
-
- if result.returncode == 0:
- return {'success': True, 'logs': result.stdout}
- else:
- return {'success': False, 'error': result.stderr}
-
- else:
- return {'success': False, 'error': 'Log retrieval not supported on this platform'}
-
- except FileNotFoundError:
- return {'success': False, 'error': 'journalctl command not found'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
+ """Get recent logs for a service via LogService fallback chain."""
+ from app.services.log_service import LogService
+ return LogService.get_journalctl_logs(unit=service_name, lines=lines)
diff --git a/backend/app/services/ssl_service.py b/backend/app/services/ssl_service.py
index 536b7b2d..9ea73f63 100644
--- a/backend/app/services/ssl_service.py
+++ b/backend/app/services/ssl_service.py
@@ -5,7 +5,7 @@ from datetime import datetime
from typing import Dict, List, Optional
from pathlib import Path
-from app.utils.system import ServiceControl, run_privileged
+from app.utils.system import ServiceControl, run_privileged, PackageManager, is_command_available
class SSLService:
@@ -18,26 +18,17 @@ class SSLService:
@classmethod
def is_certbot_installed(cls) -> bool:
"""Check if certbot is installed."""
- try:
- result = subprocess.run(
- ['which', 'certbot'],
- capture_output=True,
- text=True
- )
- return result.returncode == 0
- except Exception:
- return False
+ return is_command_available('certbot')
@classmethod
def install_certbot(cls) -> Dict:
"""Install certbot if not present."""
- try:
- result = run_privileged(['apt-get', 'update'], timeout=300)
- if result.returncode != 0:
- return {'success': False, 'error': result.stderr}
+ if not PackageManager.is_available():
+ return {'success': False, 'error': 'No supported package manager found'}
- result = run_privileged(
- ['apt-get', 'install', '-y', 'certbot', 'python3-certbot-nginx'],
+ try:
+ result = PackageManager.install(
+ ['certbot', 'python3-certbot-nginx'],
timeout=300,
)
if result.returncode != 0:
@@ -180,7 +171,7 @@ class SSLService:
expiry_part = expiry_str.split(' (')[0]
current_cert['expiry'] = expiry_part
current_cert['expiry_valid'] = 'VALID' in expiry_str
- except:
+ except Exception:
current_cert['expiry'] = expiry_str
elif line.startswith('Certificate Path:'):
current_cert['cert_path'] = line.split(':', 1)[1].strip()
@@ -190,7 +181,7 @@ class SSLService:
if current_cert:
certificates.append(current_cert)
- except Exception as e:
+ except Exception:
pass
return certificates
@@ -226,7 +217,7 @@ class SSLService:
return info
- except Exception as e:
+ except Exception:
return None
@classmethod
diff --git a/backend/app/services/system_service.py b/backend/app/services/system_service.py
index e52f39e2..194ba083 100644
--- a/backend/app/services/system_service.py
+++ b/backend/app/services/system_service.py
@@ -4,6 +4,8 @@ import subprocess
import os
from datetime import datetime
+from app.utils.system import run_privileged
+
class SystemService:
"""Service for collecting system metrics and information."""
@@ -375,23 +377,23 @@ class SystemService:
try:
# Try timedatectl first (systemd)
- result = subprocess.run(
- ['sudo', 'timedatectl', 'set-timezone', timezone_id],
- capture_output=True, text=True, timeout=10
+ result = run_privileged(
+ ['timedatectl', 'set-timezone', timezone_id],
+ timeout=10
)
if result.returncode == 0:
return {'success': True, 'message': f'Timezone set to {timezone_id}'}
# Fallback: symlink method
- result = subprocess.run(
- ['sudo', 'ln', '-sf', f'/usr/share/zoneinfo/{timezone_id}', '/etc/localtime'],
- capture_output=True, text=True, timeout=10
+ result = run_privileged(
+ ['ln', '-sf', f'/usr/share/zoneinfo/{timezone_id}', '/etc/localtime'],
+ timeout=10
)
if result.returncode == 0:
# Also update /etc/timezone
- subprocess.run(
- ['sudo', 'bash', '-c', f'echo "{timezone_id}" > /etc/timezone'],
- capture_output=True, text=True, timeout=10
+ run_privileged(
+ ['bash', '-c', f'echo "{timezone_id}" > /etc/timezone'],
+ timeout=10
)
return {'success': True, 'message': f'Timezone set to {timezone_id}'}
diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.py
index 06ef72b4..22204eb8 100644
--- a/backend/app/services/wordpress_service.py
+++ b/backend/app/services/wordpress_service.py
@@ -9,6 +9,7 @@ from typing import Dict, List, Optional
from pathlib import Path
from app import paths
+from app.utils.system import run_privileged, privileged_cmd
class WordPressService:
@@ -41,7 +42,6 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
commands = [
['curl', '-O', 'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar'],
['chmod', '+x', 'wp-cli.phar'],
- ['sudo', 'mv', 'wp-cli.phar', cls.WP_CLI_PATH]
]
for cmd in commands:
@@ -49,6 +49,10 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
if result.returncode != 0:
return {'success': False, 'error': result.stderr}
+ result = run_privileged(['mv', 'wp-cli.phar', cls.WP_CLI_PATH], timeout=120)
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr}
+
return {'success': True, 'message': 'WP-CLI installed successfully'}
except Exception as e:
return {'success': False, 'error': str(e)}
@@ -67,7 +71,7 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
return install_result
try:
- cmd = ['sudo', '-u', user, cls.WP_CLI_PATH, '--path=' + path] + command
+ cmd = privileged_cmd(['sudo', '-u', user, cls.WP_CLI_PATH, '--path=' + path] + command)
result = subprocess.run(
cmd,
capture_output=True,
@@ -157,8 +161,8 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
try:
# Create directory
- subprocess.run(['sudo', 'mkdir', '-p', path], capture_output=True)
- subprocess.run(['sudo', 'chown', 'www-data:www-data', path], capture_output=True)
+ run_privileged(['mkdir', '-p', path])
+ run_privileged(['chown', 'www-data:www-data', path])
# Download WordPress
download_result = cls.wp_cli(path, ['core', 'download', '--locale=en_US'])
@@ -228,7 +232,7 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
updates = json.loads(update_result['output'])
info['update_available'] = len(updates) > 0
info['latest_version'] = updates[0]['version'] if updates else info.get('version')
- except:
+ except Exception:
info['update_available'] = False
# Get site URL
@@ -265,7 +269,7 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
if result['success']:
try:
return json.loads(result['output'])
- except:
+ except Exception:
return []
return []
@@ -325,7 +329,7 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
if result['success']:
try:
return json.loads(result['output'])
- except:
+ except Exception:
return []
return []
@@ -357,13 +361,12 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
try:
# Create backup directory
- subprocess.run(['sudo', 'mkdir', '-p', backup_path], capture_output=True)
+ run_privileged(['mkdir', '-p', backup_path])
# Backup files
files_backup = os.path.join(backup_path, 'files.tar.gz')
- subprocess.run(
- ['sudo', 'tar', '-czf', files_backup, '-C', os.path.dirname(path), os.path.basename(path)],
- capture_output=True,
+ run_privileged(
+ ['tar', '-czf', files_backup, '-C', os.path.dirname(path), os.path.basename(path)],
timeout=600
)
@@ -379,7 +382,7 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
size = sum(os.path.getsize(os.path.join(backup_path, f))
for f in os.listdir(backup_path)
if os.path.isfile(os.path.join(backup_path, f)))
- except:
+ except Exception:
size = 0
return {
@@ -433,7 +436,7 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
'size': size,
'timestamp': timestamp
})
- except:
+ except Exception:
pass
return sorted(backups, key=lambda x: x['timestamp'], reverse=True)
@@ -454,12 +457,11 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
if os.path.exists(files_backup):
# Remove existing files
if os.path.exists(target_path):
- subprocess.run(['sudo', 'rm', '-rf', target_path], capture_output=True)
+ run_privileged(['rm', '-rf', target_path])
# Extract backup
- subprocess.run(
- ['sudo', 'tar', '-xzf', files_backup, '-C', os.path.dirname(target_path)],
- capture_output=True,
+ run_privileged(
+ ['tar', '-xzf', files_backup, '-C', os.path.dirname(target_path)],
timeout=600
)
@@ -486,7 +488,7 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
return {'success': False, 'error': 'Backup not found'}
try:
- subprocess.run(['sudo', 'rm', '-rf', backup_path], capture_output=True)
+ run_privileged(['rm', '-rf', backup_path])
return {'success': True, 'message': 'Backup deleted'}
except Exception as e:
return {'success': False, 'error': str(e)}
@@ -531,26 +533,24 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
"""Set secure file permissions for WordPress."""
try:
# Set ownership
- subprocess.run(['sudo', 'chown', '-R', 'www-data:www-data', path], capture_output=True)
+ run_privileged(['chown', '-R', 'www-data:www-data', path])
# Set directory permissions
- subprocess.run(
- ['sudo', 'find', path, '-type', 'd', '-exec', 'chmod', '755', '{}', ';'],
- capture_output=True
+ run_privileged(
+ ['find', path, '-type', 'd', '-exec', 'chmod', '755', '{}', ';']
)
# Set file permissions
- subprocess.run(
- ['sudo', 'find', path, '-type', 'f', '-exec', 'chmod', '644', '{}', ';'],
- capture_output=True
+ run_privileged(
+ ['find', path, '-type', 'f', '-exec', 'chmod', '644', '{}', ';']
)
# Protect wp-config.php
wp_config = os.path.join(path, 'wp-config.php')
if os.path.exists(wp_config):
- subprocess.run(['sudo', 'chmod', '600', wp_config], capture_output=True)
+ run_privileged(['chmod', '600', wp_config])
- except:
+ except Exception:
pass
@classmethod
@@ -598,13 +598,11 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
# Only add if not already present
if '# ServerKit Security Rules' not in existing:
new_content = security_rules + '\n' + existing
- subprocess.run(
- ['sudo', 'tee', htaccess_path],
- input=new_content,
- capture_output=True,
- text=True
+ run_privileged(
+ ['tee', htaccess_path],
+ input=new_content
)
- except:
+ except Exception:
pass
@classmethod
diff --git a/backend/app/utils/system.py b/backend/app/utils/system.py
index 1c58ea86..1c466205 100644
--- a/backend/app/utils/system.py
+++ b/backend/app/utils/system.py
@@ -75,6 +75,21 @@ def is_command_available(cmd: str) -> bool:
return False
+def sourced_result(lines: list, source: str, source_label: str) -> dict:
+ """Standard response shape for multi-source data endpoints.
+
+ Every fallback-chain endpoint should return this shape so the frontend
+ can show a consistent source-aware banner.
+ """
+ return {
+ 'success': True,
+ 'lines': lines,
+ 'count': len(lines),
+ 'source': source,
+ 'source_label': source_label,
+ }
+
+
class PackageManager:
"""Cross-distro package management helpers.
diff --git a/frontend/src/pages/Terminal.jsx b/frontend/src/pages/Terminal.jsx
index 3e722906..29fc3b88 100644
--- a/frontend/src/pages/Terminal.jsx
+++ b/frontend/src/pages/Terminal.jsx
@@ -321,20 +321,26 @@ const JournalTab = () => {
const [unit, setUnit] = useState('');
const [lineCount, setLineCount] = useState(100);
const [priority, setPriority] = useState('');
+ const [source, setSource] = useState('');
+ const [sourceLabel, setSourceLabel] = useState('');
const [commonUnits] = useState([
'nginx', 'apache2', 'mysql', 'mariadb', 'postgresql',
'php-fpm', 'docker', 'sshd', 'cron', 'systemd'
]);
+ const isJournalctl = source === 'journalctl' || source === '';
+
async function loadJournalLogs() {
setLoading(true);
setUnavailable(false);
try {
const data = await api.getJournalLogs(unit || null, lineCount);
- setLogs(data.content || data.logs || 'No logs available');
+ setLogs(data.lines?.join('\n') || 'No logs available');
+ setSource(data.source || '');
+ setSourceLabel(data.source_label || '');
} catch (err) {
const msg = err.message || '';
- if (msg.includes('not available') || msg.includes('not found')) {
+ if (msg.includes('No system log source available') || msg.includes('unavailable')) {
setUnavailable(true);
} else {
setLogs(`Error: ${msg}`);
@@ -358,11 +364,11 @@ const JournalTab = () => {
<line x1="9" y1="13" x2="15" y2="13"/>
<line x1="9" y1="17" x2="11" y2="17"/>
</svg>
- <h3>System Journal Unavailable</h3>
+ <h3>System Logs Unavailable</h3>
<p>
- <code>journalctl</code> is not available on this system.
- This typically means the server is running without systemd
- (e.g. a minimal Docker container or Windows dev environment).
+ No system log source was found on this server.
+ Neither <code>journalctl</code>, <code>/var/log/syslog</code>,
+ nor the Windows Event Log are available.
</p>
<p className="text-muted">
Use the <strong>Log Files</strong> tab to browse available log files instead.
@@ -376,7 +382,7 @@ const JournalTab = () => {
<div className="journal-container">
<div className="journal-controls">
<div className="control-group">
- <label>Service/Unit</label>
+ <label>{isJournalctl ? 'Service/Unit' : 'Filter by service'}</label>
<div className="input-with-suggestions">
<input
type="text"
@@ -384,17 +390,19 @@ const JournalTab = () => {
onChange={(e) => setUnit(e.target.value)}
placeholder="All services"
/>
- <div className="quick-units">
- {commonUnits.map(u => (
- <button
- key={u}
- className={`unit-chip ${unit === u ? 'active' : ''}`}
- onClick={() => setUnit(unit === u ? '' : u)}
- >
- {u}
- </button>
- ))}
- </div>
+ {isJournalctl && (
+ <div className="quick-units">
+ {commonUnits.map(u => (
+ <button
+ key={u}
+ className={`unit-chip ${unit === u ? 'active' : ''}`}
+ onClick={() => setUnit(unit === u ? '' : u)}
+ >
+ {u}
+ </button>
+ ))}
+ </div>
+ )}
</div>
</div>
@@ -408,26 +416,41 @@ const JournalTab = () => {
</select>
</div>
- <div className="control-group">
- <label>Priority</label>
- <select value={priority} onChange={(e) => setPriority(e.target.value)}>
- <option value="">All</option>
- <option value="0">Emergency</option>
- <option value="1">Alert</option>
- <option value="2">Critical</option>
- <option value="3">Error</option>
- <option value="4">Warning</option>
- <option value="5">Notice</option>
- <option value="6">Info</option>
- <option value="7">Debug</option>
- </select>
- </div>
+ {isJournalctl && (
+ <div className="control-group">
+ <label>Priority</label>
+ <select value={priority} onChange={(e) => setPriority(e.target.value)}>
+ <option value="">All</option>
+ <option value="0">Emergency</option>
+ <option value="1">Alert</option>
+ <option value="2">Critical</option>
+ <option value="3">Error</option>
+ <option value="4">Warning</option>
+ <option value="5">Notice</option>
+ <option value="6">Info</option>
+ <option value="7">Debug</option>
+ </select>
+ </div>
+ )}
<button className="btn btn-primary" onClick={loadJournalLogs} disabled={loading}>
{loading ? 'Loading...' : 'Load Logs'}
</button>
</div>
+ {!isJournalctl && source && (
+ <div className="journal-source-notice">
+ <svg viewBox="0 0 24 24" width="16" height="16">
+ <circle cx="12" cy="12" r="10"/>
+ <line x1="12" y1="16" x2="12" y2="12"/>
+ <line x1="12" y1="8" x2="12.01" y2="8"/>
+ </svg>
+ <span>
+ Reading from <strong>{sourceLabel}</strong> — journalctl is not available on this system
+ </span>
+ </div>
+ )}
+
<div className="journal-viewer">
<pre>{loading ? 'Loading journal logs...' : logs}</pre>
</div>
@@ -711,7 +734,7 @@ const ServicesTab = () => {
setShowLogsModal(true);
try {
const data = await api.getJournalLogs(serviceName, 100);
- setServiceLogs(data.content || data.logs || 'No logs available');
+ setServiceLogs(data.lines?.join('\n') || 'No logs available');
} catch (err) {
setServiceLogs(`Error loading logs: ${err.message}`);
}
diff --git a/frontend/src/styles/pages/_terminal.less b/frontend/src/styles/pages/_terminal.less
index ebe91d0e..81611122 100644
--- a/frontend/src/styles/pages/_terminal.less
+++ b/frontend/src/styles/pages/_terminal.less
@@ -358,6 +358,22 @@
}
}
+.journal-source-notice {
+ display: flex;
+ align-items: center;
+ gap: @space-2;
+ padding: @space-2 @space-4;
+ background: var(--bg-secondary);
+ border: 1px solid var(--border-color);
+ border-radius: @radius-md;
+ font-size: @font-size-xs;
+ color: var(--text-secondary);
+ margin-top: -@space-4;
+
+ svg { stroke: currentColor; fill: none; stroke-width: 2; flex-shrink: 0; }
+ strong { color: var(--text-primary); }
+}
+
.journal-viewer {
flex: 1;
background: var(--bg-code);