Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(wordpress): safe update manager — snapshot, rollback, schedule (#29)

Juan Denis15fb6ebae0e8
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index afb5d06b..1322180e 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -340,6 +340,9 @@ def create_app(config_name=None):
# Start per-site WordPress health poller (uptime % + auto-incidents + alerts)
_start_health_check_scheduler(app)
+ # Start per-site WordPress safe-update scheduler (#29)
+ _start_update_scheduler(app)
+
# Start API analytics flush thread
from app.middleware.api_analytics import start_analytics_flush_thread
start_analytics_flush_thread(app)
@@ -792,3 +795,76 @@ def _prune_old_health_checks(logger):
db.session.rollback()
except Exception:
pass
+
+
+_update_scheduler_thread = None
+
+
+def _start_update_scheduler(app):
+ """Background thread that runs due per-site WordPress auto-updates (safe-update
+ with snapshot + health-check + auto-rollback). Single-worker only (module-global
+ guard); each run itself runs in its own thread, so this loop only triggers them."""
+ global _update_scheduler_thread
+ if _update_scheduler_thread is not None:
+ return
+
+ import threading
+ import time
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+ def loop():
+ time.sleep(45) # let startup settle
+ while True:
+ try:
+ time.sleep(60)
+ with app.app_context():
+ _check_update_schedules(logger)
+ except Exception as e:
+ logger.error(f'Update scheduler error: {e}')
+
+ _update_scheduler_thread = threading.Thread(target=loop, daemon=True, name='wp-update-scheduler')
+ _update_scheduler_thread.start()
+
+
+def _check_update_schedules(logger):
+ from app.models.wordpress_site import WordPressSite, WordPressUpdateRun
+ from app.services.wp_update_service import WpUpdateService
+ from datetime import datetime
+ import json as _json
+
+ try:
+ from croniter import croniter
+ except ImportError:
+ return
+
+ sites = WordPressSite.query.filter(WordPressSite.auto_update_schedule.isnot(None)).all()
+ if not sites:
+ return
+ now = datetime.utcnow()
+ for site in sites:
+ try:
+ expr = (site.auto_update_schedule or '').strip()
+ if not expr or not croniter.is_valid(expr):
+ continue
+ if not site.application or site.application.status != 'running':
+ continue
+ prev = croniter(expr, now).get_prev(datetime)
+ if not (0 < (now - prev).total_seconds() <= 90):
+ continue
+ # de-dup: skip if a run already started in the last ~10 minutes
+ last = (WordPressUpdateRun.query.filter_by(site_id=site.id)
+ .order_by(WordPressUpdateRun.started_at.desc()).first())
+ if last and last.started_at and (now - last.started_at).total_seconds() < 600:
+ continue
+ exclude = []
+ if site.auto_update_exclude:
+ try:
+ exclude = _json.loads(site.auto_update_exclude)
+ except Exception:
+ exclude = []
+ logger.info(f'Scheduled WordPress safe-update: site {site.id}')
+ WpUpdateService.start_update(site, exclude=exclude, trigger='scheduled')
+ except Exception as e:
+ logger.error(f'Update schedule check failed for site {site.id}: {e}')
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.py
index cc7e59eb..ef1cf849 100644
--- a/backend/app/api/wordpress.py
+++ b/backend/app/api/wordpress.py
@@ -652,6 +652,66 @@ def set_site_cron(app_id):
return jsonify(WpSecurityService.set_cron_disabled(app.root_path, disabled)), 200
+# ---- Safe update manager (#29): run history, on-demand safe update, schedule ----
+
+@wordpress_bp.route('/sites/<int:app_id>/updates', methods=['GET'])
+@jwt_required()
+def get_site_updates(app_id):
+ """Return safe-update run history + status + the site's update schedule."""
+ from app.services.wp_update_service import WpUpdateService
+ app, err = _owner_or_admin_app(app_id)
+ if err:
+ return err
+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
+ if not wp_site:
+ return jsonify({'error': 'Not a WordPress site'}), 400
+ result = WpUpdateService.get_runs(wp_site)
+ result['schedule'] = wp_site.auto_update_schedule
+ result['exclude'] = json.loads(wp_site.auto_update_exclude) if wp_site.auto_update_exclude else []
+ return jsonify(result), 200
+
+
+@wordpress_bp.route('/sites/<int:app_id>/updates/run', methods=['POST'])
+@jwt_required()
+@admin_required
+def run_site_updates(app_id):
+ """Start a background safe update (snapshot -> update -> health-check -> auto-rollback)."""
+ from app.services.wp_update_service import WpUpdateService
+ app = _resolve_app(app_id)
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
+ if not wp_site:
+ return jsonify({'error': 'Not a WordPress site'}), 400
+ data = request.get_json() or {}
+ targets = data.get('targets') or {'core': True, 'plugins': True, 'themes': True}
+ exclude = data.get('exclude') or []
+ return jsonify(WpUpdateService.start_update(wp_site, targets=targets, exclude=exclude)), 200
+
+
+@wordpress_bp.route('/sites/<int:app_id>/updates/schedule', methods=['POST'])
+@jwt_required()
+@admin_required
+def set_site_update_schedule(app_id):
+ """Set/clear the per-site auto-update cron schedule + exclusion list."""
+ app = _resolve_app(app_id)
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()
+ if not wp_site:
+ return jsonify({'error': 'Not a WordPress site'}), 400
+ data = request.get_json() or {}
+ wp_site.auto_update_schedule = (data.get('schedule') or '').strip() or None
+ if data.get('exclude') is not None:
+ wp_site.auto_update_exclude = json.dumps(data.get('exclude'))
+ db.session.commit()
+ return jsonify({
+ 'success': True,
+ 'schedule': wp_site.auto_update_schedule,
+ 'exclude': json.loads(wp_site.auto_update_exclude) if wp_site.auto_update_exclude else [],
+ }), 200
+
+
@wordpress_bp.route('/sites/<int:app_id>/info', methods=['GET'])
@jwt_required()
def get_wordpress_info(app_id):
diff --git a/backend/app/models/wordpress_site.py b/backend/app/models/wordpress_site.py
index 366fe4fd..b601caa3 100644
--- a/backend/app/models/wordpress_site.py
+++ b/backend/app/models/wordpress_site.py
@@ -81,6 +81,10 @@ class WordPressSite(db.Model):
# Vulnerability scan (#28)
last_vuln_scan_at = db.Column(db.DateTime)
+ # Safe updates (#29)
+ auto_update_schedule = db.Column(db.String(100)) # cron expression (null = off)
+ auto_update_exclude = db.Column(db.Text) # JSON list of plugin/theme slugs to skip
+
# Auto-sync
auto_sync_schedule = db.Column(db.String(100)) # cron expression
auto_sync_enabled = db.Column(db.Boolean, default=False)
@@ -98,6 +102,7 @@ class WordPressSite(db.Model):
)
snapshots = db.relationship('DatabaseSnapshot', backref='site', lazy='dynamic', cascade='all, delete-orphan')
vulnerabilities = db.relationship('WordPressVulnerability', backref='site', lazy='dynamic', cascade='all, delete-orphan')
+ update_runs = db.relationship('WordPressUpdateRun', backref='site', lazy='dynamic', cascade='all, delete-orphan')
sync_jobs_as_source = db.relationship(
'SyncJob',
foreign_keys='SyncJob.source_site_id',
@@ -150,6 +155,8 @@ class WordPressSite(db.Model):
'disk_usage_human': DatabaseSnapshot._format_size(self.disk_usage_bytes) if self.disk_usage_bytes else None,
'disk_usage_updated_at': self.disk_usage_updated_at.isoformat() if self.disk_usage_updated_at else None,
'last_vuln_scan_at': self.last_vuln_scan_at.isoformat() if self.last_vuln_scan_at else None,
+ 'auto_update_schedule': self.auto_update_schedule,
+ 'auto_update_exclude': json.loads(self.auto_update_exclude) if self.auto_update_exclude else [],
'auto_sync_schedule': self.auto_sync_schedule,
'auto_sync_enabled': self.auto_sync_enabled,
'created_at': self.created_at.isoformat() if self.created_at else None,
@@ -349,3 +356,36 @@ class WordPressVulnerability(db.Model):
def __repr__(self):
return f'<WordPressVulnerability {self.id} {self.source}:{self.slug} {self.severity}>'
+
+
+class WordPressUpdateRun(db.Model):
+ """A record of a safe-update run: snapshot -> update -> health-check -> rollback."""
+
+ __tablename__ = 'wordpress_update_runs'
+
+ id = db.Column(db.Integer, primary_key=True)
+ site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=False, index=True)
+
+ status = db.Column(db.String(20), default='running') # running|completed|rolled_back|failed
+ trigger = db.Column(db.String(20), default='manual') # manual|scheduled
+ # JSON: {targets, excluded, updated:[{type,slug,from,to}], health_before, health_after, rolled_back}
+ details = db.Column(db.Text)
+ error = db.Column(db.Text)
+
+ started_at = db.Column(db.DateTime, default=datetime.utcnow)
+ finished_at = db.Column(db.DateTime)
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'site_id': self.site_id,
+ 'status': self.status,
+ 'trigger': self.trigger,
+ 'details': json.loads(self.details) if self.details else {},
+ 'error': self.error,
+ 'started_at': self.started_at.isoformat() if self.started_at else None,
+ 'finished_at': self.finished_at.isoformat() if self.finished_at else None,
+ }
+
+ def __repr__(self):
+ return f'<WordPressUpdateRun {self.id} site={self.site_id} {self.status}>'
diff --git a/backend/app/services/environment_health_service.py b/backend/app/services/environment_health_service.py
index e3e3456b..20e37261 100644
--- a/backend/app/services/environment_health_service.py
+++ b/backend/app/services/environment_health_service.py
@@ -33,6 +33,14 @@ class EnvironmentHealthService:
return {'success': False, 'error': 'Site not found'}
compose_path = EnvironmentPipelineService._get_compose_path(site)
+ if not compose_path and site.application and site.application.root_path:
+ # Production sites (created by WordPressService.create_site) have no
+ # container_prefix, so _get_compose_path returns None; their compose
+ # lives directly at the Application root_path. Without this fallback,
+ # health is 'unknown' for every production site (breaking #26/#27).
+ candidate = os.path.join(site.application.root_path, 'docker-compose.yml')
+ if os.path.exists(candidate):
+ compose_path = candidate
checks = {
'container': {'status': 'unknown', 'message': ''},
'mysql': {'status': 'unknown', 'message': ''},
diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.py
index 822db0ab..8fbbe89f 100644
--- a/backend/app/services/wordpress_service.py
+++ b/backend/app/services/wordpress_service.py
@@ -58,12 +58,17 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
return {'success': False, 'error': str(e)}
@classmethod
- def wp_cli(cls, path: str, command: List[str], user: str = 'www-data') -> Dict:
- """Execute a WP-CLI command. Auto-detects Docker-based sites."""
+ def wp_cli(cls, path: str, command: List[str], user: str = 'www-data', timeout: int = None) -> Dict:
+ """Execute a WP-CLI command. Auto-detects Docker-based sites.
+
+ ``timeout`` overrides the default per-call wall-clock limit; pass a
+ generous value for long operations like ``db export``/``db import`` so a
+ large database is never truncated mid-restore.
+ """
# Check if this is a Docker-based site (has docker-compose.yml)
compose_file = os.path.join(path, 'docker-compose.yml')
if os.path.exists(compose_file):
- return cls._wp_cli_docker(path, command)
+ return cls._wp_cli_docker(path, command, timeout=timeout)
if not cls.is_wp_cli_installed():
install_result = cls.install_wp_cli()
@@ -76,7 +81,7 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
cmd,
capture_output=True,
text=True,
- timeout=300,
+ timeout=timeout or 300,
cwd=path
)
@@ -91,7 +96,7 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
return {'success': False, 'error': str(e)}
@classmethod
- def _wp_cli_docker(cls, path: str, command: List[str]) -> Dict:
+ def _wp_cli_docker(cls, path: str, command: List[str], timeout: int = None) -> Dict:
"""Execute a WP-CLI command inside a Docker WordPress container."""
# Resolve container name from the Application record
container_name = None
@@ -129,7 +134,7 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
cmd,
capture_output=True,
text=True,
- timeout=60
+ timeout=timeout or 60
)
return {
diff --git a/backend/app/services/wp_update_service.py b/backend/app/services/wp_update_service.py
new file mode 100644
index 00000000..e9158a1f
--- /dev/null
+++ b/backend/app/services/wp_update_service.py
@@ -0,0 +1,245 @@
+"""Safe WordPress update manager (#29).
+
+Runs updates with a safety net, all via the Docker-aware WP-CLI bridge:
+ 1. record the current core/plugin/theme versions
+ 2. snapshot the DB (wp db export to a container-local /tmp path)
+ 3. apply the requested updates (honouring an exclusion list)
+ 4. health-check the site (EnvironmentHealthService)
+ 5. if the update broke a previously-healthy site, AUTO-ROLLBACK: version-pin
+ each updated component back (wp <type> update --version=<old> --force) and
+ re-import the DB snapshot, then re-check health
+ 6. persist a WordPressUpdateRun record (the report)
+
+The run executes in a background thread (updates are slow) so the single worker
+never blocks; the UI polls get_runs() for status.
+
+Deferred: staging-first promotion (update a staging env via the promote pipeline,
+validate, then promote to production) — needs a staging env + the full env
+pipeline orchestration; revisit on top of #15/#18.
+"""
+
+import json
+import logging
+import threading
+from datetime import datetime, timedelta
+
+logger = logging.getLogger(__name__)
+
+
+class WpUpdateService:
+ STALE_RUN_MINUTES = 30 # a 'running' row older than this is treated as crashed
+ DB_TIMEOUT = 600 # generous wall-clock for db export/import (never truncate a restore)
+ MAX_CONCURRENT = 2 # bound simultaneous heavy updates (scheduler stampede protection)
+ _run_semaphore = threading.Semaphore(MAX_CONCURRENT)
+
+ # ---------- public API ----------
+
+ @classmethod
+ def get_runs(cls, site, limit=20):
+ from app.models.wordpress_site import WordPressUpdateRun
+ rows = (WordPressUpdateRun.query.filter_by(site_id=site.id)
+ .order_by(WordPressUpdateRun.started_at.desc()).limit(limit).all())
+ running = any(r.status == 'running' and not cls._is_stale(r) for r in rows)
+ return {'success': True, 'runs': [r.to_dict() for r in rows], 'running': running}
+
+ @classmethod
+ def start_update(cls, site, targets=None, exclude=None, trigger='manual'):
+ from flask import current_app
+ from app import db
+ from app.models.wordpress_site import WordPressUpdateRun
+ existing = (WordPressUpdateRun.query.filter_by(site_id=site.id, status='running')
+ .order_by(WordPressUpdateRun.started_at.desc()).first())
+ if existing and not cls._is_stale(existing):
+ return {'success': True, 'status': 'running', 'run_id': existing.id}
+
+ targets = targets or {'core': True, 'plugins': True, 'themes': True}
+ exclude = exclude or []
+ run = WordPressUpdateRun(
+ site_id=site.id, status='running', trigger=trigger,
+ details=json.dumps({'targets': targets, 'excluded': exclude}),
+ )
+ db.session.add(run)
+ db.session.commit()
+ run_id = run.id
+ app = current_app._get_current_object()
+ path = site.application.root_path if site.application else None
+ threading.Thread(
+ target=cls._run, args=(app, site.id, run_id, path, targets, exclude),
+ daemon=True, name=f'wp-update-{site.id}'
+ ).start()
+ return {'success': True, 'status': 'running', 'run_id': run_id}
+
+ @staticmethod
+ def _is_stale(run):
+ if not run.started_at:
+ return False
+ return (datetime.utcnow() - run.started_at) > timedelta(minutes=WpUpdateService.STALE_RUN_MINUTES)
+
+ # ---------- worker ----------
+
+ @classmethod
+ def _run(cls, app, site_id, run_id, path, targets, exclude):
+ with app.app_context():
+ from app import db
+ from app.models.wordpress_site import WordPressSite, WordPressUpdateRun
+ from app.services.wordpress_service import WordPressService
+ run = WordPressUpdateRun.query.get(run_id)
+ details = json.loads(run.details) if run and run.details else {}
+ snapshot = f'/tmp/wp-preupdate-{run_id}.sql'
+ keep_snapshot = False
+ # Bound concurrency so a shared 3am cron doesn't stampede the host.
+ with cls._run_semaphore:
+ try:
+ if not path:
+ raise RuntimeError('Site has no root path')
+ site = WordPressSite.query.get(site_id)
+ port = site.application.port if site and site.application else None
+
+ health_before = cls._site_status(path, port)
+ pre = cls._versions(path)
+
+ # "Safe" requires a DB net — abort BEFORE touching anything if the
+ # snapshot can't be taken (large DBs use a generous timeout).
+ export = WordPressService.wp_cli(path, ['db', 'export', snapshot], timeout=cls.DB_TIMEOUT)
+ if not export.get('success'):
+ raise RuntimeError('Could not snapshot the database; aborting to stay safe. '
+ + (export.get('error') or ''))
+
+ cls._apply_updates(path, targets, exclude)
+
+ post = cls._versions(path)
+ updated = cls._diff(pre, post)
+ health_after = cls._site_status(path, port)
+
+ # Roll back if the update regressed a previously-healthy site
+ # (degraded counts: a 5xx after an update is a regression).
+ rolled_back = False
+ if health_before == 'healthy' and health_after in ('unhealthy', 'degraded') and updated:
+ cls._rollback(path, updated, snapshot)
+ rolled_back = True
+ health_after = cls._site_status(path, port)
+
+ warning = None
+ if health_before != 'healthy':
+ warning = 'Baseline health could not be confirmed healthy, so auto-rollback was not attempted.'
+ keep_snapshot = True
+ if health_after != 'healthy':
+ warning = ((warning + ' ') if warning else '') + \
+ 'Site is not healthy after the update; the pre-update DB snapshot was kept for manual restore.'
+ keep_snapshot = True
+
+ details.update({
+ 'updated': updated,
+ 'health_before': health_before,
+ 'health_after': health_after,
+ 'rolled_back': rolled_back,
+ 'warning': warning,
+ })
+ run.status = 'rolled_back' if rolled_back else 'completed'
+ run.details = json.dumps(details)
+ run.finished_at = datetime.utcnow()
+ db.session.commit()
+ except Exception as e:
+ logger.error(f'Safe update failed for site {site_id}: {e}')
+ keep_snapshot = True # leave the snapshot for recovery
+ try:
+ if run is not None:
+ run.status = 'failed'
+ run.error = str(e)
+ run.details = json.dumps(details)
+ run.finished_at = datetime.utcnow()
+ db.session.commit()
+ except Exception:
+ db.session.rollback()
+ finally:
+ # Only drop the snapshot when the site ended verified-healthy.
+ if path and not keep_snapshot:
+ try:
+ WordPressService.wp_cli(path, ['eval', f"@unlink('{snapshot}');"])
+ except Exception:
+ pass
+
+ # ---------- steps ----------
+
+ @staticmethod
+ def _versions(path):
+ from app.services.wordpress_service import WordPressService
+ core = WordPressService.wp_cli(path, ['core', 'version'])
+ return {
+ 'core': (core.get('output') or '').strip() if core.get('success') else None,
+ 'plugins': {p.get('name'): p.get('version')
+ for p in (WordPressService.get_plugins(path) or []) if p.get('name')},
+ 'themes': {t.get('name'): t.get('version')
+ for t in (WordPressService.get_themes(path) or []) if t.get('name')},
+ }
+
+ @staticmethod
+ def _site_status(path, port):
+ """A quiet, SIDE-EFFECT-FREE liveness check (does NOT write health_status
+ or fire #27 transition alerts, unlike EnvironmentHealthService.check_health
+ — so an auto-rollback never pages on-call with spurious down/up). `wp eval`
+ loads WP incl. plugins so a PHP fatal is caught; the HTTP probe catches a
+ 5xx/connection regression. Returns healthy | degraded | unhealthy | unknown."""
+ from app.services.wordpress_service import WordPressService
+ from app.services.environment_health_service import EnvironmentHealthService
+ wp_ok = WordPressService.wp_cli(path, ['eval', "echo 'OK';"]).get('success', False)
+ http_status = 'unknown'
+ if port:
+ http_status = (EnvironmentHealthService._check_wordpress_http(port) or {}).get('status', 'unknown')
+ if not wp_ok or http_status == 'unhealthy':
+ return 'unhealthy'
+ if http_status == 'degraded':
+ return 'degraded'
+ if wp_ok and http_status in ('healthy', 'unknown'):
+ return 'healthy'
+ return 'unknown'
+
+ @classmethod
+ def _apply_updates(cls, path, targets, exclude):
+ from app.services.wordpress_service import WordPressService
+ ex = set(exclude or [])
+ if targets.get('core'):
+ WordPressService.update_wordpress(path)
+ if targets.get('plugins'):
+ avail = [p.get('name') for p in (WordPressService.get_plugins(path) or [])
+ if p.get('update') == 'available' and p.get('name') and p.get('name') not in ex]
+ if avail:
+ WordPressService.update_plugins(path, plugins=avail)
+ if targets.get('themes'):
+ avail = [t.get('name') for t in (WordPressService.get_themes(path) or [])
+ if t.get('update') == 'available' and t.get('name') and t.get('name') not in ex]
+ if avail:
+ WordPressService.update_themes(path, themes=avail)
+
+ @staticmethod
+ def _diff(pre, post):
+ updated = []
+ if pre.get('core') and post.get('core') and pre['core'] != post['core']:
+ updated.append({'type': 'core', 'slug': 'wordpress', 'from': pre['core'], 'to': post['core']})
+ for kind in ('plugins', 'themes'):
+ for slug, newv in (post.get(kind) or {}).items():
+ oldv = (pre.get(kind) or {}).get(slug)
+ if oldv and newv and oldv != newv:
+ updated.append({'type': kind[:-1], 'slug': slug, 'from': oldv, 'to': newv})
+ return updated
+
+ @classmethod
+ def _rollback(cls, path, updated, snapshot):
+ """Version-pin each updated component back to its pre-update version, then
+ re-import the DB snapshot. --skip-plugins/--skip-themes so the downgrade
+ runs even if a bad update left the site fatally broken (a loaded plugin
+ would otherwise crash wp-cli). Best-effort (a component not on
+ wordpress.org can't be version-downgraded; the DB snapshot is the net)."""
+ from app.services.wordpress_service import WordPressService
+ skip = ['--skip-plugins', '--skip-themes']
+ for u in updated:
+ t, slug, old = u.get('type'), u.get('slug'), u.get('from')
+ if t == 'core':
+ WordPressService.wp_cli(path, ['core', 'update', f'--version={old}', '--force'] + skip)
+ WordPressService.wp_cli(path, ['core', 'update-db'] + skip)
+ elif t == 'plugin':
+ WordPressService.wp_cli(path, ['plugin', 'update', slug, f'--version={old}', '--force'] + skip)
+ elif t == 'theme':
+ WordPressService.wp_cli(path, ['theme', 'update', slug, f'--version={old}', '--force'] + skip)
+ if snapshot:
+ WordPressService.wp_cli(path, ['db', 'import', snapshot] + skip, timeout=cls.DB_TIMEOUT)
diff --git a/backend/migrations/versions/012_wordpress_update_runs.py b/backend/migrations/versions/012_wordpress_update_runs.py
new file mode 100644
index 00000000..7b078f7e
--- /dev/null
+++ b/backend/migrations/versions/012_wordpress_update_runs.py
@@ -0,0 +1,65 @@
+"""Safe-update manager: run history + per-site schedule (#29).
+
+Adds:
+- table wordpress_update_runs (one row per safe-update run, FK site_id -> wordpress_sites.id)
+- wordpress_sites.auto_update_schedule (cron string, null = off)
+- wordpress_sites.auto_update_exclude (JSON list of slugs to skip)
+
+Idempotent: MigrationService._fix_missing_columns runs db.create_all() (creating
+the table) and ALTER-adds the columns on boot before Alembic, so guard on the
+live schema — like 009/010/011.
+
+Revision ID: 012_wordpress_update_runs
+Revises: 011_wordpress_vulnerabilities
+Create Date: 2026-06-01
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '012_wordpress_update_runs'
+down_revision = '011_wordpress_vulnerabilities'
+branch_labels = None
+depends_on = None
+
+
+def _has_col(inspector, table, col):
+ if table not in inspector.get_table_names():
+ return False
+ return col in {c['name'] for c in inspector.get_columns(table)}
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+
+ if 'wordpress_update_runs' not in inspector.get_table_names():
+ op.create_table(
+ 'wordpress_update_runs',
+ sa.Column('id', sa.Integer(), primary_key=True),
+ sa.Column('site_id', sa.Integer(), sa.ForeignKey('wordpress_sites.id'), nullable=False, index=True),
+ sa.Column('status', sa.String(length=20)),
+ sa.Column('trigger', sa.String(length=20)),
+ sa.Column('details', sa.Text()),
+ sa.Column('error', sa.Text()),
+ sa.Column('started_at', sa.DateTime()),
+ sa.Column('finished_at', sa.DateTime()),
+ )
+
+ if 'wordpress_sites' in inspector.get_table_names():
+ with op.batch_alter_table('wordpress_sites') as batch_op:
+ if not _has_col(inspector, 'wordpress_sites', 'auto_update_schedule'):
+ batch_op.add_column(sa.Column('auto_update_schedule', sa.String(length=100), nullable=True))
+ if not _has_col(inspector, 'wordpress_sites', 'auto_update_exclude'):
+ batch_op.add_column(sa.Column('auto_update_exclude', sa.Text(), nullable=True))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ with op.batch_alter_table('wordpress_sites') as batch_op:
+ if _has_col(inspector, 'wordpress_sites', 'auto_update_exclude'):
+ batch_op.drop_column('auto_update_exclude')
+ if _has_col(inspector, 'wordpress_sites', 'auto_update_schedule'):
+ batch_op.drop_column('auto_update_schedule')
+ if 'wordpress_update_runs' in inspector.get_table_names():
+ op.drop_table('wordpress_update_runs')
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.md
index 31155d08..1e4f3e2b 100644
--- a/docs/WORDPRESS_ROADMAP.md
+++ b/docs/WORDPRESS_ROADMAP.md
@@ -263,11 +263,12 @@ Highest-effort, broadest surface — but by now the `WordPressSite` is a first-c
- **Done when:** Vulnerable plugins/themes are flagged per site with severity.
- **Landed:** New `WpVulnerabilityService` reads installed plugin/theme/core slug+version via the **Docker-aware WP-CLI** bridge (`wp core version` + `get_plugins`/`get_themes` directly — *not* the host-filesystem-gated `get_wordpress_info`, which fails for volume-backed sites) and cross-references the **keyless community WPVulnerability API** (`https://www.wpvulnerability.net/{plugin,theme,core}/…`, no signup, 1h in-memory cache, descriptive UA, 8s timeout). It matches the installed version against each advisory's `operator` bounds (plugins/themes; core advisories all apply since the feed is version-scoped), extracts CVE id / severity (`cvss3` → `cvss` short-code → score fallback) / fixed-in / reference, and persists results as a new **`WordPressVulnerability`** child model (FK → `wordpress_sites.id`) + a `last_vuln_scan_at` column (Alembic **011**, idempotent). The scan runs in a **background thread** (Lynis-style, so the single worker never blocks on the WP-CLI + external HTTP), and a new **Vulnerabilities tab** on the site detail polls for status and renders findings with severity badges, CVE links, installed/fixed versions, and a summary. On-demand only (no scheduled external calls). Security hardening (3-lens review): `reference_url` is restricted to http(s) (blocks `javascript:` hrefs), the feed slug is percent-encoded, and an unrecognized version operator skips rather than over-flags. *(Deferred follow-ups: a scheduled periodic re-scan, and an optional "bring-your-own WPScan API key" for manually-verified data.)* Verified: backend `py_compile`, frontend lint-clean + production build, 3-lens adversarial review (major fixed: the Docker volume-backed core-read gating). Not runtime-exercised on a real host.
-### #29 — Safe update manager `[L]` 🟡
+### #29 — Safe update manager `[L]` 🟡 — ✅ Done (snapshot → update → health-check → auto-rollback + history + schedule; staging-first deferred)
- **Today:** Update primitives exist (#7); no history, scheduling, exclusions, staging-first, and pre-update backup is DB-only/core-only.
- **Do:** Scheduled updates via the cron workflow scheduler + a maintenance-window concept; an exclusion list + update-run records per site; **files + db** pre-update snapshot (not just db); run updates against the staging env via the promote pipeline; auto-rollback on failure using the pre-update snapshot + `restore_snapshot` (#10).
- **Reuse:** cron scheduler, `db_sync_service` snapshots, promote pipeline, `restore_snapshot`.
- **Done when:** Updates run on a schedule, staging-first, with backup + auto-rollback and a report.
+- **Landed:** New `WpUpdateService.start_update` runs a **background safe update** (Docker-correct, all via `wp_cli`): record pre-update versions → `wp db export` a DB snapshot (a generous **600s** timeout — added a `timeout` param to `wp_cli` — so a large DB is never truncated; **aborts if the snapshot fails** — no net, no update) → apply updates only to components with an available update **minus an exclusion list** → a **quiet, side-effect-free** health probe (`wp eval` + the HTTP probe; deliberately does NOT call `check_health`, so an auto-rollback never fires spurious #27 down/up pages) → if the update **regressed a previously-healthy site** (now unhealthy/degraded), **AUTO-ROLLBACK**: version-pin each updated component back (`wp <type> update --version=<old> --force --skip-plugins --skip-themes`, so it runs even on a fatally-broken site) + re-import the snapshot → re-check → persist a `WordPressUpdateRun` **report**. The snapshot is **kept for manual restore** whenever the site doesn't end verified-healthy; deleted only on success. A per-site cron **schedule** + exclusion list is driven by a new daemon-thread scheduler **bounded by a concurrency semaphore** (a shared 3am cron can't stampede the host). New model `WordPressUpdateRun` + 2 columns (Alembic **012**); a new **Updates tab** (run-now, schedule, exclusions, run-history). **Also fixed a latent #26/#27 bug** surfaced by the review: `EnvironmentHealthService.check_health` returned `unknown` for *every* production site (its `_get_compose_path` needs a `container_prefix` production sites lack), making uptime/incidents/alerts inert for the primary site type — now falls back to the Application `root_path` compose so production health actually works. *(Deferred: **staging-first** promotion — update a staging env via the promote pipeline, validate, then promote to prod — needs a staging env + full env-pipeline orchestration; revisit on #15/#18.)* Verified: backend `py_compile`, frontend lint-clean (full build was blocked only by a concurrent agent's unrelated in-progress AI import, not #29 code), 2-lens adversarial review (blockers fixed: production-site health gating + DB-import timeout; majors fixed: scheduler stampede, snapshot-abort). Not runtime-exercised on a real host.
### #30 — Per-site security depth `[L]` 🟡 — ✅ Done (file integrity + WP_DEBUG toggle + WP-Cron, Docker-correct; brute-force rate-limit jail deferred)
- **Today:** ClamAV + file-integrity scan host paths (`/var/www`, `/home`, `/etc`) and can't reach Docker WP volumes; nothing resolves a site to a scannable docroot; integrity never calls `wp ... verify-checksums`; no `wp-login.php`/`xmlrpc` rate-limit jail.
diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsx
index 0a8efebf..22f54f01 100644
--- a/frontend/src/pages/WordPressDetail.jsx
+++ b/frontend/src/pages/WordPressDetail.jsx
@@ -73,7 +73,7 @@ const DetailPageSkeleton = () => (
</div>
);
-const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'php', 'git', 'backups', 'uptime', 'analytics', 'vulnerabilities', 'security'];
+const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'php', 'git', 'backups', 'uptime', 'analytics', 'vulnerabilities', 'security', 'updates'];
const WordPressDetail = () => {
const { id } = useParams();
@@ -368,6 +368,12 @@ const WordPressDetail = () => {
>
<Lock size={14} /> Security
</div>
+ <div
+ className={`app-detail-tab ${activeTab === 'updates' ? 'active' : ''}`}
+ onClick={() => setActiveTab('updates')}
+ >
+ <RefreshCw size={14} /> Updates
+ </div>
</div>
{/* Clone Site Modal */}
@@ -415,6 +421,7 @@ const WordPressDetail = () => {
{activeTab === 'analytics' && <AnalyticsTab siteId={site.id} />}
{activeTab === 'vulnerabilities' && <VulnerabilitiesTab siteId={site.id} />}
{activeTab === 'security' && <SecurityTab siteId={site.id} />}
+ {activeTab === 'updates' && <UpdatesTab siteId={site.id} />}
</ErrorBoundary>
</div>
</div>
@@ -647,6 +654,138 @@ const UptimeTab = ({ siteId }) => {
);
};
+// Updates Tab — safe update manager (#29): snapshot -> update -> health-check ->
+// auto-rollback, plus a per-site schedule and a run-history report.
+const UPDATE_SCHEDULES = [
+ { label: 'Off', value: '' },
+ { label: 'Weekly (Sun 3am)', value: '0 3 * * 0' },
+ { label: 'Daily (3am)', value: '0 3 * * *' },
+];
+
+const UpdatesTab = ({ siteId }) => {
+ const toast = useToast();
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [busy, setBusy] = useState(false);
+ const [schedule, setSchedule] = useState('');
+ const [excludeText, setExcludeText] = useState('');
+
+ const load = React.useCallback(async () => {
+ try {
+ const res = await wordpressApi.getUpdates(siteId);
+ setData(res);
+ setSchedule(res.schedule || '');
+ setExcludeText((res.exclude || []).join(', '));
+ } catch (err) {
+ toast.error(err.message || 'Failed to load updates');
+ } finally {
+ setLoading(false);
+ }
+ }, [siteId, toast]);
+
+ useEffect(() => { load(); }, [load]);
+ useEffect(() => {
+ if (!data?.running) return undefined;
+ const t = setTimeout(() => { wordpressApi.getUpdates(siteId).then(setData).catch(() => {}); }, 3000);
+ return () => clearTimeout(t);
+ }, [data, siteId]);
+
+ const toList = (s) => s.split(',').map(x => x.trim()).filter(Boolean);
+
+ async function runUpdate() {
+ if (!window.confirm('Run a safe update now? A database snapshot is taken first and the site auto-rolls-back if the update breaks it.')) return;
+ setBusy(true);
+ try {
+ await wordpressApi.runUpdates(siteId, { exclude: toList(excludeText) });
+ toast.info('Safe update started…');
+ setData(await wordpressApi.getUpdates(siteId));
+ } catch (err) { toast.error(err.message || 'Failed to start update'); }
+ finally { setBusy(false); }
+ }
+ async function saveSchedule() {
+ setBusy(true);
+ try {
+ await wordpressApi.setUpdateSchedule(siteId, { schedule, exclude: toList(excludeText) });
+ toast.success('Schedule saved');
+ await load();
+ } catch (err) { toast.error(err.message || 'Failed to save schedule'); }
+ finally { setBusy(false); }
+ }
+
+ if (loading) return <div className="tab-loading"><p className="hint">Loading updates...</p></div>;
+
+ const runs = data?.runs || [];
+ const running = data?.running;
+ const statusVariant = (s) => ({ completed: 'success', rolled_back: 'warning', failed: 'destructive', running: 'info' }[s] || 'secondary');
+
+ return (
+ <div className="app-overview-grid">
+ <div className="app-overview-left">
+ <div className="app-panel">
+ <div className="app-panel-header">Safe update</div>
+ <div className="app-panel-body">
+ <p className="hint">Snapshots the database, updates core + plugins + themes, health-checks the site, and automatically rolls back (version-pin + DB restore) if the update breaks it.</p>
+ <div className="form-group">
+ <Label>Exclude (skip) plugins/themes</Label>
+ <Input value={excludeText} onChange={e => setExcludeText(e.target.value)} placeholder="e.g. woocommerce, my-custom-plugin" />
+ <span className="form-hint">Comma-separated slugs to never auto-update.</span>
+ </div>
+ <div className="app-detail-actions">
+ <Button size="sm" onClick={runUpdate} disabled={busy || running}>{running ? 'Updating…' : 'Run safe update now'}</Button>
+ </div>
+ </div>
+ </div>
+
+ <div className="app-panel">
+ <div className="app-panel-header">Schedule</div>
+ <div className="app-panel-body">
+ <div className="form-group">
+ <Label>Automatic safe updates</Label>
+ <select value={schedule} onChange={e => setSchedule(e.target.value)} disabled={busy}>
+ {UPDATE_SCHEDULES.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
+ {schedule && !UPDATE_SCHEDULES.some(s => s.value === schedule) && <option value={schedule}>{schedule}</option>}
+ </select>
+ <span className="form-hint">Runs the same safe update (with auto-rollback) on a schedule.</span>
+ </div>
+ <div className="app-detail-actions">
+ <Button variant="outline" size="sm" onClick={saveSchedule} disabled={busy}>Save schedule</Button>
+ </div>
+ </div>
+ </div>
+
+ <div className="app-panel">
+ <div className="app-panel-header">Update history</div>
+ <div className="app-panel-body">
+ {runs.length === 0 ? (
+ <p className="hint">No updates have run yet.</p>
+ ) : runs.map(r => {
+ const d = r.details || {};
+ const n = (d.updated || []).length;
+ return (
+ <div className="form-group" key={r.id}>
+ <div>
+ <Badge variant={statusVariant(r.status)}>{r.status.replace('_', ' ')}</Badge>{' '}
+ <span className="form-hint">{r.started_at ? new Date(r.started_at).toLocaleString() : ''} · {r.trigger}</span>
+ </div>
+ <span className="form-hint">
+ {n === 0 ? 'No components needed updating' : `${n} component${n === 1 ? '' : 's'} updated`}
+ {d.rolled_back ? ' · auto-rolled back (update regressed the site)' : ''}
+ {r.error ? ` · ${r.error}` : ''}
+ </span>
+ {d.warning && <span className="form-hint">⚠ {d.warning}</span>}
+ {(d.updated || []).slice(0, 10).map((u, i) => (
+ <span className="form-hint" key={i}>{u.type} {u.slug}: {u.from} → {u.to}</span>
+ ))}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
// Security Tab — per-site security depth (#30): file-integrity verification,
// WP_DEBUG toggle, and WP-Cron management, all via the Docker-aware WP-CLI bridge.
const SecurityTab = ({ siteId }) => {
diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.js
index f6d32951..4b300527 100644
--- a/frontend/src/services/wordpress.js
+++ b/frontend/src/services/wordpress.js
@@ -189,6 +189,11 @@ const wordpressApi = {
getVulnerabilities: (siteId) => api.request(`${BASE_PATH}/${siteId}/vulnerabilities`),
scanVulnerabilities: (siteId) => api.request(`${BASE_PATH}/${siteId}/vulnerabilities/scan`, { method: 'POST' }),
+ // Safe update manager (#29): run history, on-demand safe update, schedule
+ getUpdates: (siteId) => api.request(`${BASE_PATH}/${siteId}/updates`),
+ runUpdates: (siteId, body = {}) => api.request(`${BASE_PATH}/${siteId}/updates/run`, { method: 'POST', body }),
+ setUpdateSchedule: (siteId, body) => api.request(`${BASE_PATH}/${siteId}/updates/schedule`, { method: 'POST', body }),
+
// Security depth (#30): file integrity / debug toggle / WP-Cron
getIntegrity: (siteId) => api.request(`${BASE_PATH}/${siteId}/integrity`),
scanIntegrity: (siteId) => api.request(`${BASE_PATH}/${siteId}/integrity/scan`, { method: 'POST' }),