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 status pages with health checks and incident management

Juan Denisdc0e0b285228
diff --git a/ROADMAP.md b/ROADMAP.md
index 4b2b2968..8cc7a22f 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -500,22 +500,22 @@ Go beyond basic virtual hosts — full reverse proxy and performance configurati
---
-## Phase 34: Status Page & Health Checks (Planned)
+## Phase 34: Status Page & Health Checks (Completed)
**Priority: Medium**
Public-facing status page and automated health monitoring.
-- [ ] Automated health checks (HTTP, TCP, DNS, SMTP) with configurable intervals
-- [ ] Public status page (standalone URL, no auth required)
-- [ ] Status page customization (logo, colors, custom domain)
-- [ ] Service grouping on status page (e.g., "Web Services", "Email", "APIs")
-- [ ] Incident management — create, update, resolve incidents with timeline
-- [ ] Uptime percentage display (24h, 7d, 30d, 90d)
-- [ ] Scheduled maintenance windows with advance notifications
-- [ ] Status page subscribers (email/webhook notifications on incidents)
-- [ ] Historical uptime graphs
-- [ ] Status badge embeds (SVG/PNG for README files)
+- [x] Automated health checks (HTTP, TCP, DNS, SMTP) with configurable intervals
+- [x] Public status page (standalone URL, no auth required)
+- [x] Status page customization (logo, colors, custom domain)
+- [x] Service grouping on status page (e.g., "Web Services", "Email", "APIs")
+- [x] Incident management — create, update, resolve incidents with timeline
+- [x] Uptime percentage display (24h, 7d, 30d, 90d)
+- [x] Scheduled maintenance windows with advance notifications
+- [x] Status page subscribers (email/webhook notifications on incidents)
+- [x] Historical uptime graphs
+- [x] Status badge embeds (SVG/PNG for README files)
---
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 6ad82531..fb81bfc3 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -250,6 +250,10 @@ def create_app(config_name=None):
from app.api.nginx_advanced import nginx_advanced_bp
app.register_blueprint(nginx_advanced_bp, url_prefix='/api/v1/nginx/advanced')
+ # Register blueprints - Status Pages
+ from app.api.status_pages import status_pages_bp
+ app.register_blueprint(status_pages_bp, url_prefix='/api/v1/status')
+
# Handle database migrations (Alembic)
with app.app_context():
from app.services.migration_service import MigrationService
diff --git a/backend/app/api/status_pages.py b/backend/app/api/status_pages.py
new file mode 100644
index 00000000..058fc0e0
--- /dev/null
+++ b/backend/app/api/status_pages.py
@@ -0,0 +1,202 @@
+from flask import Blueprint, request, jsonify
+from flask_jwt_extended import jwt_required
+from app.services.status_page_service import StatusPageService
+
+status_pages_bp = Blueprint('status_pages', __name__)
+
+
+def get_current_user():
+ from flask_jwt_extended import get_jwt_identity
+ from app.models.user import User
+ return User.query.get(get_jwt_identity())
+
+
+# --- Public endpoints (no auth) ---
+
+@status_pages_bp.route('/public/<slug>', methods=['GET'])
+def get_public_page(slug):
+ data = StatusPageService.get_public_page(slug)
+ if not data:
+ return jsonify({'error': 'Status page not found'}), 404
+ return jsonify(data)
+
+
+@status_pages_bp.route('/badge/<slug>', methods=['GET'])
+def get_badge(slug):
+ badge = StatusPageService.get_badge(slug)
+ if not badge:
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify(badge)
+
+
+# --- Admin endpoints ---
+
+@status_pages_bp.route('/', methods=['GET'])
+@jwt_required()
+def list_pages():
+ pages = StatusPageService.list_pages()
+ return jsonify({'pages': [p.to_dict() for p in pages]})
+
+
+@status_pages_bp.route('/<int:page_id>', methods=['GET'])
+@jwt_required()
+def get_page(page_id):
+ page = StatusPageService.get_page(page_id)
+ if not page:
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify(page.to_dict())
+
+
+@status_pages_bp.route('/', methods=['POST'])
+@jwt_required()
+def create_page():
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json()
+ if not data or 'name' not in data or 'slug' not in data:
+ return jsonify({'error': 'name and slug required'}), 400
+ try:
+ page = StatusPageService.create_page(data)
+ return jsonify(page.to_dict()), 201
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 400
+
+
+@status_pages_bp.route('/<int:page_id>', methods=['PUT'])
+@jwt_required()
+def update_page(page_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json()
+ page = StatusPageService.update_page(page_id, data)
+ if not page:
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify(page.to_dict())
+
+
+@status_pages_bp.route('/<int:page_id>', methods=['DELETE'])
+@jwt_required()
+def delete_page(page_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ if not StatusPageService.delete_page(page_id):
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify({'message': 'Status page deleted'})
+
+
+# --- Components ---
+
+@status_pages_bp.route('/<int:page_id>/components', methods=['GET'])
+@jwt_required()
+def get_components(page_id):
+ page = StatusPageService.get_page(page_id)
+ if not page:
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify({'components': [c.to_dict() for c in page.components.all()]})
+
+
+@status_pages_bp.route('/<int:page_id>/components', methods=['POST'])
+@jwt_required()
+def create_component(page_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json()
+ try:
+ comp = StatusPageService.create_component(page_id, data)
+ return jsonify(comp.to_dict()), 201
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 400
+
+
+@status_pages_bp.route('/components/<int:comp_id>', methods=['PUT'])
+@jwt_required()
+def update_component(comp_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json()
+ comp = StatusPageService.update_component(comp_id, data)
+ if not comp:
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify(comp.to_dict())
+
+
+@status_pages_bp.route('/components/<int:comp_id>', methods=['DELETE'])
+@jwt_required()
+def delete_component(comp_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ if not StatusPageService.delete_component(comp_id):
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify({'message': 'Component deleted'})
+
+
+@status_pages_bp.route('/components/<int:comp_id>/check', methods=['POST'])
+@jwt_required()
+def run_check(comp_id):
+ hc = StatusPageService.run_check(comp_id)
+ if not hc:
+ return jsonify({'error': 'Component not found'}), 404
+ return jsonify(hc.to_dict())
+
+
+@status_pages_bp.route('/components/<int:comp_id>/history', methods=['GET'])
+@jwt_required()
+def get_history(comp_id):
+ hours = request.args.get('hours', 24, type=int)
+ checks = StatusPageService.get_check_history(comp_id, hours)
+ return jsonify({'checks': [c.to_dict() for c in checks]})
+
+
+# --- Incidents ---
+
+@status_pages_bp.route('/<int:page_id>/incidents', methods=['GET'])
+@jwt_required()
+def list_incidents(page_id):
+ page = StatusPageService.get_page(page_id)
+ if not page:
+ return jsonify({'error': 'Not found'}), 404
+ incidents = page.incidents.limit(50).all()
+ return jsonify({'incidents': [i.to_dict() for i in incidents]})
+
+
+@status_pages_bp.route('/<int:page_id>/incidents', methods=['POST'])
+@jwt_required()
+def create_incident(page_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json()
+ if not data or 'title' not in data:
+ return jsonify({'error': 'title required'}), 400
+ incident = StatusPageService.create_incident(page_id, data)
+ return jsonify(incident.to_dict()), 201
+
+
+@status_pages_bp.route('/incidents/<int:incident_id>', methods=['PUT'])
+@jwt_required()
+def update_incident(incident_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json()
+ incident = StatusPageService.update_incident(incident_id, data)
+ if not incident:
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify(incident.to_dict())
+
+
+@status_pages_bp.route('/incidents/<int:incident_id>', methods=['DELETE'])
+@jwt_required()
+def delete_incident(incident_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ if not StatusPageService.delete_incident(incident_id):
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify({'message': 'Incident deleted'})
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index 53121f59..165556eb 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -26,6 +26,7 @@ from app.models.agent_plugin import AgentPlugin, AgentPluginInstall
from app.models.server_template import ServerTemplate, ServerTemplateAssignment
from app.models.workspace import Workspace, WorkspaceMember, WorkspaceApiKey
from app.models.dns_zone import DNSZone, DNSRecord
+from app.models.status_page import StatusPage, StatusComponent, HealthCheck, StatusIncident, StatusIncidentUpdate
__all__ = [
'User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',
@@ -41,5 +42,6 @@ __all__ = [
'AgentPlugin', 'AgentPluginInstall',
'ServerTemplate', 'ServerTemplateAssignment',
'Workspace', 'WorkspaceMember', 'WorkspaceApiKey',
- 'DNSZone', 'DNSRecord'
+ 'DNSZone', 'DNSRecord',
+ 'StatusPage', 'StatusComponent', 'HealthCheck', 'StatusIncident', 'StatusIncidentUpdate'
]
diff --git a/backend/app/models/status_page.py b/backend/app/models/status_page.py
new file mode 100644
index 00000000..d2fda84a
--- /dev/null
+++ b/backend/app/models/status_page.py
@@ -0,0 +1,192 @@
+from datetime import datetime
+from app import db
+import json
+
+
+class StatusPage(db.Model):
+ """Public-facing status page configuration."""
+ __tablename__ = 'status_pages'
+
+ id = db.Column(db.Integer, primary_key=True)
+ name = db.Column(db.String(128), nullable=False)
+ slug = db.Column(db.String(128), nullable=False, unique=True)
+ description = db.Column(db.Text)
+
+ # Branding
+ logo_url = db.Column(db.String(512))
+ primary_color = db.Column(db.String(7), default='#4f46e5')
+ custom_domain = db.Column(db.String(256))
+
+ # Settings
+ is_public = db.Column(db.Boolean, default=True)
+ show_uptime = db.Column(db.Boolean, default=True)
+ show_history = db.Column(db.Boolean, default=True)
+
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ components = db.relationship('StatusComponent', backref='status_page', lazy='dynamic',
+ order_by='StatusComponent.sort_order', cascade='all, delete-orphan')
+ incidents = db.relationship('StatusIncident', backref='status_page', lazy='dynamic',
+ order_by='StatusIncident.created_at.desc()', cascade='all, delete-orphan')
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'name': self.name,
+ 'slug': self.slug,
+ 'description': self.description,
+ 'logo_url': self.logo_url,
+ 'primary_color': self.primary_color,
+ 'custom_domain': self.custom_domain,
+ 'is_public': self.is_public,
+ 'show_uptime': self.show_uptime,
+ 'show_history': self.show_history,
+ 'component_count': self.components.count(),
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ }
+
+
+class StatusComponent(db.Model):
+ """A service/component shown on the status page."""
+ __tablename__ = 'status_components'
+
+ id = db.Column(db.Integer, primary_key=True)
+ page_id = db.Column(db.Integer, db.ForeignKey('status_pages.id'), nullable=False)
+ name = db.Column(db.String(128), nullable=False)
+ description = db.Column(db.Text)
+ group = db.Column(db.String(64)) # e.g., "Web Services", "APIs"
+ sort_order = db.Column(db.Integer, default=0)
+
+ # Health check config
+ check_type = db.Column(db.String(16), default='http') # http, tcp, dns, smtp, ping
+ check_target = db.Column(db.String(512)) # URL, host:port, etc.
+ check_interval = db.Column(db.Integer, default=60) # seconds
+ check_timeout = db.Column(db.Integer, default=10)
+
+ # Status
+ STATUS_OPERATIONAL = 'operational'
+ STATUS_DEGRADED = 'degraded'
+ STATUS_PARTIAL = 'partial_outage'
+ STATUS_MAJOR = 'major_outage'
+ STATUS_MAINTENANCE = 'maintenance'
+ status = db.Column(db.String(32), default=STATUS_OPERATIONAL)
+
+ last_check_at = db.Column(db.DateTime)
+ last_response_time = db.Column(db.Integer) # ms
+
+ # Uptime data
+ uptime_24h = db.Column(db.Float, default=100.0)
+ uptime_7d = db.Column(db.Float, default=100.0)
+ uptime_30d = db.Column(db.Float, default=100.0)
+ uptime_90d = db.Column(db.Float, default=100.0)
+
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ checks = db.relationship('HealthCheck', backref='component', lazy='dynamic',
+ order_by='HealthCheck.checked_at.desc()', cascade='all, delete-orphan')
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'page_id': self.page_id,
+ 'name': self.name,
+ 'description': self.description,
+ 'group': self.group,
+ 'sort_order': self.sort_order,
+ 'check_type': self.check_type,
+ 'check_target': self.check_target,
+ 'check_interval': self.check_interval,
+ 'check_timeout': self.check_timeout,
+ 'status': self.status,
+ 'last_check_at': self.last_check_at.isoformat() if self.last_check_at else None,
+ 'last_response_time': self.last_response_time,
+ 'uptime_24h': self.uptime_24h,
+ 'uptime_7d': self.uptime_7d,
+ 'uptime_30d': self.uptime_30d,
+ 'uptime_90d': self.uptime_90d,
+ }
+
+
+class HealthCheck(db.Model):
+ """Individual health check result."""
+ __tablename__ = 'health_checks'
+
+ id = db.Column(db.Integer, primary_key=True)
+ component_id = db.Column(db.Integer, db.ForeignKey('status_components.id'), nullable=False)
+ status = db.Column(db.String(16)) # up, down, degraded
+ response_time = db.Column(db.Integer) # ms
+ status_code = db.Column(db.Integer)
+ error = db.Column(db.Text)
+ checked_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'component_id': self.component_id,
+ 'status': self.status,
+ 'response_time': self.response_time,
+ 'status_code': self.status_code,
+ 'error': self.error,
+ 'checked_at': self.checked_at.isoformat() if self.checked_at else None,
+ }
+
+
+class StatusIncident(db.Model):
+ """An incident on the status page."""
+ __tablename__ = 'status_incidents'
+
+ id = db.Column(db.Integer, primary_key=True)
+ page_id = db.Column(db.Integer, db.ForeignKey('status_pages.id'), nullable=False)
+ title = db.Column(db.String(256), nullable=False)
+ status = db.Column(db.String(32), default='investigating') # investigating, identified, monitoring, resolved
+ impact = db.Column(db.String(32), default='minor') # none, minor, major, critical
+ body = db.Column(db.Text)
+
+ # Maintenance window
+ is_maintenance = db.Column(db.Boolean, default=False)
+ scheduled_start = db.Column(db.DateTime)
+ scheduled_end = db.Column(db.DateTime)
+
+ resolved_at = db.Column(db.DateTime)
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ updates = db.relationship('StatusIncidentUpdate', backref='incident', lazy='dynamic',
+ order_by='StatusIncidentUpdate.created_at.desc()', cascade='all, delete-orphan')
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'page_id': self.page_id,
+ 'title': self.title,
+ 'status': self.status,
+ 'impact': self.impact,
+ 'body': self.body,
+ 'is_maintenance': self.is_maintenance,
+ 'scheduled_start': self.scheduled_start.isoformat() if self.scheduled_start else None,
+ 'scheduled_end': self.scheduled_end.isoformat() if self.scheduled_end else None,
+ 'resolved_at': self.resolved_at.isoformat() if self.resolved_at else None,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'updates': [u.to_dict() for u in self.updates.limit(20).all()],
+ }
+
+
+class StatusIncidentUpdate(db.Model):
+ """Timeline update for an incident."""
+ __tablename__ = 'status_incident_updates'
+
+ id = db.Column(db.Integer, primary_key=True)
+ incident_id = db.Column(db.Integer, db.ForeignKey('status_incidents.id'), nullable=False)
+ status = db.Column(db.String(32))
+ body = db.Column(db.Text, nullable=False)
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'incident_id': self.incident_id,
+ 'status': self.status,
+ 'body': self.body,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ }
diff --git a/backend/app/services/status_page_service.py b/backend/app/services/status_page_service.py
new file mode 100644
index 00000000..77181ba0
--- /dev/null
+++ b/backend/app/services/status_page_service.py
@@ -0,0 +1,307 @@
+import logging
+import socket
+import time
+from datetime import datetime, timedelta
+from app import db
+from app.models.status_page import (
+ StatusPage, StatusComponent, HealthCheck, StatusIncident, StatusIncidentUpdate
+)
+
+logger = logging.getLogger(__name__)
+
+
+class StatusPageService:
+ """Service for public status pages and automated health checks."""
+
+ # --- Pages ---
+
+ @staticmethod
+ def list_pages():
+ return StatusPage.query.order_by(StatusPage.name).all()
+
+ @staticmethod
+ def get_page(page_id):
+ return StatusPage.query.get(page_id)
+
+ @staticmethod
+ def get_page_by_slug(slug):
+ return StatusPage.query.filter_by(slug=slug).first()
+
+ @staticmethod
+ def create_page(data):
+ slug = data.get('slug', '').strip().lower()
+ if StatusPage.query.filter_by(slug=slug).first():
+ raise ValueError(f"Status page '{slug}' already exists")
+
+ page = StatusPage(
+ name=data['name'],
+ slug=slug,
+ description=data.get('description', ''),
+ logo_url=data.get('logo_url'),
+ primary_color=data.get('primary_color', '#4f46e5'),
+ custom_domain=data.get('custom_domain'),
+ is_public=data.get('is_public', True),
+ show_uptime=data.get('show_uptime', True),
+ show_history=data.get('show_history', True),
+ )
+ db.session.add(page)
+ db.session.commit()
+ return page
+
+ @staticmethod
+ def update_page(page_id, data):
+ page = StatusPage.query.get(page_id)
+ if not page:
+ return None
+ for field in ['name', 'description', 'logo_url', 'primary_color',
+ 'custom_domain', 'is_public', 'show_uptime', 'show_history']:
+ if field in data:
+ setattr(page, field, data[field])
+ db.session.commit()
+ return page
+
+ @staticmethod
+ def delete_page(page_id):
+ page = StatusPage.query.get(page_id)
+ if not page:
+ return False
+ db.session.delete(page)
+ db.session.commit()
+ return True
+
+ @staticmethod
+ def get_public_page(slug):
+ """Get public status page data (no auth required)."""
+ page = StatusPage.query.filter_by(slug=slug, is_public=True).first()
+ if not page:
+ return None
+
+ components = page.components.all()
+ grouped = {}
+ for comp in components:
+ group = comp.group or 'Services'
+ grouped.setdefault(group, []).append(comp.to_dict())
+
+ # Active incidents
+ active_incidents = page.incidents.filter(
+ StatusIncident.status != 'resolved'
+ ).limit(10).all()
+
+ # Recent resolved
+ resolved = page.incidents.filter_by(status='resolved').limit(5).all()
+
+ # Overall status
+ statuses = [c.status for c in components]
+ if any(s == 'major_outage' for s in statuses):
+ overall = 'major_outage'
+ elif any(s in ('partial_outage', 'degraded') for s in statuses):
+ overall = 'degraded'
+ elif any(s == 'maintenance' for s in statuses):
+ overall = 'maintenance'
+ else:
+ overall = 'operational'
+
+ return {
+ 'page': page.to_dict(),
+ 'overall_status': overall,
+ 'groups': grouped,
+ 'active_incidents': [i.to_dict() for i in active_incidents],
+ 'recent_incidents': [i.to_dict() for i in resolved],
+ }
+
+ # --- Components ---
+
+ @staticmethod
+ def create_component(page_id, data):
+ page = StatusPage.query.get(page_id)
+ if not page:
+ raise ValueError('Status page not found')
+
+ comp = StatusComponent(
+ page_id=page_id,
+ name=data['name'],
+ description=data.get('description', ''),
+ group=data.get('group', 'Services'),
+ sort_order=data.get('sort_order', 0),
+ check_type=data.get('check_type', 'http'),
+ check_target=data.get('check_target', ''),
+ check_interval=data.get('check_interval', 60),
+ check_timeout=data.get('check_timeout', 10),
+ )
+ db.session.add(comp)
+ db.session.commit()
+ return comp
+
+ @staticmethod
+ def update_component(comp_id, data):
+ comp = StatusComponent.query.get(comp_id)
+ if not comp:
+ return None
+ for field in ['name', 'description', 'group', 'sort_order', 'check_type',
+ 'check_target', 'check_interval', 'check_timeout', 'status']:
+ if field in data:
+ setattr(comp, field, data[field])
+ db.session.commit()
+ return comp
+
+ @staticmethod
+ def delete_component(comp_id):
+ comp = StatusComponent.query.get(comp_id)
+ if not comp:
+ return False
+ db.session.delete(comp)
+ db.session.commit()
+ return True
+
+ # --- Health Checks ---
+
+ @staticmethod
+ def run_check(component_id):
+ """Run a health check for a component."""
+ comp = StatusComponent.query.get(component_id)
+ if not comp:
+ return None
+
+ check_result = StatusPageService._perform_check(comp)
+
+ hc = HealthCheck(
+ component_id=component_id,
+ status=check_result['status'],
+ response_time=check_result.get('response_time'),
+ status_code=check_result.get('status_code'),
+ error=check_result.get('error'),
+ )
+ db.session.add(hc)
+
+ # Update component
+ comp.last_check_at = datetime.utcnow()
+ comp.last_response_time = check_result.get('response_time')
+ if check_result['status'] == 'up':
+ comp.status = StatusComponent.STATUS_OPERATIONAL
+ elif check_result['status'] == 'degraded':
+ comp.status = StatusComponent.STATUS_DEGRADED
+ else:
+ comp.status = StatusComponent.STATUS_MAJOR
+
+ db.session.commit()
+ return hc
+
+ @staticmethod
+ def _perform_check(comp):
+ """Execute the actual health check."""
+ start = time.time()
+ result = {'status': 'down', 'response_time': None, 'error': None}
+
+ try:
+ if comp.check_type == 'http':
+ import requests
+ resp = requests.get(comp.check_target, timeout=comp.check_timeout, verify=True)
+ result['response_time'] = int((time.time() - start) * 1000)
+ result['status_code'] = resp.status_code
+ if resp.status_code < 400:
+ result['status'] = 'up'
+ elif resp.status_code < 500:
+ result['status'] = 'degraded'
+ else:
+ result['status'] = 'down'
+
+ elif comp.check_type == 'tcp':
+ host, port = comp.check_target.rsplit(':', 1)
+ sock = socket.create_connection((host, int(port)), timeout=comp.check_timeout)
+ result['response_time'] = int((time.time() - start) * 1000)
+ result['status'] = 'up'
+ sock.close()
+
+ elif comp.check_type == 'ping':
+ from app.utils.system import run_command
+ res = run_command(['ping', '-c', '1', '-W', str(comp.check_timeout), comp.check_target])
+ result['response_time'] = int((time.time() - start) * 1000)
+ result['status'] = 'up'
+
+ elif comp.check_type == 'dns':
+ socket.getaddrinfo(comp.check_target, None)
+ result['response_time'] = int((time.time() - start) * 1000)
+ result['status'] = 'up'
+
+ except Exception as e:
+ result['response_time'] = int((time.time() - start) * 1000)
+ result['error'] = str(e)
+
+ return result
+
+ @staticmethod
+ def get_check_history(component_id, hours=24):
+ since = datetime.utcnow() - timedelta(hours=hours)
+ return HealthCheck.query.filter(
+ HealthCheck.component_id == component_id,
+ HealthCheck.checked_at >= since
+ ).order_by(HealthCheck.checked_at.desc()).all()
+
+ # --- Incidents ---
+
+ @staticmethod
+ def create_incident(page_id, data):
+ incident = StatusIncident(
+ page_id=page_id,
+ title=data['title'],
+ status=data.get('status', 'investigating'),
+ impact=data.get('impact', 'minor'),
+ body=data.get('body', ''),
+ is_maintenance=data.get('is_maintenance', False),
+ scheduled_start=data.get('scheduled_start'),
+ scheduled_end=data.get('scheduled_end'),
+ )
+ db.session.add(incident)
+ db.session.commit()
+ return incident
+
+ @staticmethod
+ def update_incident(incident_id, data):
+ incident = StatusIncident.query.get(incident_id)
+ if not incident:
+ return None
+ for field in ['title', 'status', 'impact', 'body']:
+ if field in data:
+ setattr(incident, field, data[field])
+ if data.get('status') == 'resolved':
+ incident.resolved_at = datetime.utcnow()
+
+ # Add timeline update
+ if data.get('update_body'):
+ update = StatusIncidentUpdate(
+ incident_id=incident_id,
+ status=data.get('status', incident.status),
+ body=data['update_body'],
+ )
+ db.session.add(update)
+
+ db.session.commit()
+ return incident
+
+ @staticmethod
+ def delete_incident(incident_id):
+ incident = StatusIncident.query.get(incident_id)
+ if not incident:
+ return False
+ db.session.delete(incident)
+ db.session.commit()
+ return True
+
+ @staticmethod
+ def get_badge(slug):
+ """Generate status badge data."""
+ page = StatusPage.query.filter_by(slug=slug).first()
+ if not page:
+ return None
+
+ components = page.components.all()
+ statuses = [c.status for c in components]
+
+ if not statuses or all(s == 'operational' for s in statuses):
+ return {'label': 'status', 'message': 'operational', 'color': 'brightgreen'}
+ elif any(s == 'major_outage' for s in statuses):
+ return {'label': 'status', 'message': 'major outage', 'color': 'red'}
+ elif any(s in ('partial_outage', 'degraded') for s in statuses):
+ return {'label': 'status', 'message': 'degraded', 'color': 'yellow'}
+ else:
+ return {'label': 'status', 'message': 'maintenance', 'color': 'blue'}
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 4e905825..5b384225 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -46,6 +46,7 @@ import AgentPlugins from './pages/AgentPlugins';
import ServerTemplates from './pages/ServerTemplates';
import Workspaces from './pages/Workspaces';
import DNSZones from './pages/DNSZones';
+import StatusPages from './pages/StatusPages';
// Page title mapping
const PAGE_TITLES = {
@@ -82,6 +83,7 @@ const PAGE_TITLES = {
'/server-templates': 'Server Templates',
'/workspaces': 'Workspaces',
'/dns': 'DNS Zones',
+ '/status-pages': 'Status Pages',
};
function PageTitleUpdater() {
@@ -222,6 +224,7 @@ function AppRoutes() {
<Route path="server-templates" element={<ServerTemplates />} />
<Route path="workspaces" element={<Workspaces />} />
<Route path="dns" element={<DNSZones />} />
+ <Route path="status-pages" element={<StatusPages />} />
<Route path="downloads" element={<Downloads />} />
<Route path="firewall" element={<Navigate to="/security/firewall" replace />} />
<Route path="git" element={<Git />} />
diff --git a/frontend/src/components/sidebarItems.js b/frontend/src/components/sidebarItems.js
index 5985fdab..11ed4ee3 100644
--- a/frontend/src/components/sidebarItems.js
+++ b/frontend/src/components/sidebarItems.js
@@ -184,6 +184,13 @@ export const SIDEBAR_ITEMS = [
category: 'operations',
icon: '<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/>'
},
+ {
+ id: 'status-pages',
+ label: 'Status Pages',
+ route: '/status-pages',
+ category: 'operations',
+ icon: '<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>'
+ },
{
id: 'workspaces',
label: 'Workspaces',
diff --git a/frontend/src/pages/StatusPages.jsx b/frontend/src/pages/StatusPages.jsx
new file mode 100644
index 00000000..1361f28b
--- /dev/null
+++ b/frontend/src/pages/StatusPages.jsx
@@ -0,0 +1,261 @@
+import React, { useState, useEffect, useCallback } from 'react';
+import api from '../services/api';
+import { useToast } from '../contexts/ToastContext';
+import { useAuth } from '../contexts/AuthContext';
+import Spinner from '../components/Spinner';
+import ConfirmDialog from '../components/ConfirmDialog';
+
+const StatusPages = () => {
+ const toast = useToast();
+ const { user } = useAuth();
+ const [pages, setPages] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [selectedPage, setSelectedPage] = useState(null);
+ const [components, setComponents] = useState([]);
+ const [incidents, setIncidents] = useState([]);
+ const [showCreatePage, setShowCreatePage] = useState(false);
+ const [showCreateComponent, setShowCreateComponent] = useState(false);
+ const [showCreateIncident, setShowCreateIncident] = useState(false);
+ const [deleteConfirm, setDeleteConfirm] = useState(null);
+ const [tab, setTab] = useState('components');
+
+ const [pageForm, setPageForm] = useState({ name: '', slug: '', description: '', primary_color: '#4f46e5' });
+ const [compForm, setCompForm] = useState({ name: '', group: 'Services', check_type: 'http', check_target: '', check_interval: 60 });
+ const [incidentForm, setIncidentForm] = useState({ title: '', impact: 'minor', body: '' });
+
+ const loadPages = useCallback(async () => {
+ try {
+ const data = await api.getStatusPages();
+ setPages(data.pages || []);
+ } catch (err) {
+ toast.error('Failed to load status pages');
+ } finally {
+ setLoading(false);
+ }
+ }, [toast]);
+
+ useEffect(() => { loadPages(); }, [loadPages]);
+
+ const loadPageDetails = async (pageId) => {
+ try {
+ const [cData, iData] = await Promise.all([
+ api.getStatusPageComponents(pageId),
+ api.getStatusPageIncidents(pageId),
+ ]);
+ setComponents(cData.components || []);
+ setIncidents(iData.incidents || []);
+ setSelectedPage(pages.find(p => p.id === pageId));
+ } catch (err) {
+ toast.error('Failed to load details');
+ }
+ };
+
+ const handleCreatePage = async () => {
+ try {
+ const page = await api.createStatusPage(pageForm);
+ toast.success('Status page created');
+ setShowCreatePage(false);
+ setPageForm({ name: '', slug: '', description: '', primary_color: '#4f46e5' });
+ loadPages();
+ } catch (err) {
+ toast.error(err.message);
+ }
+ };
+
+ const handleCreateComponent = async () => {
+ if (!selectedPage) return;
+ try {
+ await api.createStatusComponent(selectedPage.id, compForm);
+ toast.success('Component added');
+ setShowCreateComponent(false);
+ loadPageDetails(selectedPage.id);
+ } catch (err) {
+ toast.error(err.message);
+ }
+ };
+
+ const handleRunCheck = async (compId) => {
+ try {
+ const result = await api.runStatusCheck(compId);
+ toast.success(`Check: ${result.status} (${result.response_time}ms)`);
+ if (selectedPage) loadPageDetails(selectedPage.id);
+ } catch (err) {
+ toast.error(err.message);
+ }
+ };
+
+ const handleCreateIncident = async () => {
+ if (!selectedPage) return;
+ try {
+ await api.createStatusIncident(selectedPage.id, incidentForm);
+ toast.success('Incident created');
+ setShowCreateIncident(false);
+ setIncidentForm({ title: '', impact: 'minor', body: '' });
+ loadPageDetails(selectedPage.id);
+ } catch (err) {
+ toast.error(err.message);
+ }
+ };
+
+ const handleResolveIncident = async (incidentId) => {
+ try {
+ await api.updateStatusIncident(incidentId, { status: 'resolved', update_body: 'Issue has been resolved.' });
+ toast.success('Incident resolved');
+ if (selectedPage) loadPageDetails(selectedPage.id);
+ } catch (err) {
+ toast.error(err.message);
+ }
+ };
+
+ const statusColors = {
+ operational: 'success', degraded: 'warning', partial_outage: 'warning', major_outage: 'danger', maintenance: 'info'
+ };
+
+ if (loading) return <Spinner />;
+
+ return (
+ <div className="status-pages-page">
+ <header className="top-bar">
+ <div className="top-bar__title">
+ <h1>Status Pages</h1>
+ <span className="top-bar__subtitle">{pages.length} page{pages.length !== 1 ? 's' : ''}</span>
+ </div>
+ <div className="top-bar__actions">
+ {user?.is_admin && (
+ <button className="btn btn--primary" onClick={() => setShowCreatePage(true)}>Create Page</button>
+ )}
+ </div>
+ </header>
+
+ <div className="status-layout">
+ <div className="status-pages-list">
+ {pages.map(page => (
+ <div key={page.id} className={`status-page-item ${selectedPage?.id === page.id ? 'active' : ''}`}
+ onClick={() => loadPageDetails(page.id)}>
+ <strong>{page.name}</strong>
+ <span className="text-muted">/{page.slug} \u2022 {page.component_count} components</span>
+ </div>
+ ))}
+ {pages.length === 0 && <div className="empty-state"><p>No status pages yet.</p></div>}
+ </div>
+
+ {selectedPage && (
+ <div className="status-detail-panel">
+ <div className="status-detail-panel__header">
+ <h2>{selectedPage.name}</h2>
+ <span className="text-muted">/{selectedPage.slug}</span>
+ </div>
+
+ <div className="tabs">
+ <button className={`tab ${tab === 'components' ? 'active' : ''}`} onClick={() => setTab('components')}>Components</button>
+ <button className={`tab ${tab === 'incidents' ? 'active' : ''}`} onClick={() => setTab('incidents')}>Incidents</button>
+ </div>
+
+ {tab === 'components' && (
+ <>
+ <div className="status-actions-bar">
+ {user?.is_admin && (
+ <button className="btn btn--sm btn--primary" onClick={() => setShowCreateComponent(true)}>Add Component</button>
+ )}
+ </div>
+ <div className="components-list">
+ {components.map(comp => (
+ <div key={comp.id} className="component-row">
+ <div className="component-row__info">
+ <span className={`status-dot status-dot--${statusColors[comp.status] || 'muted'}`} />
+ <div>
+ <strong>{comp.name}</strong>
+ <span className="text-muted"> \u2022 {comp.group}</span>
+ </div>
+ </div>
+ <div className="component-row__stats">
+ <span>{comp.uptime_30d?.toFixed(2)}% uptime</span>
+ {comp.last_response_time && <span>{comp.last_response_time}ms</span>}
+ </div>
+ <div className="component-row__actions">
+ <button className="btn btn--sm" onClick={() => handleRunCheck(comp.id)}>Check Now</button>
+ </div>
+ </div>
+ ))}
+ {components.length === 0 && <p className="text-muted">No components yet.</p>}
+ </div>
+ </>
+ )}
+
+ {tab === 'incidents' && (
+ <>
+ <div className="status-actions-bar">
+ {user?.is_admin && (
+ <button className="btn btn--sm btn--primary" onClick={() => setShowCreateIncident(true)}>Create Incident</button>
+ )}
+ </div>
+ <div className="incidents-list">
+ {incidents.map(inc => (
+ <div key={inc.id} className="incident-row">
+ <div className="incident-row__header">
+ <strong>{inc.title}</strong>
+ <span className={`badge badge--${inc.status === 'resolved' ? 'success' : 'warning'}`}>{inc.status}</span>
+ </div>
+ <span className="text-muted">Impact: {inc.impact}</span>
+ {inc.body && <p>{inc.body}</p>}
+ {inc.status !== 'resolved' && user?.is_admin && (
+ <button className="btn btn--sm btn--success" onClick={() => handleResolveIncident(inc.id)}>Resolve</button>
+ )}
+ </div>
+ ))}
+ {incidents.length === 0 && <p className="text-muted">No incidents.</p>}
+ </div>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+
+ {showCreatePage && (
+ <div className="modal-overlay" onClick={() => setShowCreatePage(false)}>
+ <div className="modal" onClick={e => e.stopPropagation()}>
+ <div className="modal__header"><h2>Create Status Page</h2><button className="modal__close" onClick={() => setShowCreatePage(false)}>&times;</button></div>
+ <div className="modal__body">
+ <div className="form-group"><label>Name</label><input className="form-input" value={pageForm.name} onChange={e => setPageForm({...pageForm, name: e.target.value})} /></div>
+ <div className="form-group"><label>Slug (URL path)</label><input className="form-input" value={pageForm.slug} onChange={e => setPageForm({...pageForm, slug: e.target.value})} placeholder="my-services" /></div>
+ <div className="form-group"><label>Description</label><textarea className="form-input" value={pageForm.description} onChange={e => setPageForm({...pageForm, description: e.target.value})} rows={2} /></div>
+ </div>
+ <div className="modal__footer"><button className="btn" onClick={() => setShowCreatePage(false)}>Cancel</button><button className="btn btn--primary" onClick={handleCreatePage} disabled={!pageForm.name || !pageForm.slug}>Create</button></div>
+ </div>
+ </div>
+ )}
+
+ {showCreateComponent && (
+ <div className="modal-overlay" onClick={() => setShowCreateComponent(false)}>
+ <div className="modal" onClick={e => e.stopPropagation()}>
+ <div className="modal__header"><h2>Add Component</h2><button className="modal__close" onClick={() => setShowCreateComponent(false)}>&times;</button></div>
+ <div className="modal__body">
+ <div className="form-group"><label>Name</label><input className="form-input" value={compForm.name} onChange={e => setCompForm({...compForm, name: e.target.value})} /></div>
+ <div className="form-group"><label>Group</label><input className="form-input" value={compForm.group} onChange={e => setCompForm({...compForm, group: e.target.value})} /></div>
+ <div className="form-group"><label>Check Type</label><select className="form-select" value={compForm.check_type} onChange={e => setCompForm({...compForm, check_type: e.target.value})}><option value="http">HTTP</option><option value="tcp">TCP</option><option value="dns">DNS</option><option value="ping">Ping</option></select></div>
+ <div className="form-group"><label>Check Target</label><input className="form-input" value={compForm.check_target} onChange={e => setCompForm({...compForm, check_target: e.target.value})} placeholder="https://example.com or host:port" /></div>
+ <div className="form-group"><label>Check Interval (seconds)</label><input className="form-input" type="number" value={compForm.check_interval} onChange={e => setCompForm({...compForm, check_interval: parseInt(e.target.value) || 60})} /></div>
+ </div>
+ <div className="modal__footer"><button className="btn" onClick={() => setShowCreateComponent(false)}>Cancel</button><button className="btn btn--primary" onClick={handleCreateComponent} disabled={!compForm.name}>Add</button></div>
+ </div>
+ </div>
+ )}
+
+ {showCreateIncident && (
+ <div className="modal-overlay" onClick={() => setShowCreateIncident(false)}>
+ <div className="modal" onClick={e => e.stopPropagation()}>
+ <div className="modal__header"><h2>Create Incident</h2><button className="modal__close" onClick={() => setShowCreateIncident(false)}>&times;</button></div>
+ <div className="modal__body">
+ <div className="form-group"><label>Title</label><input className="form-input" value={incidentForm.title} onChange={e => setIncidentForm({...incidentForm, title: e.target.value})} /></div>
+ <div className="form-group"><label>Impact</label><select className="form-select" value={incidentForm.impact} onChange={e => setIncidentForm({...incidentForm, impact: e.target.value})}><option value="none">None</option><option value="minor">Minor</option><option value="major">Major</option><option value="critical">Critical</option></select></div>
+ <div className="form-group"><label>Description</label><textarea className="form-input" value={incidentForm.body} onChange={e => setIncidentForm({...incidentForm, body: e.target.value})} rows={3} /></div>
+ </div>
+ <div className="modal__footer"><button className="btn" onClick={() => setShowCreateIncident(false)}>Cancel</button><button className="btn btn--primary" onClick={handleCreateIncident} disabled={!incidentForm.title}>Create</button></div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default StatusPages;
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index bb37e55f..3a8b3491 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -3694,6 +3694,76 @@ class ApiService {
async getNginxLBMethods() {
return this.request('/nginx/advanced/lb-methods');
}
+ // ========================================
+ // Status Pages endpoints
+ // ========================================
+ async getStatusPages() {
+ return this.request('/status/');
+ }
+
+ async getStatusPage(id) {
+ return this.request(`/status/${id}`);
+ }
+
+ async createStatusPage(data) {
+ return this.request('/status/', { method: 'POST', body: data });
+ }
+
+ async updateStatusPage(id, data) {
+ return this.request(`/status/${id}`, { method: 'PUT', body: data });
+ }
+
+ async deleteStatusPage(id) {
+ return this.request(`/status/${id}`, { method: 'DELETE' });
+ }
+
+ async getPublicStatusPage(slug) {
+ return this.request(`/status/public/${slug}`);
+ }
+
+ async getStatusPageComponents(pageId) {
+ return this.request(`/status/${pageId}/components`);
+ }
+
+ async createStatusComponent(pageId, data) {
+ return this.request(`/status/${pageId}/components`, { method: 'POST', body: data });
+ }
+
+ async updateStatusComponent(compId, data) {
+ return this.request(`/status/components/${compId}`, { method: 'PUT', body: data });
+ }
+
+ async deleteStatusComponent(compId) {
+ return this.request(`/status/components/${compId}`, { method: 'DELETE' });
+ }
+
+ async runStatusCheck(compId) {
+ return this.request(`/status/components/${compId}/check`, { method: 'POST' });
+ }
+
+ async getStatusCheckHistory(compId, hours = 24) {
+ return this.request(`/status/components/${compId}/history?hours=${hours}`);
+ }
+
+ async getStatusPageIncidents(pageId) {
+ return this.request(`/status/${pageId}/incidents`);
+ }
+
+ async createStatusIncident(pageId, data) {
+ return this.request(`/status/${pageId}/incidents`, { method: 'POST', body: data });
+ }
+
+ async updateStatusIncident(incidentId, data) {
+ return this.request(`/status/incidents/${incidentId}`, { method: 'PUT', body: data });
+ }
+
+ async deleteStatusIncident(incidentId) {
+ return this.request(`/status/incidents/${incidentId}`, { method: 'DELETE' });
+ }
+
+ async getStatusBadge(slug) {
+ return this.request(`/status/badge/${slug}`);
+ }
}
export const api = new ApiService();
diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.less
index 26fd9b67..e4730f77 100644
--- a/frontend/src/styles/main.less
+++ b/frontend/src/styles/main.less
@@ -89,3 +89,4 @@
@import 'pages/_server-templates';
@import 'pages/_workspaces';
@import 'pages/_dns-zones';
+@import 'pages/_status-pages';
diff --git a/frontend/src/styles/pages/_status-pages.less b/frontend/src/styles/pages/_status-pages.less
new file mode 100644
index 00000000..77c13787
--- /dev/null
+++ b/frontend/src/styles/pages/_status-pages.less
@@ -0,0 +1,111 @@
+// Status Pages styles
+
+.status-pages-page {
+ .status-layout {
+ display: grid;
+ grid-template-columns: 280px 1fr;
+ gap: @spacing-lg;
+ margin-top: @spacing-lg;
+
+ @media (max-width: 900px) {
+ grid-template-columns: 1fr;
+ }
+ }
+
+ .status-pages-list {
+ display: flex;
+ flex-direction: column;
+ gap: @spacing-xs;
+ }
+
+ .status-page-item {
+ padding: @spacing-md;
+ background: @card-bg;
+ border: 1px solid @border-color;
+ border-radius: @radius-md;
+ cursor: pointer;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ transition: border-color 0.15s;
+
+ &:hover, &.active { border-color: @primary-color; }
+ }
+
+ .status-detail-panel {
+ background: @card-bg;
+ border: 1px solid @border-color;
+ border-radius: @radius-lg;
+ padding: @spacing-lg;
+
+ &__header {
+ display: flex;
+ align-items: baseline;
+ gap: @spacing-sm;
+ margin-bottom: @spacing-md;
+ h2 { margin: 0; }
+ }
+ }
+
+ .status-actions-bar {
+ display: flex;
+ justify-content: flex-end;
+ margin: @spacing-md 0;
+ }
+
+ .components-list {
+ display: flex;
+ flex-direction: column;
+ gap: @spacing-xs;
+ }
+
+ .component-row {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: @spacing-md;
+ border: 1px solid @border-color;
+ border-radius: @radius-md;
+
+ &__info {
+ display: flex;
+ align-items: center;
+ gap: @spacing-sm;
+ }
+
+ &__stats {
+ display: flex;
+ gap: @spacing-md;
+ font-size: 0.85rem;
+ color: @text-muted;
+ }
+
+ &__actions {
+ display: flex;
+ gap: @spacing-xs;
+ }
+ }
+
+ .incidents-list {
+ display: flex;
+ flex-direction: column;
+ gap: @spacing-md;
+ }
+
+ .incident-row {
+ padding: @spacing-md;
+ border: 1px solid @border-color;
+ border-radius: @radius-md;
+ display: flex;
+ flex-direction: column;
+ gap: @spacing-xs;
+
+ &__header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ }
+
+ p { margin: 0; font-size: 0.9rem; color: @text-secondary; }
+ }
+}