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.

Delete nine backend functions with no callers

Juan Denisd7234b822df8
diff --git a/backend/app/middleware/rate_limit.py b/backend/app/middleware/rate_limit.py
index 48c0b0d0..dda3b360 100644
--- a/backend/app/middleware/rate_limit.py
+++ b/backend/app/middleware/rate_limit.py
@@ -24,34 +24,6 @@ def get_rate_limit_key():
return f'ip:{get_client_ip()}'
-def get_dynamic_limit():
- """Return rate limit string based on auth context tier."""
- from app.services.settings_service import SettingsService
-
- # API key tier
- api_key = getattr(g, 'api_key', None)
- if api_key:
- tier = api_key.tier or 'standard'
- setting_key = f'rate_limit_{tier}'
- return SettingsService.get(setting_key, _default_for_tier(tier))
-
- # Authenticated user
- api_key_user = getattr(g, 'api_key_user', None)
- if api_key_user:
- return SettingsService.get('rate_limit_standard', '100 per minute')
-
- try:
- from flask_jwt_extended import get_jwt_identity
- user_id = get_jwt_identity()
- if user_id:
- return SettingsService.get('rate_limit_standard', '100 per minute')
- except Exception:
- pass
-
- # Unauthenticated
- return SettingsService.get('rate_limit_unauthenticated', '30 per minute')
-
-
def _default_for_tier(tier):
"""Return default rate limit for a tier."""
defaults = {
diff --git a/backend/app/services/anomaly_detection_service.py b/backend/app/services/anomaly_detection_service.py
index 6d3255f8..0bba3df2 100644
--- a/backend/app/services/anomaly_detection_service.py
+++ b/backend/app/services/anomaly_detection_service.py
@@ -390,29 +390,5 @@ class AnomalyDetectionService:
if not self._command_counts[server_id]:
del self._command_counts[server_id]
- def load_known_ips(self):
- """
- Load known IPs from database.
-
- Should be called on startup to populate the known IPs cache.
- """
- try:
- from app.models.server import AgentSession
-
- sessions = AgentSession.query.filter(
- AgentSession.ip_address.isnot(None)
- ).all()
-
- with self._lock:
- for session in sessions:
- if session.server_id and session.ip_address:
- self._known_ips[session.server_id].add(session.ip_address)
-
- print(f"[AnomalyDetection] Loaded known IPs for {len(self._known_ips)} servers")
-
- except Exception as e:
- print(f"[AnomalyDetection] Error loading known IPs: {e}")
-
-
# Global instance
anomaly_detection_service = AnomalyDetectionService()
diff --git a/backend/app/services/db_sync_service.py b/backend/app/services/db_sync_service.py
index 126808ba..a961d40a 100644
--- a/backend/app/services/db_sync_service.py
+++ b/backend/app/services/db_sync_service.py
@@ -492,95 +492,6 @@ class DatabaseSyncService:
return options
- @classmethod
- def run_search_replace(cls, db_name: str, search: str, replace: str,
- table_prefix: str = 'wp_', host: str = 'localhost',
- user: str = 'root', password: str = None,
- dry_run: bool = False) -> Dict:
- """
- Run WordPress-aware search-replace on a database.
-
- This is a pure SQL approach without requiring WP-CLI.
- For better serialized data handling, use WP-CLI if available.
-
- Args:
- db_name: Database name
- search: String to search for
- replace: String to replace with
- table_prefix: WordPress table prefix
- host: MySQL host
- user: MySQL user
- password: MySQL password
- dry_run: Only count replacements, don't apply
-
- Returns:
- Dict with success status and replacement count
- """
- try:
- # Get list of tables
- tables_result = cls._run_mysql(
- f"SHOW TABLES LIKE '{table_prefix}%'",
- database=db_name, host=host, user=user, password=password
- )
-
- if not tables_result['success']:
- return tables_result
-
- tables = [line.strip() for line in tables_result['output'].strip().split('\n')[1:] if line.strip()]
- total_replacements = 0
-
- for table in tables:
- # Get columns
- cols_result = cls._run_mysql(
- f"SHOW COLUMNS FROM `{table}`",
- database=db_name, host=host, user=user, password=password
- )
-
- if not cols_result['success']:
- continue
-
- # Find text/varchar columns
- text_columns = []
- for line in cols_result['output'].strip().split('\n')[1:]:
- parts = line.split('\t')
- if len(parts) >= 2:
- col_name = parts[0]
- col_type = parts[1].lower()
- if any(t in col_type for t in ['varchar', 'text', 'longtext', 'mediumtext']):
- text_columns.append(col_name)
-
- # Count or replace in each column
- for col in text_columns:
- if dry_run:
- count_query = f"SELECT COUNT(*) FROM `{table}` WHERE `{col}` LIKE '%{search}%'"
- count_result = cls._run_mysql(
- count_query,
- database=db_name, host=host, user=user, password=password
- )
- if count_result['success']:
- try:
- count = int(count_result['output'].strip().split('\n')[1])
- total_replacements += count
- except (IndexError, ValueError):
- pass
- else:
- # Note: This is basic replacement, doesn't handle serialized data perfectly
- update_query = f"UPDATE `{table}` SET `{col}` = REPLACE(`{col}`, '{search}', '{replace}') WHERE `{col}` LIKE '%{search}%'"
- cls._run_mysql(
- update_query,
- database=db_name, host=host, user=user, password=password
- )
-
- return {
- 'success': True,
- 'dry_run': dry_run,
- 'replacements': total_replacements if dry_run else 'Applied to all matching rows',
- 'tables_processed': len(tables)
- }
-
- except Exception as e:
- return {'success': False, 'error': str(e)}
-
@classmethod
def delete_snapshot(cls, file_path: str) -> Dict:
"""Delete a snapshot file."""
diff --git a/backend/app/services/module_service.py b/backend/app/services/module_service.py
index 13d75647..435bb324 100644
--- a/backend/app/services/module_service.py
+++ b/backend/app/services/module_service.py
@@ -62,32 +62,3 @@ def list_modules():
}
for name, meta in MODULES.items()
]
-
-
-def attach_module_guard(bp, name):
- """Attach a before_request that 503s a blueprint when its module is off.
-
- Mirrors plugin_service._attach_status_guard so a disabled module's API
- behaves exactly like a disabled plugin's.
-
- Idempotent: core blueprints are module-level singletons reused across app
- instances (e.g. every test builds a fresh app), and Flask forbids calling
- the `before_request` setup method after a blueprint has been registered
- once. We attach the handler a single time — it lives on the blueprint and
- applies to every app it's registered on — and read the toggle fresh on each
- request, so re-creating the app never re-attaches.
- """
- if getattr(bp, '_module_guard_attached', False):
- return
-
- def _check():
- if not is_module_enabled(name):
- from flask import jsonify
- return jsonify({
- 'error': f"The {MODULES[name]['label']} module is disabled",
- 'module': name,
- }), 503
- return None
-
- bp.before_request(_check)
- bp._module_guard_attached = True
diff --git a/backend/app/services/nonce_service.py b/backend/app/services/nonce_service.py
index b138c14b..b6efa22b 100644
--- a/backend/app/services/nonce_service.py
+++ b/backend/app/services/nonce_service.py
@@ -80,28 +80,6 @@ class NonceService:
self._nonces[key] = expiry
return True
- def is_replay(self, server_id: str, nonce: str) -> bool:
- """
- Check if a nonce would be considered a replay (without recording).
-
- Args:
- server_id: The server ID associated with the nonce
- nonce: The nonce value to check
-
- Returns:
- bool: True if this would be a replay, False otherwise
- """
- if not nonce:
- return True
-
- key = (server_id, nonce)
- now = time.time()
-
- with self._lock:
- if key in self._nonces:
- return self._nonces[key] > now
- return False
-
def _cleanup_loop(self):
"""Background thread to clean up expired nonces."""
while not self._stop_cleanup.is_set():
diff --git a/backend/app/services/server_metrics_service.py b/backend/app/services/server_metrics_service.py
index 0208e9e6..12356b7f 100644
--- a/backend/app/services/server_metrics_service.py
+++ b/backend/app/services/server_metrics_service.py
@@ -13,7 +13,7 @@ from typing import Dict, List, Optional, Any
from sqlalchemy import func, and_
from app import db
-from app.models.server import Server, ServerMetrics
+from app.models.server import ServerMetrics
logger = logging.getLogger(__name__)
@@ -250,66 +250,6 @@ class ServerMetricsService:
'coverage': cls.coverage(hours_back),
}
- @classmethod
- def get_multi_server_comparison(cls, server_ids: List[str], metric: str = 'cpu',
- period: str = '24h') -> Dict[str, Any]:
- """Get metrics comparison across multiple servers.
-
- Args:
- server_ids: List of server UUIDs
- metric: 'cpu', 'memory', 'disk', or 'network'
- period: Time period
-
- Returns:
- Dict with comparison data for each server
- """
- hours_back = {
- '1h': 1,
- '6h': 6,
- '24h': 24,
- '7d': 24 * 7,
- }.get(period, 24)
-
- cutoff = datetime.utcnow() - timedelta(hours=hours_back)
-
- result = {
- 'metric': metric,
- 'period': period,
- 'servers': {}
- }
-
- metric_column = {
- 'cpu': ServerMetrics.cpu_percent,
- 'memory': ServerMetrics.memory_percent,
- 'disk': ServerMetrics.disk_percent,
- }.get(metric, ServerMetrics.cpu_percent)
-
- for server_id in server_ids:
- # Get server info
- server = Server.query.get(server_id)
- if not server:
- continue
-
- # Query metrics
- records = ServerMetrics.query.filter(
- ServerMetrics.server_id == server_id,
- ServerMetrics.timestamp >= cutoff
- ).order_by(ServerMetrics.timestamp.asc()).all()
-
- # Calculate statistics
- values = [getattr(r, metric_column.key) for r in records if getattr(r, metric_column.key) is not None]
-
- result['servers'][server_id] = {
- 'name': server.name,
- 'current': values[-1] if values else None,
- 'avg': round(sum(values) / len(values), 1) if values else None,
- 'min': round(min(values), 1) if values else None,
- 'max': round(max(values), 1) if values else None,
- 'points': len(values)
- }
-
- return result
-
@classmethod
def cleanup_old_metrics(cls) -> Dict[str, int]:
"""Remove metrics older than retention period.
diff --git a/backend/app/services/telemetry_service.py b/backend/app/services/telemetry_service.py
index c11794ee..8e14c363 100644
--- a/backend/app/services/telemetry_service.py
+++ b/backend/app/services/telemetry_service.py
@@ -71,26 +71,6 @@ class TelemetryService:
db.session.rollback()
return None
- @classmethod
- def emit_for_request(cls, source, event_type, message=None, severity=SystemEvent.SEVERITY_INFO,
- resource_type=None, resource_id=None, correlation_id=None, payload=None,
- commit=True):
- """Emit an event, deriving actor/workspace from the current request context."""
- actor_user_id, workspace_id = cls._get_request_scope()
- return cls.emit(
- source=source,
- event_type=event_type,
- message=message,
- severity=severity,
- resource_type=resource_type,
- resource_id=resource_id,
- actor_user_id=actor_user_id,
- workspace_id=workspace_id,
- correlation_id=correlation_id,
- payload=payload,
- commit=commit,
- )
-
@classmethod
def _create_event(cls, source, event_type, message, severity, resource_type,
resource_id, actor_user_id, workspace_id, correlation_id, payload):
diff --git a/backend/app/services/webhook_service.py b/backend/app/services/webhook_service.py
index f0802ac1..7225a8b3 100644
--- a/backend/app/services/webhook_service.py
+++ b/backend/app/services/webhook_service.py
@@ -584,56 +584,3 @@ class WebhookService:
except Exception as e:
db.session.rollback()
return {'success': False, 'error': str(e)}
-
- @classmethod
- def get_webhook_setup_instructions(cls, webhook_id: int) -> Dict:
- """Get setup instructions for a webhook."""
- from app.models import GitWebhook
-
- webhook = GitWebhook.query.get(webhook_id)
- if not webhook:
- return {'success': False, 'error': 'Webhook not found'}
-
- webhook_url = webhook.to_dict()['webhook_url']
-
- instructions = {
- 'github': {
- 'title': 'GitHub Webhook Setup',
- 'steps': [
- 'Go to your GitHub repository Settings > Webhooks',
- 'Click "Add webhook"',
- f'Payload URL: YOUR_SERVER_URL{webhook_url}',
- 'Content type: application/json',
- f'Secret: (the secret provided when creating this webhook)',
- 'Select "Just the push event" or customize events',
- 'Click "Add webhook"'
- ]
- },
- 'gitlab': {
- 'title': 'GitLab Webhook Setup',
- 'steps': [
- 'Go to your GitLab project Settings > Webhooks',
- f'URL: YOUR_SERVER_URL{webhook_url}',
- f'Secret token: (the secret provided when creating this webhook)',
- 'Select "Push events" trigger',
- 'Click "Add webhook"'
- ]
- },
- 'bitbucket': {
- 'title': 'Bitbucket Webhook Setup',
- 'steps': [
- 'Go to your Bitbucket repository Settings > Webhooks',
- 'Click "Add webhook"',
- f'URL: YOUR_SERVER_URL{webhook_url}',
- 'Select "Repository push" trigger',
- 'Click "Save"'
- ]
- }
- }
-
- return {
- 'success': True,
- 'source': webhook.source,
- 'webhook_url': webhook_url,
- 'instructions': instructions.get(webhook.source, {})
- }
diff --git a/backend/app/utils/ip_utils.py b/backend/app/utils/ip_utils.py
index f7dccb3b..773209c4 100644
--- a/backend/app/utils/ip_utils.py
+++ b/backend/app/utils/ip_utils.py
@@ -149,31 +149,3 @@ def normalize_ip(ip: str) -> str:
return str(ipaddress.ip_address(ip))
except ValueError:
return ip
-
-
-def get_ip_info(ip: str) -> dict:
- """
- Get information about an IP address.
-
- Args:
- ip: The IP address to analyze
-
- Returns:
- dict: Information about the IP
- """
- try:
- addr = ipaddress.ip_address(ip)
- return {
- 'ip': str(addr),
- 'version': addr.version,
- 'is_private': addr.is_private,
- 'is_loopback': addr.is_loopback,
- 'is_multicast': addr.is_multicast,
- 'is_reserved': addr.is_reserved,
- 'is_global': addr.is_global,
- }
- except ValueError:
- return {
- 'ip': ip,
- 'error': 'Invalid IP address'
- }