From cf7ccf8af3eb176d7f3377a111158227041a099e Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Tue, 27 Jan 2026 19:35:21 -0500 Subject: [PATCH] Add WordPress environment pipeline API and models Introduces a comprehensive REST API for WordPress multi-environment management, including endpoints for project listing, environment CRUD, promotion, sync, comparison, locking, activity logs, container logs, resource limits, basic auth, WP-CLI, health checks, disk usage, bulk operations, and auto-sync scheduling. Adds new models for environment activity, promotion jobs, and sanitization profiles, and integrates auto-sync scheduling into the app startup. Updates model imports and registration to include the new models. --- backend/app/__init__.py | 79 + backend/app/api/environment_pipeline.py | 1527 +++++++++++ backend/app/models/__init__.py | 6 +- backend/app/models/environment_activity.py | 54 + backend/app/models/metrics_history.py | 2 +- backend/app/models/promotion_job.py | 70 + backend/app/models/sanitization_profile.py | 167 ++ backend/app/models/wordpress_site.py | 50 + backend/app/services/db_sync_service.py | 341 ++- .../services/environment_docker_service.py | 481 ++++ .../services/environment_domain_service.py | 395 +++ .../services/environment_health_service.py | 291 ++ .../services/environment_pipeline_service.py | 1677 ++++++++++++ backend/app/services/git_wordpress_service.py | 105 + backend/app/services/template_service.py | 66 +- backend/app/services/wordpress_env_service.py | 46 +- backend/app/sockets.py | 75 + frontend/src/App.jsx | 6 + frontend/src/components/Sidebar.jsx | 6 + .../src/components/wordpress/ActivityFeed.jsx | 139 + .../wordpress/AutoSyncScheduleModal.jsx | 191 ++ .../components/wordpress/BasicAuthModal.jsx | 163 ++ .../components/wordpress/BulkActionsBar.jsx | 115 + .../src/components/wordpress/CompareView.jsx | 223 ++ .../components/wordpress/ContainerLogs.jsx | 123 + .../src/components/wordpress/DiskUsageBar.jsx | 87 + .../wordpress/EnvironmentStatusBadge.jsx | 34 + .../wordpress/HealthStatusPanel.jsx | 137 + .../src/components/wordpress/PipelineView.jsx | 608 +++++ .../src/components/wordpress/PromoteModal.jsx | 248 ++ .../wordpress/ResourceLimitsModal.jsx | 148 ++ .../wordpress/SanitizationProfileForm.jsx | 336 +++ .../src/components/wordpress/SyncModal.jsx | 219 ++ .../components/wordpress/WpCliTerminal.jsx | 197 ++ frontend/src/components/wordpress/index.js | 16 + frontend/src/pages/WordPressProject.jsx | 953 +++++++ frontend/src/pages/WordPressProjects.jsx | 139 + frontend/src/services/wordpress.js | 158 ++ .../src/styles/components/_metrics-graph.less | 2 +- frontend/src/styles/components/_modals.less | 8 + frontend/src/styles/layout/_sidebar.less | 6 + frontend/src/styles/main.less | 1 + .../src/styles/pages/_wordpress-pipeline.less | 2342 +++++++++++++++++ 43 files changed, 11999 insertions(+), 38 deletions(-) create mode 100644 backend/app/api/environment_pipeline.py create mode 100644 backend/app/models/environment_activity.py create mode 100644 backend/app/models/promotion_job.py create mode 100644 backend/app/models/sanitization_profile.py create mode 100644 backend/app/services/environment_docker_service.py create mode 100644 backend/app/services/environment_domain_service.py create mode 100644 backend/app/services/environment_health_service.py create mode 100644 backend/app/services/environment_pipeline_service.py create mode 100644 frontend/src/components/wordpress/ActivityFeed.jsx create mode 100644 frontend/src/components/wordpress/AutoSyncScheduleModal.jsx create mode 100644 frontend/src/components/wordpress/BasicAuthModal.jsx create mode 100644 frontend/src/components/wordpress/BulkActionsBar.jsx create mode 100644 frontend/src/components/wordpress/CompareView.jsx create mode 100644 frontend/src/components/wordpress/ContainerLogs.jsx create mode 100644 frontend/src/components/wordpress/DiskUsageBar.jsx create mode 100644 frontend/src/components/wordpress/EnvironmentStatusBadge.jsx create mode 100644 frontend/src/components/wordpress/HealthStatusPanel.jsx create mode 100644 frontend/src/components/wordpress/PipelineView.jsx create mode 100644 frontend/src/components/wordpress/PromoteModal.jsx create mode 100644 frontend/src/components/wordpress/ResourceLimitsModal.jsx create mode 100644 frontend/src/components/wordpress/SanitizationProfileForm.jsx create mode 100644 frontend/src/components/wordpress/SyncModal.jsx create mode 100644 frontend/src/components/wordpress/WpCliTerminal.jsx create mode 100644 frontend/src/pages/WordPressProject.jsx create mode 100644 frontend/src/pages/WordPressProjects.jsx create mode 100644 frontend/src/styles/pages/_wordpress-pipeline.less diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 3137dcbd..320c0a56 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -85,9 +85,11 @@ def create_app(config_name=None): from app.api.php import php_bp from app.api.wordpress import wordpress_bp from app.api.wordpress_sites import wordpress_sites_bp + from app.api.environment_pipeline import environment_pipeline_bp app.register_blueprint(php_bp, url_prefix='/api/v1/php') app.register_blueprint(wordpress_bp, url_prefix='/api/v1/wordpress') app.register_blueprint(wordpress_sites_bp, url_prefix='/api/v1/wordpress') + app.register_blueprint(environment_pipeline_bp, url_prefix='/api/v1/wordpress/projects') # Register blueprints - Python from app.api.python import python_bp @@ -191,6 +193,9 @@ def create_app(config_name=None): if not MetricsHistoryService.is_running(): MetricsHistoryService.start_collection(app) + # Start auto-sync scheduler for WordPress environments + _start_auto_sync_scheduler(app) + # Serve frontend for root path @app.route('/') def serve_index(): @@ -212,3 +217,77 @@ def create_app(config_name=None): def get_socketio(): """Get the SocketIO instance.""" return socketio + + +_auto_sync_thread = None + + +def _start_auto_sync_scheduler(app): + """Start a background thread that checks for auto-sync schedules.""" + global _auto_sync_thread + if _auto_sync_thread is not None: + return + + import threading + import time + import logging + + logger = logging.getLogger(__name__) + + def auto_sync_loop(): + while True: + try: + time.sleep(60) # Check every 60 seconds + with app.app_context(): + _check_auto_sync_schedules(logger) + except Exception as e: + logger.error(f'Auto-sync scheduler error: {e}') + + _auto_sync_thread = threading.Thread( + target=auto_sync_loop, + daemon=True, + name='auto-sync-scheduler' + ) + _auto_sync_thread.start() + + +def _check_auto_sync_schedules(logger): + """Check all auto-sync enabled sites and run syncs that are due.""" + from app.models.wordpress_site import WordPressSite + from datetime import datetime + + sites = WordPressSite.query.filter_by(auto_sync_enabled=True).all() + if not sites: + return + + try: + from croniter import croniter + except ImportError: + logger.debug('croniter not installed, skipping auto-sync check') + return + + now = datetime.utcnow() + + for site in sites: + if not site.auto_sync_schedule: + continue + + try: + if not croniter.is_valid(site.auto_sync_schedule): + continue + + cron = croniter(site.auto_sync_schedule, now) + prev_run = cron.get_prev(datetime) + + # Check if a run was due in the last 90 seconds (to account for check interval) + seconds_since_due = (now - prev_run).total_seconds() + if seconds_since_due <= 90: + logger.info(f'Auto-sync triggered for site {site.id} ({site.name})') + from app.services.environment_pipeline_service import EnvironmentPipelineService + EnvironmentPipelineService.sync_from_production( + env_site_id=site.id, + sync_type='full', + user_id=None + ) + except Exception as e: + logger.error(f'Auto-sync check failed for site {site.id}: {e}') diff --git a/backend/app/api/environment_pipeline.py b/backend/app/api/environment_pipeline.py new file mode 100644 index 00000000..dce8d270 --- /dev/null +++ b/backend/app/api/environment_pipeline.py @@ -0,0 +1,1527 @@ +""" +Environment Pipeline API + +REST endpoints for WordPress multi-environment management: +- Project listing and pipeline overview +- Environment CRUD and lifecycle (start/stop/restart) +- Code/database promotion between environments +- Sync from production +- Environment comparison +- Locking/unlocking +- Activity log +- Container logs +""" + +import threading +from flask import Blueprint, request, jsonify +from flask_jwt_extended import jwt_required, get_jwt_identity + +from app import db, limiter +from app.models.application import Application +from app.models.wordpress_site import WordPressSite +from app.models.environment_activity import EnvironmentActivity +from app.models.promotion_job import PromotionJob +from app.models.sanitization_profile import SanitizationProfile +from app.services.environment_pipeline_service import EnvironmentPipelineService +from app.services.environment_docker_service import EnvironmentDockerService +from app.services.git_wordpress_service import GitWordPressService + +environment_pipeline_bp = Blueprint('environment_pipeline', __name__) + + +# ============================================================================= +# Helper: Verify ownership of a production site +# ============================================================================= + +def _get_production_site(prod_id, user_id): + """Get a production site with ownership check. + + Returns (site, error_response) tuple. + If site is found and owned by user, returns (site, None). + Otherwise returns (None, error_response). + """ + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == prod_id, + Application.user_id == user_id + ).first() + + if not site: + return None, (jsonify({'error': 'Project not found'}), 404) + + if not site.is_production and site.environment_type not in ('production', 'standalone'): + return None, (jsonify({'error': 'Site is not a production environment'}), 400) + + return site, None + + +def _get_environment_site(env_id, user_id): + """Get an environment site with ownership check.""" + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == env_id, + Application.user_id == user_id + ).first() + + if not site: + return None, (jsonify({'error': 'Environment not found'}), 404) + + return site, None + + +# ============================================================================= +# Project Listing +# ============================================================================= + +@environment_pipeline_bp.route('', methods=['GET']) +@jwt_required() +def list_projects(): + """List all WordPress projects with environment summary. + + Returns production sites with a count of child environments for each. + """ + user_id = get_jwt_identity() + + sites = WordPressSite.query.join(Application).filter( + Application.user_id == user_id, + Application.app_type == 'wordpress', + WordPressSite.is_production == True + ).all() + + projects = [] + for site in sites: + project = site.to_dict() + project['environment_count'] = len(site.environments) + project['environment_types'] = [ + e.environment_type for e in site.environments + ] + projects.append(project) + + return jsonify({ + 'projects': projects, + 'total': len(projects) + }) + + +# ============================================================================= +# Pipeline View +# ============================================================================= + +@environment_pipeline_bp.route('//pipeline', methods=['GET']) +@jwt_required() +def get_pipeline(prod_id): + """Get full pipeline view: all environments, statuses, last actions.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + result = EnvironmentPipelineService.get_pipeline_status(prod_id) + if not result.get('success'): + return jsonify(result), 500 + + return jsonify(result) + + +# ============================================================================= +# Environment CRUD +# ============================================================================= + +@environment_pipeline_bp.route('//environments', methods=['POST']) +@jwt_required() +def create_environment(prod_id): + """Create a new environment (dev/staging/multidev). + + Body: { + type: "development" | "staging" | "multidev", + branch?: string, (required for multidev) + domain?: string, + clone_db?: boolean (default true), + resource_limits?: { memory, cpus, db_memory, db_cpus }, + name?: string + } + """ + user_id = get_jwt_identity() + data = request.get_json() or {} + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_type = data.get('type', 'development') + if env_type not in ('development', 'staging', 'multidev'): + return jsonify({'error': 'Invalid environment type. Must be development, staging, or multidev.'}), 400 + + # Emit WebSocket event for operation start + _emit_pipeline_event(prod_id, 'environment_creating', { + 'type': env_type, + 'message': f'Creating {env_type} environment...' + }) + + def progress_callback(progress_data): + _emit_pipeline_event(prod_id, 'operation_progress', progress_data) + + result = EnvironmentPipelineService.create_project_environment( + production_site_id=prod_id, + env_type=env_type, + config=data, + user_id=user_id, + progress_callback=progress_callback + ) + + # Emit completion event + _emit_pipeline_event(prod_id, 'environment_created' if result.get('success') else 'environment_create_failed', { + 'type': env_type, + 'success': result.get('success', False), + 'message': result.get('message') or result.get('error'), + }) + + if result.get('success'): + return jsonify(result), 201 + else: + return jsonify(result), 500 + + +@environment_pipeline_bp.route('//environments/', methods=['DELETE']) +@jwt_required() +def delete_environment(prod_id, env_id): + """Delete an environment and all its resources.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + result = EnvironmentPipelineService.delete_environment(env_id, user_id=user_id) + + _emit_pipeline_event(prod_id, 'environment_deleted' if result.get('success') else 'environment_delete_failed', { + 'env_id': env_id, + 'success': result.get('success', False), + 'message': result.get('message') or result.get('error'), + }) + + if result.get('success'): + return jsonify(result) + else: + return jsonify(result), 500 + + +# ============================================================================= +# Container Lifecycle +# ============================================================================= + +@environment_pipeline_bp.route('//environments//start', methods=['POST']) +@jwt_required() +def start_environment(prod_id, env_id): + """Start an environment's containers.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + compose_path = EnvironmentPipelineService._get_compose_path(env_site) + if not compose_path: + return jsonify({'error': 'No Docker compose configuration found for this environment'}), 400 + + result = EnvironmentDockerService.start_environment(compose_path) + + if result.get('success'): + env_site.application.status = 'running' + db.session.commit() + _emit_pipeline_event(prod_id, 'environment_started', {'env_id': env_id}) + + return jsonify(result) if result.get('success') else (jsonify(result), 500) + + +@environment_pipeline_bp.route('//environments//stop', methods=['POST']) +@jwt_required() +def stop_environment(prod_id, env_id): + """Stop an environment's containers.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + compose_path = EnvironmentPipelineService._get_compose_path(env_site) + if not compose_path: + return jsonify({'error': 'No Docker compose configuration found for this environment'}), 400 + + result = EnvironmentDockerService.stop_environment(compose_path) + + if result.get('success'): + env_site.application.status = 'stopped' + db.session.commit() + _emit_pipeline_event(prod_id, 'environment_stopped', {'env_id': env_id}) + + return jsonify(result) if result.get('success') else (jsonify(result), 500) + + +@environment_pipeline_bp.route('//environments//restart', methods=['POST']) +@jwt_required() +def restart_environment(prod_id, env_id): + """Restart an environment's containers.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + compose_path = EnvironmentPipelineService._get_compose_path(env_site) + if not compose_path: + return jsonify({'error': 'No Docker compose configuration found for this environment'}), 400 + + result = EnvironmentDockerService.restart_environment(compose_path) + + if result.get('success'): + env_site.application.status = 'running' + db.session.commit() + _emit_pipeline_event(prod_id, 'environment_restarted', {'env_id': env_id}) + + return jsonify(result) if result.get('success') else (jsonify(result), 500) + + +# ============================================================================= +# Promotion +# ============================================================================= + +@environment_pipeline_bp.route('//promote', methods=['POST']) +@jwt_required() +@limiter.limit("5 per minute") +def promote(prod_id): + """Promote code/DB between environments. + + Body: { + source_env_id: int, + target_env_id: int, + type: "code" | "database" | "full", + config: { + include_plugins?: boolean, + include_themes?: boolean, + include_mu_plugins?: boolean, + include_uploads?: boolean, + backup_target_first?: boolean, + search_replace?: { old: new }, + sanitize?: boolean, + truncate_tables?: [string], + exclude_tables?: [string] + } + } + """ + user_id = get_jwt_identity() + data = request.get_json() or {} + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + source_env_id = data.get('source_env_id') + target_env_id = data.get('target_env_id') + promotion_type = data.get('type', 'code') + + if not source_env_id or not target_env_id: + return jsonify({'error': 'source_env_id and target_env_id are required'}), 400 + + if promotion_type not in ('code', 'database', 'full'): + return jsonify({'error': 'type must be code, database, or full'}), 400 + + # Verify ownership of both environments + source_site, error = _get_environment_site(source_env_id, user_id) + if error: + return error + + target_site, error = _get_environment_site(target_env_id, user_id) + if error: + return error + + # Verify both belong to this project (or are the production site itself) + for env_site, label in [(source_site, 'Source'), (target_site, 'Target')]: + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': f'{label} environment does not belong to this project'}), 400 + + config = data.get('config', {}) + + # Emit WebSocket event for operation start + _emit_pipeline_event(prod_id, 'promotion_started', { + 'source_env_id': source_env_id, + 'target_env_id': target_env_id, + 'type': promotion_type, + 'message': f'Promoting {promotion_type} from {source_site.environment_type} to {target_site.environment_type}...' + }) + + # Progress callback emits WebSocket events + def progress_callback(progress_data): + _emit_pipeline_event(prod_id, 'operation_progress', progress_data) + + # Run promotion (long-running operations run in the request thread) + if promotion_type == 'code': + result = EnvironmentPipelineService.promote_code( + source_env_id, target_env_id, config=config, user_id=user_id, + progress_callback=progress_callback + ) + elif promotion_type == 'database': + result = EnvironmentPipelineService.promote_database( + source_env_id, target_env_id, config=config, user_id=user_id, + progress_callback=progress_callback + ) + else: + result = EnvironmentPipelineService.promote_full( + source_env_id, target_env_id, config=config, user_id=user_id, + progress_callback=progress_callback + ) + + # Emit completion event + _emit_pipeline_event(prod_id, 'promotion_completed' if result.get('success') else 'promotion_failed', { + 'source_env_id': source_env_id, + 'target_env_id': target_env_id, + 'type': promotion_type, + 'success': result.get('success', False), + 'message': result.get('message') or result.get('error'), + }) + + if result.get('success'): + return jsonify(result) + else: + return jsonify(result), 500 + + +# ============================================================================= +# Sync from Production +# ============================================================================= + +@environment_pipeline_bp.route('//environments//sync', methods=['POST']) +@jwt_required() +@limiter.limit("5 per minute") +def sync_environment(prod_id, env_id): + """Pull from production into environment. + + Body: { + type: "database" | "files" | "full", + sanitize?: boolean, + search_replace?: { old: new }, + truncate_tables?: [string], + exclude_tables?: [string] + } + """ + user_id = get_jwt_identity() + data = request.get_json() or {} + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + sync_type = data.get('type', 'full') + if sync_type not in ('database', 'files', 'full'): + return jsonify({'error': 'type must be database, files, or full'}), 400 + + _emit_pipeline_event(prod_id, 'sync_started', { + 'env_id': env_id, + 'type': sync_type, + 'message': f'Syncing {sync_type} from production...' + }) + + def progress_callback(progress_data): + _emit_pipeline_event(prod_id, 'operation_progress', progress_data) + + result = EnvironmentPipelineService.sync_from_production( + env_site_id=env_id, + sync_type=sync_type, + options=data, + user_id=user_id, + progress_callback=progress_callback + ) + + _emit_pipeline_event(prod_id, 'sync_completed' if result.get('success') else 'sync_failed', { + 'env_id': env_id, + 'type': sync_type, + 'success': result.get('success', False), + 'message': result.get('message') or result.get('error'), + }) + + if result.get('success'): + return jsonify(result) + else: + return jsonify(result), 500 + + +# ============================================================================= +# Environment Comparison +# ============================================================================= + +@environment_pipeline_bp.route('//compare', methods=['GET']) +@jwt_required() +def compare_environments(prod_id): + """Compare two environments (plugins, themes, versions). + + Query: ?env_a=:id&env_b=:id + """ + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_a_id = request.args.get('env_a', type=int) + env_b_id = request.args.get('env_b', type=int) + + if not env_a_id or not env_b_id: + return jsonify({'error': 'env_a and env_b query parameters are required'}), 400 + + # Verify ownership + env_a, error = _get_environment_site(env_a_id, user_id) + if error: + return error + + env_b, error = _get_environment_site(env_b_id, user_id) + if error: + return error + + # Verify both belong to this project + for env_site, label in [(env_a, 'env_a'), (env_b, 'env_b')]: + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': f'{label} does not belong to this project'}), 400 + + result = EnvironmentPipelineService.compare_environments(env_a_id, env_b_id) + if result.get('success'): + return jsonify(result) + else: + return jsonify(result), 500 + + +# ============================================================================= +# Environment Locking +# ============================================================================= + +@environment_pipeline_bp.route('//environments//lock', methods=['POST']) +@jwt_required() +def lock_environment(prod_id, env_id): + """Lock an environment. + + Body: { + reason: string, + duration_minutes?: int (default 30) + } + """ + user_id = get_jwt_identity() + data = request.get_json() or {} + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + reason = data.get('reason', 'Manually locked') + duration = data.get('duration_minutes', 30) + + result = EnvironmentPipelineService.lock_environment( + site_id=env_id, + reason=reason, + user_id=user_id, + duration_minutes=duration + ) + + if result.get('success'): + _emit_pipeline_event(prod_id, 'environment_locked', { + 'env_id': env_id, + 'reason': reason, + }) + return jsonify(result) + else: + return jsonify(result), 400 + + +@environment_pipeline_bp.route('//environments//lock', methods=['DELETE']) +@jwt_required() +def unlock_environment(prod_id, env_id): + """Unlock an environment.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + result = EnvironmentPipelineService.unlock_environment( + site_id=env_id, + user_id=user_id + ) + + if result.get('success'): + _emit_pipeline_event(prod_id, 'environment_unlocked', {'env_id': env_id}) + return jsonify(result) + else: + return jsonify(result), 400 + + +# ============================================================================= +# Activity Log +# ============================================================================= + +@environment_pipeline_bp.route('//activity', methods=['GET']) +@jwt_required() +def get_activity(prod_id): + """Activity log for all environments in project. + + Query: ?env_id=&action=&limit=50&offset=0 + """ + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + # Build query for all environments in this project + env_ids = [prod_id] + [e.id for e in site.environments] + + # Filter by specific environment if requested + filter_env_id = request.args.get('env_id', type=int) + if filter_env_id: + if filter_env_id not in env_ids: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + env_ids = [filter_env_id] + + query = EnvironmentActivity.query.filter( + EnvironmentActivity.site_id.in_(env_ids) + ) + + # Filter by action + action = request.args.get('action') + if action: + query = query.filter(EnvironmentActivity.action == action) + + # Pagination + limit = request.args.get('limit', 50, type=int) + offset = request.args.get('offset', 0, type=int) + + total = query.count() + activities = query.order_by( + EnvironmentActivity.created_at.desc() + ).offset(offset).limit(limit).all() + + return jsonify({ + 'activities': [a.to_dict() for a in activities], + 'total': total, + 'limit': limit, + 'offset': offset + }) + + +# ============================================================================= +# Container Logs +# ============================================================================= + +@environment_pipeline_bp.route('//environments//logs', methods=['GET']) +@jwt_required() +def get_container_logs(prod_id, env_id): + """Docker container logs for environment. + + Query: ?service=wordpress|mysql&lines=100 + """ + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + compose_path = EnvironmentPipelineService._get_compose_path(env_site) + if not compose_path: + return jsonify({'error': 'No Docker compose configuration found for this environment'}), 400 + + service = request.args.get('service', 'wordpress') + if service not in ('wordpress', 'db'): + return jsonify({'error': 'service must be wordpress or db'}), 400 + + lines = request.args.get('lines', 100, type=int) + lines = min(lines, 1000) # Cap at 1000 lines + + result = EnvironmentDockerService.get_container_logs(compose_path, service=service, lines=lines) + if result.get('success'): + return jsonify(result) + else: + return jsonify(result), 500 + + +# ============================================================================= +# Promotion History +# ============================================================================= + +@environment_pipeline_bp.route('//promotions', methods=['GET']) +@jwt_required() +def get_promotions(prod_id): + """Get promotion history for a project. + + Query: ?limit=20&offset=0&status= + """ + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_ids = [prod_id] + [e.id for e in site.environments] + + query = PromotionJob.query.filter( + (PromotionJob.source_site_id.in_(env_ids)) | + (PromotionJob.target_site_id.in_(env_ids)) + ) + + status = request.args.get('status') + if status: + query = query.filter(PromotionJob.status == status) + + limit = request.args.get('limit', 20, type=int) + offset = request.args.get('offset', 0, type=int) + + total = query.count() + promotions = query.order_by( + PromotionJob.created_at.desc() + ).offset(offset).limit(limit).all() + + return jsonify({ + 'promotions': [p.to_dict() for p in promotions], + 'total': total, + 'limit': limit, + 'offset': offset + }) + + +# ============================================================================= +# Environment Status (single environment detail) +# ============================================================================= + +@environment_pipeline_bp.route('//environments/', methods=['GET']) +@jwt_required() +def get_environment(prod_id, env_id): + """Get detailed status for a single environment.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + env_data = env_site.to_dict(include_snapshots=True) + + # Add container status + compose_path = EnvironmentPipelineService._get_compose_path(env_site) + if compose_path: + env_data['container_status'] = EnvironmentDockerService.get_environment_status(compose_path) + + # Add last promotion info + last_promotion = PromotionJob.query.filter( + (PromotionJob.source_site_id == env_id) | + (PromotionJob.target_site_id == env_id) + ).order_by(PromotionJob.created_at.desc()).first() + if last_promotion: + env_data['last_promotion'] = last_promotion.to_dict() + + # Add recent activity + recent_activities = EnvironmentActivity.query.filter_by( + site_id=env_id + ).order_by( + EnvironmentActivity.created_at.desc() + ).limit(10).all() + env_data['recent_activity'] = [a.to_dict() for a in recent_activities] + + return jsonify(env_data) + + +# ============================================================================= +# Git Branches +# ============================================================================= + +@environment_pipeline_bp.route('//git/branches', methods=['GET']) +@jwt_required() +def list_branches(prod_id): + """List available git branches for multidev creation. + + Returns remote branches with latest commit info and whether + a multidev environment already exists for each branch. + """ + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + result = GitWordPressService.list_branches(prod_id) + if result.get('success'): + return jsonify(result) + else: + return jsonify(result), 400 + + +# ============================================================================= +# Multidev Cleanup +# ============================================================================= + +@environment_pipeline_bp.route('//multidev/cleanup', methods=['POST']) +@jwt_required() +def cleanup_multidevs(prod_id): + """Check for multidev environments with merged/deleted branches and clean them up. + + Body: { + dry_run?: boolean (default true - only report, don't delete) + } + """ + user_id = get_jwt_identity() + data = request.get_json() or {} + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + dry_run = data.get('dry_run', True) + + result = EnvironmentPipelineService.cleanup_stale_multidevs( + production_site_id=prod_id, + dry_run=dry_run, + user_id=user_id + ) + + if result.get('success'): + return jsonify(result) + else: + return jsonify(result), 500 + + +# ============================================================================= +# Sanitization Profiles +# ============================================================================= + +@environment_pipeline_bp.route('/sanitization-profiles', methods=['GET']) +@jwt_required() +def list_sanitization_profiles(): + """List all sanitization profiles for the current user. + + Automatically seeds built-in profiles on first access. + """ + user_id = get_jwt_identity() + + # Seed built-in profiles if none exist + existing = SanitizationProfile.query.filter_by(user_id=user_id).count() + if existing == 0: + SanitizationProfile.seed_builtins(user_id) + + profiles = SanitizationProfile.query.filter_by( + user_id=user_id + ).order_by( + SanitizationProfile.is_builtin.desc(), + SanitizationProfile.is_default.desc(), + SanitizationProfile.name + ).all() + + return jsonify({ + 'profiles': [p.to_dict() for p in profiles], + 'total': len(profiles) + }) + + +@environment_pipeline_bp.route('/sanitization-profiles', methods=['POST']) +@jwt_required() +def create_sanitization_profile(): + """Create a new sanitization profile. + + Body: { + name: string, + description?: string, + config: { ... }, + is_default?: boolean + } + """ + user_id = get_jwt_identity() + data = request.get_json() or {} + + name = data.get('name', '').strip() + if not name: + return jsonify({'error': 'Profile name is required'}), 400 + + if len(name) > 100: + return jsonify({'error': 'Profile name must be 100 characters or less'}), 400 + + config = data.get('config', {}) + if not isinstance(config, dict): + return jsonify({'error': 'Config must be a JSON object'}), 400 + + # If setting as default, unset any existing default + is_default = data.get('is_default', False) + if is_default: + SanitizationProfile.query.filter_by( + user_id=user_id, is_default=True + ).update({'is_default': False}) + + import json + profile = SanitizationProfile( + user_id=user_id, + name=name, + description=data.get('description', ''), + config=json.dumps(config), + is_default=is_default, + is_builtin=False, + ) + db.session.add(profile) + db.session.commit() + + return jsonify({ + 'success': True, + 'profile': profile.to_dict() + }), 201 + + +@environment_pipeline_bp.route('/sanitization-profiles/', methods=['PUT']) +@jwt_required() +def update_sanitization_profile(profile_id): + """Update a sanitization profile. + + Body: { + name?: string, + description?: string, + config?: { ... }, + is_default?: boolean + } + """ + user_id = get_jwt_identity() + data = request.get_json() or {} + + profile = SanitizationProfile.query.filter_by( + id=profile_id, user_id=user_id + ).first() + + if not profile: + return jsonify({'error': 'Profile not found'}), 404 + + if 'name' in data: + name = data['name'].strip() + if not name: + return jsonify({'error': 'Profile name is required'}), 400 + if len(name) > 100: + return jsonify({'error': 'Profile name must be 100 characters or less'}), 400 + profile.name = name + + if 'description' in data: + profile.description = data['description'] + + if 'config' in data: + if not isinstance(data['config'], dict): + return jsonify({'error': 'Config must be a JSON object'}), 400 + import json + profile.config = json.dumps(data['config']) + + if 'is_default' in data: + if data['is_default']: + SanitizationProfile.query.filter_by( + user_id=user_id, is_default=True + ).update({'is_default': False}) + profile.is_default = data['is_default'] + + db.session.commit() + + return jsonify({ + 'success': True, + 'profile': profile.to_dict() + }) + + +@environment_pipeline_bp.route('/sanitization-profiles/', methods=['DELETE']) +@jwt_required() +def delete_sanitization_profile(profile_id): + """Delete a sanitization profile. Built-in profiles cannot be deleted.""" + user_id = get_jwt_identity() + + profile = SanitizationProfile.query.filter_by( + id=profile_id, user_id=user_id + ).first() + + if not profile: + return jsonify({'error': 'Profile not found'}), 404 + + if profile.is_builtin: + return jsonify({'error': 'Built-in profiles cannot be deleted'}), 400 + + db.session.delete(profile) + db.session.commit() + + return jsonify({ + 'success': True, + 'message': f'Profile "{profile.name}" deleted' + }) + + +# ============================================================================= +# Resource Limits +# ============================================================================= + +@environment_pipeline_bp.route('//environments//resources', methods=['PUT']) +@jwt_required() +def update_resource_limits(prod_id, env_id): + """Update memory/CPU limits for an environment, restart containers. + + Body: { + memory: "512M", + cpus: "1.0", + db_memory: "384M", + db_cpus: "0.5" + } + """ + user_id = get_jwt_identity() + data = request.get_json() or {} + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + compose_path = EnvironmentPipelineService._get_compose_path(env_site) + if not compose_path: + return jsonify({'error': 'No Docker compose configuration found'}), 400 + + import json as json_lib + result = EnvironmentDockerService.update_resource_limits(compose_path, data) + + if result.get('success'): + env_site.resource_limits = json_lib.dumps(data) + db.session.commit() + _emit_pipeline_event(prod_id, 'environment_restarted', {'env_id': env_id, 'reason': 'resource_limits_updated'}) + return jsonify({'success': True, 'message': 'Resource limits updated, containers restarted', 'limits': data}) + else: + return jsonify(result), 500 + + +# ============================================================================= +# Basic Auth +# ============================================================================= + +@environment_pipeline_bp.route('//environments//auth', methods=['POST']) +@jwt_required() +def enable_basic_auth(prod_id, env_id): + """Enable Basic Auth for an environment. Returns generated credentials. + + Body: { username?: string } (password is auto-generated) + """ + user_id = get_jwt_identity() + data = request.get_json() or {} + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + from app.services.environment_domain_service import EnvironmentDomainService + import secrets + import string + + username = data.get('username', 'admin') + password = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(16)) + + # Determine site_name for Nginx config + site_name = f'wp-{env_site.container_prefix}' if env_site.container_prefix else None + if not site_name: + return jsonify({'error': 'Cannot determine Nginx config name'}), 400 + + result = EnvironmentDomainService.enable_basic_auth(site_name, username, password) + + if result.get('success'): + env_site.basic_auth_enabled = True + env_site.basic_auth_user = username + env_site.basic_auth_password_hash = result.get('password_hash', '') + db.session.commit() + + return jsonify({ + 'success': True, + 'enabled': True, + 'username': username, + 'password': password, + 'message': 'Basic Auth enabled. Save these credentials - password will not be shown again.' + }) + else: + return jsonify(result), 500 + + +@environment_pipeline_bp.route('//environments//auth', methods=['DELETE']) +@jwt_required() +def disable_basic_auth(prod_id, env_id): + """Disable Basic Auth for an environment.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + from app.services.environment_domain_service import EnvironmentDomainService + + site_name = f'wp-{env_site.container_prefix}' if env_site.container_prefix else None + if not site_name: + return jsonify({'error': 'Cannot determine Nginx config name'}), 400 + + result = EnvironmentDomainService.disable_basic_auth(site_name) + + if result.get('success'): + env_site.basic_auth_enabled = False + env_site.basic_auth_user = None + env_site.basic_auth_password_hash = None + db.session.commit() + return jsonify({'success': True, 'enabled': False, 'message': 'Basic Auth disabled'}) + else: + return jsonify(result), 500 + + +@environment_pipeline_bp.route('//environments//auth', methods=['GET']) +@jwt_required() +def get_basic_auth_status(prod_id, env_id): + """Get Basic Auth status for an environment.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + return jsonify({ + 'enabled': env_site.basic_auth_enabled or False, + 'username': env_site.basic_auth_user if env_site.basic_auth_enabled else None, + }) + + +# ============================================================================= +# WP-CLI Execution +# ============================================================================= + +@environment_pipeline_bp.route('//environments//exec', methods=['POST']) +@jwt_required() +@limiter.limit("30 per minute") +def execute_wp_cli(prod_id, env_id): + """Execute a WP-CLI command in an environment container. + + Body: { command: "wp plugin list --format=table" } + """ + user_id = get_jwt_identity() + data = request.get_json() or {} + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + command = data.get('command', '').strip() + if not command: + return jsonify({'error': 'command is required'}), 400 + + # Ensure command starts with 'wp' + if not command.startswith('wp '): + command = f'wp {command}' + + # Add --allow-root flag if not present + if '--allow-root' not in command: + command += ' --allow-root' + + compose_path = EnvironmentPipelineService._get_compose_path(env_site) + if not compose_path: + return jsonify({'error': 'No Docker compose configuration found'}), 400 + + result = EnvironmentDockerService.exec_in_container(compose_path, 'wordpress', command) + + return jsonify({ + 'success': result.get('success', False), + 'output': result.get('output', ''), + 'error': result.get('error', ''), + 'command': command, + }) + + +# ============================================================================= +# Health Checks +# ============================================================================= + +@environment_pipeline_bp.route('//environments//health', methods=['GET']) +@jwt_required() +def get_environment_health(prod_id, env_id): + """Run and return health check results for an environment.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + from app.services.environment_health_service import EnvironmentHealthService + result = EnvironmentHealthService.check_health(env_id) + + if result.get('success'): + return jsonify(result) + else: + return jsonify(result), 500 + + +@environment_pipeline_bp.route('//health', methods=['GET']) +@jwt_required() +def get_project_health(prod_id): + """Health summary for all project environments.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + from app.services.environment_health_service import EnvironmentHealthService + result = EnvironmentHealthService.check_all_project_health(prod_id) + + if result.get('success'): + return jsonify(result) + else: + return jsonify(result), 500 + + +# ============================================================================= +# Disk Usage +# ============================================================================= + +@environment_pipeline_bp.route('//environments//disk-usage', methods=['GET']) +@jwt_required() +def get_environment_disk_usage(prod_id, env_id): + """Return disk usage breakdown for an environment.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + from app.services.environment_health_service import EnvironmentHealthService + result = EnvironmentHealthService.get_disk_usage(env_id) + + if result.get('success'): + return jsonify(result) + else: + return jsonify(result), 500 + + +@environment_pipeline_bp.route('//disk-usage', methods=['GET']) +@jwt_required() +def get_project_disk_usage(prod_id): + """Disk usage for all project environments.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + from app.services.environment_health_service import EnvironmentHealthService + result = EnvironmentHealthService.get_disk_usage_for_project(prod_id) + + if result.get('success'): + return jsonify(result) + else: + return jsonify(result), 500 + + +# ============================================================================= +# Bulk Operations +# ============================================================================= + +@environment_pipeline_bp.route('//bulk', methods=['POST']) +@jwt_required() +@limiter.limit("5 per minute") +def bulk_operations(prod_id): + """Execute bulk operations on multiple environments. + + Body: { + operations: [ + { action: "stop"|"start"|"restart"|"sync", env_ids: [1, 2, 3] } + ] + } + """ + user_id = get_jwt_identity() + data = request.get_json() or {} + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + operations = data.get('operations', []) + if not operations: + return jsonify({'error': 'operations array is required'}), 400 + + results = [] + env_ids_in_project = {prod_id} | {e.id for e in site.environments} + + for op in operations: + action = op.get('action') + env_ids = op.get('env_ids', []) + + if action not in ('stop', 'start', 'restart', 'sync'): + results.append({'action': action, 'error': 'Invalid action'}) + continue + + op_results = [] + for env_id in env_ids: + if env_id not in env_ids_in_project: + op_results.append({'env_id': env_id, 'success': False, 'error': 'Not in this project'}) + continue + + env_site = WordPressSite.query.get(env_id) + if not env_site: + op_results.append({'env_id': env_id, 'success': False, 'error': 'Not found'}) + continue + + compose_path = EnvironmentPipelineService._get_compose_path(env_site) + if not compose_path: + op_results.append({'env_id': env_id, 'success': False, 'error': 'No compose config'}) + continue + + if action == 'stop': + result = EnvironmentDockerService.stop_environment(compose_path) + if result.get('success') and env_site.application: + env_site.application.status = 'stopped' + elif action == 'start': + result = EnvironmentDockerService.start_environment(compose_path) + if result.get('success') and env_site.application: + env_site.application.status = 'running' + elif action == 'restart': + result = EnvironmentDockerService.restart_environment(compose_path) + if result.get('success') and env_site.application: + env_site.application.status = 'running' + elif action == 'sync': + result = EnvironmentPipelineService.sync_from_production( + env_site_id=env_id, sync_type='full', user_id=user_id + ) + + op_results.append({ + 'env_id': env_id, + 'success': result.get('success', False), + 'message': result.get('message') or result.get('error'), + }) + + results.append({'action': action, 'results': op_results}) + + db.session.commit() + + _emit_pipeline_event(prod_id, 'bulk_operation_completed', { + 'operations': [op.get('action') for op in operations], + }) + + return jsonify({'success': True, 'results': results}) + + +# ============================================================================= +# Auto-Sync Schedule +# ============================================================================= + +@environment_pipeline_bp.route('//environments//auto-sync', methods=['PUT']) +@jwt_required() +def update_auto_sync_schedule(prod_id, env_id): + """Set/update auto-sync schedule for an environment. + + Body: { + enabled: true, + schedule: "0 3 * * *" + } + """ + user_id = get_jwt_identity() + data = request.get_json() or {} + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + if env_site.is_production or env_site.environment_type == 'production': + return jsonify({'error': 'Cannot set auto-sync on production environment'}), 400 + + enabled = data.get('enabled', False) + schedule = data.get('schedule', '') + + if enabled and not schedule: + return jsonify({'error': 'schedule is required when enabled is true'}), 400 + + # Validate cron expression + if enabled and schedule: + try: + from croniter import croniter + if not croniter.is_valid(schedule): + return jsonify({'error': 'Invalid cron expression'}), 400 + except ImportError: + # If croniter is not installed, do basic validation + parts = schedule.split() + if len(parts) != 5: + return jsonify({'error': 'Invalid cron expression (must have 5 fields)'}), 400 + + env_site.auto_sync_enabled = enabled + env_site.auto_sync_schedule = schedule if enabled else None + db.session.commit() + + return jsonify({ + 'success': True, + 'enabled': enabled, + 'schedule': schedule if enabled else None, + 'message': f'Auto-sync {"enabled" if enabled else "disabled"}', + }) + + +@environment_pipeline_bp.route('//environments//auto-sync', methods=['GET']) +@jwt_required() +def get_auto_sync_schedule(prod_id, env_id): + """Get current auto-sync schedule for an environment.""" + user_id = get_jwt_identity() + + site, error = _get_production_site(prod_id, user_id) + if error: + return error + + env_site, error = _get_environment_site(env_id, user_id) + if error: + return error + + if env_site.id != prod_id and env_site.production_site_id != prod_id: + return jsonify({'error': 'Environment does not belong to this project'}), 400 + + result = { + 'enabled': env_site.auto_sync_enabled or False, + 'schedule': env_site.auto_sync_schedule, + } + + # Calculate next run times if enabled + if env_site.auto_sync_enabled and env_site.auto_sync_schedule: + try: + from croniter import croniter + from datetime import datetime + cron = croniter(env_site.auto_sync_schedule, datetime.utcnow()) + result['next_runs'] = [ + cron.get_next(datetime).isoformat() for _ in range(3) + ] + except ImportError: + result['next_runs'] = [] + + return jsonify(result) + + +# ============================================================================= +# WebSocket Helper +# ============================================================================= + +def _emit_pipeline_event(prod_id, event_type, data): + """Emit a WebSocket event for pipeline operations. + + Events are broadcast to the room 'pipeline_{prod_id}'. + """ + try: + from app import get_socketio + sio = get_socketio() + if sio: + import time + sio.emit('pipeline_event', { + 'project_id': prod_id, + 'event': event_type, + 'data': data, + 'timestamp': time.time() + }, room=f'pipeline_{prod_id}') + except Exception: + pass # WebSocket emit is best-effort, don't fail the request diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index b01c83c0..c1340a4d 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -12,11 +12,15 @@ from app.models.webhook import GitWebhook, WebhookLog, GitDeployment from app.models.server import Server, ServerGroup, ServerMetrics, ServerCommand, AgentSession from app.models.security_alert import SecurityAlert from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob +from app.models.environment_activity import EnvironmentActivity +from app.models.promotion_job import PromotionJob +from app.models.sanitization_profile import SanitizationProfile __all__ = [ 'User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory', 'NotificationPreferences', 'Deployment', 'DeploymentDiff', 'SystemSettings', 'AuditLog', 'MetricsHistory', 'Workflow', 'GitWebhook', 'WebhookLog', 'GitDeployment', 'Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'SecurityAlert', - 'WordPressSite', 'DatabaseSnapshot', 'SyncJob' + 'WordPressSite', 'DatabaseSnapshot', 'SyncJob', + 'EnvironmentActivity', 'PromotionJob', 'SanitizationProfile' ] diff --git a/backend/app/models/environment_activity.py b/backend/app/models/environment_activity.py new file mode 100644 index 00000000..c78437fb --- /dev/null +++ b/backend/app/models/environment_activity.py @@ -0,0 +1,54 @@ +""" +Environment Activity Model + +Audit log for all environment actions (create, deploy, promote, lock, etc.). +Tracks who did what, when, and how long it took. +""" + +from datetime import datetime +from app import db +import json + + +class EnvironmentActivity(db.Model): + """Audit log for environment actions.""" + + __tablename__ = 'environment_activities' + + id = db.Column(db.Integer, primary_key=True) + site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=False) + user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True) + + # Action details + action = db.Column(db.String(50), nullable=False) # create, deploy, promote, lock, unlock, destroy + description = db.Column(db.Text) + activity_metadata = db.Column('metadata', db.Text) # JSON + + # Result + status = db.Column(db.String(20), default='completed') # pending, running, completed, failed + error_message = db.Column(db.Text) + duration_seconds = db.Column(db.Float) + + # Timestamps + created_at = db.Column(db.DateTime, default=datetime.utcnow) + + # Relationships + site = db.relationship('WordPressSite', backref=db.backref('activities', lazy='dynamic')) + user = db.relationship('User', backref=db.backref('environment_activities', lazy='dynamic')) + + def to_dict(self): + return { + 'id': self.id, + 'site_id': self.site_id, + 'user_id': self.user_id, + 'action': self.action, + 'description': self.description, + 'metadata': json.loads(self.activity_metadata) if self.activity_metadata else None, + 'status': self.status, + 'error_message': self.error_message, + 'duration_seconds': self.duration_seconds, + 'created_at': self.created_at.isoformat() if self.created_at else None, + } + + def __repr__(self): + return f'' diff --git a/backend/app/models/metrics_history.py b/backend/app/models/metrics_history.py index b5dd9872..a96d7282 100644 --- a/backend/app/models/metrics_history.py +++ b/backend/app/models/metrics_history.py @@ -51,7 +51,7 @@ class MetricsHistory(db.Model): def to_dict(self): """Convert to dictionary for API response.""" return { - 'timestamp': self.timestamp.isoformat(), + 'timestamp': self.timestamp.isoformat() + 'Z', 'level': self.level, 'cpu': { 'percent': round(self.cpu_percent, 1), diff --git a/backend/app/models/promotion_job.py b/backend/app/models/promotion_job.py new file mode 100644 index 00000000..160d2fdb --- /dev/null +++ b/backend/app/models/promotion_job.py @@ -0,0 +1,70 @@ +""" +Promotion Job Model + +Tracks code/data promotions between WordPress environments +(e.g., staging -> production, dev -> staging). +""" + +from datetime import datetime +from app import db +import json + + +class PromotionJob(db.Model): + """Track code/data promotions between environments.""" + + __tablename__ = 'promotion_jobs' + + id = db.Column(db.Integer, primary_key=True) + + # Source and target sites + source_site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=False) + target_site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=False) + user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True) + + # Promotion details + promotion_type = db.Column(db.String(20), nullable=False) # code, database, files, full + config = db.Column(db.Text) # JSON: search_replace, exclude_tables, etc. + + # Status tracking + status = db.Column(db.String(20), default='pending') # pending, running, completed, failed, rolled_back + pre_promotion_snapshot_id = db.Column(db.Integer, db.ForeignKey('database_snapshots.id'), nullable=True) + error_message = db.Column(db.Text) + + # Timing + started_at = db.Column(db.DateTime) + completed_at = db.Column(db.DateTime) + duration_seconds = db.Column(db.Float) + + # Timestamps + created_at = db.Column(db.DateTime, default=datetime.utcnow) + + # Relationships + source_site = db.relationship('WordPressSite', foreign_keys=[source_site_id], + backref=db.backref('promotions_as_source', lazy='dynamic')) + target_site = db.relationship('WordPressSite', foreign_keys=[target_site_id], + backref=db.backref('promotions_as_target', lazy='dynamic')) + user = db.relationship('User', backref=db.backref('promotion_jobs', lazy='dynamic')) + pre_promotion_snapshot = db.relationship('DatabaseSnapshot', foreign_keys=[pre_promotion_snapshot_id]) + + def to_dict(self): + return { + 'id': self.id, + 'source_site_id': self.source_site_id, + 'target_site_id': self.target_site_id, + 'user_id': self.user_id, + 'promotion_type': self.promotion_type, + 'config': json.loads(self.config) if self.config else None, + 'status': self.status, + 'pre_promotion_snapshot_id': self.pre_promotion_snapshot_id, + 'error_message': self.error_message, + 'started_at': self.started_at.isoformat() if self.started_at else None, + 'completed_at': self.completed_at.isoformat() if self.completed_at else None, + 'duration_seconds': self.duration_seconds, + 'created_at': self.created_at.isoformat() if self.created_at else None, + 'source_site': self.source_site.to_dict() if self.source_site else None, + 'target_site': self.target_site.to_dict() if self.target_site else None, + } + + def __repr__(self): + return f'{self.target_site_id}>' diff --git a/backend/app/models/sanitization_profile.py b/backend/app/models/sanitization_profile.py new file mode 100644 index 00000000..aa89e109 --- /dev/null +++ b/backend/app/models/sanitization_profile.py @@ -0,0 +1,167 @@ +""" +Sanitization Profile Model + +Reusable database sanitization presets for WordPress environment sync/promote operations. +Profiles define which data to anonymize, truncate, or strip when copying databases +between environments. +""" + +from datetime import datetime +from app import db +import json + + +class SanitizationProfile(db.Model): + """Reusable database sanitization preset.""" + + __tablename__ = 'sanitization_profiles' + + id = db.Column(db.Integer, primary_key=True) + user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) + name = db.Column(db.String(100), nullable=False) + description = db.Column(db.Text) + + # JSON config with sanitization rules + config = db.Column(db.Text, nullable=False) + # Expected structure: + # { + # "anonymize_emails": true, + # "anonymize_names": true, + # "reset_passwords": true, + # "truncate_tables": ["wp_actionscheduler_actions", "wp_actionscheduler_logs"], + # "exclude_tables": [], + # "strip_payment_data": false, + # "remove_transients": true, + # "custom_search_replace": {} + # } + + is_default = db.Column(db.Boolean, default=False) + is_builtin = db.Column(db.Boolean, default=False) + + created_at = db.Column(db.DateTime, default=datetime.utcnow) + updated_at = db.Column(db.DateTime, onupdate=datetime.utcnow) + + # Relationships + user = db.relationship('User', backref=db.backref('sanitization_profiles', lazy='dynamic')) + + def get_config(self): + """Parse and return the config dict.""" + try: + return json.loads(self.config) if self.config else {} + except (json.JSONDecodeError, TypeError): + return {} + + def set_config(self, config_dict): + """Set config from a dict.""" + self.config = json.dumps(config_dict) + + def to_dict(self): + return { + 'id': self.id, + 'user_id': self.user_id, + 'name': self.name, + 'description': self.description, + 'config': self.get_config(), + 'is_default': self.is_default, + 'is_builtin': self.is_builtin, + 'created_at': self.created_at.isoformat() if self.created_at else None, + 'updated_at': self.updated_at.isoformat() if self.updated_at else None, + } + + def __repr__(self): + return f'' + + # ==================== BUILT-IN PROFILES ==================== + + BUILTIN_PROFILES = [ + { + 'name': 'Basic', + 'description': 'Anonymize email addresses and reset user passwords. Suitable for most development environments.', + 'config': { + 'anonymize_emails': True, + 'anonymize_names': False, + 'reset_passwords': True, + 'truncate_tables': [ + 'actionscheduler_actions', + 'actionscheduler_logs', + ], + 'exclude_tables': [], + 'strip_payment_data': False, + 'remove_transients': True, + 'custom_search_replace': {}, + } + }, + { + 'name': 'Full', + 'description': 'Full sanitization: anonymize emails, names, reset passwords, and clear analytics/session data.', + 'config': { + 'anonymize_emails': True, + 'anonymize_names': True, + 'reset_passwords': True, + 'truncate_tables': [ + 'actionscheduler_actions', + 'actionscheduler_logs', + 'statistics_visits', + 'statistics_pages', + 'slim_stats', + 'redirection_logs', + 'redirection_404', + ], + 'exclude_tables': [], + 'strip_payment_data': False, + 'remove_transients': True, + 'custom_search_replace': {}, + } + }, + { + 'name': 'WooCommerce', + 'description': 'Strip WooCommerce order/payment data, anonymize customers, and clear session data.', + 'config': { + 'anonymize_emails': True, + 'anonymize_names': True, + 'reset_passwords': True, + 'truncate_tables': [ + 'actionscheduler_actions', + 'actionscheduler_logs', + 'wc_orders', + 'wc_order_addresses', + 'wc_order_operational_data', + 'wc_order_stats', + 'woocommerce_sessions', + 'woocommerce_log', + ], + 'exclude_tables': [], + 'strip_payment_data': True, + 'remove_transients': True, + 'custom_search_replace': {}, + } + }, + ] + + @classmethod + def seed_builtins(cls, user_id): + """Create built-in profiles for a user if they don't exist.""" + created = [] + for profile_data in cls.BUILTIN_PROFILES: + existing = cls.query.filter_by( + user_id=user_id, + name=profile_data['name'], + is_builtin=True + ).first() + + if not existing: + profile = cls( + user_id=user_id, + name=profile_data['name'], + description=profile_data['description'], + config=json.dumps(profile_data['config']), + is_builtin=True, + is_default=(profile_data['name'] == 'Basic'), + ) + db.session.add(profile) + created.append(profile_data['name']) + + if created: + db.session.commit() + + return created diff --git a/backend/app/models/wordpress_site.py b/backend/app/models/wordpress_site.py index af9b886e..ada77465 100644 --- a/backend/app/models/wordpress_site.py +++ b/backend/app/models/wordpress_site.py @@ -47,6 +47,38 @@ class WordPressSite(db.Model): # Sync settings (JSON) sync_config = db.Column(db.Text) # schedule, search_replace, anonymize, etc. + # Environment management + environment_type = db.Column(db.String(20), default='standalone') # standalone, production, staging, development, multidev + multidev_branch = db.Column(db.String(200)) + is_locked = db.Column(db.Boolean, default=False) + locked_by = db.Column(db.String(100)) + locked_reason = db.Column(db.String(200)) + lock_expires_at = db.Column(db.DateTime) + + # Docker compose tracking + compose_project_name = db.Column(db.String(100)) + container_prefix = db.Column(db.String(100)) + + # Resource limits (stored as JSON for flexibility) + resource_limits = db.Column(db.Text) # JSON: {memory, cpus, db_memory, db_cpus} + + # Basic Auth + basic_auth_enabled = db.Column(db.Boolean, default=False) + basic_auth_user = db.Column(db.String(100)) + basic_auth_password_hash = db.Column(db.String(200)) + + # Health tracking + health_status = db.Column(db.String(20), default='unknown') # healthy, degraded, unhealthy, unknown + last_health_check = db.Column(db.DateTime) + + # Disk usage tracking + disk_usage_bytes = db.Column(db.BigInteger, default=0) + disk_usage_updated_at = db.Column(db.DateTime) + + # Auto-sync + auto_sync_schedule = db.Column(db.String(100)) # cron expression + auto_sync_enabled = db.Column(db.Boolean, default=False) + # Timestamps created_at = db.Column(db.DateTime, default=datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) @@ -93,6 +125,24 @@ class WordPressSite(db.Model): 'is_production': self.is_production, 'production_site_id': self.production_site_id, 'sync_config': json.loads(self.sync_config) if self.sync_config else None, + 'environment_type': self.environment_type, + 'multidev_branch': self.multidev_branch, + 'is_locked': self.is_locked, + 'locked_by': self.locked_by, + 'locked_reason': self.locked_reason, + 'lock_expires_at': self.lock_expires_at.isoformat() if self.lock_expires_at else None, + 'compose_project_name': self.compose_project_name, + 'container_prefix': self.container_prefix, + 'resource_limits': json.loads(self.resource_limits) if self.resource_limits else None, + 'basic_auth_enabled': self.basic_auth_enabled, + 'basic_auth_user': self.basic_auth_user, + 'health_status': self.health_status, + 'last_health_check': self.last_health_check.isoformat() if self.last_health_check else None, + 'disk_usage_bytes': self.disk_usage_bytes, + '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, + '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, 'updated_at': self.updated_at.isoformat() if self.updated_at else None, } diff --git a/backend/app/services/db_sync_service.py b/backend/app/services/db_sync_service.py index 8c188547..02231fad 100644 --- a/backend/app/services/db_sync_service.py +++ b/backend/app/services/db_sync_service.py @@ -355,6 +355,8 @@ class DatabaseSyncService: search_replace = options.get('search_replace', {}) new_prefix = options.get('table_prefix') anonymize = options.get('anonymize', False) + anonymize_names = options.get('anonymize_names', False) + reset_passwords = options.get('reset_passwords', False) truncate_tables = options.get('truncate_tables', []) try: @@ -394,9 +396,15 @@ class DatabaseSyncService: for search, replace in search_replace.items(): line = cls._safe_search_replace(line, search, replace) - # Anonymize user data - if anonymize and 'user_email' in line.lower(): - line = cls._anonymize_line(line) + # Anonymize user data (enhanced with name and password support) + if anonymize and ('user_email' in line.lower() or 'user_pass' in line.lower() + or 'display_name' in line.lower() or 'first_name' in line.lower() + or 'last_name' in line.lower() or 'nickname' in line.lower()): + line = cls._anonymize_line( + line, + anonymize_names=anonymize_names, + reset_passwords=reset_passwords + ) outfile.write(line) @@ -436,16 +444,85 @@ class DatabaseSyncService: return text @classmethod - def _anonymize_line(cls, line: str) -> str: - """Anonymize user data in a SQL line.""" + def _anonymize_line(cls, line: str, anonymize_names: bool = False, + reset_passwords: bool = False) -> str: + """Anonymize user data in a SQL line. + + Args: + line: SQL line to anonymize + anonymize_names: Also anonymize display_name, first_name, last_name + reset_passwords: Replace password hashes with a known hash + """ # Replace email addresses line = re.sub( r"'([^']+@[^']+)'", lambda m: f"'user{hash(m.group(1)) % 10000}@example.com'", line ) + + # Anonymize display names in user meta + if anonymize_names and ('display_name' in line.lower() or 'first_name' in line.lower() + or 'last_name' in line.lower() or 'nickname' in line.lower()): + line = re.sub( + r"('(?:first_name|last_name|nickname|display_name)'\s*,\s*')([^']+)(')", + lambda m: f"{m.group(1)}User {hash(m.group(2)) % 10000}{m.group(3)}", + line + ) + + # Reset passwords to a known hash (password: 'changeme') + if reset_passwords and 'user_pass' in line.lower(): + line = re.sub( + r"\$P\$[A-Za-z0-9./]{31}", + "$P$BchangemeHASHEDplaceholder00000", + line + ) + return line + @classmethod + def apply_sanitization_profile(cls, profile_config: dict) -> dict: + """Convert a sanitization profile config into db clone/sync options. + + Args: + profile_config: Dict from SanitizationProfile.get_config() + + Returns: + Dict of options suitable for clone_database/clone_between_containers + """ + options = {} + + if profile_config.get('anonymize_emails') or profile_config.get('anonymize_names'): + options['anonymize'] = True + options['anonymize_names'] = profile_config.get('anonymize_names', False) + options['reset_passwords'] = profile_config.get('reset_passwords', False) + + if profile_config.get('truncate_tables'): + options['truncate_tables'] = list(profile_config['truncate_tables']) + + if profile_config.get('exclude_tables'): + options['exclude_tables'] = list(profile_config['exclude_tables']) + + if profile_config.get('custom_search_replace'): + options['search_replace'] = dict(profile_config['custom_search_replace']) + + # WooCommerce payment data stripping - add payment tables to truncate list + if profile_config.get('strip_payment_data'): + wc_payment_tables = [ + 'wc_order_payment_lookup', + 'woocommerce_payment_tokens', + 'woocommerce_payment_tokenmeta', + ] + existing_truncate = options.get('truncate_tables', []) + for table in wc_payment_tables: + if table not in existing_truncate: + existing_truncate.append(table) + options['truncate_tables'] = existing_truncate + + if profile_config.get('remove_transients'): + options['remove_transients'] = True + + return options + @classmethod def run_search_replace(cls, db_name: str, search: str, replace: str, table_prefix: str = 'wp_', host: str = 'localhost', @@ -576,6 +653,260 @@ class DatabaseSyncService: except Exception: return [] + # ==================== CONTAINER-TO-CONTAINER OPERATIONS ==================== + + @classmethod + def export_from_container(cls, compose_path: str, db_name: str, + db_user: str = 'root', db_password: str = None, + output_path: str = None, compress: bool = True, + exclude_tables: List[str] = None) -> Dict: + """ + Export a database from a Docker container's MySQL instance. + + Uses docker compose exec to run mysqldump inside the container. + + Args: + compose_path: Path to the environment's docker-compose.yml + db_name: Database name to export + db_user: MySQL user + db_password: MySQL password + output_path: Where to save the dump (auto-generated if None) + compress: Whether to gzip the output + exclude_tables: Tables to exclude from the dump + + Returns: + Dict with success status, file_path, and size_bytes + """ + cls._ensure_dirs() + + if not os.path.exists(compose_path): + return {'success': False, 'error': f'Compose file not found: {compose_path}'} + + timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') + if not output_path: + output_path = os.path.join(cls.SNAPSHOT_DIR, f'{db_name}_{timestamp}.sql') + if compress: + output_path += '.gz' + + try: + # Build mysqldump command to run inside container + dump_cmd = ['mysqldump', '-u', db_user] + if db_password: + dump_cmd.append(f'-p{db_password}') + dump_cmd.extend([ + '--single-transaction', + '--routines', + '--triggers', + '--add-drop-table', + ]) + + if exclude_tables: + for table in exclude_tables: + dump_cmd.extend(['--ignore-table', f'{db_name}.{table}']) + + dump_cmd.append(db_name) + + # Run via docker compose exec + full_cmd = ['docker', 'compose', '-f', compose_path, 'exec', '-T', 'db'] + dump_cmd + + if compress: + process = subprocess.Popen( + full_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE + ) + with gzip.open(output_path, 'wb') as f: + while True: + chunk = process.stdout.read(8192) + if not chunk: + break + f.write(chunk) + process.wait() + if process.returncode != 0: + error = process.stderr.read().decode() + if os.path.exists(output_path): + os.remove(output_path) + return {'success': False, 'error': f'Container mysqldump failed: {error}'} + else: + with open(output_path, 'w') as f: + result = subprocess.run( + full_cmd, stdout=f, stderr=subprocess.PIPE, text=True, timeout=600 + ) + if result.returncode != 0: + if os.path.exists(output_path): + os.remove(output_path) + return {'success': False, 'error': f'Container mysqldump failed: {result.stderr}'} + + size_bytes = os.path.getsize(output_path) + return { + 'success': True, + 'file_path': output_path, + 'size_bytes': size_bytes, + 'compressed': compress, + 'db_name': db_name, + } + + except subprocess.TimeoutExpired: + if os.path.exists(output_path): + os.remove(output_path) + return {'success': False, 'error': 'Container mysqldump timed out'} + except Exception as e: + if os.path.exists(output_path): + os.remove(output_path) + return {'success': False, 'error': str(e)} + + @classmethod + def import_to_container(cls, compose_path: str, snapshot_path: str, + db_name: str, db_user: str = 'root', + db_password: str = None) -> Dict: + """ + Import a SQL dump into a Docker container's MySQL instance. + + Args: + compose_path: Path to the environment's docker-compose.yml + snapshot_path: Path to the .sql or .sql.gz file to import + db_name: Target database name + db_user: MySQL user + db_password: MySQL password + + Returns: + Dict with success status + """ + if not os.path.exists(compose_path): + return {'success': False, 'error': f'Compose file not found: {compose_path}'} + + if not os.path.exists(snapshot_path): + return {'success': False, 'error': f'Snapshot file not found: {snapshot_path}'} + + try: + # Build mysql import command + import_cmd = ['docker', 'compose', '-f', compose_path, 'exec', '-T', 'db', + 'mysql', '-u', db_user] + if db_password: + import_cmd.append(f'-p{db_password}') + import_cmd.append(db_name) + + if snapshot_path.endswith('.gz'): + with gzip.open(snapshot_path, 'rb') as f: + result = subprocess.run( + import_cmd, + stdin=f, + capture_output=True, + timeout=1800 + ) + else: + with open(snapshot_path, 'r') as f: + result = subprocess.run( + import_cmd, + stdin=f, + capture_output=True, + timeout=1800 + ) + + if result.returncode != 0: + error = result.stderr.decode() if isinstance(result.stderr, bytes) else result.stderr + return {'success': False, 'error': f'Container import failed: {error}'} + + return {'success': True, 'message': f'Imported {snapshot_path} into container DB {db_name}'} + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Container import timed out (>30 minutes)'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def clone_between_containers(cls, source_compose_path: str, target_compose_path: str, + source_db: str, target_db: str, + source_user: str = 'root', target_user: str = 'root', + source_password: str = None, target_password: str = None, + options: Dict = None) -> Dict: + """ + Clone a database from one Docker container to another with optional transformations. + + Exports from source container, optionally transforms the dump, + then imports into the target container. + + Args: + source_compose_path: Path to source environment's docker-compose.yml + target_compose_path: Path to target environment's docker-compose.yml + source_db: Source database name + target_db: Target database name + source_user/target_user: MySQL users + source_password/target_password: MySQL passwords + options: Transformation options (search_replace, table_prefix, + anonymize, truncate_tables, exclude_tables) + + Returns: + Dict with success status and clone info + """ + options = options or {} + cls._ensure_dirs() + + try: + # Step 1: Export from source container (uncompressed for transformation) + export_result = cls.export_from_container( + compose_path=source_compose_path, + db_name=source_db, + db_user=source_user, + db_password=source_password, + compress=False, + exclude_tables=options.get('exclude_tables', []) + ) + + if not export_result['success']: + return export_result + + dump_file = export_result['file_path'] + transformed_file = dump_file.replace('.sql', '_transformed.sql') + + try: + # Step 2: Transform the dump if needed + needs_transform = any([ + options.get('search_replace'), + options.get('table_prefix'), + options.get('anonymize'), + options.get('truncate_tables') + ]) + + if needs_transform: + transform_result = cls._transform_dump( + dump_file, + transformed_file, + options + ) + if not transform_result['success']: + return transform_result + import_file = transformed_file + else: + import_file = dump_file + + # Step 3: Import into target container + import_result = cls.import_to_container( + compose_path=target_compose_path, + snapshot_path=import_file, + db_name=target_db, + db_user=target_user, + db_password=target_password + ) + + if not import_result['success']: + return import_result + + return { + 'success': True, + 'message': f'Database cloned from container to container: {source_db} → {target_db}', + 'transformations_applied': list(options.keys()) if needs_transform else [] + } + + finally: + # Cleanup temp files + for f in [dump_file, transformed_file]: + if os.path.exists(f): + os.remove(f) + + except Exception as e: + return {'success': False, 'error': str(e)} + @classmethod def cleanup_old_snapshots(cls, days: int = 30, keep_tagged: bool = True) -> Dict: """ diff --git a/backend/app/services/environment_docker_service.py b/backend/app/services/environment_docker_service.py new file mode 100644 index 00000000..78dabbb3 --- /dev/null +++ b/backend/app/services/environment_docker_service.py @@ -0,0 +1,481 @@ +""" +Environment Docker Service + +Manages per-environment Docker Compose stacks for WordPress multidev. +Each environment (production, staging, dev, multidev branches) gets its own +isolated Docker Compose project with unique containers, networks, and volumes. +""" + +import os +import json +import shutil +import subprocess +from typing import Dict +from app.services.template_service import TemplateService + + +class EnvironmentDockerService: + """Service for managing per-environment Docker Compose stacks.""" + + APPS_DIR = '/var/serverkit/apps' + + # Docker Compose template for a WordPress environment + COMPOSE_TEMPLATE = """services: + wordpress: + image: wordpress:latest + container_name: {project}-{env_type}-wp + restart: unless-stopped + ports: + - "127.0.0.1:{wp_port}:80" + environment: + WORDPRESS_DB_HOST: {project}-{env_type}-db:3306 + WORDPRESS_DB_USER: ${{DB_USER}} + WORDPRESS_DB_PASSWORD: ${{DB_PASSWORD}} + WORDPRESS_DB_NAME: ${{DB_NAME}} + WORDPRESS_TABLE_PREFIX: ${{TABLE_PREFIX}} + volumes: + - ./wordpress:/var/www/html + networks: + - {network_name} + deploy: + resources: + limits: + memory: {memory_limit} + cpus: '{cpu_limit}' + + db: + image: mysql:8.0 + container_name: {project}-{env_type}-db + restart: unless-stopped + environment: + MYSQL_DATABASE: ${{DB_NAME}} + MYSQL_USER: ${{DB_USER}} + MYSQL_PASSWORD: ${{DB_PASSWORD}} + MYSQL_ROOT_PASSWORD: ${{DB_ROOT_PASSWORD}} + volumes: + - ./mysql-data:/var/lib/mysql + networks: + - {network_name} + deploy: + resources: + limits: + memory: {db_memory_limit} + cpus: '{db_cpu_limit}' + +networks: + {network_name}: + driver: bridge +""" + + # Resource limits by environment type + RESOURCE_LIMITS = { + 'production': {'memory': '512M', 'cpus': '1.0', 'db_memory': '512M', 'db_cpus': '0.5'}, + 'staging': {'memory': '384M', 'cpus': '0.5', 'db_memory': '384M', 'db_cpus': '0.25'}, + 'development': {'memory': '256M', 'cpus': '0.5', 'db_memory': '256M', 'db_cpus': '0.25'}, + 'multidev': {'memory': '256M', 'cpus': '0.25', 'db_memory': '256M', 'db_cpus': '0.25'}, + } + + @classmethod + def get_env_directory(cls, project_name: str, env_type: str) -> str: + """Get the directory path for an environment. + + Returns: + Path like /var/serverkit/apps/wp-{project}/{env_type}/ + """ + return os.path.join(cls.APPS_DIR, f'wp-{project_name}', env_type) + + @classmethod + def generate_compose_file(cls, project_name: str, env_type: str, config: Dict) -> Dict: + """Generate a docker-compose.yml for a single environment. + + Args: + project_name: The project identifier (slug) + env_type: Environment type (production, staging, development, multidev) + config: Configuration dict with optional overrides for ports, resources, etc. + + Returns: + Dict with success status, compose_path, and env_path + """ + try: + env_dir = cls.get_env_directory(project_name, env_type) + os.makedirs(env_dir, exist_ok=True) + + # Find available port for WordPress + wp_port = config.get('wp_port') or cls._find_available_port() + + # Get resource limits for this environment type + limits = cls.RESOURCE_LIMITS.get(env_type, cls.RESOURCE_LIMITS['development']) + + # Network name (unique per environment) + network_name = f'{project_name}-{env_type}-net' + + # Generate compose content from template + compose_content = cls.COMPOSE_TEMPLATE.format( + project=project_name, + env_type=env_type, + wp_port=wp_port, + network_name=network_name, + memory_limit=config.get('memory_limit', limits['memory']), + cpu_limit=config.get('cpu_limit', limits['cpus']), + db_memory_limit=config.get('db_memory_limit', limits['db_memory']), + db_cpu_limit=config.get('db_cpu_limit', limits['db_cpus']), + ) + + # Write docker-compose.yml + compose_path = os.path.join(env_dir, 'docker-compose.yml') + with open(compose_path, 'w') as f: + f.write(compose_content) + + # Generate .env file with variables + env_vars = { + 'DB_NAME': config.get('db_name', f'wp_{project_name}_{env_type}'), + 'DB_USER': config.get('db_user', f'wp_{project_name}'), + 'DB_PASSWORD': config.get('db_password', cls._generate_password()), + 'DB_ROOT_PASSWORD': config.get('db_root_password', cls._generate_password()), + 'TABLE_PREFIX': config.get('table_prefix', 'wp_'), + } + + env_path = os.path.join(env_dir, '.env') + with open(env_path, 'w') as f: + for key, value in env_vars.items(): + f.write(f'{key}={value}\n') + + return { + 'success': True, + 'compose_path': compose_path, + 'env_path': env_path, + 'env_dir': env_dir, + 'wp_port': wp_port, + 'env_vars': env_vars, + } + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def start_environment(cls, compose_path: str) -> Dict: + """Start a Docker Compose environment. + + Args: + compose_path: Path to docker-compose.yml + + Returns: + Dict with success status + """ + try: + result = subprocess.run( + ['docker', 'compose', '-f', compose_path, 'up', '-d'], + capture_output=True, + text=True, + timeout=120 + ) + + if result.returncode != 0: + return {'success': False, 'error': result.stderr} + + return {'success': True, 'output': result.stdout} + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Docker compose up timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def stop_environment(cls, compose_path: str) -> Dict: + """Stop a Docker Compose environment. + + Args: + compose_path: Path to docker-compose.yml + + Returns: + Dict with success status + """ + try: + result = subprocess.run( + ['docker', 'compose', '-f', compose_path, 'down'], + capture_output=True, + text=True, + timeout=60 + ) + + if result.returncode != 0: + return {'success': False, 'error': result.stderr} + + return {'success': True, 'output': result.stdout} + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Docker compose down timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def restart_environment(cls, compose_path: str) -> Dict: + """Restart a Docker Compose environment (stop + start). + + Args: + compose_path: Path to docker-compose.yml + + Returns: + Dict with success status + """ + stop_result = cls.stop_environment(compose_path) + if not stop_result.get('success'): + return stop_result + + return cls.start_environment(compose_path) + + @classmethod + def destroy_environment(cls, compose_path: str, remove_volumes: bool = False) -> Dict: + """Destroy a Docker Compose environment and optionally remove data. + + Args: + compose_path: Path to docker-compose.yml + remove_volumes: If True, also remove Docker volumes + + Returns: + Dict with success status + """ + try: + cmd = ['docker', 'compose', '-f', compose_path, 'down'] + if remove_volumes: + cmd.append('-v') + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=60 + ) + + if result.returncode != 0: + return {'success': False, 'error': result.stderr} + + # Remove the environment directory + env_dir = os.path.dirname(compose_path) + if os.path.exists(env_dir): + shutil.rmtree(env_dir) + + return {'success': True, 'output': result.stdout} + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Docker compose down timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def get_environment_status(cls, compose_path: str) -> Dict: + """Get the status of a Docker Compose environment. + + Args: + compose_path: Path to docker-compose.yml + + Returns: + Dict with running status and container details + """ + try: + result = subprocess.run( + ['docker', 'compose', '-f', compose_path, 'ps', '--format', 'json'], + capture_output=True, + text=True, + timeout=30 + ) + + if result.returncode != 0: + return {'success': False, 'running': False, 'error': result.stderr} + + containers = [] + if result.stdout.strip(): + # docker compose ps --format json outputs one JSON object per line + for line in result.stdout.strip().split('\n'): + line = line.strip() + if line: + try: + containers.append(json.loads(line)) + except json.JSONDecodeError: + continue + + running = all( + c.get('State') == 'running' + for c in containers + ) if containers else False + + return { + 'success': True, + 'running': running, + 'containers': containers, + } + + except subprocess.TimeoutExpired: + return {'success': False, 'running': False, 'error': 'Status check timed out'} + except Exception as e: + return {'success': False, 'running': False, 'error': str(e)} + + @classmethod + def get_container_logs(cls, compose_path: str, service: str = 'wordpress', lines: int = 100) -> Dict: + """Get logs from a container in the environment. + + Args: + compose_path: Path to docker-compose.yml + service: Service name (wordpress or db) + lines: Number of tail lines + + Returns: + Dict with success status and logs + """ + try: + result = subprocess.run( + ['docker', 'compose', '-f', compose_path, 'logs', '--tail', str(lines), service], + capture_output=True, + text=True, + timeout=30 + ) + + if result.returncode != 0: + return {'success': False, 'error': result.stderr} + + return {'success': True, 'logs': result.stdout} + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Log retrieval timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def exec_in_container(cls, compose_path: str, service: str, command: str) -> Dict: + """Execute a command inside a container. + + Args: + compose_path: Path to docker-compose.yml + service: Service name (wordpress or db) + command: Command to execute + + Returns: + Dict with success status and output + """ + try: + result = subprocess.run( + ['docker', 'compose', '-f', compose_path, 'exec', '-T', service] + command.split(), + capture_output=True, + text=True, + timeout=120 + ) + + if result.returncode != 0: + return {'success': False, 'error': result.stderr, 'output': result.stdout} + + return {'success': True, 'output': result.stdout} + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Command execution timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def update_resource_limits(cls, compose_path: str, limits: Dict) -> Dict: + """Update resource limits in a docker-compose.yml and restart containers. + + Args: + compose_path: Path to docker-compose.yml + limits: Dict with optional keys: memory, cpus, db_memory, db_cpus + + Returns: + Dict with success status + """ + try: + import yaml + + with open(compose_path, 'r') as f: + compose_content = f.read() + + compose_data = yaml.safe_load(compose_content) + + # Update WordPress service limits + wp_service = compose_data.get('services', {}).get('wordpress', {}) + if wp_service: + deploy = wp_service.setdefault('deploy', {}) + resources = deploy.setdefault('resources', {}) + resource_limits = resources.setdefault('limits', {}) + + if 'memory' in limits: + resource_limits['memory'] = limits['memory'] + if 'cpus' in limits: + resource_limits['cpus'] = str(limits['cpus']) + + # Update DB service limits + db_service = compose_data.get('services', {}).get('db', {}) + if db_service: + deploy = db_service.setdefault('deploy', {}) + resources = deploy.setdefault('resources', {}) + resource_limits = resources.setdefault('limits', {}) + + if 'db_memory' in limits: + resource_limits['memory'] = limits['db_memory'] + if 'db_cpus' in limits: + resource_limits['cpus'] = str(limits['db_cpus']) + + # Write updated compose file + with open(compose_path, 'w') as f: + yaml.dump(compose_data, f, default_flow_style=False, sort_keys=False) + + # Restart containers to apply new limits + return cls.restart_environment(compose_path) + + except ImportError: + # Fallback: regex-based replacement if PyYAML not available + return cls._update_limits_regex(compose_path, limits) + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def _update_limits_regex(cls, compose_path: str, limits: Dict) -> Dict: + """Fallback resource limits update using regex when PyYAML is unavailable.""" + import re + try: + with open(compose_path, 'r') as f: + content = f.read() + + if 'memory' in limits: + content = re.sub( + r'(wordpress:.*?limits:.*?memory:\s*)\S+', + r'\g<1>' + limits['memory'], + content, count=1, flags=re.DOTALL + ) + if 'cpus' in limits: + content = re.sub( + r'(wordpress:.*?limits:.*?cpus:\s*)[\'"]?\S+[\'"]?', + r"\g<1>'" + str(limits['cpus']) + "'", + content, count=1, flags=re.DOTALL + ) + if 'db_memory' in limits: + content = re.sub( + r'(db:.*?limits:.*?memory:\s*)\S+', + r'\g<1>' + limits['db_memory'], + content, count=1, flags=re.DOTALL + ) + if 'db_cpus' in limits: + content = re.sub( + r'(db:.*?limits:.*?cpus:\s*)[\'"]?\S+[\'"]?', + r"\g<1>'" + str(limits['db_cpus']) + "'", + content, count=1, flags=re.DOTALL + ) + + with open(compose_path, 'w') as f: + f.write(content) + + return cls.restart_environment(compose_path) + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def _find_available_port(cls) -> int: + """Find an available port. Delegates to TemplateService.""" + return TemplateService._find_available_port() + + @classmethod + def _generate_password(cls, length: int = 32) -> str: + """Generate a random password.""" + import secrets + import string + chars = string.ascii_letters + string.digits + return ''.join(secrets.choice(chars) for _ in range(length)) diff --git a/backend/app/services/environment_domain_service.py b/backend/app/services/environment_domain_service.py new file mode 100644 index 00000000..8f09c872 --- /dev/null +++ b/backend/app/services/environment_domain_service.py @@ -0,0 +1,395 @@ +""" +Environment Domain Service + +Manages per-environment domains and Nginx configurations for WordPress multidev. +Generates subdomains (staging.example.com, dev.example.com, branch-name.example.com) +and creates corresponding Nginx virtual host configs. +""" + +import os +import re +import subprocess +from typing import Dict + + +class EnvironmentDomainService: + """Service for managing per-environment domains and Nginx configs.""" + + SITES_AVAILABLE = '/etc/nginx/sites-available' + SITES_ENABLED = '/etc/nginx/sites-enabled' + + # Nginx template for environment proxy (based on NginxService.DOCKER_SITE_TEMPLATE) + ENV_SITE_TEMPLATE = '''server {{ + listen 80; + listen [::]:80; + server_name {domain}; + + access_log /var/log/nginx/{site_name}.access.log; + error_log /var/log/nginx/{site_name}.error.log; + +{extra_headers} + location / {{ + proxy_pass http://127.0.0.1:{port}; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache_bypass $http_upgrade; + proxy_read_timeout 86400; + proxy_connect_timeout 60; + proxy_send_timeout 60; + }} +{robots_block} +}} +''' + + # Extra headers for non-production environments + NON_PROD_HEADERS = ' add_header X-Robots-Tag "noindex, nofollow" always;' + + # Robots.txt block for non-production environments + ROBOTS_BLOCK = ''' + location = /robots.txt {{ + return 200 "User-agent: *\\nDisallow: /\\n"; + add_header Content-Type text/plain; + }} +''' + + @classmethod + def generate_domain(cls, production_domain: str, env_type: str, + branch_name: str = None) -> str: + """Generate a domain name for an environment. + + Args: + production_domain: The production domain (e.g., example.com) + env_type: Environment type (production, staging, development, multidev) + branch_name: Branch name for multidev environments + + Returns: + Domain string for the environment + """ + if env_type == 'production': + return production_domain + + if not production_domain: + # Fallback for sites without a domain + slug = cls.slugify(branch_name) if branch_name else env_type + return f'{env_type}-{slug}.localhost' + + if env_type == 'staging': + return f'staging.{production_domain}' + + if env_type == 'development': + return f'dev.{production_domain}' + + if env_type == 'multidev' and branch_name: + slug = cls.slugify(branch_name) + return f'{slug}.{production_domain}' + + # Fallback + return f'{env_type}.{production_domain}' + + @classmethod + def create_nginx_config(cls, site_name: str, domain: str, upstream_port: int, + env_type: str = 'production') -> Dict: + """Create and enable an Nginx virtual host for an environment. + + Args: + site_name: Unique site name for the config file + domain: Domain name to serve + upstream_port: Port the Docker container listens on + env_type: Environment type (controls noindex headers) + + Returns: + Dict with success status + """ + try: + is_production = env_type == 'production' + + # Build template variables + extra_headers = '' if is_production else cls.NON_PROD_HEADERS + robots_block = '' if is_production else cls.ROBOTS_BLOCK + + config = cls.ENV_SITE_TEMPLATE.format( + domain=domain, + site_name=site_name, + port=upstream_port, + extra_headers=extra_headers, + robots_block=robots_block, + ) + + # Write config file using sudo tee + config_path = os.path.join(cls.SITES_AVAILABLE, site_name) + process = subprocess.run( + ['sudo', 'tee', config_path], + input=config, + capture_output=True, + text=True + ) + if process.returncode != 0: + return {'success': False, 'error': f'Failed to write config: {process.stderr}'} + + # Enable the site (symlink to sites-enabled) + enabled_path = os.path.join(cls.SITES_ENABLED, site_name) + result = subprocess.run( + ['sudo', 'ln', '-sf', config_path, enabled_path], + capture_output=True, + text=True + ) + if result.returncode != 0: + return {'success': False, 'error': f'Failed to enable site: {result.stderr}'} + + # Reload Nginx + reload_result = cls._reload_nginx() + if not reload_result.get('success'): + return reload_result + + return { + 'success': True, + 'config_path': config_path, + 'domain': domain, + } + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def remove_nginx_config(cls, site_name: str) -> Dict: + """Remove an Nginx virtual host config and reload. + + Args: + site_name: The config file name to remove + + Returns: + Dict with success status + """ + try: + # Remove symlink from sites-enabled + enabled_path = os.path.join(cls.SITES_ENABLED, site_name) + subprocess.run( + ['sudo', 'rm', '-f', enabled_path], + capture_output=True, + text=True + ) + + # Remove config from sites-available + available_path = os.path.join(cls.SITES_AVAILABLE, site_name) + subprocess.run( + ['sudo', 'rm', '-f', available_path], + capture_output=True, + text=True + ) + + # Reload Nginx + cls._reload_nginx() + + return {'success': True, 'message': f'Nginx config for {site_name} removed'} + + except Exception as e: + return {'success': False, 'error': str(e)} + + # ==================== BASIC AUTH ==================== + + HTPASSWD_DIR = '/etc/nginx/htpasswd' + + @classmethod + def enable_basic_auth(cls, site_name: str, username: str, password: str) -> Dict: + """Enable HTTP Basic Auth on an Nginx site. + + Generates an htpasswd file and modifies the Nginx config to require auth. + + Args: + site_name: The Nginx config file name + username: Basic Auth username + password: Plain text password (will be hashed) + + Returns: + Dict with success status and credentials + """ + try: + # Ensure htpasswd directory exists + subprocess.run( + ['sudo', 'mkdir', '-p', cls.HTPASSWD_DIR], + capture_output=True, text=True + ) + + # Generate password hash using openssl + hash_result = subprocess.run( + ['openssl', 'passwd', '-apr1', password], + capture_output=True, text=True, timeout=10 + ) + if hash_result.returncode != 0: + return {'success': False, 'error': f'Failed to hash password: {hash_result.stderr}'} + + password_hash = hash_result.stdout.strip() + htpasswd_content = f'{username}:{password_hash}\n' + + # Write htpasswd file + htpasswd_path = os.path.join(cls.HTPASSWD_DIR, site_name) + process = subprocess.run( + ['sudo', 'tee', htpasswd_path], + input=htpasswd_content, + capture_output=True, text=True + ) + if process.returncode != 0: + return {'success': False, 'error': f'Failed to write htpasswd: {process.stderr}'} + + # Set correct permissions + subprocess.run( + ['sudo', 'chmod', '644', htpasswd_path], + capture_output=True, text=True + ) + + # Modify Nginx config to add auth_basic directives + config_path = os.path.join(cls.SITES_AVAILABLE, site_name) + read_result = subprocess.run( + ['sudo', 'cat', config_path], + capture_output=True, text=True + ) + if read_result.returncode != 0: + return {'success': False, 'error': 'Failed to read Nginx config'} + + config_content = read_result.stdout + + # Check if auth_basic already exists + if 'auth_basic' in config_content: + # Already has basic auth, just update htpasswd file + pass + else: + # Insert auth_basic directives after server_name line + auth_block = ( + f'\n auth_basic "Restricted Access";\n' + f' auth_basic_user_file {htpasswd_path};\n' + ) + config_content = re.sub( + r'(server_name\s+[^;]+;)', + r'\1' + auth_block, + config_content, + count=1 + ) + + # Write updated config + process = subprocess.run( + ['sudo', 'tee', config_path], + input=config_content, + capture_output=True, text=True + ) + if process.returncode != 0: + return {'success': False, 'error': f'Failed to update Nginx config: {process.stderr}'} + + # Reload Nginx + reload_result = cls._reload_nginx() + if not reload_result.get('success'): + return reload_result + + return { + 'success': True, + 'username': username, + 'password_hash': password_hash, + 'htpasswd_path': htpasswd_path, + } + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def disable_basic_auth(cls, site_name: str) -> Dict: + """Disable HTTP Basic Auth on an Nginx site. + + Removes auth_basic directives from config and deletes the htpasswd file. + + Args: + site_name: The Nginx config file name + + Returns: + Dict with success status + """ + try: + # Remove htpasswd file + htpasswd_path = os.path.join(cls.HTPASSWD_DIR, site_name) + subprocess.run( + ['sudo', 'rm', '-f', htpasswd_path], + capture_output=True, text=True + ) + + # Remove auth_basic directives from Nginx config + config_path = os.path.join(cls.SITES_AVAILABLE, site_name) + read_result = subprocess.run( + ['sudo', 'cat', config_path], + capture_output=True, text=True + ) + if read_result.returncode != 0: + return {'success': False, 'error': 'Failed to read Nginx config'} + + config_content = read_result.stdout + + # Remove auth_basic lines + config_content = re.sub(r'\n\s*auth_basic\s+"[^"]*";\n', '\n', config_content) + config_content = re.sub(r'\s*auth_basic_user_file\s+[^;]+;\n', '', config_content) + + # Write updated config + process = subprocess.run( + ['sudo', 'tee', config_path], + input=config_content, + capture_output=True, text=True + ) + if process.returncode != 0: + return {'success': False, 'error': f'Failed to update Nginx config: {process.stderr}'} + + # Reload Nginx + reload_result = cls._reload_nginx() + if not reload_result.get('success'): + return reload_result + + return {'success': True, 'message': 'Basic Auth disabled'} + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def slugify(cls, text: str) -> str: + """Convert text to a URL-safe slug. + + Args: + text: Input string (e.g., branch name) + + Returns: + Lowercase slug with only alphanumeric chars and hyphens + """ + text = text.lower() + text = re.sub(r'[^a-z0-9]+', '-', text) + text = text.strip('-') + return text + + @classmethod + def _reload_nginx(cls) -> Dict: + """Test and reload Nginx configuration.""" + try: + # Test config first + test_result = subprocess.run( + ['sudo', 'nginx', '-t'], + capture_output=True, + text=True, + timeout=10 + ) + if test_result.returncode != 0: + return {'success': False, 'error': f'Nginx config test failed: {test_result.stderr}'} + + # Reload + result = subprocess.run( + ['sudo', 'systemctl', 'reload', 'nginx'], + capture_output=True, + text=True, + timeout=30 + ) + if result.returncode != 0: + return {'success': False, 'error': f'Nginx reload failed: {result.stderr}'} + + return {'success': True} + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Nginx reload timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} diff --git a/backend/app/services/environment_health_service.py b/backend/app/services/environment_health_service.py new file mode 100644 index 00000000..6398c403 --- /dev/null +++ b/backend/app/services/environment_health_service.py @@ -0,0 +1,291 @@ +""" +Environment Health Service + +Monitors the health of WordPress environment containers, databases, +and WordPress HTTP responses. Also tracks disk usage. +""" + +import os +import subprocess +from datetime import datetime +from typing import Dict, Optional + +from app import db +from app.models.wordpress_site import WordPressSite +from app.services.environment_docker_service import EnvironmentDockerService +from app.services.environment_pipeline_service import EnvironmentPipelineService + + +class EnvironmentHealthService: + """Service for checking environment health and disk usage.""" + + @classmethod + def check_health(cls, site_id: int) -> Dict: + """Run health checks for a single environment. + + Checks: container running, MySQL connectivity, WordPress HTTP response. + + Returns: + Dict with overall status and individual check results + """ + site = WordPressSite.query.get(site_id) + if not site: + return {'success': False, 'error': 'Site not found'} + + compose_path = EnvironmentPipelineService._get_compose_path(site) + checks = { + 'container': {'status': 'unknown', 'message': ''}, + 'mysql': {'status': 'unknown', 'message': ''}, + 'wordpress': {'status': 'unknown', 'message': ''}, + } + + # Container check + if compose_path: + status_result = EnvironmentDockerService.get_environment_status(compose_path) + if status_result.get('running'): + checks['container'] = {'status': 'healthy', 'message': 'All containers running'} + elif status_result.get('success'): + checks['container'] = {'status': 'unhealthy', 'message': 'Containers not running'} + else: + checks['container'] = {'status': 'unhealthy', 'message': status_result.get('error', 'Status check failed')} + else: + checks['container'] = {'status': 'unknown', 'message': 'No Docker compose configuration'} + + # MySQL check + if compose_path and checks['container']['status'] == 'healthy': + mysql_result = EnvironmentDockerService.exec_in_container( + compose_path, 'db', 'mysqladmin ping -h 127.0.0.1' + ) + if mysql_result.get('success'): + checks['mysql'] = {'status': 'healthy', 'message': 'MySQL is alive'} + else: + checks['mysql'] = {'status': 'unhealthy', 'message': mysql_result.get('error', 'MySQL ping failed')} + elif checks['container']['status'] != 'healthy': + checks['mysql'] = {'status': 'unknown', 'message': 'Container not running'} + + # WordPress HTTP check + if compose_path and checks['container']['status'] == 'healthy': + port = site.application.port if site.application else None + if port: + wp_result = cls._check_wordpress_http(port) + checks['wordpress'] = wp_result + else: + checks['wordpress'] = {'status': 'unknown', 'message': 'No port configured'} + elif checks['container']['status'] != 'healthy': + checks['wordpress'] = {'status': 'unknown', 'message': 'Container not running'} + + # Determine overall status + statuses = [c['status'] for c in checks.values()] + if all(s == 'healthy' for s in statuses): + overall = 'healthy' + elif any(s == 'unhealthy' for s in statuses): + overall = 'unhealthy' + elif any(s == 'healthy' for s in statuses): + overall = 'degraded' + else: + overall = 'unknown' + + # Update site record + site.health_status = overall + site.last_health_check = datetime.utcnow() + db.session.commit() + + return { + 'success': True, + 'site_id': site_id, + 'overall_status': overall, + 'checks': checks, + 'checked_at': datetime.utcnow().isoformat(), + } + + @classmethod + def check_all_project_health(cls, production_site_id: int) -> Dict: + """Check health for all environments in a project. + + Returns: + Dict with health data for production and all child environments + """ + prod_site = WordPressSite.query.get(production_site_id) + if not prod_site: + return {'success': False, 'error': 'Production site not found'} + + results = {} + + # Check production + prod_health = cls.check_health(production_site_id) + results[production_site_id] = prod_health + + # Check all child environments + for env in prod_site.environments: + env_health = cls.check_health(env.id) + results[env.id] = env_health + + return { + 'success': True, + 'project_id': production_site_id, + 'environments': results, + } + + @classmethod + def get_disk_usage(cls, site_id: int) -> Dict: + """Calculate disk usage for an environment. + + Measures WordPress files and MySQL data directories. + + Returns: + Dict with usage breakdown in bytes + """ + site = WordPressSite.query.get(site_id) + if not site: + return {'success': False, 'error': 'Site not found'} + + app = site.application + if not app or not app.root_path: + return {'success': False, 'error': 'No application root path'} + + env_dir = app.root_path + usage = { + 'wordpress': 0, + 'mysql': 0, + 'snapshots': 0, + 'total': 0, + } + + # WordPress files + wp_dir = os.path.join(env_dir, 'wordpress') + if os.path.exists(wp_dir): + usage['wordpress'] = cls._get_dir_size(wp_dir) + elif os.path.exists(env_dir): + usage['wordpress'] = cls._get_dir_size(env_dir) + + # MySQL data + mysql_dir = os.path.join(env_dir, 'mysql-data') + if os.path.exists(mysql_dir): + usage['mysql'] = cls._get_dir_size(mysql_dir) + + # Snapshots + snapshots_dir = os.path.join(env_dir, 'snapshots') + if os.path.exists(snapshots_dir): + usage['snapshots'] = cls._get_dir_size(snapshots_dir) + + usage['total'] = usage['wordpress'] + usage['mysql'] + usage['snapshots'] + + # Update site record + site.disk_usage_bytes = usage['total'] + site.disk_usage_updated_at = datetime.utcnow() + db.session.commit() + + return { + 'success': True, + 'site_id': site_id, + 'usage': usage, + 'total_human': cls._format_size(usage['total']), + 'breakdown': { + 'wordpress': cls._format_size(usage['wordpress']), + 'mysql': cls._format_size(usage['mysql']), + 'snapshots': cls._format_size(usage['snapshots']), + }, + 'updated_at': datetime.utcnow().isoformat(), + } + + @classmethod + def get_disk_usage_for_project(cls, production_site_id: int) -> Dict: + """Get disk usage for all environments in a project. + + Returns: + Dict with disk usage data for each environment + """ + prod_site = WordPressSite.query.get(production_site_id) + if not prod_site: + return {'success': False, 'error': 'Production site not found'} + + results = {} + total = 0 + + # Production + prod_usage = cls.get_disk_usage(production_site_id) + results[production_site_id] = prod_usage + if prod_usage.get('success'): + total += prod_usage['usage']['total'] + + # Child environments + for env in prod_site.environments: + env_usage = cls.get_disk_usage(env.id) + results[env.id] = env_usage + if env_usage.get('success'): + total += env_usage['usage']['total'] + + return { + 'success': True, + 'project_id': production_site_id, + 'environments': results, + 'project_total': total, + 'project_total_human': cls._format_size(total), + } + + @classmethod + def _check_wordpress_http(cls, port: int) -> Dict: + """Check WordPress HTTP response on localhost.""" + try: + result = subprocess.run( + ['curl', '-s', '-o', '/dev/null', '-w', '%{http_code}', + '--max-time', '5', f'http://127.0.0.1:{port}/wp-login.php'], + capture_output=True, + text=True, + timeout=10 + ) + + status_code = result.stdout.strip() + if status_code in ('200', '302', '301'): + return {'status': 'healthy', 'message': f'HTTP {status_code}'} + elif status_code == '401': + return {'status': 'healthy', 'message': 'HTTP 401 (Basic Auth enabled)'} + elif status_code == '000' or not status_code: + return {'status': 'unhealthy', 'message': 'Connection refused'} + else: + return {'status': 'degraded', 'message': f'HTTP {status_code}'} + + except subprocess.TimeoutExpired: + return {'status': 'unhealthy', 'message': 'HTTP check timed out'} + except Exception as e: + return {'status': 'unknown', 'message': str(e)} + + @classmethod + def _get_dir_size(cls, path: str) -> int: + """Get total size of a directory in bytes.""" + try: + result = subprocess.run( + ['du', '-sb', path], + capture_output=True, + text=True, + timeout=30 + ) + if result.returncode == 0 and result.stdout.strip(): + return int(result.stdout.split()[0]) + except Exception: + pass + + # Fallback: walk directory + total = 0 + try: + for dirpath, dirnames, filenames in os.walk(path): + for f in filenames: + fp = os.path.join(dirpath, f) + try: + total += os.path.getsize(fp) + except OSError: + pass + except Exception: + pass + return total + + @staticmethod + def _format_size(size_bytes: int) -> str: + """Format bytes to human-readable string.""" + if not size_bytes: + return '0 B' + for unit in ['B', 'KB', 'MB', 'GB']: + if size_bytes < 1024: + return f'{size_bytes:.1f} {unit}' + size_bytes /= 1024 + return f'{size_bytes:.1f} TB' diff --git a/backend/app/services/environment_pipeline_service.py b/backend/app/services/environment_pipeline_service.py new file mode 100644 index 00000000..93adff6c --- /dev/null +++ b/backend/app/services/environment_pipeline_service.py @@ -0,0 +1,1677 @@ +""" +Environment Pipeline Service + +Orchestrates the full WordPress environment lifecycle: +- Create isolated environments (dev, staging, multidev) +- Promote code/database between environments +- Sync environments from production +- Lock/unlock environments during operations +- Compare environments (plugins, themes, versions) +- Activity tracking and audit trail + +This is the "conductor" that coordinates EnvironmentDockerService, +DatabaseSyncService, EnvironmentDomainService, and the WordPress models. +""" + +import os +import json +import shutil +import secrets +import string +import subprocess +import time +from datetime import datetime, timedelta +from typing import Dict, Optional + +from app import db +from app.models.application import Application +from app.models.wordpress_site import WordPressSite, DatabaseSnapshot +from app.models.environment_activity import EnvironmentActivity +from app.models.promotion_job import PromotionJob +from app.services.environment_docker_service import EnvironmentDockerService +from app.services.environment_domain_service import EnvironmentDomainService +from app.services.db_sync_service import DatabaseSyncService + + +class EnvironmentPipelineService: + """Orchestrate WordPress environment creation, sync, and promotion.""" + + # ==================== ENVIRONMENT CREATION ==================== + + @classmethod + def _emit_progress(cls, callback, step: int, total: int, message: str): + """Emit a progress callback if provided.""" + if callback: + try: + callback({ + 'step': step, + 'total': total, + 'message': message, + 'percent': int((step / total) * 100) if total > 0 else 0, + }) + except Exception: + pass + + @classmethod + def _send_notification(cls, action: str, details: Dict, user_id: int = None): + """Send a notification about a pipeline operation via configured channels.""" + try: + from app.services.notification_service import NotificationService + message = details.get('message', f'WordPress Pipeline: {action}') + + alerts = [{ + 'title': f'Pipeline: {action}', + 'message': message, + 'severity': 'info', + 'source': 'wordpress_pipeline', + }] + NotificationService.send_all(alerts) + except Exception: + pass # Notifications are best-effort + + @classmethod + def create_project_environment(cls, production_site_id: int, env_type: str, + config: Dict, user_id: int, + progress_callback=None) -> Dict: + """ + Create a fully isolated Docker environment for a WordPress project. + + Creates a new docker-compose stack, clones the production database, + copies WordPress files, generates Nginx config, and wires everything up. + + Args: + production_site_id: ID of the production WordPressSite + env_type: 'development', 'staging', or 'multidev' + config: Configuration dict: + - name: Environment display name + - domain: Custom domain (auto-generated if None) + - branch: Git branch for multidev envs + - clone_db: Whether to clone production DB (default True) + - resource_limits: Optional {memory, cpus, db_memory, db_cpus} + user_id: ID of the user creating the environment + + Returns: + Dict with success status and environment details + """ + if env_type not in ['development', 'staging', 'multidev']: + return {'success': False, 'error': 'Invalid environment type. Must be development, staging, or multidev.'} + + prod_site = WordPressSite.query.get(production_site_id) + if not prod_site: + return {'success': False, 'error': 'Production site not found'} + + if not prod_site.is_production and prod_site.environment_type != 'production': + return {'success': False, 'error': 'Source site is not a production environment'} + + prod_app = prod_site.application + if not prod_app: + return {'success': False, 'error': 'Production application not found'} + + # Check for existing environment of same type (except multidev) + if env_type != 'multidev': + existing = WordPressSite.query.filter_by( + production_site_id=production_site_id, + environment_type=env_type + ).first() + if existing: + return {'success': False, 'error': f'A {env_type} environment already exists for this project'} + + # Start activity tracking + start_time = time.time() + activity = cls._create_activity( + site_id=production_site_id, + user_id=user_id, + action='environment_created', + description=f'Creating {env_type} environment', + status='running' + ) + + try: + # Generate project name slug + project_name = cls._slugify(prod_app.name) + + # Handle multidev naming + branch_name = config.get('branch') + if env_type == 'multidev': + if not branch_name: + return {'success': False, 'error': 'Branch name required for multidev environments'} + env_type_dir = f'multidev-{EnvironmentDomainService.slugify(branch_name)}' + else: + env_type_dir = env_type + + cls._emit_progress(progress_callback, 1, 10, 'Generating Docker Compose configuration...') + + # Step 1: Generate Docker Compose stack + compose_config = { + 'db_name': f'wp_{project_name}_{env_type_dir}'.replace('-', '_')[:64], + 'db_user': f'wp_{project_name}'[:32], + 'db_password': cls._generate_password(), + 'db_root_password': cls._generate_password(), + 'table_prefix': 'wp_', + } + if config.get('resource_limits'): + compose_config.update(config['resource_limits']) + + compose_result = EnvironmentDockerService.generate_compose_file( + project_name=project_name, + env_type=env_type_dir, + config=compose_config + ) + + if not compose_result['success']: + cls._finish_activity(activity, 'failed', compose_result.get('error'), start_time) + return compose_result + + compose_path = compose_result['compose_path'] + env_dir = compose_result['env_dir'] + wp_port = compose_result['wp_port'] + env_vars = compose_result['env_vars'] + + cls._emit_progress(progress_callback, 2, 10, 'Generating domain...') + + # Step 2: Generate domain + prod_domain = None + if prod_app.domains: + prod_domains = list(prod_app.domains) + if prod_domains: + prod_domain = prod_domains[0].domain + + domain = config.get('domain') or EnvironmentDomainService.generate_domain( + production_domain=prod_domain or '', + env_type=env_type, + branch_name=branch_name + ) + + # Step 3: Create Application record + env_name = config.get('name', f"{prod_app.name} ({env_type.title()})") + if env_type == 'multidev': + env_name = f"{prod_app.name} ({branch_name})" + + env_app = Application( + name=env_name, + app_type='wordpress', + status='deploying', + php_version=prod_app.php_version, + port=wp_port, + root_path=env_dir, + environment_type=env_type, + linked_app_id=prod_app.id, + user_id=user_id + ) + db.session.add(env_app) + db.session.flush() + + # Step 4: Create WordPressSite record + env_site = WordPressSite( + application_id=env_app.id, + wp_version=prod_site.wp_version, + multisite=prod_site.multisite, + admin_user=prod_site.admin_user, + admin_email=prod_site.admin_email, + db_name=env_vars['DB_NAME'], + db_user=env_vars['DB_USER'], + db_host='localhost', + db_prefix=env_vars['TABLE_PREFIX'], + git_repo_url=prod_site.git_repo_url, + git_branch=branch_name or prod_site.git_branch, + git_paths=prod_site.git_paths, + auto_deploy=False, + is_production=False, + production_site_id=production_site_id, + environment_type=env_type, + multidev_branch=branch_name, + compose_project_name=project_name, + container_prefix=f'{project_name}-{env_type_dir}', + ) + db.session.add(env_site) + db.session.flush() + + cls._emit_progress(progress_callback, 5, 10, 'Starting Docker containers...') + + # Step 5: Start Docker containers + start_result = EnvironmentDockerService.start_environment(compose_path) + if not start_result['success']: + db.session.rollback() + cls._finish_activity(activity, 'failed', f"Docker start failed: {start_result.get('error')}", start_time) + # Cleanup compose files + EnvironmentDockerService.destroy_environment(compose_path, remove_volumes=True) + return {'success': False, 'error': f"Failed to start containers: {start_result.get('error')}"} + + cls._emit_progress(progress_callback, 6, 10, 'Waiting for MySQL to be ready...') + + # Step 6: Wait for MySQL to be ready + cls._wait_for_mysql(compose_path, env_vars['DB_USER'], env_vars['DB_PASSWORD']) + + cls._emit_progress(progress_callback, 7, 10, 'Cloning production database...') + + # Step 7: Clone production database if requested + if config.get('clone_db', True): + prod_compose_path = cls._get_compose_path(prod_site) + + if prod_compose_path: + # Container-to-container clone + clone_options = { + 'exclude_tables': config.get('exclude_tables', []), + 'truncate_tables': config.get('truncate_tables', [ + 'actionscheduler_actions', + 'actionscheduler_logs', + ]), + } + + # Add search-replace for domain + if prod_domain and domain: + clone_options['search_replace'] = { + f'https://{prod_domain}': f'https://{domain}', + f'http://{prod_domain}': f'http://{domain}', + prod_domain: domain, + } + + clone_result = DatabaseSyncService.clone_between_containers( + source_compose_path=prod_compose_path, + target_compose_path=compose_path, + source_db=prod_site.db_name, + target_db=env_vars['DB_NAME'], + source_user=prod_site.db_user, + target_user=env_vars['DB_USER'], + source_password=cls._get_env_password(prod_site), + target_password=env_vars['DB_PASSWORD'], + options=clone_options + ) + else: + # Production runs on host MySQL — export from host, import to container + clone_options = { + 'exclude_tables': config.get('exclude_tables', []), + 'truncate_tables': config.get('truncate_tables', [ + 'actionscheduler_actions', + 'actionscheduler_logs', + ]), + } + + if prod_domain and domain: + clone_options['search_replace'] = { + f'https://{prod_domain}': f'https://{domain}', + f'http://{prod_domain}': f'http://{domain}', + prod_domain: domain, + } + + # Export from host MySQL + export_result = DatabaseSyncService.create_snapshot( + db_name=prod_site.db_name, + name=f'env_clone_{env_type_dir}', + host=prod_site.db_host or 'localhost', + user=prod_site.db_user, + password=cls._get_db_password_from_config(prod_site), + compress=False, + exclude_tables=clone_options.get('exclude_tables', []) + ) + + if not export_result['success']: + clone_result = export_result + else: + dump_file = export_result['snapshot']['file_path'] + transformed_file = dump_file.replace('.sql', '_transformed.sql') + + try: + # Transform if needed + needs_transform = any([ + clone_options.get('search_replace'), + clone_options.get('truncate_tables') + ]) + + import_file = dump_file + clone_result = None + + if needs_transform: + transform_result = DatabaseSyncService._transform_dump( + dump_file, transformed_file, clone_options + ) + if not transform_result['success']: + clone_result = transform_result + else: + import_file = transformed_file + + # Import into container if transform didn't fail + if clone_result is None: + clone_result = DatabaseSyncService.import_to_container( + compose_path=compose_path, + snapshot_path=import_file, + db_name=env_vars['DB_NAME'], + db_user=env_vars['DB_USER'], + db_password=env_vars['DB_PASSWORD'] + ) + finally: + for f in [dump_file, transformed_file]: + if os.path.exists(f): + os.remove(f) + + if not clone_result.get('success'): + # DB clone failed — log warning but don't fail entire creation + activity_meta = {'warning': f"DB clone failed: {clone_result.get('error')}"} + else: + activity_meta = {'db_cloned': True} + else: + activity_meta = {'db_cloned': False} + + cls._emit_progress(progress_callback, 8, 10, 'Copying WordPress files...') + + # Step 8: Copy WordPress files from production if they exist + prod_wp_dir = prod_app.root_path + env_wp_dir = os.path.join(env_dir, 'wordpress') + if prod_wp_dir and os.path.exists(prod_wp_dir): + cls._copy_wordpress_files(prod_wp_dir, env_wp_dir) + + cls._emit_progress(progress_callback, 9, 10, 'Creating Nginx configuration...') + + # Step 9: Create Nginx config + site_name = f'wp-{project_name}-{env_type_dir}' + nginx_result = EnvironmentDomainService.create_nginx_config( + site_name=site_name, + domain=domain, + upstream_port=wp_port, + env_type=env_type + ) + if not nginx_result['success']: + activity_meta['nginx_warning'] = nginx_result.get('error') + + cls._emit_progress(progress_callback, 10, 10, 'Finalizing environment...') + + # Step 10: Update application status + env_app.status = 'running' + db.session.commit() + + # Finish activity + activity_meta.update({ + 'env_type': env_type, + 'domain': domain, + 'port': wp_port, + 'project_name': project_name, + 'site_id': env_site.id, + }) + cls._finish_activity(activity, 'completed', None, start_time, activity_meta) + + return { + 'success': True, + 'message': f'{env_type.title()} environment created successfully', + 'environment': env_site.to_dict(), + 'application': env_app.to_dict(), + 'domain': domain, + 'compose_path': compose_path, + } + + except Exception as e: + db.session.rollback() + cls._finish_activity(activity, 'failed', str(e), start_time) + return {'success': False, 'error': str(e)} + + # ==================== SYNC FROM PRODUCTION ==================== + + @classmethod + def sync_from_production(cls, env_site_id: int, sync_type: str = 'full', + options: Dict = None, user_id: int = None, + progress_callback=None) -> Dict: + """ + Pull production data (database and/or files) into a lower environment. + + Args: + env_site_id: ID of the target environment's WordPressSite + sync_type: 'database', 'files', or 'full' (both) + options: Sync options: + - sanitize: Whether to apply sanitization + - search_replace: Additional search/replace pairs + - truncate_tables: Tables to empty + - exclude_tables: Tables to skip + user_id: ID of the user performing the sync + + Returns: + Dict with success status + """ + options = options or {} + + env_site = WordPressSite.query.get(env_site_id) + if not env_site: + return {'success': False, 'error': 'Environment not found'} + + if env_site.is_production or env_site.environment_type == 'production': + return {'success': False, 'error': 'Cannot sync into a production environment'} + + prod_site = env_site.production_site + if not prod_site: + return {'success': False, 'error': 'Production site not found'} + + # Check lock + if env_site.is_locked: + return {'success': False, 'error': f'Environment is locked: {env_site.locked_reason}'} + + start_time = time.time() + activity = cls._create_activity( + site_id=env_site_id, + user_id=user_id, + action='synced_from_production', + description=f'Syncing {sync_type} from production', + status='running' + ) + + # Lock during sync + cls._lock_environment(env_site, 'Sync from production in progress', user_id) + cls._emit_progress(progress_callback, 1, 5, 'Locking environment...') + + try: + env_compose_path = cls._get_compose_path(env_site) + prod_compose_path = cls._get_compose_path(prod_site) + pre_sync_snapshot_path = None + + # Sync database + if sync_type in ('database', 'full'): + cls._emit_progress(progress_callback, 2, 5, 'Creating pre-sync snapshot...') + # Create pre-sync snapshot for rollback safety + if env_compose_path: + env_vars = cls._read_env_vars(env_site) + snapshot_result = DatabaseSyncService.export_from_container( + compose_path=env_compose_path, + db_name=env_site.db_name, + db_user=env_vars.get('DB_USER', env_site.db_user), + db_password=env_vars.get('DB_PASSWORD'), + ) + if snapshot_result['success']: + pre_sync_snapshot_path = snapshot_result['file_path'] + + # Build clone options + clone_options = { + 'search_replace': options.get('search_replace', {}), + 'truncate_tables': options.get('truncate_tables', []), + 'exclude_tables': options.get('exclude_tables', []), + 'anonymize': options.get('sanitize', False), + } + + # Auto-add domain search-replace + prod_domain = cls._get_primary_domain(prod_site) + env_domain = cls._get_primary_domain(env_site) + if prod_domain and env_domain and prod_domain != env_domain: + clone_options['search_replace'].update({ + f'https://{prod_domain}': f'https://{env_domain}', + f'http://{prod_domain}': f'http://{env_domain}', + prod_domain: env_domain, + }) + + cls._emit_progress(progress_callback, 3, 5, 'Syncing database...') + + # Clone DB + if prod_compose_path and env_compose_path: + clone_result = DatabaseSyncService.clone_between_containers( + source_compose_path=prod_compose_path, + target_compose_path=env_compose_path, + source_db=prod_site.db_name, + target_db=env_site.db_name, + source_user=prod_site.db_user, + target_user=env_site.db_user, + source_password=cls._get_env_password(prod_site), + target_password=cls._get_env_password(env_site), + options=clone_options, + ) + else: + # Fallback: host-to-host clone + clone_result = DatabaseSyncService.clone_database( + source_db=prod_site.db_name, + target_db=env_site.db_name, + source_host=prod_site.db_host or 'localhost', + target_host=env_site.db_host or 'localhost', + source_user=prod_site.db_user, + target_user=env_site.db_user, + source_password=cls._get_db_password_from_config(prod_site), + target_password=cls._get_db_password_from_config(env_site), + options=clone_options, + ) + + if not clone_result['success']: + cls._unlock_environment(env_site) + cls._finish_activity(activity, 'failed', clone_result.get('error'), start_time) + return clone_result + + cls._emit_progress(progress_callback, 4, 5, 'Syncing files...') + + # Sync files + if sync_type in ('files', 'full'): + prod_app = prod_site.application + env_app = env_site.application + + if prod_app and env_app and prod_app.root_path and env_app.root_path: + prod_wp_dir = prod_app.root_path + env_wp_dir = os.path.join(env_app.root_path, 'wordpress') if env_compose_path else env_app.root_path + + files_result = cls._sync_wordpress_files(prod_wp_dir, env_wp_dir) + if not files_result['success']: + cls._unlock_environment(env_site) + cls._finish_activity(activity, 'failed', files_result.get('error'), start_time) + return files_result + + cls._emit_progress(progress_callback, 5, 5, 'Complete') + + # Update timestamp + env_site.updated_at = datetime.utcnow() + db.session.commit() + + cls._unlock_environment(env_site) + cls._finish_activity(activity, 'completed', None, start_time, { + 'sync_type': sync_type, + 'pre_sync_snapshot': pre_sync_snapshot_path, + }) + + cls._send_notification('Sync Completed', { + 'message': f'Environment synced from production ({sync_type})', + 'sync_type': sync_type, + }, user_id) + + return { + 'success': True, + 'message': f'Environment synced from production ({sync_type})', + 'pre_sync_snapshot': pre_sync_snapshot_path, + } + + except Exception as e: + cls._unlock_environment(env_site) + cls._finish_activity(activity, 'failed', str(e), start_time) + return {'success': False, 'error': str(e)} + + # ==================== CODE PROMOTION ==================== + + @classmethod + def promote_code(cls, source_site_id: int, target_site_id: int, + config: Dict = None, user_id: int = None, + progress_callback=None) -> Dict: + """ + Promote code (wp-content: themes, plugins, mu-plugins) from source to target. + + Uses rsync to selectively copy WordPress code files upstream. + + Args: + source_site_id: ID of the source WordPressSite + target_site_id: ID of the target WordPressSite + config: Promotion config: + - include_plugins: bool (default True) + - include_themes: bool (default True) + - include_mu_plugins: bool (default True) + - include_uploads: bool (default False) + - backup_target_first: bool (default True) + user_id: ID of the user performing the promotion + + Returns: + Dict with success status and promotion job details + """ + config = config or {} + + source_site = WordPressSite.query.get(source_site_id) + target_site = WordPressSite.query.get(target_site_id) + + if not source_site or not target_site: + return {'success': False, 'error': 'Source or target site not found'} + + # Check locks + for site, label in [(source_site, 'Source'), (target_site, 'Target')]: + if site.is_locked: + return {'success': False, 'error': f'{label} environment is locked: {site.locked_reason}'} + + start_time = time.time() + + # Create PromotionJob + job = PromotionJob( + source_site_id=source_site_id, + target_site_id=target_site_id, + user_id=user_id, + promotion_type='code', + config=json.dumps(config), + status='running', + started_at=datetime.utcnow(), + ) + db.session.add(job) + db.session.flush() + + activity = cls._create_activity( + site_id=target_site_id, + user_id=user_id, + action='promoted_code', + description=f'Code promotion from {source_site.environment_type} to {target_site.environment_type}', + status='running' + ) + + # Lock both environments + cls._lock_environment(source_site, 'Code promotion in progress (source)', user_id) + cls._lock_environment(target_site, 'Code promotion in progress (target)', user_id) + + try: + source_app = source_site.application + target_app = target_site.application + + if not source_app or not target_app: + raise ValueError('Source or target application record not found') + + source_compose = cls._get_compose_path(source_site) + target_compose = cls._get_compose_path(target_site) + + # Determine WordPress file paths + source_wp_dir = os.path.join(source_app.root_path, 'wordpress') if source_compose else source_app.root_path + target_wp_dir = os.path.join(target_app.root_path, 'wordpress') if target_compose else target_app.root_path + + if not os.path.exists(source_wp_dir): + raise ValueError(f'Source WordPress directory not found: {source_wp_dir}') + + cls._emit_progress(progress_callback, 1, 5, 'Locking environments...') + + # Step 1: Backup target wp-content if requested + pre_snapshot_id = None + if config.get('backup_target_first', True) and target_compose: + cls._emit_progress(progress_callback, 2, 5, 'Creating pre-promotion snapshot...') + target_vars = cls._read_env_vars(target_site) + snapshot_result = DatabaseSyncService.export_from_container( + compose_path=target_compose, + db_name=target_site.db_name, + db_user=target_vars.get('DB_USER', target_site.db_user), + db_password=target_vars.get('DB_PASSWORD'), + ) + if snapshot_result['success']: + # Save snapshot record + snapshot_record = DatabaseSnapshot( + site_id=target_site_id, + name=f'pre-promotion-{datetime.now().strftime("%Y%m%d_%H%M%S")}', + tag='pre-promotion', + file_path=snapshot_result['file_path'], + size_bytes=snapshot_result['size_bytes'], + compressed=snapshot_result['compressed'], + status='completed', + ) + db.session.add(snapshot_record) + db.session.flush() + pre_snapshot_id = snapshot_record.id + job.pre_promotion_snapshot_id = pre_snapshot_id + + cls._emit_progress(progress_callback, 3, 5, 'Syncing code files...') + + # Step 2: Rsync wp-content directories + sync_paths = [] + if config.get('include_plugins', True): + sync_paths.append('wp-content/plugins/') + if config.get('include_themes', True): + sync_paths.append('wp-content/themes/') + if config.get('include_mu_plugins', True): + sync_paths.append('wp-content/mu-plugins/') + if config.get('include_uploads', False): + sync_paths.append('wp-content/uploads/') + + for rel_path in sync_paths: + source_path = os.path.join(source_wp_dir, rel_path) + target_path = os.path.join(target_wp_dir, rel_path) + + if not os.path.exists(source_path): + continue + + os.makedirs(target_path, exist_ok=True) + + rsync_result = cls._rsync_directory(source_path, target_path) + if not rsync_result['success']: + raise ValueError(f'rsync failed for {rel_path}: {rsync_result.get("error")}') + + cls._emit_progress(progress_callback, 4, 5, 'Flushing caches...') + + # Step 3: Flush caches on target (if containers are running) + if target_compose: + EnvironmentDockerService.exec_in_container( + target_compose, 'wordpress', + 'wp cache flush --allow-root' + ) + + # Step 4: Search-replace for domain differences + target_domain = cls._get_primary_domain(target_site) + source_domain = cls._get_primary_domain(source_site) + if source_domain and target_domain and source_domain != target_domain: + # Domain replacement only needed if wp-config has hardcoded URLs + pass # wp-config handles this via WP_HOME/WP_SITEURL + + # Complete promotion job + job.status = 'completed' + job.completed_at = datetime.utcnow() + job.duration_seconds = time.time() - start_time + db.session.commit() + + cls._emit_progress(progress_callback, 5, 5, 'Complete') + + cls._unlock_environment(source_site) + cls._unlock_environment(target_site) + cls._finish_activity(activity, 'completed', None, start_time, { + 'promotion_job_id': job.id, + 'paths_synced': sync_paths, + 'pre_promotion_snapshot_id': pre_snapshot_id, + }) + + cls._send_notification('Code Promoted', { + 'message': f'Code promoted from {source_site.environment_type} to {target_site.environment_type}', + 'source': source_site.environment_type, + 'target': target_site.environment_type, + }, user_id) + + return { + 'success': True, + 'message': f'Code promoted from {source_site.environment_type} to {target_site.environment_type}', + 'promotion_job': job.to_dict(), + } + + except Exception as e: + job.status = 'failed' + job.error_message = str(e) + job.completed_at = datetime.utcnow() + job.duration_seconds = time.time() - start_time + db.session.commit() + + cls._unlock_environment(source_site) + cls._unlock_environment(target_site) + cls._finish_activity(activity, 'failed', str(e), start_time) + return {'success': False, 'error': str(e)} + + # ==================== DATABASE PROMOTION ==================== + + @classmethod + def promote_database(cls, source_site_id: int, target_site_id: int, + config: Dict = None, user_id: int = None, + progress_callback=None) -> Dict: + """ + Promote database from source environment to target. + + Exports source DB, applies transformations (search-replace, sanitization), + and imports into target. Creates a pre-promotion snapshot of target for safety. + + Args: + source_site_id: ID of the source WordPressSite + target_site_id: ID of the target WordPressSite + config: Promotion config: + - search_replace: Additional search/replace pairs + - sanitize: Whether to anonymize user data + - truncate_tables: Tables to empty + - exclude_tables: Tables to skip + - backup_target_first: bool (default True) + user_id: ID of the user performing the promotion + + Returns: + Dict with success status and promotion job details + """ + config = config or {} + + source_site = WordPressSite.query.get(source_site_id) + target_site = WordPressSite.query.get(target_site_id) + + if not source_site or not target_site: + return {'success': False, 'error': 'Source or target site not found'} + + # Check locks + for site, label in [(source_site, 'Source'), (target_site, 'Target')]: + if site.is_locked: + return {'success': False, 'error': f'{label} environment is locked: {site.locked_reason}'} + + start_time = time.time() + + job = PromotionJob( + source_site_id=source_site_id, + target_site_id=target_site_id, + user_id=user_id, + promotion_type='database', + config=json.dumps(config), + status='running', + started_at=datetime.utcnow(), + ) + db.session.add(job) + db.session.flush() + + activity = cls._create_activity( + site_id=target_site_id, + user_id=user_id, + action='promoted_database', + description=f'Database promotion from {source_site.environment_type} to {target_site.environment_type}', + status='running' + ) + + # Lock target + cls._lock_environment(target_site, 'Database promotion in progress', user_id) + cls._emit_progress(progress_callback, 1, 5, 'Locking environments...') + + try: + source_compose = cls._get_compose_path(source_site) + target_compose = cls._get_compose_path(target_site) + + cls._emit_progress(progress_callback, 2, 5, 'Creating pre-promotion snapshot...') + + # Step 1: Backup target DB + pre_snapshot_id = None + if config.get('backup_target_first', True): + if target_compose: + target_vars = cls._read_env_vars(target_site) + snapshot_result = DatabaseSyncService.export_from_container( + compose_path=target_compose, + db_name=target_site.db_name, + db_user=target_vars.get('DB_USER', target_site.db_user), + db_password=target_vars.get('DB_PASSWORD'), + ) + else: + snapshot_result = DatabaseSyncService.create_snapshot( + db_name=target_site.db_name, + name=f'pre-promotion-{datetime.now().strftime("%Y%m%d_%H%M%S")}', + tag='pre-promotion', + host=target_site.db_host or 'localhost', + user=target_site.db_user, + password=cls._get_db_password_from_config(target_site), + ) + + if snapshot_result['success']: + file_path = snapshot_result.get('file_path') or snapshot_result.get('snapshot', {}).get('file_path') + size_bytes = snapshot_result.get('size_bytes') or snapshot_result.get('snapshot', {}).get('size_bytes', 0) + + snapshot_record = DatabaseSnapshot( + site_id=target_site_id, + name=f'pre-promotion-{datetime.now().strftime("%Y%m%d_%H%M%S")}', + tag='pre-promotion', + file_path=file_path, + size_bytes=size_bytes, + compressed=snapshot_result.get('compressed', True), + status='completed', + ) + db.session.add(snapshot_record) + db.session.flush() + pre_snapshot_id = snapshot_record.id + job.pre_promotion_snapshot_id = pre_snapshot_id + + cls._emit_progress(progress_callback, 3, 5, 'Cloning database with transformations...') + + # Step 2: Clone DB with transformations + clone_options = { + 'search_replace': config.get('search_replace', {}), + 'truncate_tables': config.get('truncate_tables', []), + 'exclude_tables': config.get('exclude_tables', []), + 'anonymize': config.get('sanitize', False), + } + + # Auto-add domain search-replace + source_domain = cls._get_primary_domain(source_site) + target_domain = cls._get_primary_domain(target_site) + if source_domain and target_domain and source_domain != target_domain: + clone_options['search_replace'].update({ + f'https://{source_domain}': f'https://{target_domain}', + f'http://{source_domain}': f'http://{target_domain}', + source_domain: target_domain, + }) + + if source_compose and target_compose: + clone_result = DatabaseSyncService.clone_between_containers( + source_compose_path=source_compose, + target_compose_path=target_compose, + source_db=source_site.db_name, + target_db=target_site.db_name, + source_user=source_site.db_user, + target_user=target_site.db_user, + source_password=cls._get_env_password(source_site), + target_password=cls._get_env_password(target_site), + options=clone_options, + ) + else: + clone_result = DatabaseSyncService.clone_database( + source_db=source_site.db_name, + target_db=target_site.db_name, + source_host=source_site.db_host or 'localhost', + target_host=target_site.db_host or 'localhost', + source_user=source_site.db_user, + target_user=target_site.db_user, + source_password=cls._get_db_password_from_config(source_site), + target_password=cls._get_db_password_from_config(target_site), + options=clone_options, + ) + + if not clone_result['success']: + raise ValueError(f"Database clone failed: {clone_result.get('error')}") + + cls._emit_progress(progress_callback, 4, 5, 'Flushing caches...') + + # Step 3: Flush caches + if target_compose: + EnvironmentDockerService.exec_in_container( + target_compose, 'wordpress', + 'wp cache flush --allow-root' + ) + + cls._emit_progress(progress_callback, 5, 5, 'Complete') + + # Complete + job.status = 'completed' + job.completed_at = datetime.utcnow() + job.duration_seconds = time.time() - start_time + db.session.commit() + + cls._unlock_environment(target_site) + cls._finish_activity(activity, 'completed', None, start_time, { + 'promotion_job_id': job.id, + 'pre_promotion_snapshot_id': pre_snapshot_id, + }) + + cls._send_notification('Database Promoted', { + 'message': f'Database promoted from {source_site.environment_type} to {target_site.environment_type}', + 'source': source_site.environment_type, + 'target': target_site.environment_type, + }, user_id) + + return { + 'success': True, + 'message': f'Database promoted from {source_site.environment_type} to {target_site.environment_type}', + 'promotion_job': job.to_dict(), + } + + except Exception as e: + job.status = 'failed' + job.error_message = str(e) + job.completed_at = datetime.utcnow() + job.duration_seconds = time.time() - start_time + db.session.commit() + + cls._unlock_environment(target_site) + cls._finish_activity(activity, 'failed', str(e), start_time) + return {'success': False, 'error': str(e)} + + # ==================== FULL PROMOTION ==================== + + @classmethod + def promote_full(cls, source_site_id: int, target_site_id: int, + config: Dict = None, user_id: int = None, + progress_callback=None) -> Dict: + """ + Promote both code and database from source to target. + + Runs promote_code followed by promote_database sequentially. + + Args: + source_site_id: ID of the source WordPressSite + target_site_id: ID of the target WordPressSite + config: Combined promotion config + user_id: ID of the user performing the promotion + + Returns: + Dict with success status and both promotion results + """ + config = config or {} + + # Promote code first + code_result = cls.promote_code( + source_site_id=source_site_id, + target_site_id=target_site_id, + config=config, + user_id=user_id, + progress_callback=progress_callback + ) + + if not code_result['success']: + return { + 'success': False, + 'error': f"Code promotion failed: {code_result.get('error')}", + 'code_result': code_result, + 'db_result': None, + } + + # Then promote database + db_result = cls.promote_database( + source_site_id=source_site_id, + target_site_id=target_site_id, + config=config, + user_id=user_id, + progress_callback=progress_callback + ) + + if not db_result['success']: + return { + 'success': False, + 'error': f"Database promotion failed (code was promoted): {db_result.get('error')}", + 'code_result': code_result, + 'db_result': db_result, + } + + cls._send_notification('Full Promotion Completed', { + 'message': 'Full promotion completed (code + database)', + }, user_id) + + return { + 'success': True, + 'message': 'Full promotion completed (code + database)', + 'code_result': code_result, + 'db_result': db_result, + } + + # ==================== ENVIRONMENT LOCKING ==================== + + @classmethod + def lock_environment(cls, site_id: int, reason: str, + user_id: int = None, duration_minutes: int = 30) -> Dict: + """ + Lock an environment to prevent concurrent operations. + + Args: + site_id: WordPressSite ID + reason: Why it's being locked + user_id: Who is locking it + duration_minutes: Auto-unlock after this many minutes + + Returns: + Dict with success status + """ + site = WordPressSite.query.get(site_id) + if not site: + return {'success': False, 'error': 'Site not found'} + + if site.is_locked: + return {'success': False, 'error': f'Already locked: {site.locked_reason}'} + + cls._lock_environment(site, reason, user_id, duration_minutes) + + cls._create_activity( + site_id=site_id, + user_id=user_id, + action='locked', + description=f'Environment locked: {reason}', + status='completed', + metadata={'reason': reason, 'duration_minutes': duration_minutes} + ) + + return {'success': True, 'message': f'Environment locked: {reason}'} + + @classmethod + def unlock_environment(cls, site_id: int, user_id: int = None) -> Dict: + """ + Unlock an environment. + + Args: + site_id: WordPressSite ID + user_id: Who is unlocking it + + Returns: + Dict with success status + """ + site = WordPressSite.query.get(site_id) + if not site: + return {'success': False, 'error': 'Site not found'} + + if not site.is_locked: + return {'success': True, 'message': 'Environment was not locked'} + + cls._unlock_environment(site) + + cls._create_activity( + site_id=site_id, + user_id=user_id, + action='unlocked', + description='Environment unlocked', + status='completed' + ) + + return {'success': True, 'message': 'Environment unlocked'} + + # ==================== PIPELINE STATUS ==================== + + @classmethod + def get_pipeline_status(cls, production_site_id: int) -> Dict: + """ + Get full pipeline status for a WordPress project. + + Returns all environments with their status, last sync, last promotion, + container health, and activity counts. + + Args: + production_site_id: ID of the production WordPressSite + + Returns: + Dict with production info and all environment statuses + """ + prod_site = WordPressSite.query.get(production_site_id) + if not prod_site: + return {'success': False, 'error': 'Production site not found'} + + prod_data = prod_site.to_dict() + + # Get container status for production + prod_compose = cls._get_compose_path(prod_site) + if prod_compose: + prod_data['container_status'] = EnvironmentDockerService.get_environment_status(prod_compose) + + # Get all child environments + environments = [] + for env in prod_site.environments: + env_data = env.to_dict() + + # Container status + env_compose = cls._get_compose_path(env) + if env_compose: + env_data['container_status'] = EnvironmentDockerService.get_environment_status(env_compose) + + # Last promotion (as target) + last_promotion = PromotionJob.query.filter_by( + target_site_id=env.id + ).order_by(PromotionJob.created_at.desc()).first() + if last_promotion: + env_data['last_promotion'] = { + 'id': last_promotion.id, + 'type': last_promotion.promotion_type, + 'status': last_promotion.status, + 'created_at': last_promotion.created_at.isoformat() if last_promotion.created_at else None, + } + + # Recent activity count + recent_cutoff = datetime.utcnow() - timedelta(days=7) + env_data['recent_activity_count'] = EnvironmentActivity.query.filter( + EnvironmentActivity.site_id == env.id, + EnvironmentActivity.created_at >= recent_cutoff + ).count() + + environments.append(env_data) + + # Sort: staging first, then development, then multidevs + type_order = {'staging': 0, 'development': 1, 'multidev': 2} + environments.sort(key=lambda e: type_order.get(e.get('environment_type', ''), 3)) + + return { + 'success': True, + 'production': prod_data, + 'environments': environments, + 'total_environments': len(environments), + } + + # ==================== ENVIRONMENT COMPARISON ==================== + + @classmethod + def compare_environments(cls, site_id_a: int, site_id_b: int) -> Dict: + """ + Compare two environments (plugins, themes, WP version, PHP version). + + Args: + site_id_a: First WordPressSite ID + site_id_b: Second WordPressSite ID + + Returns: + Dict with comparison data (differences and matches) + """ + site_a = WordPressSite.query.get(site_id_a) + site_b = WordPressSite.query.get(site_id_b) + + if not site_a or not site_b: + return {'success': False, 'error': 'One or both sites not found'} + + comparison = { + 'site_a': {'id': site_a.id, 'type': site_a.environment_type}, + 'site_b': {'id': site_b.id, 'type': site_b.environment_type}, + 'differences': [], + 'matches': [], + } + + # Compare basic fields + for field, label in [ + ('wp_version', 'WordPress Version'), + ('db_prefix', 'Table Prefix'), + ('multisite', 'Multisite'), + ]: + val_a = getattr(site_a, field) + val_b = getattr(site_b, field) + entry = {'field': label, 'a': str(val_a), 'b': str(val_b)} + if val_a != val_b: + comparison['differences'].append(entry) + else: + comparison['matches'].append(entry) + + # Compare PHP versions + app_a = site_a.application + app_b = site_b.application + if app_a and app_b: + if app_a.php_version != app_b.php_version: + comparison['differences'].append({ + 'field': 'PHP Version', + 'a': app_a.php_version or 'default', + 'b': app_b.php_version or 'default', + }) + else: + comparison['matches'].append({ + 'field': 'PHP Version', + 'a': app_a.php_version or 'default', + 'b': app_b.php_version or 'default', + }) + + # Compare plugins via WP-CLI (if containers are running) + compose_a = cls._get_compose_path(site_a) + compose_b = cls._get_compose_path(site_b) + + if compose_a and compose_b: + plugins_a = cls._get_wp_plugins(compose_a) + plugins_b = cls._get_wp_plugins(compose_b) + + if plugins_a is not None and plugins_b is not None: + all_plugins = set(list(plugins_a.keys()) + list(plugins_b.keys())) + plugin_diffs = [] + plugin_matches = [] + + for plugin in sorted(all_plugins): + ver_a = plugins_a.get(plugin, 'not installed') + ver_b = plugins_b.get(plugin, 'not installed') + entry = {'plugin': plugin, 'a': ver_a, 'b': ver_b} + if ver_a != ver_b: + plugin_diffs.append(entry) + else: + plugin_matches.append(entry) + + comparison['plugin_differences'] = plugin_diffs + comparison['plugin_matches'] = plugin_matches + + comparison['success'] = True + return comparison + + # ==================== DELETE ENVIRONMENT ==================== + + @classmethod + def delete_environment(cls, env_site_id: int, user_id: int = None) -> Dict: + """ + Delete an environment and all its resources. + + Stops containers, removes Docker stack, deletes files, Nginx config, + and database records. + + Args: + env_site_id: ID of the environment's WordPressSite + user_id: ID of the user deleting the environment + + Returns: + Dict with success status + """ + env_site = WordPressSite.query.get(env_site_id) + if not env_site: + return {'success': False, 'error': 'Environment not found'} + + if env_site.is_production or env_site.environment_type == 'production': + return {'success': False, 'error': 'Cannot delete a production environment'} + + if env_site.is_locked: + return {'success': False, 'error': f'Environment is locked: {env_site.locked_reason}'} + + start_time = time.time() + activity = cls._create_activity( + site_id=env_site.production_site_id or env_site_id, + user_id=user_id, + action='environment_deleted', + description=f'Deleting {env_site.environment_type} environment', + status='running' + ) + + try: + env_app = env_site.application + + # Step 1: Stop and destroy Docker containers + compose_path = cls._get_compose_path(env_site) + if compose_path and os.path.exists(compose_path): + EnvironmentDockerService.destroy_environment(compose_path, remove_volumes=True) + + # Step 2: Remove Nginx config + if env_site.compose_project_name and env_site.container_prefix: + site_name = f'wp-{env_site.container_prefix}' + EnvironmentDomainService.remove_nginx_config(site_name) + + # Step 3: Delete related records + # Delete promotions involving this site + PromotionJob.query.filter( + (PromotionJob.source_site_id == env_site_id) | + (PromotionJob.target_site_id == env_site_id) + ).delete(synchronize_session='fetch') + + # Delete activities for this site + EnvironmentActivity.query.filter_by(site_id=env_site_id).delete(synchronize_session='fetch') + + # Delete snapshots + for snapshot in env_site.snapshots: + if snapshot.file_path and os.path.exists(snapshot.file_path): + os.remove(snapshot.file_path) + + # Step 4: Delete WordPressSite and Application records + db.session.delete(env_site) + if env_app: + db.session.delete(env_app) + + db.session.commit() + + cls._finish_activity(activity, 'completed', None, start_time, { + 'deleted_site_id': env_site_id, + }) + + return {'success': True, 'message': 'Environment deleted successfully'} + + except Exception as e: + db.session.rollback() + cls._finish_activity(activity, 'failed', str(e), start_time) + return {'success': False, 'error': str(e)} + + # ==================== MULTIDEV CLEANUP ==================== + + @classmethod + def cleanup_stale_multidevs(cls, production_site_id: int, + dry_run: bool = True, + user_id: int = None) -> Dict: + """ + Find and optionally delete multidev environments whose branches + no longer exist on the remote. + + Args: + production_site_id: ID of the production WordPressSite + dry_run: If True, only report stale envs without deleting + user_id: ID of the user performing the cleanup + + Returns: + Dict with list of stale environments and cleanup results + """ + from app.services.git_wordpress_service import GitWordPressService + + prod_site = WordPressSite.query.get(production_site_id) + if not prod_site: + return {'success': False, 'error': 'Production site not found'} + + if not prod_site.git_repo_url: + return {'success': False, 'error': 'No repository connected to production site'} + + # Get current remote branches + branches_result = GitWordPressService.list_branches(production_site_id) + if not branches_result.get('success'): + return {'success': False, 'error': f"Failed to list branches: {branches_result.get('error')}"} + + remote_branches = {b['name'] for b in branches_result.get('branches', [])} + + # Find multidev environments with missing branches + multidev_envs = WordPressSite.query.filter_by( + production_site_id=production_site_id, + environment_type='multidev' + ).all() + + stale = [] + cleaned = [] + errors = [] + + for env in multidev_envs: + if env.multidev_branch and env.multidev_branch not in remote_branches: + stale.append({ + 'id': env.id, + 'name': env.application.name if env.application else f'env-{env.id}', + 'branch': env.multidev_branch, + 'created_at': env.created_at.isoformat() if env.created_at else None, + }) + + if not dry_run: + result = cls.delete_environment(env.id, user_id=user_id) + if result.get('success'): + cleaned.append(env.id) + else: + errors.append({ + 'id': env.id, + 'error': result.get('error') + }) + + return { + 'success': True, + 'dry_run': dry_run, + 'stale_environments': stale, + 'stale_count': len(stale), + 'cleaned_count': len(cleaned), + 'errors': errors, + } + + # ==================== PRIVATE HELPERS ==================== + + @classmethod + def _get_compose_path(cls, site: WordPressSite) -> Optional[str]: + """Get the docker-compose.yml path for a site's environment.""" + if not site.compose_project_name or not site.container_prefix: + return None + + # Determine env type directory from container_prefix + project_name = site.compose_project_name + prefix = site.container_prefix + env_type_dir = prefix.replace(f'{project_name}-', '', 1) if prefix.startswith(project_name) else prefix + + compose_path = os.path.join( + EnvironmentDockerService.get_env_directory(project_name, env_type_dir), + 'docker-compose.yml' + ) + + if os.path.exists(compose_path): + return compose_path + return None + + @classmethod + def _get_env_password(cls, site: WordPressSite) -> Optional[str]: + """Get the DB password from a site's Docker .env file.""" + compose_path = cls._get_compose_path(site) + if not compose_path: + return cls._get_db_password_from_config(site) + + env_file = os.path.join(os.path.dirname(compose_path), '.env') + if os.path.exists(env_file): + try: + with open(env_file, 'r') as f: + for line in f: + if line.startswith('DB_PASSWORD='): + return line.strip().split('=', 1)[1] + except Exception: + pass + + return cls._get_db_password_from_config(site) + + @classmethod + def _read_env_vars(cls, site: WordPressSite) -> Dict: + """Read all env vars from a site's Docker .env file.""" + compose_path = cls._get_compose_path(site) + if not compose_path: + return {} + + env_file = os.path.join(os.path.dirname(compose_path), '.env') + env_vars = {} + if os.path.exists(env_file): + try: + with open(env_file, 'r') as f: + for line in f: + line = line.strip() + if '=' in line and not line.startswith('#'): + key, value = line.split('=', 1) + env_vars[key] = value + except Exception: + pass + return env_vars + + @classmethod + def _get_db_password_from_config(cls, site: WordPressSite) -> Optional[str]: + """Get database password from wp-config.php.""" + if not site.application or not site.application.root_path: + return None + + config_path = os.path.join(site.application.root_path, 'wp-config.php') + if not os.path.exists(config_path): + return None + + try: + import re + with open(config_path, 'r') as f: + content = f.read() + match = re.search(r"define\s*\(\s*['\"]DB_PASSWORD['\"]\s*,\s*['\"]([^'\"]*)['\"]", content) + return match.group(1) if match else None + except Exception: + return None + + @classmethod + def _get_primary_domain(cls, site: WordPressSite) -> Optional[str]: + """Get the primary domain for a site.""" + if not site.application: + return None + domains = list(site.application.domains) + if domains: + return domains[0].domain + return None + + @classmethod + def _lock_environment(cls, site: WordPressSite, reason: str, + user_id: int = None, duration_minutes: int = 30): + """Lock an environment (internal helper, no activity log).""" + site.is_locked = True + site.locked_by = str(user_id) if user_id else 'system' + site.locked_reason = reason + site.lock_expires_at = datetime.utcnow() + timedelta(minutes=duration_minutes) + db.session.commit() + + @classmethod + def _unlock_environment(cls, site: WordPressSite): + """Unlock an environment (internal helper, no activity log).""" + site.is_locked = False + site.locked_by = None + site.locked_reason = None + site.lock_expires_at = None + db.session.commit() + + @classmethod + def _create_activity(cls, site_id: int, user_id: int, action: str, + description: str, status: str = 'completed', + metadata: Dict = None) -> EnvironmentActivity: + """Create an activity log entry.""" + activity = EnvironmentActivity( + site_id=site_id, + user_id=user_id, + action=action, + description=description, + status=status, + activity_metadata=json.dumps(metadata) if metadata else None, + created_at=datetime.utcnow(), + ) + db.session.add(activity) + db.session.flush() + return activity + + @classmethod + def _finish_activity(cls, activity: EnvironmentActivity, status: str, + error: str = None, start_time: float = None, + metadata: Dict = None): + """Finish an activity log entry.""" + activity.status = status + activity.error_message = error + if start_time: + activity.duration_seconds = time.time() - start_time + if metadata: + existing = json.loads(activity.activity_metadata) if activity.activity_metadata else {} + existing.update(metadata) + activity.activity_metadata = json.dumps(existing) + db.session.commit() + + @classmethod + def _copy_wordpress_files(cls, source_dir: str, target_dir: str) -> Dict: + """Copy WordPress files from source to target directory.""" + try: + if os.path.exists(target_dir): + shutil.rmtree(target_dir) + + shutil.copytree(source_dir, target_dir) + + # Set permissions + subprocess.run( + ['sudo', 'chown', '-R', 'www-data:www-data', target_dir], + capture_output=True, timeout=60 + ) + + return {'success': True} + except Exception as e: + return {'success': False, 'error': f'Failed to copy files: {str(e)}'} + + @classmethod + def _sync_wordpress_files(cls, source_dir: str, target_dir: str) -> Dict: + """Sync WordPress files using rsync (more efficient than full copy).""" + try: + result = subprocess.run( + [ + 'rsync', '-a', '--delete', + '--exclude', '.git', + '--exclude', 'wp-config.php', + '--exclude', '.env', + f'{source_dir}/', + f'{target_dir}/' + ], + capture_output=True, + text=True, + timeout=300 + ) + + if result.returncode != 0: + return {'success': False, 'error': f'rsync failed: {result.stderr}'} + + return {'success': True} + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'File sync timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def _rsync_directory(cls, source: str, target: str) -> Dict: + """Rsync a single directory from source to target.""" + try: + os.makedirs(target, exist_ok=True) + + result = subprocess.run( + [ + 'rsync', '-a', '--delete', + '--exclude', '.git', + f'{source}', + f'{target}' + ], + capture_output=True, + text=True, + timeout=300 + ) + + if result.returncode != 0: + return {'success': False, 'error': result.stderr} + + return {'success': True} + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'rsync timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def _wait_for_mysql(cls, compose_path: str, db_user: str, db_password: str, + max_attempts: int = 30, interval: int = 2): + """Wait for MySQL to be ready inside the container.""" + for attempt in range(max_attempts): + result = EnvironmentDockerService.exec_in_container( + compose_path, 'db', + f'mysqladmin -u {db_user} -p{db_password} ping' + ) + if result.get('success'): + return True + time.sleep(interval) + + return False + + @classmethod + def _get_wp_plugins(cls, compose_path: str) -> Optional[Dict]: + """Get installed plugins and versions via WP-CLI.""" + result = EnvironmentDockerService.exec_in_container( + compose_path, 'wordpress', + 'wp plugin list --format=json --allow-root' + ) + + if not result.get('success'): + return None + + try: + plugins_list = json.loads(result['output']) + return {p['name']: p.get('version', 'unknown') for p in plugins_list} + except (json.JSONDecodeError, KeyError): + return None + + @staticmethod + def _slugify(text: str) -> str: + """Convert text to a URL/filesystem-safe slug.""" + import re + text = text.lower() + text = re.sub(r'[^a-z0-9]+', '-', text) + text = text.strip('-') + return text or 'site' + + @staticmethod + def _generate_password(length: int = 32) -> str: + """Generate a secure random password.""" + chars = string.ascii_letters + string.digits + return ''.join(secrets.choice(chars) for _ in range(length)) diff --git a/backend/app/services/git_wordpress_service.py b/backend/app/services/git_wordpress_service.py index abfd91cd..7dbe19da 100644 --- a/backend/app/services/git_wordpress_service.py +++ b/backend/app/services/git_wordpress_service.py @@ -380,6 +380,111 @@ class GitWordPressService: except Exception as e: return {'success': False, 'error': str(e)} + @classmethod + def list_branches(cls, site_id: int) -> Dict: + """ + List remote branches for a site's connected repository. + + Args: + site_id: ID of the WordPressSite + + Returns: + Dict with list of branches and their latest commit info + """ + site = WordPressSite.query.get(site_id) + if not site: + return {'success': False, 'error': 'Site not found'} + + if not site.git_repo_url: + return {'success': False, 'error': 'No repository connected'} + + if not site.application or not site.application.root_path: + return {'success': False, 'error': 'Site application path not found'} + + wp_content_path = os.path.join(site.application.root_path, 'wp-content') + git_dir = os.path.join(wp_content_path, '.git') + + try: + if os.path.exists(git_dir): + # Fetch latest from remote + cls._run_git(wp_content_path, ['fetch', '--prune', 'origin']) + + # List remote branches with latest commit info + log_format = '%(refname:short)|%(objectname:short)|%(subject)|%(authorname)|%(creatordate:iso8601)' + result = cls._run_git(wp_content_path, [ + 'for-each-ref', + '--sort=-creatordate', + f'--format={log_format}', + 'refs/remotes/origin/' + ]) + else: + # No local clone — use ls-remote to list branches + result = subprocess.run( + ['git', 'ls-remote', '--heads', site.git_repo_url], + capture_output=True, text=True, timeout=30 + ) + if result.returncode != 0: + return {'success': False, 'error': f'Failed to list branches: {result.stderr}'} + + branches = [] + for line in result.stdout.strip().split('\n'): + if not line: + continue + sha, ref = line.split('\t') + branch_name = ref.replace('refs/heads/', '') + branches.append({ + 'name': branch_name, + 'short_sha': sha[:7], + 'message': '', + 'author': '', + 'date': '', + 'is_current': branch_name == site.git_branch, + }) + return {'success': True, 'branches': branches} + + if not result['success']: + return result + + branches = [] + existing_multidevs = set() + for env in site.environments: + if env.environment_type == 'multidev' and env.multidev_branch: + existing_multidevs.add(env.multidev_branch) + + for line in result['output'].strip().split('\n'): + if not line: + continue + parts = line.split('|') + if len(parts) < 5: + continue + + ref_name = parts[0] + # Strip 'origin/' prefix + branch_name = ref_name.replace('origin/', '', 1) + + # Skip HEAD pointer + if branch_name == 'HEAD': + continue + + branches.append({ + 'name': branch_name, + 'short_sha': parts[1], + 'message': parts[2], + 'author': parts[3], + 'date': parts[4], + 'is_current': branch_name == site.git_branch, + 'has_multidev': branch_name in existing_multidevs, + }) + + return { + 'success': True, + 'branches': branches, + 'current_branch': site.git_branch, + } + + except Exception as e: + return {'success': False, 'error': str(e)} + @classmethod def rollback_to_commit(cls, site_id: int, commit_sha: str) -> Dict: """ diff --git a/backend/app/services/template_service.py b/backend/app/services/template_service.py index e2b1c1f8..1c6d54ae 100644 --- a/backend/app/services/template_service.py +++ b/backend/app/services/template_service.py @@ -30,6 +30,7 @@ class TemplateService: CONFIG_DIR = '/etc/serverkit' TEMPLATES_DIR = '/etc/serverkit/templates' + LOCAL_TEMPLATES_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'templates') INSTALLED_DIR = '/var/serverkit/apps' TEMPLATE_CONFIG = os.path.join(CONFIG_DIR, 'templates.json') @@ -350,26 +351,32 @@ class TemplateService: def list_local_templates(cls) -> List[Dict]: """List locally available templates.""" templates = [] + seen_ids = set() - if not os.path.exists(cls.TEMPLATES_DIR): - return templates + for templates_dir in [cls.TEMPLATES_DIR, cls.LOCAL_TEMPLATES_DIR]: + if not os.path.exists(templates_dir): + continue - for filename in os.listdir(cls.TEMPLATES_DIR): - if filename.endswith('.yaml') or filename.endswith('.yml'): - filepath = os.path.join(cls.TEMPLATES_DIR, filename) - result = cls.parse_template(filepath) - if result.get('success'): - template = result['template'] - templates.append({ - 'id': filename.rsplit('.', 1)[0], - 'name': template.get('name'), - 'version': template.get('version'), - 'description': template.get('description'), - 'icon': template.get('icon'), - 'categories': template.get('categories', []), - 'source': 'local', - 'filepath': filepath - }) + for filename in os.listdir(templates_dir): + if filename.endswith('.yaml') or filename.endswith('.yml'): + template_id = filename.rsplit('.', 1)[0] + if template_id in seen_ids: + continue + filepath = os.path.join(templates_dir, filename) + result = cls.parse_template(filepath) + if result.get('success'): + template = result['template'] + seen_ids.add(template_id) + templates.append({ + 'id': template_id, + 'name': template.get('name'), + 'version': template.get('version'), + 'description': template.get('description'), + 'icon': template.get('icon'), + 'categories': template.get('categories', []), + 'source': 'local', + 'filepath': filepath + }) return templates @@ -427,17 +434,18 @@ class TemplateService: @classmethod def get_template(cls, template_id: str) -> Dict: """Get full template details.""" - # Check local first - for ext in ['.yaml', '.yml']: - filepath = os.path.join(cls.TEMPLATES_DIR, f"{template_id}{ext}") - if os.path.exists(filepath): - result = cls.parse_template(filepath) - if result.get('success'): - template = result['template'] - template['source'] = 'local' - template['filepath'] = filepath - return {'success': True, 'template': template} - return result + # Check local directories (system dir, then bundled fallback) + for templates_dir in [cls.TEMPLATES_DIR, cls.LOCAL_TEMPLATES_DIR]: + for ext in ['.yaml', '.yml']: + filepath = os.path.join(templates_dir, f"{template_id}{ext}") + if os.path.exists(filepath): + result = cls.parse_template(filepath) + if result.get('success'): + template = result['template'] + template['source'] = 'local' + template['filepath'] = filepath + return {'success': True, 'template': template} + return result # Check remote repos config = cls.get_config() diff --git a/backend/app/services/wordpress_env_service.py b/backend/app/services/wordpress_env_service.py index ffb0b0b3..11b72453 100644 --- a/backend/app/services/wordpress_env_service.py +++ b/backend/app/services/wordpress_env_service.py @@ -3,6 +3,10 @@ WordPress Environment Service Manage WordPress production/development/staging environments. Handles environment creation, database cloning, and synchronization. + +For Docker-isolated environments (compose_project_name set), delegates to +EnvironmentPipelineService. For legacy/standalone environments, handles +directly using host MySQL and file system operations. """ import os @@ -30,6 +34,10 @@ class WordPressEnvService: """ Create a new environment linked to production. + If config['isolated'] is True, delegates to EnvironmentPipelineService + for full Docker-isolated environment creation. Otherwise uses the + legacy shared-host approach. + Args: production_site_id: ID of the production WordPressSite env_type: 'development' or 'staging' @@ -39,11 +47,22 @@ class WordPressEnvService: - port: Optional custom port - clone_db: Whether to clone the production database - sync_schedule: Optional cron schedule for auto-sync + - isolated: If True, use Docker-isolated pipeline (default False) user_id: User ID creating the environment Returns: Dict with success status and environment info """ + # Delegate to pipeline service for Docker-isolated environments + if config.get('isolated'): + from app.services.environment_pipeline_service import EnvironmentPipelineService + return EnvironmentPipelineService.create_project_environment( + production_site_id=production_site_id, + env_type=env_type, + config=config, + user_id=user_id + ) + # Validate environment type if env_type not in ['development', 'staging']: return {'success': False, 'error': 'Invalid environment type. Must be development or staging.'} @@ -213,6 +232,9 @@ class WordPressEnvService: """ Sync an environment from its production source. + Docker-isolated environments (those with compose_project_name) are + delegated to EnvironmentPipelineService for container-aware sync. + Args: env_site_id: ID of the environment WordPressSite to sync options: Optional override options for sync @@ -229,6 +251,16 @@ class WordPressEnvService: if env_site.is_production: return {'success': False, 'error': 'Cannot sync a production site'} + # Delegate Docker-isolated environments to pipeline service + if env_site.compose_project_name: + from app.services.environment_pipeline_service import EnvironmentPipelineService + return EnvironmentPipelineService.sync_from_production( + env_site_id=env_site_id, + sync_type=options.pop('sync_type', 'full'), + options=options, + user_id=options.pop('user_id', None) + ) + prod_site = env_site.production_site if not prod_site: return {'success': False, 'error': 'Production site not found'} @@ -325,14 +357,18 @@ class WordPressEnvService: @classmethod def delete_environment(cls, env_site_id: int, delete_files: bool = True, - delete_database: bool = True) -> Dict: + delete_database: bool = True, user_id: int = None) -> Dict: """ Delete an environment. + Docker-isolated environments are delegated to EnvironmentPipelineService + for proper container and Nginx cleanup. + Args: env_site_id: ID of the environment WordPressSite delete_files: Whether to delete WordPress files delete_database: Whether to drop the database + user_id: ID of the user performing the deletion Returns: Dict with success status @@ -344,6 +380,14 @@ class WordPressEnvService: if env_site.is_production: return {'success': False, 'error': 'Cannot delete a production site this way'} + # Delegate Docker-isolated environments to pipeline service + if env_site.compose_project_name: + from app.services.environment_pipeline_service import EnvironmentPipelineService + return EnvironmentPipelineService.delete_environment( + env_site_id=env_site_id, + user_id=user_id + ) + env_app = env_site.application try: diff --git a/backend/app/sockets.py b/backend/app/sockets.py index ba31909a..f7062e63 100644 --- a/backend/app/sockets.py +++ b/backend/app/sockets.py @@ -24,6 +24,9 @@ build_log_queues = {} # app_id -> queue # Store active container log streams container_log_streams = {} # sid -> {'process': Popen, 'app_id': int, 'thread': Thread, 'stop_event': Event} +# Store active pipeline subscriptions +pipeline_subscribers = {} # sid -> set of project_ids + def init_socketio(app): """Initialize SocketIO with the Flask app.""" @@ -67,6 +70,9 @@ def handle_disconnect(): # Stop any container log streams for this client stop_container_log_stream(sid) + # Remove from pipeline subscribers + pipeline_subscribers.pop(sid, None) + @socketio.on('subscribe_metrics') def handle_subscribe_metrics(): @@ -450,3 +456,72 @@ def emit_container_log(app_id: int, line: str, level: str = 'info'): }, 'timestamp': time.time() }, room=f'logs_{app_id}') + + +# ==================== PIPELINE EVENT STREAMING ==================== + +@socketio.on('subscribe_pipeline') +def handle_subscribe_pipeline(data): + """Subscribe to real-time pipeline events for a WordPress project. + + data: { + 'project_id': int (production site ID) + } + + Emits 'pipeline_event' with: + - project_id: int + - event: string (e.g. 'promotion_started', 'sync_completed') + - data: dict with event-specific details + - timestamp: float + """ + sid = request.sid + project_id = data.get('project_id') + + if not project_id: + emit('error', {'message': 'project_id required'}) + return + + room = f'pipeline_{project_id}' + join_room(room) + + if sid not in pipeline_subscribers: + pipeline_subscribers[sid] = set() + pipeline_subscribers[sid].add(project_id) + + emit('subscribed', {'channel': 'pipeline', 'project_id': project_id}) + + +@socketio.on('unsubscribe_pipeline') +def handle_unsubscribe_pipeline(data): + """Unsubscribe from pipeline events for a project.""" + sid = request.sid + project_id = data.get('project_id') + + if project_id: + leave_room(f'pipeline_{project_id}') + if sid in pipeline_subscribers: + pipeline_subscribers[sid].discard(project_id) + if not pipeline_subscribers[sid]: + del pipeline_subscribers[sid] + + emit('unsubscribed', {'channel': 'pipeline', 'project_id': project_id}) + + +def emit_pipeline_event(project_id: int, event: str, data: dict = None): + """Emit a pipeline event to all subscribers of a project. + + Called from EnvironmentPipelineService or API endpoints to notify + the frontend about long-running operations (promote, sync, create). + + Args: + project_id: Production site ID + event: Event type (e.g. 'promotion_started', 'sync_completed', + 'environment_created', 'environment_deleted') + data: Event-specific payload + """ + socketio.emit('pipeline_event', { + 'project_id': project_id, + 'event': event, + 'data': data or {}, + 'timestamp': time.time() + }, room=f'pipeline_{project_id}') diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 1cf2434b..e4f65f38 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -32,6 +32,8 @@ import ServerDetail from './pages/ServerDetail'; import Downloads from './pages/Downloads'; import WordPress from './pages/WordPress'; import WordPressDetail from './pages/WordPressDetail'; +import WordPressProjects from './pages/WordPressProjects'; +import WordPressProject from './pages/WordPressProject'; import SSLCertificates from './pages/SSLCertificates'; // Page title mapping @@ -42,6 +44,7 @@ const PAGE_TITLES = { '/setup': 'Setup', '/apps': 'Applications', '/wordpress': 'WordPress Sites', + '/wordpress/projects': 'WordPress Projects', '/templates': 'Templates', '/workflow': 'Workflow Builder', '/domains': 'Domains', @@ -72,6 +75,7 @@ function PageTitleUpdater() { if (!title) { if (path.startsWith('/apps/')) title = 'Application Details'; else if (path.startsWith('/servers/')) title = 'Server Details'; + else if (path.startsWith('/wordpress/projects/')) title = 'WordPress Pipeline'; else if (path.startsWith('/wordpress/')) title = 'WordPress Site'; else title = 'ServerKit'; } @@ -159,6 +163,8 @@ function AppRoutes() { } /> } /> } /> + } /> + } /> } /> } /> } /> diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx index 045db719..cd8611b3 100644 --- a/frontend/src/components/Sidebar.jsx +++ b/frontend/src/components/Sidebar.jsx @@ -118,6 +118,12 @@ const Sidebar = () => { WordPress + `nav-item nav-sub-item ${isActive ? 'active' : ''}`}> + + + + Pipeline + `nav-item ${isActive ? 'active' : ''}`}> diff --git a/frontend/src/components/wordpress/ActivityFeed.jsx b/frontend/src/components/wordpress/ActivityFeed.jsx new file mode 100644 index 00000000..0a41a740 --- /dev/null +++ b/frontend/src/components/wordpress/ActivityFeed.jsx @@ -0,0 +1,139 @@ +import React, { useState, useEffect } from 'react'; +import { ArrowUpRight, ArrowDownLeft, Database, GitBranch, Lock, Unlock, Trash2, Play, Square, RefreshCw, Camera, AlertCircle } from 'lucide-react'; +import wordpressApi from '../../services/wordpress'; + +const ACTION_ICONS = { + create: Play, + deploy: GitBranch, + promote: ArrowUpRight, + sync: ArrowDownLeft, + lock: Lock, + unlock: Unlock, + destroy: Trash2, + snapshot_created: Camera, + snapshot_restored: Database, + started: Play, + stopped: Square, + restarted: RefreshCw +}; + +const ACTION_COLORS = { + create: 'success', + deploy: 'info', + promote: 'primary', + sync: 'info', + lock: 'warning', + unlock: 'default', + destroy: 'danger', + snapshot_created: 'info', + snapshot_restored: 'warning', + started: 'success', + stopped: 'default', + restarted: 'info' +}; + +function formatRelativeTime(dateString) { + if (!dateString) return ''; + const date = new Date(dateString); + const now = new Date(); + const diffMs = now - date; + const diffMinutes = Math.floor(diffMs / 60000); + const diffHours = Math.floor(diffMs / 3600000); + const diffDays = Math.floor(diffMs / 86400000); + + if (diffMinutes < 1) return 'Just now'; + if (diffMinutes < 60) return `${diffMinutes}m ago`; + if (diffHours < 24) return `${diffHours}h ago`; + if (diffDays < 7) return `${diffDays}d ago`; + return date.toLocaleDateString(); +} + +const ActivityFeed = ({ projectId, envId, limit = 20, compact = false }) => { + const [activities, setActivities] = useState([]); + const [loading, setLoading] = useState(true); + const [total, setTotal] = useState(0); + + useEffect(() => { + loadActivities(); + }, [projectId, envId]); + + async function loadActivities() { + setLoading(true); + try { + const params = { limit }; + if (envId) params.env_id = envId; + const data = await wordpressApi.getProjectActivity(projectId, params); + setActivities(data.activities || []); + setTotal(data.total || 0); + } catch (err) { + console.error('Failed to load activities:', err); + } finally { + setLoading(false); + } + } + + if (loading) { + return ( +
+ {[1, 2, 3].map(i => ( +
+
+
+
+
+
+
+ ))} +
+ ); + } + + if (activities.length === 0) { + return ( +
+

No activity recorded yet.

+
+ ); + } + + return ( +
+ {activities.map(activity => { + const Icon = ACTION_ICONS[activity.action] || AlertCircle; + const colorClass = ACTION_COLORS[activity.action] || 'default'; + + return ( +
+
+ +
+
+ + {activity.description || `${activity.action} performed`} + + {activity.status === 'failed' && activity.error_message && ( + {activity.error_message} + )} +
+
+ {formatRelativeTime(activity.created_at)} + {activity.status === 'failed' && ( + Failed + )} + {activity.status === 'running' && ( + Running + )} +
+
+ ); + })} + {total > activities.length && !compact && ( + + )} +
+ ); +}; + +export default ActivityFeed; diff --git a/frontend/src/components/wordpress/AutoSyncScheduleModal.jsx b/frontend/src/components/wordpress/AutoSyncScheduleModal.jsx new file mode 100644 index 00000000..e9355eff --- /dev/null +++ b/frontend/src/components/wordpress/AutoSyncScheduleModal.jsx @@ -0,0 +1,191 @@ +import React, { useState, useEffect } from 'react'; +import { Clock, RefreshCw } from 'lucide-react'; +import Spinner from '../Spinner'; + +const SCHEDULE_PRESETS = [ + { label: 'Daily at 3 AM', value: '0 3 * * *' }, + { label: 'Weekly Sunday 3 AM', value: '0 3 * * 0' }, + { label: 'Every 6 hours', value: '0 */6 * * *' }, + { label: 'Every 12 hours', value: '0 */12 * * *' }, + { label: 'Custom', value: 'custom' }, +]; + +const AutoSyncScheduleModal = ({ environment, prodId, onClose, api }) => { + const [loading, setLoading] = useState(true); + const [saving, setSaving] = useState(false); + const [enabled, setEnabled] = useState(false); + const [schedule, setSchedule] = useState('0 3 * * *'); + const [selectedPreset, setSelectedPreset] = useState('0 3 * * *'); + const [customCron, setCustomCron] = useState(''); + const [nextRuns, setNextRuns] = useState([]); + + useEffect(() => { + loadSchedule(); + }, []); + + async function loadSchedule() { + setLoading(true); + try { + const data = await api.getAutoSyncSchedule(prodId, environment.id); + setEnabled(data.enabled || false); + if (data.schedule) { + const matchingPreset = SCHEDULE_PRESETS.find(p => p.value === data.schedule); + if (matchingPreset) { + setSelectedPreset(data.schedule); + } else { + setSelectedPreset('custom'); + setCustomCron(data.schedule); + } + setSchedule(data.schedule); + } + setNextRuns(data.next_runs || []); + } catch { + // Default values already set + } finally { + setLoading(false); + } + } + + function handlePresetChange(value) { + setSelectedPreset(value); + if (value !== 'custom') { + setSchedule(value); + } + } + + function handleCustomCronChange(value) { + setCustomCron(value); + setSchedule(value); + } + + async function handleSave() { + setSaving(true); + try { + const finalSchedule = selectedPreset === 'custom' ? customCron : selectedPreset; + await api.updateAutoSyncSchedule(prodId, environment.id, { + enabled, + schedule: finalSchedule, + }); + onClose(); + } catch (err) { + console.error('Failed to save auto-sync schedule:', err); + } finally { + setSaving(false); + } + } + + function formatDateTime(iso) { + if (!iso) return ''; + const d = new Date(iso); + return d.toLocaleString(); + } + + const envName = environment?.name || 'Environment'; + + return ( +
+
e.stopPropagation()}> +
+

+ + Auto-Sync Schedule +

+ +
+ + {loading ? ( +
+ + Loading schedule... +
+ ) : ( +
+
{envName}
+ +
+ +

+ Automatically sync this environment from production on a schedule. +

+
+ + {enabled && ( + <> +
+ +
+ {SCHEDULE_PRESETS.map(preset => ( + + ))} +
+
+ + {selectedPreset === 'custom' && ( +
+ + handleCustomCronChange(e.target.value)} + placeholder="0 3 * * *" + className="auto-sync-cron-input" + /> + + Format: minute hour day-of-month month day-of-week + +
+ )} + + {nextRuns.length > 0 && ( +
+
Next Scheduled Runs
+
    + {nextRuns.map((run, i) => ( +
  • + + {formatDateTime(run)} +
  • + ))} +
+
+ )} + + )} +
+ )} + +
+ + +
+
+
+ ); +}; + +export default AutoSyncScheduleModal; diff --git a/frontend/src/components/wordpress/BasicAuthModal.jsx b/frontend/src/components/wordpress/BasicAuthModal.jsx new file mode 100644 index 00000000..cdd04dde --- /dev/null +++ b/frontend/src/components/wordpress/BasicAuthModal.jsx @@ -0,0 +1,163 @@ +import React, { useState, useEffect } from 'react'; +import { Shield, Copy, Check, AlertTriangle } from 'lucide-react'; +import Spinner from '../Spinner'; + +const BasicAuthModal = ({ environment, prodId, onClose, api }) => { + const [loading, setLoading] = useState(true); + const [status, setStatus] = useState({ enabled: false, username: null }); + const [credentials, setCredentials] = useState(null); + const [toggling, setToggling] = useState(false); + const [copied, setCopied] = useState(null); + + useEffect(() => { + loadStatus(); + }, []); + + async function loadStatus() { + setLoading(true); + try { + const data = await api.getBasicAuthStatus(prodId, environment.id); + setStatus(data); + } catch { + setStatus({ enabled: false, username: null }); + } finally { + setLoading(false); + } + } + + async function handleEnable() { + setToggling(true); + try { + const data = await api.enableBasicAuth(prodId, environment.id); + if (data.success) { + setStatus({ enabled: true, username: data.username }); + setCredentials({ username: data.username, password: data.password }); + } + } catch (err) { + console.error('Failed to enable basic auth:', err); + } finally { + setToggling(false); + } + } + + async function handleDisable() { + setToggling(true); + try { + const data = await api.disableBasicAuth(prodId, environment.id); + if (data.success) { + setStatus({ enabled: false, username: null }); + setCredentials(null); + } + } catch (err) { + console.error('Failed to disable basic auth:', err); + } finally { + setToggling(false); + } + } + + function copyToClipboard(text, field) { + navigator.clipboard.writeText(text); + setCopied(field); + setTimeout(() => setCopied(null), 2000); + } + + const envName = environment?.name || 'Environment'; + + return ( +
+
e.stopPropagation()}> +
+

+ + Basic Auth +

+ +
+ +
+
{envName}
+ + {loading ? ( +
+ + Loading status... +
+ ) : ( + <> +
+ +

+ Adds password protection to the site. Visitors must enter credentials to access any page. +

+
+ + {status.enabled && status.username && !credentials && ( +
+
+ +
+ {status.username} +
+
+

+ Password was shown when Basic Auth was first enabled. Disable and re-enable to generate new credentials. +

+
+ )} + + {credentials && ( +
+
+ + Save these credentials now. The password will not be shown again. +
+
+ +
+ {credentials.username} + +
+
+
+ +
+ {credentials.password} + +
+
+
+ )} + + )} +
+ +
+ +
+
+
+ ); +}; + +export default BasicAuthModal; diff --git a/frontend/src/components/wordpress/BulkActionsBar.jsx b/frontend/src/components/wordpress/BulkActionsBar.jsx new file mode 100644 index 00000000..9491be8c --- /dev/null +++ b/frontend/src/components/wordpress/BulkActionsBar.jsx @@ -0,0 +1,115 @@ +import React, { useState } from 'react'; +import { Square, Play, RefreshCw, ArrowDownLeft, X } from 'lucide-react'; +import Spinner from '../Spinner'; + +const BulkActionsBar = ({ selectedIds, environments, prodId, onClear, onExecute, api }) => { + const [executing, setExecuting] = useState(false); + const [confirmAction, setConfirmAction] = useState(null); + + if (!selectedIds || selectedIds.length === 0) return null; + + const selectedNames = selectedIds.map(id => { + const env = environments.find(e => e.id === id); + return env?.name || `#${id}`; + }); + + async function handleAction(action) { + if (action === 'stop' || action === 'sync') { + setConfirmAction(action); + return; + } + await executeAction(action); + } + + async function executeAction(action) { + setExecuting(true); + setConfirmAction(null); + try { + await onExecute(action, selectedIds); + } finally { + setExecuting(false); + } + } + + return ( +
+ {confirmAction ? ( +
+ + {confirmAction === 'stop' && `Stop ${selectedIds.length} environment(s)?`} + {confirmAction === 'sync' && `Sync ${selectedIds.length} environment(s) from production?`} + + + +
+ ) : ( + <> +
+ {selectedIds.length} + selected +
+ +
+ + + + +
+ + + + )} +
+ ); +}; + +export default BulkActionsBar; diff --git a/frontend/src/components/wordpress/CompareView.jsx b/frontend/src/components/wordpress/CompareView.jsx new file mode 100644 index 00000000..f0c40f6c --- /dev/null +++ b/frontend/src/components/wordpress/CompareView.jsx @@ -0,0 +1,223 @@ +import React, { useState, useEffect } from 'react'; +import { GitCompare, Check, X, Minus, RefreshCw } from 'lucide-react'; +import wordpressApi from '../../services/wordpress'; +import Spinner from '../Spinner'; + +const CompareView = ({ projectId, envA, envB, onClose }) => { + const [comparison, setComparison] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + + useEffect(() => { + loadComparison(); + }, [envA?.id, envB?.id]); + + async function loadComparison() { + if (!envA?.id || !envB?.id) return; + + setLoading(true); + setError(null); + try { + const data = await wordpressApi.compareEnvironments(projectId, envA.id, envB.id); + setComparison(data); + } catch (err) { + setError(err.message || 'Failed to compare environments'); + } finally { + setLoading(false); + } + } + + const envAType = envA?.environment_type || 'production'; + const envBType = envB?.environment_type || 'development'; + + return ( +
+
e.stopPropagation()}> +
+

+ + Compare Environments +

+ +
+ +
+
+ {envAType} + {envA?.name || 'Environment A'} +
+ +
+ {envBType} + {envB?.name || 'Environment B'} +
+ +
+ +
+ {loading && ( +
+ + Comparing environments... +
+ )} + + {error && ( +
+

{error}

+ +
+ )} + + {!loading && !error && comparison && ( + <> + {/* Version Comparison */} + + + + + + + {/* Plugins Comparison */} + {comparison.plugins && ( + + {comparison.plugins.map(plugin => ( + + ))} + {comparison.plugins.length === 0 && ( +
No plugin data available
+ )} +
+ )} + + {/* Themes Comparison */} + {comparison.themes && ( + + {comparison.themes.map(theme => ( + + ))} + {comparison.themes.length === 0 && ( +
No theme data available
+ )} +
+ )} + + )} +
+ +
+ +
+
+
+ ); +}; + +const CompareSection = ({ title, summary, children }) => ( +
+
+

{title}

+ {summary && {summary}} +
+
+ {children} +
+
+); + +const CompareRow = ({ label, valueA, valueB, status }) => { + const match = valueA === valueB && valueA != null; + const onlyA = valueA && !valueB; + const onlyB = !valueA && valueB; + const different = valueA && valueB && valueA !== valueB; + + let statusClass = 'match'; + let StatusIcon = Check; + if (different || status === 'different') { + statusClass = 'different'; + StatusIcon = X; + } else if (onlyA || status === 'only_a') { + statusClass = 'only-a'; + StatusIcon = Minus; + } else if (onlyB || status === 'only_b') { + statusClass = 'only-b'; + StatusIcon = Minus; + } + + return ( +
+
+ + {label} +
+
+ {valueA || --} +
+
+ {valueB || --} +
+
+ ); +}; + +function getPluginSummary(plugins) { + const match = plugins.filter(p => p.status === 'match').length; + const diff = plugins.filter(p => p.status === 'different').length; + const onlyA = plugins.filter(p => p.status === 'only_a').length; + const onlyB = plugins.filter(p => p.status === 'only_b').length; + const parts = []; + if (match) parts.push(`${match} matching`); + if (diff) parts.push(`${diff} different`); + if (onlyA) parts.push(`${onlyA} only in A`); + if (onlyB) parts.push(`${onlyB} only in B`); + return parts.join(', '); +} + +function getThemeSummary(themes) { + const match = themes.filter(t => t.status === 'match').length; + const diff = themes.filter(t => t.status === 'different').length; + const onlyA = themes.filter(t => t.status === 'only_a').length; + const onlyB = themes.filter(t => t.status === 'only_b').length; + const parts = []; + if (match) parts.push(`${match} matching`); + if (diff) parts.push(`${diff} different`); + if (onlyA) parts.push(`${onlyA} only in A`); + if (onlyB) parts.push(`${onlyB} only in B`); + return parts.join(', '); +} + +export default CompareView; diff --git a/frontend/src/components/wordpress/ContainerLogs.jsx b/frontend/src/components/wordpress/ContainerLogs.jsx new file mode 100644 index 00000000..e4bebba2 --- /dev/null +++ b/frontend/src/components/wordpress/ContainerLogs.jsx @@ -0,0 +1,123 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { Terminal, X, Download } from 'lucide-react'; +import wordpressApi from '../../services/wordpress'; + +const ContainerLogs = ({ projectId, envId, onClose }) => { + const [logs, setLogs] = useState([]); + const [loading, setLoading] = useState(true); + const [service, setService] = useState('wordpress'); + const [lines, setLines] = useState(100); + const [autoScroll, setAutoScroll] = useState(true); + const logsEndRef = useRef(null); + const containerRef = useRef(null); + + useEffect(() => { + loadLogs(); + }, [projectId, envId, service, lines]); + + useEffect(() => { + if (autoScroll && logsEndRef.current) { + logsEndRef.current.scrollIntoView({ behavior: 'smooth' }); + } + }, [logs, autoScroll]); + + async function loadLogs() { + setLoading(true); + try { + const data = await wordpressApi.getEnvironmentLogs(projectId, envId, { service, lines }); + setLogs(data.logs || []); + } catch (err) { + console.error('Failed to load logs:', err); + setLogs([`Error loading logs: ${err.message}`]); + } finally { + setLoading(false); + } + } + + function handleScroll() { + if (!containerRef.current) return; + const { scrollTop, scrollHeight, clientHeight } = containerRef.current; + setAutoScroll(scrollHeight - scrollTop - clientHeight < 50); + } + + function handleDownload() { + const text = logs.join('\n'); + const blob = new Blob([text], { type: 'text/plain' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `env-${envId}-${service}-logs.txt`; + a.click(); + URL.revokeObjectURL(url); + } + + return ( +
+
+
+ + Container Logs +
+
+ + + + + {onClose && ( + + )} +
+
+
+ {loading ? ( +
Loading logs...
+ ) : logs.length === 0 ? ( +
No logs available.
+ ) : ( +
+                        {logs.map((line, i) => (
+                            
{line}
+ ))} +
+
+ )} +
+
+ ); +}; + +function RefreshIcon() { + return ( + + + + + ); +} + +export default ContainerLogs; diff --git a/frontend/src/components/wordpress/DiskUsageBar.jsx b/frontend/src/components/wordpress/DiskUsageBar.jsx new file mode 100644 index 00000000..8c8d9e96 --- /dev/null +++ b/frontend/src/components/wordpress/DiskUsageBar.jsx @@ -0,0 +1,87 @@ +import React from 'react'; +import { HardDrive } from 'lucide-react'; + +const REFERENCE_THRESHOLD = 10 * 1024 * 1024 * 1024; // 10 GB reference + +const DiskUsageBar = ({ usage, showBreakdown = true, compact = false }) => { + if (!usage) return null; + + const total = usage.total || 0; + const wordpress = usage.wordpress || 0; + const mysql = usage.mysql || 0; + const snapshots = usage.snapshots || 0; + + const percent = REFERENCE_THRESHOLD > 0 + ? Math.min((total / REFERENCE_THRESHOLD) * 100, 100) + : 0; + + const wpPercent = total > 0 ? (wordpress / total) * percent : 0; + const dbPercent = total > 0 ? (mysql / total) * percent : 0; + const snapPercent = total > 0 ? (snapshots / total) * percent : 0; + + const colorClass = percent < 70 ? 'green' : percent < 90 ? 'yellow' : 'red'; + + function formatSize(bytes) { + if (!bytes) return '0 B'; + for (const unit of ['B', 'KB', 'MB', 'GB']) { + if (bytes < 1024) return `${bytes.toFixed(1)} ${unit}`; + bytes /= 1024; + } + return `${bytes.toFixed(1)} TB`; + } + + if (compact) { + return ( +
+ + {formatSize(total)} +
+ ); + } + + return ( +
+
+ + {formatSize(total)} +
+ +
+
+
+
+
+ + {showBreakdown && ( +
+
+ + WordPress {formatSize(wordpress)} +
+
+ + MySQL {formatSize(mysql)} +
+
+ + Snapshots {formatSize(snapshots)} +
+
+ )} +
+ ); +}; + +export default DiskUsageBar; diff --git a/frontend/src/components/wordpress/EnvironmentStatusBadge.jsx b/frontend/src/components/wordpress/EnvironmentStatusBadge.jsx new file mode 100644 index 00000000..4d4b75a7 --- /dev/null +++ b/frontend/src/components/wordpress/EnvironmentStatusBadge.jsx @@ -0,0 +1,34 @@ +import React from 'react'; +import { Lock } from 'lucide-react'; + +const EnvironmentStatusBadge = ({ type, status, isLocked }) => { + function getTypeBadgeClass() { + switch (type) { + case 'production': return 'env-production'; + case 'staging': return 'env-staging'; + case 'multidev': return 'env-multidev'; + default: return 'env-development'; + } + } + + const isRunning = status === 'running'; + + return ( +
+ + {type?.toUpperCase() || 'DEV'} + + {isLocked && ( + + + + )} + + + {isRunning ? 'Running' : 'Stopped'} + +
+ ); +}; + +export default EnvironmentStatusBadge; diff --git a/frontend/src/components/wordpress/HealthStatusPanel.jsx b/frontend/src/components/wordpress/HealthStatusPanel.jsx new file mode 100644 index 00000000..fa9e70b6 --- /dev/null +++ b/frontend/src/components/wordpress/HealthStatusPanel.jsx @@ -0,0 +1,137 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { Activity, RefreshCw, CheckCircle, AlertTriangle, XCircle, HelpCircle } from 'lucide-react'; +import Spinner from '../Spinner'; + +const STATUS_CONFIG = { + healthy: { icon: CheckCircle, color: 'green', label: 'Healthy' }, + degraded: { icon: AlertTriangle, color: 'yellow', label: 'Degraded' }, + unhealthy: { icon: XCircle, color: 'red', label: 'Unhealthy' }, + unknown: { icon: HelpCircle, color: 'gray', label: 'Unknown' }, +}; + +const HealthDot = ({ status, size = 8 }) => { + const colorMap = { + healthy: 'var(--color-success, #22c55e)', + degraded: 'var(--color-warning, #eab308)', + unhealthy: 'var(--color-danger, #ef4444)', + unknown: 'var(--color-text-tertiary, #6b7280)', + }; + + return ( + + ); +}; + +const HealthStatusPanel = ({ projectId, environments, api, compact = false }) => { + const [healthData, setHealthData] = useState({}); + const [loading, setLoading] = useState(true); + const intervalRef = useRef(null); + + useEffect(() => { + loadHealth(); + + // Auto-refresh every 30 seconds + intervalRef.current = setInterval(loadHealth, 30000); + + return () => { + if (intervalRef.current) clearInterval(intervalRef.current); + }; + }, [projectId]); + + async function loadHealth() { + try { + const data = await api.getProjectHealth(projectId); + if (data.success) { + setHealthData(data.environments || {}); + } + } catch { + // Silently fail - health checks are optional + } finally { + setLoading(false); + } + } + + if (compact) { + // Return just dots for pipeline cards + return null; // Dots are rendered directly via HealthDot export + } + + if (loading) { + return ( +
+
+ + Checking health... +
+
+ ); + } + + return ( +
+
+

+ + Environment Health +

+ +
+ +
+ {Object.entries(healthData).map(([envId, data]) => { + const env = environments?.find(e => String(e.id) === String(envId)); + const envName = env?.name || `Environment ${envId}`; + const overall = data?.overall_status || 'unknown'; + const checks = data?.checks || {}; + + return ( +
+
+ + {envName} + + {STATUS_CONFIG[overall]?.label || 'Unknown'} + +
+
+ {Object.entries(checks).map(([checkName, checkData]) => ( +
+ + + {checkName.charAt(0).toUpperCase() + checkName.slice(1)} + + + {checkData.message} + +
+ ))} +
+
+ ); + })} +
+ + {Object.keys(healthData).length === 0 && ( +
+ No health data available +
+ )} +
+ ); +}; + +export { HealthDot }; +export default HealthStatusPanel; diff --git a/frontend/src/components/wordpress/PipelineView.jsx b/frontend/src/components/wordpress/PipelineView.jsx new file mode 100644 index 00000000..69146e42 --- /dev/null +++ b/frontend/src/components/wordpress/PipelineView.jsx @@ -0,0 +1,608 @@ +import React, { useState } from 'react'; +import { + ExternalLink, Play, Square, RefreshCw, ArrowRight, + ArrowDownLeft, Lock, Unlock, FileText, Trash2, MoreVertical, + GitBranch, Plus, GitCompare, Cpu, Shield, Terminal, Clock, + HardDrive, Settings +} from 'lucide-react'; +import EnvironmentStatusBadge from './EnvironmentStatusBadge'; +import { HealthDot } from './HealthStatusPanel'; +import DiskUsageBar from './DiskUsageBar'; + +const PipelineView = ({ + pipeline, + onPromote, + onSync, + onStart, + onStop, + onRestart, + onDelete, + onLock, + onUnlock, + onViewLogs, + onCreateMultidev, + onCompare, + onResourceLimits, + onBasicAuth, + onWpCli, + onAutoSync, + onHealthCheck, + operationInProgress, + healthData, + diskUsageData, + bulkSelected, + onBulkToggle, +}) => { + if (!pipeline) return null; + + const { production, environments = [] } = pipeline; + const devEnv = environments.find(e => e.environment_type === 'development'); + const stagingEnv = environments.find(e => e.environment_type === 'staging'); + const multidevEnvs = environments.filter(e => e.environment_type === 'multidev'); + + // Pipeline order: Dev -> Staging -> Production + const pipelineEnvs = [devEnv, stagingEnv].filter(Boolean); + + return ( +
+
+ {/* Development */} + {devEnv ? ( + + ) : ( + + )} + + {/* Arrow: Dev -> Staging (Promote) */} + devEnv && stagingEnv && onPromote?.(devEnv, stagingEnv)} + /> + + {/* Staging */} + {stagingEnv ? ( + + ) : ( + + )} + + {/* Arrow: Staging -> Production (Promote) */} + stagingEnv && production && onPromote?.(stagingEnv, production)} + /> + + {/* Production */} + {production && ( + + )} +
+ + {/* Sync arrows (below, reversed) */} +
+ {devEnv && ( +
+ +
+ )} + {stagingEnv && ( +
+ +
+ )} +
+ + {/* Compare row */} + {onCompare && (devEnv || stagingEnv) && production && ( +
+ {devEnv && ( + + )} + {stagingEnv && ( + + )} + {devEnv && stagingEnv && ( + + )} +
+ )} + + {/* Multidev section */} +
+
+

+ + Multidev Environments + {multidevEnvs.length > 0 && ( + {multidevEnvs.length} + )} +

+ +
+ {multidevEnvs.length > 0 ? ( +
+ {multidevEnvs.map(env => ( + + ))} +
+ ) : ( +
+ +

No multidev environments yet

+ Create branch-based environments for feature development and testing + +
+ )} +
+
+ ); +}; + +const PipelineCard = ({ + env, + isProduction = false, + onStart, + onStop, + onRestart, + onDelete, + onLock, + onUnlock, + onViewLogs, + onResourceLimits, + onBasicAuth, + onWpCli, + onAutoSync, + onHealthCheck, + operationInProgress, + healthStatus, + diskUsage, + bulkSelected, + onBulkToggle, +}) => { + const [showMenu, setShowMenu] = useState(false); + const isRunning = env.status === 'running' || env.application?.status === 'running'; + const envType = env.environment_type || (isProduction ? 'production' : 'development'); + const domain = env.application?.domains?.[0] || env.url || ''; + + function formatRelativeTime(dateString) { + if (!dateString) return null; + const date = new Date(dateString); + const now = new Date(); + const diffMs = now - date; + const diffDays = Math.floor(diffMs / 86400000); + const diffHours = Math.floor(diffMs / 3600000); + + if (diffHours < 1) return 'Just now'; + if (diffHours < 24) return `${diffHours}h ago`; + if (diffDays < 7) return `${diffDays}d ago`; + return date.toLocaleDateString(); + } + + return ( +
+
+ {onBulkToggle && !isProduction && ( + onBulkToggle(env.id)} + /> + )} + + {healthStatus && ( + + )} +
+ + {showMenu && ( +
setShowMenu(false)}> + {isRunning ? ( + <> + + + + ) : ( + + )} + +
+ + + + {!isProduction && onAutoSync && ( + + )} +
+ {env.is_locked ? ( + + ) : ( + + )} + {!isProduction && ( + + )} +
+ )} +
+
+ +
+

{env.name}

+ {domain && ( + + {domain} + + )} +
+ {env.wp_version && ( + v{env.wp_version} + )} + {env.last_sync && !isProduction && ( + + Synced {formatRelativeTime(env.last_sync)} + + )} + {diskUsage && ( + + )} +
+
+ +
+ {domain && ( + + Visit + + )} + +
+ + {env.is_locked && env.locked_reason && ( +
+ + {env.locked_reason} +
+ )} +
+ ); +}; + +const PipelineArrow = ({ label, direction, disabled, onClick }) => { + return ( +
+ +
+ ); +}; + +const EmptySlot = ({ type }) => { + return ( +
+
+ + {type.toUpperCase()} + +

No {type} environment

+
+
+ ); +}; + +const MultidevCard = ({ + env, onStart, onStop, onRestart, onDelete, onPromote, + onSync, onLock, onUnlock, onViewLogs, + devEnv, stagingEnv, production +}) => { + const [showMenu, setShowMenu] = useState(false); + const isRunning = env.status === 'running' || env.application?.status === 'running'; + const domain = env.application?.domains?.[0] || env.url || ''; + + function formatRelativeTime(dateString) { + if (!dateString) return null; + const date = new Date(dateString); + const now = new Date(); + const diffMs = now - date; + const diffDays = Math.floor(diffMs / 86400000); + const diffHours = Math.floor(diffMs / 3600000); + if (diffHours < 1) return 'Just now'; + if (diffHours < 24) return `${diffHours}h ago`; + if (diffDays < 7) return `${diffDays}d ago`; + return date.toLocaleDateString(); + } + + // Determine best promote target + const promoteTarget = devEnv || stagingEnv || production; + + return ( +
+
+
+ MULTIDEV + + + {isRunning ? 'Running' : 'Stopped'} + + {env.is_locked && ( + + )} +
+
+ + {showMenu && ( +
setShowMenu(false)}> + {isRunning ? ( + <> + + + + ) : ( + + )} + + + {env.is_locked ? ( + + ) : ( + + )} + +
+ )} +
+
+
+
{env.name}
+ {env.multidev_branch && ( + + + {env.multidev_branch} + + )} + {domain && ( + + {domain} + + )} +
+ {env.created_at && ( + + Created {formatRelativeTime(env.created_at)} + + )} +
+
+
+ {domain && ( + + Visit + + )} + + + +
+ {env.is_locked && env.locked_reason && ( +
+ + {env.locked_reason} +
+ )} +
+ ); +}; + +export default PipelineView; diff --git a/frontend/src/components/wordpress/PromoteModal.jsx b/frontend/src/components/wordpress/PromoteModal.jsx new file mode 100644 index 00000000..d7032316 --- /dev/null +++ b/frontend/src/components/wordpress/PromoteModal.jsx @@ -0,0 +1,248 @@ +import React, { useState, useEffect } from 'react'; +import { ArrowRight, Shield } from 'lucide-react'; +import wordpressApi from '../../services/wordpress'; +import Spinner from '../Spinner'; + +const PromoteModal = ({ sourceEnv, targetEnv, onClose, onPromote }) => { + const [promotionType, setPromotionType] = useState('code'); + const [config, setConfig] = useState({ + include_plugins: true, + include_themes: true, + include_mu_plugins: true, + include_uploads: false, + backup_target_first: true, + sanitize: false, + sanitization_profile_id: '' + }); + const [loading, setLoading] = useState(false); + const [profiles, setProfiles] = useState([]); + + useEffect(() => { + loadProfiles(); + }, []); + + async function loadProfiles() { + try { + const data = await wordpressApi.getSanitizationProfiles(); + setProfiles(data.profiles || []); + const defaultProfile = (data.profiles || []).find(p => p.is_default); + if (defaultProfile) { + setConfig(prev => ({ ...prev, sanitization_profile_id: String(defaultProfile.id) })); + } + } catch { + setProfiles([]); + } + } + + async function handleSubmit(e) { + e.preventDefault(); + setLoading(true); + try { + const submitConfig = { ...config }; + if (submitConfig.sanitization_profile_id) { + submitConfig.sanitization_profile_id = Number(submitConfig.sanitization_profile_id); + } else { + delete submitConfig.sanitization_profile_id; + } + await onPromote({ + source_env_id: sourceEnv.id, + target_env_id: targetEnv.id, + type: promotionType, + config: submitConfig + }); + } finally { + setLoading(false); + } + } + + function handleConfigChange(key, value) { + setConfig(prev => ({ ...prev, [key]: value })); + } + + const sourceType = sourceEnv.environment_type || 'development'; + const targetType = targetEnv.environment_type || 'staging'; + + return ( +
+
e.stopPropagation()}> +
+

Promote Environment

+ +
+ +
+
+
+ {sourceType} + {sourceEnv.name} +
+ +
+ {targetType} + {targetEnv.name} +
+
+ +
+ +
+ + + +
+
+ + {(promotionType === 'code' || promotionType === 'full') && ( +
+ +
+ + + + +
+
+ )} + + {(promotionType === 'database' || promotionType === 'full') && ( + <> +
+ +
+ + {config.sanitize && profiles.length > 0 && ( +
+ + + {config.sanitization_profile_id && ( + + {profiles.find(p => String(p.id) === config.sanitization_profile_id)?.description || ''} + + )} +
+ )} + + )} + +
+ + Recommended. Allows rollback if something goes wrong. +
+ + {targetType === 'production' && ( +
+ + + + + + You are promoting to production. This will affect the live site. +
+ )} + +
+ + +
+
+
+
+ ); +}; + +export default PromoteModal; diff --git a/frontend/src/components/wordpress/ResourceLimitsModal.jsx b/frontend/src/components/wordpress/ResourceLimitsModal.jsx new file mode 100644 index 00000000..f2bec00a --- /dev/null +++ b/frontend/src/components/wordpress/ResourceLimitsModal.jsx @@ -0,0 +1,148 @@ +import React, { useState } from 'react'; +import { Cpu, HardDrive, AlertTriangle } from 'lucide-react'; +import Spinner from '../Spinner'; + +const PRESETS = { + low: { memory: '256M', cpus: '0.25', db_memory: '256M', db_cpus: '0.25' }, + standard: { memory: '512M', cpus: '1.0', db_memory: '384M', db_cpus: '0.5' }, + high: { memory: '2G', cpus: '2.0', db_memory: '1G', db_cpus: '1.0' }, +}; + +const MEMORY_OPTIONS = ['256M', '384M', '512M', '768M', '1G', '1.5G', '2G']; +const CPU_OPTIONS = ['0.25', '0.5', '1.0', '1.5', '2.0']; + +const ResourceLimitsModal = ({ environment, currentLimits, onClose, onApply }) => { + const [limits, setLimits] = useState({ + memory: currentLimits?.memory || '512M', + cpus: currentLimits?.cpus || '1.0', + db_memory: currentLimits?.db_memory || '384M', + db_cpus: currentLimits?.db_cpus || '0.5', + }); + const [loading, setLoading] = useState(false); + + function applyPreset(preset) { + setLimits({ ...PRESETS[preset] }); + } + + function handleChange(key, value) { + setLimits(prev => ({ ...prev, [key]: value })); + } + + async function handleSubmit(e) { + e.preventDefault(); + setLoading(true); + try { + await onApply(limits); + } finally { + setLoading(false); + } + } + + const envName = environment?.name || 'Environment'; + + return ( +
+
e.stopPropagation()}> +
+

+ + Resource Limits +

+ +
+ +
+
{envName}
+ +
+ Presets: + {Object.entries(PRESETS).map(([key]) => ( + + ))} +
+ +
+

+ + WordPress Container +

+
+ + +
+
+ + +
+
+ +
+

+ + Database Container +

+
+ + +
+
+ + +
+
+ +
+ + Applying resource limits will restart the environment containers. +
+ +
+ + +
+
+
+
+ ); +}; + +export default ResourceLimitsModal; diff --git a/frontend/src/components/wordpress/SanitizationProfileForm.jsx b/frontend/src/components/wordpress/SanitizationProfileForm.jsx new file mode 100644 index 00000000..f47ddca2 --- /dev/null +++ b/frontend/src/components/wordpress/SanitizationProfileForm.jsx @@ -0,0 +1,336 @@ +import React, { useState, useEffect } from 'react'; +import { Shield, Plus, Trash2, Star, Edit3, Save } from 'lucide-react'; +import wordpressApi from '../../services/wordpress'; +import Spinner from '../Spinner'; + +const SanitizationProfileForm = ({ onClose, onProfilesChange }) => { + const [profiles, setProfiles] = useState([]); + const [loading, setLoading] = useState(true); + const [editingProfile, setEditingProfile] = useState(null); + const [showCreateForm, setShowCreateForm] = useState(false); + + useEffect(() => { + loadProfiles(); + }, []); + + async function loadProfiles() { + setLoading(true); + try { + const data = await wordpressApi.getSanitizationProfiles(); + setProfiles(data.profiles || []); + } catch { + setProfiles([]); + } finally { + setLoading(false); + } + } + + async function handleDelete(profileId) { + try { + await wordpressApi.deleteSanitizationProfile(profileId); + setProfiles(prev => prev.filter(p => p.id !== profileId)); + onProfilesChange?.(); + } catch { + // handled silently + } + } + + async function handleSetDefault(profileId) { + try { + await wordpressApi.updateSanitizationProfile(profileId, { is_default: true }); + setProfiles(prev => prev.map(p => ({ + ...p, + is_default: p.id === profileId + }))); + onProfilesChange?.(); + } catch { + // handled silently + } + } + + async function handleSaveProfile(profileData) { + try { + if (editingProfile) { + const result = await wordpressApi.updateSanitizationProfile( + editingProfile.id, + profileData + ); + setProfiles(prev => prev.map(p => + p.id === editingProfile.id ? result.profile : p + )); + } else { + const result = await wordpressApi.createSanitizationProfile(profileData); + setProfiles(prev => [...prev, result.profile]); + } + setEditingProfile(null); + setShowCreateForm(false); + onProfilesChange?.(); + } catch { + // handled silently + } + } + + return ( +
+
e.stopPropagation()}> +
+

+ + Sanitization Profiles +

+ +
+ +
+ {loading ? ( +
+ +
+ ) : ( + <> +
+ {profiles.map(profile => ( + { setEditingProfile(profile); setShowCreateForm(false); }} + onDelete={() => handleDelete(profile.id)} + onSetDefault={() => handleSetDefault(profile.id)} + /> + ))} +
+ + {!showCreateForm && !editingProfile && ( + + )} + + {(showCreateForm || editingProfile) && ( + { setEditingProfile(null); setShowCreateForm(false); }} + /> + )} + + )} +
+ +
+ +
+
+
+ ); +}; + +const ProfileCard = ({ profile, onEdit, onDelete, onSetDefault }) => ( +
+
+
+
{profile.name}
+ {profile.is_builtin && Built-in} + {profile.is_default && Default} +
+
+ {!profile.is_default && ( + + )} + + {!profile.is_builtin && ( + + )} +
+
+ {profile.description && ( +

{profile.description}

+ )} +
+ +
+
+); + +const ProfileRuleTags = ({ config }) => { + const tags = []; + if (config.anonymize_emails) tags.push('Anonymize emails'); + if (config.anonymize_names) tags.push('Anonymize names'); + if (config.reset_passwords) tags.push('Reset passwords'); + if (config.strip_payment_data) tags.push('Strip payments'); + if (config.remove_transients) tags.push('Clear transients'); + if (config.truncate_tables?.length > 0) tags.push(`Truncate ${config.truncate_tables.length} tables`); + if (config.exclude_tables?.length > 0) tags.push(`Exclude ${config.exclude_tables.length} tables`); + if (config.custom_search_replace && Object.keys(config.custom_search_replace).length > 0) { + tags.push(`${Object.keys(config.custom_search_replace).length} replacements`); + } + + return ( +
+ {tags.map(tag => ( + {tag} + ))} + {tags.length === 0 && ( + No rules configured + )} +
+ ); +}; + +const ProfileEditor = ({ profile, onSave, onCancel }) => { + const [name, setName] = useState(profile?.name || ''); + const [description, setDescription] = useState(profile?.description || ''); + const [config, setConfig] = useState(profile?.config || { + anonymize_emails: false, + anonymize_names: false, + reset_passwords: false, + truncate_tables: [], + exclude_tables: [], + strip_payment_data: false, + remove_transients: false, + custom_search_replace: {}, + }); + const [truncateInput, setTruncateInput] = useState( + (profile?.config?.truncate_tables || []).join(', ') + ); + const [excludeInput, setExcludeInput] = useState( + (profile?.config?.exclude_tables || []).join(', ') + ); + const [saving, setSaving] = useState(false); + + function handleConfigToggle(key) { + setConfig(prev => ({ ...prev, [key]: !prev[key] })); + } + + async function handleSubmit(e) { + e.preventDefault(); + setSaving(true); + try { + const finalConfig = { + ...config, + truncate_tables: truncateInput.split(',').map(s => s.trim()).filter(Boolean), + exclude_tables: excludeInput.split(',').map(s => s.trim()).filter(Boolean), + }; + await onSave({ name, description, config: finalConfig }); + } finally { + setSaving(false); + } + } + + return ( +
+

{profile ? 'Edit Profile' : 'Create Profile'}

+ +
+ + setName(e.target.value)} + placeholder="My Custom Profile" + required + disabled={profile?.is_builtin} + /> +
+ +
+ + setDescription(e.target.value)} + placeholder="What this profile does..." + /> +
+ +
+ +
+ + + + + +
+
+ +
+ + setTruncateInput(e.target.value)} + placeholder="actionscheduler_actions, actionscheduler_logs" + /> + Tables to empty (structure preserved, data removed) +
+ +
+ + setExcludeInput(e.target.value)} + placeholder="wp_users, wp_usermeta" + /> + Tables to skip during sync/promote +
+ +
+ + +
+
+ ); +}; + +export default SanitizationProfileForm; diff --git a/frontend/src/components/wordpress/SyncModal.jsx b/frontend/src/components/wordpress/SyncModal.jsx new file mode 100644 index 00000000..a4f9b6aa --- /dev/null +++ b/frontend/src/components/wordpress/SyncModal.jsx @@ -0,0 +1,219 @@ +import React, { useState, useEffect } from 'react'; +import { ArrowDownLeft, Shield } from 'lucide-react'; +import wordpressApi from '../../services/wordpress'; +import Spinner from '../Spinner'; + +const SyncModal = ({ environment, productionName, onClose, onSync }) => { + const [syncType, setSyncType] = useState('database'); + const [config, setConfig] = useState({ + sanitize: false, + truncate_tables: '', + exclude_tables: '', + sanitization_profile_id: '' + }); + const [loading, setLoading] = useState(false); + const [profiles, setProfiles] = useState([]); + + useEffect(() => { + loadProfiles(); + }, []); + + async function loadProfiles() { + try { + const data = await wordpressApi.getSanitizationProfiles(); + setProfiles(data.profiles || []); + // Auto-select default profile + const defaultProfile = (data.profiles || []).find(p => p.is_default); + if (defaultProfile) { + setConfig(prev => ({ + ...prev, + sanitization_profile_id: String(defaultProfile.id), + sanitize: true + })); + } + } catch { + setProfiles([]); + } + } + + async function handleSubmit(e) { + e.preventDefault(); + setLoading(true); + try { + await onSync({ + type: syncType, + sanitize: config.sanitize, + sanitization_profile_id: config.sanitization_profile_id + ? Number(config.sanitization_profile_id) : null, + truncate_tables: config.truncate_tables + ? config.truncate_tables.split(',').map(s => s.trim()).filter(Boolean) + : [], + exclude_tables: config.exclude_tables + ? config.exclude_tables.split(',').map(s => s.trim()).filter(Boolean) + : [] + }); + } finally { + setLoading(false); + } + } + + function handleConfigChange(key, value) { + setConfig(prev => ({ ...prev, [key]: value })); + } + + const envType = environment.environment_type || 'development'; + + return ( +
+
e.stopPropagation()}> +
+

Sync from Production

+ +
+ +
+
+
+ Production + {productionName} +
+ +
+ {envType} + {environment.name} +
+
+ +
+ +
+ + + +
+
+ + {(syncType === 'database' || syncType === 'full') && ( + <> +
+ +
+ + {config.sanitize && profiles.length > 0 && ( +
+ + + {config.sanitization_profile_id && ( + + {profiles.find(p => String(p.id) === config.sanitization_profile_id)?.description || ''} + + )} +
+ )} + +
+ + handleConfigChange('exclude_tables', e.target.value)} + placeholder="wp_users, wp_usermeta" + /> + Tables to skip during sync +
+ +
+ + handleConfigChange('truncate_tables', e.target.value)} + placeholder="wp_actionscheduler_actions, wp_actionscheduler_logs" + /> + Tables to empty (structure kept, data removed) +
+ + )} + +
+ + + + +
+ This will overwrite data +

The current {syncType === 'files' ? 'files' : syncType === 'database' ? 'database' : 'database and files'} in this environment will be replaced with production data. A snapshot will be created before syncing.

+
+
+ +
+ + +
+
+
+
+ ); +}; + +export default SyncModal; diff --git a/frontend/src/components/wordpress/WpCliTerminal.jsx b/frontend/src/components/wordpress/WpCliTerminal.jsx new file mode 100644 index 00000000..d2dfdcca --- /dev/null +++ b/frontend/src/components/wordpress/WpCliTerminal.jsx @@ -0,0 +1,197 @@ +import React, { useState, useRef, useEffect } from 'react'; +import { Terminal, Play, Clock, X } from 'lucide-react'; +import Spinner from '../Spinner'; + +const QUICK_COMMANDS = [ + { label: 'Plugin List', command: 'wp plugin list --format=table' }, + { label: 'Cache Flush', command: 'wp cache flush' }, + { label: 'DB Check', command: 'wp db check' }, + { label: 'Site URL', command: 'wp option get siteurl' }, +]; + +const HISTORY_KEY = 'wp_cli_history'; +const MAX_HISTORY = 50; + +const WpCliTerminal = ({ environment, prodId, onClose, api }) => { + const [command, setCommand] = useState(''); + const [output, setOutput] = useState([]); + const [executing, setExecuting] = useState(false); + const [showHistory, setShowHistory] = useState(false); + const [historyIndex, setHistoryIndex] = useState(-1); + + const inputRef = useRef(null); + const outputRef = useRef(null); + + const history = JSON.parse(localStorage.getItem(HISTORY_KEY) || '[]'); + + useEffect(() => { + inputRef.current?.focus(); + }, []); + + useEffect(() => { + if (outputRef.current) { + outputRef.current.scrollTop = outputRef.current.scrollHeight; + } + }, [output]); + + function saveToHistory(cmd) { + const updated = [cmd, ...history.filter(h => h !== cmd)].slice(0, MAX_HISTORY); + localStorage.setItem(HISTORY_KEY, JSON.stringify(updated)); + } + + async function executeCommand(cmd) { + if (!cmd.trim()) return; + + const cmdStr = cmd.trim(); + setCommand(''); + setExecuting(true); + saveToHistory(cmdStr); + setHistoryIndex(-1); + + setOutput(prev => [...prev, { type: 'command', text: cmdStr }]); + + try { + const result = await api.executeWpCli(prodId, environment.id, cmdStr); + if (result.success) { + setOutput(prev => [...prev, { type: 'output', text: result.output || '(no output)' }]); + } else { + setOutput(prev => [...prev, { type: 'error', text: result.error || 'Command failed' }]); + } + } catch (err) { + setOutput(prev => [...prev, { type: 'error', text: err.message || 'Execution failed' }]); + } finally { + setExecuting(false); + inputRef.current?.focus(); + } + } + + function handleKeyDown(e) { + if (e.key === 'Enter' && !executing) { + executeCommand(command); + } else if (e.key === 'ArrowUp') { + e.preventDefault(); + if (history.length > 0) { + const newIndex = Math.min(historyIndex + 1, history.length - 1); + setHistoryIndex(newIndex); + setCommand(history[newIndex]); + } + } else if (e.key === 'ArrowDown') { + e.preventDefault(); + if (historyIndex > 0) { + const newIndex = historyIndex - 1; + setHistoryIndex(newIndex); + setCommand(history[newIndex]); + } else { + setHistoryIndex(-1); + setCommand(''); + } + } + } + + const envName = environment?.name || 'Environment'; + + return ( +
+
e.stopPropagation()}> +
+

+ + WP-CLI - {envName} +

+ +
+ +
+ {QUICK_COMMANDS.map(qc => ( + + ))} + +
+ + {showHistory && history.length > 0 && ( +
+ {history.slice(0, 10).map((cmd, i) => ( + + ))} +
+ )} + +
+ {output.length === 0 && ( +
+ Enter a WP-CLI command below or use the quick actions above. +
+ )} + {output.map((entry, i) => ( +
+ {entry.type === 'command' && ( +
+ $ + {entry.text} +
+ )} + {entry.type === 'output' && ( +
{entry.text}
+ )} + {entry.type === 'error' && ( +
{entry.text}
+ )} +
+ ))} + {executing && ( +
+ + Executing... +
+ )} +
+ +
+ $ + setCommand(e.target.value)} + onKeyDown={handleKeyDown} + placeholder="wp plugin list --format=table" + disabled={executing} + className="wpcli-input" + /> + +
+
+
+ ); +}; + +export default WpCliTerminal; diff --git a/frontend/src/components/wordpress/index.js b/frontend/src/components/wordpress/index.js index 5a81f25b..757372c1 100644 --- a/frontend/src/components/wordpress/index.js +++ b/frontend/src/components/wordpress/index.js @@ -4,3 +4,19 @@ export { default as EnvironmentCard } from './EnvironmentCard'; export { default as SnapshotTable } from './SnapshotTable'; export { default as GitConnectForm } from './GitConnectForm'; export { default as CommitList } from './CommitList'; +export { default as PipelineView } from './PipelineView'; +export { default as PromoteModal } from './PromoteModal'; +export { default as SyncModal } from './SyncModal'; +export { default as ActivityFeed } from './ActivityFeed'; +export { default as ContainerLogs } from './ContainerLogs'; +export { default as EnvironmentStatusBadge } from './EnvironmentStatusBadge'; +export { default as CompareView } from './CompareView'; +export { default as SanitizationProfileForm } from './SanitizationProfileForm'; +export { default as ResourceLimitsModal } from './ResourceLimitsModal'; +export { default as BasicAuthModal } from './BasicAuthModal'; +export { default as WpCliTerminal } from './WpCliTerminal'; +export { default as HealthStatusPanel } from './HealthStatusPanel'; +export { HealthDot } from './HealthStatusPanel'; +export { default as DiskUsageBar } from './DiskUsageBar'; +export { default as AutoSyncScheduleModal } from './AutoSyncScheduleModal'; +export { default as BulkActionsBar } from './BulkActionsBar'; diff --git a/frontend/src/pages/WordPressProject.jsx b/frontend/src/pages/WordPressProject.jsx new file mode 100644 index 00000000..c6ac50fd --- /dev/null +++ b/frontend/src/pages/WordPressProject.jsx @@ -0,0 +1,953 @@ +import React, { useState, useEffect, useCallback, useRef } from 'react'; +import { useParams, useNavigate, Link } from 'react-router-dom'; +import { Plus, ExternalLink, RefreshCw, GitBranch, Search, Shield, Activity, Settings } from 'lucide-react'; +import wordpressApi from '../services/wordpress'; +import { useToast } from '../contexts/ToastContext'; +import { + PipelineView, + PromoteModal, + SyncModal, + ActivityFeed, + ContainerLogs, + CompareView, + SanitizationProfileForm, + ResourceLimitsModal, + BasicAuthModal, + WpCliTerminal, + HealthStatusPanel, + AutoSyncScheduleModal, + BulkActionsBar, +} from '../components/wordpress'; +import { ConfirmDialog } from '../components/ConfirmDialog'; +import Spinner from '../components/Spinner'; +import { io } from 'socket.io-client'; + +const SOCKET_URL = import.meta.env.VITE_API_URL?.replace('/api/v1', '') || 'http://localhost:5000'; + +const WordPressProject = () => { + const { id } = useParams(); + const navigate = useNavigate(); + const toast = useToast(); + + const [pipeline, setPipeline] = useState(null); + const [loading, setLoading] = useState(true); + const [activeTab, setActiveTab] = useState('pipeline'); + const [showCreateEnvModal, setShowCreateEnvModal] = useState(false); + const [promoteModal, setPromoteModal] = useState(null); + const [syncModal, setSyncModal] = useState(null); + const [logsPanel, setLogsPanel] = useState(null); + const [confirmDialog, setConfirmDialog] = useState(null); + const [operationInProgress, setOperationInProgress] = useState(null); + const [operationProgress, setOperationProgress] = useState(null); + const [compareModal, setCompareModal] = useState(null); + const [showSanitizationProfiles, setShowSanitizationProfiles] = useState(false); + + // Phase 7 state + const [resourceLimitsModal, setResourceLimitsModal] = useState(null); + const [basicAuthModal, setBasicAuthModal] = useState(null); + const [wpCliModal, setWpCliModal] = useState(null); + const [autoSyncModal, setAutoSyncModal] = useState(null); + const [healthData, setHealthData] = useState({}); + const [diskUsageData, setDiskUsageData] = useState({}); + const [bulkSelected, setBulkSelected] = useState([]); + + const socketRef = useRef(null); + + useEffect(() => { + loadPipeline(); + connectSocket(); + + return () => { + if (socketRef.current) { + socketRef.current.emit('unsubscribe_pipeline', { project_id: Number(id) }); + socketRef.current.disconnect(); + } + }; + }, [id]); + + function connectSocket() { + const token = localStorage.getItem('access_token'); + if (!token) return; + + const socket = io(SOCKET_URL, { + query: { token }, + transports: ['websocket', 'polling'] + }); + + socket.on('connect', () => { + socket.emit('subscribe_pipeline', { project_id: Number(id) }); + }); + + socket.on('pipeline_event', (data) => { + handlePipelineEvent(data); + }); + + socketRef.current = socket; + } + + function handlePipelineEvent(data) { + const { event, data: eventData } = data; + + switch (event) { + case 'environment_created': + case 'environment_deleted': + case 'promotion_completed': + case 'sync_completed': + loadPipeline(); + if (eventData.success) { + toast.success(eventData.message || `${event.replace(/_/g, ' ')} successfully`); + } + setOperationInProgress(null); + break; + case 'environment_create_failed': + case 'environment_delete_failed': + case 'promotion_failed': + case 'sync_failed': + loadPipeline(); + toast.error(eventData.message || `${event.replace(/_/g, ' ')}`); + setOperationInProgress(null); + break; + case 'environment_started': + case 'environment_stopped': + case 'environment_restarted': + case 'environment_locked': + case 'environment_unlocked': + loadPipeline(); + break; + case 'promotion_started': + case 'sync_started': + case 'environment_creating': + setOperationInProgress(event); + setOperationProgress(null); + break; + case 'operation_progress': + setOperationProgress(eventData); + break; + case 'bulk_operation_completed': + loadPipeline(); + toast.success('Bulk operation completed'); + break; + default: + break; + } + } + + async function loadPipeline() { + try { + const data = await wordpressApi.getProjectPipeline(id); + setPipeline(data); + } catch (err) { + console.error('Failed to load pipeline:', err); + toast.error('Failed to load project pipeline'); + } finally { + setLoading(false); + } + } + + const handlePromote = useCallback((sourceEnv, targetEnv) => { + setPromoteModal({ sourceEnv, targetEnv }); + }, []); + + const handleDoPromote = useCallback(async (config) => { + toast.info('Starting promotion...', { duration: 3000 }); + try { + await wordpressApi.promoteEnvironment(id, config); + setPromoteModal(null); + } catch (err) { + toast.error(err.message || 'Promotion failed'); + } + }, [id, toast]); + + const handleSync = useCallback((env) => { + setSyncModal({ environment: env }); + }, []); + + const handleDoSync = useCallback(async (config) => { + const env = syncModal.environment; + toast.info('Starting sync...', { duration: 3000 }); + try { + await wordpressApi.syncProjectEnvironment(id, env.id, config); + setSyncModal(null); + } catch (err) { + toast.error(err.message || 'Sync failed'); + } + }, [id, syncModal, toast]); + + const handleStart = useCallback(async (env) => { + try { + await wordpressApi.startEnvironment(id, env.id); + toast.success('Environment started'); + loadPipeline(); + } catch (err) { + toast.error(err.message || 'Failed to start environment'); + } + }, [id, toast]); + + const handleStop = useCallback(async (env) => { + setConfirmDialog({ + title: 'Stop Environment', + message: `Stop the ${env.environment_type || ''} environment "${env.name}"?`, + confirmText: 'Stop', + variant: 'warning', + onConfirm: async () => { + try { + await wordpressApi.stopEnvironment(id, env.id); + toast.success('Environment stopped'); + loadPipeline(); + } catch (err) { + toast.error(err.message || 'Failed to stop environment'); + } finally { + setConfirmDialog(null); + } + }, + onCancel: () => setConfirmDialog(null) + }); + }, [id, toast]); + + const handleRestart = useCallback(async (env) => { + try { + await wordpressApi.restartEnvironment(id, env.id); + toast.success('Environment restarted'); + loadPipeline(); + } catch (err) { + toast.error(err.message || 'Failed to restart environment'); + } + }, [id, toast]); + + const handleDelete = useCallback((env) => { + setConfirmDialog({ + title: 'Delete Environment', + message: `Are you sure you want to delete "${env.name}"? This will remove all containers, files, and database for this environment.`, + confirmText: 'Delete Environment', + variant: 'danger', + onConfirm: async () => { + try { + await wordpressApi.deleteProjectEnvironment(id, env.id); + toast.success('Environment deleted'); + loadPipeline(); + } catch (err) { + toast.error(err.message || 'Failed to delete environment'); + } finally { + setConfirmDialog(null); + } + }, + onCancel: () => setConfirmDialog(null) + }); + }, [id, toast]); + + const handleLock = useCallback(async (env) => { + try { + await wordpressApi.lockEnvironment(id, env.id, { + reason: 'Manually locked', + duration_minutes: 60 + }); + toast.success('Environment locked'); + loadPipeline(); + } catch (err) { + toast.error(err.message || 'Failed to lock environment'); + } + }, [id, toast]); + + const handleUnlock = useCallback(async (env) => { + try { + await wordpressApi.unlockEnvironment(id, env.id); + toast.success('Environment unlocked'); + loadPipeline(); + } catch (err) { + toast.error(err.message || 'Failed to unlock environment'); + } + }, [id, toast]); + + const handleViewLogs = useCallback((env) => { + setLogsPanel({ envId: env.id }); + }, []); + + const handleCompare = useCallback((envA, envB) => { + setCompareModal({ envA, envB }); + }, []); + + // Phase 7 handlers + const handleResourceLimits = useCallback((env) => { + setResourceLimitsModal({ environment: env, currentLimits: env.resource_limits }); + }, []); + + const handleApplyResourceLimits = useCallback(async (limits) => { + const env = resourceLimitsModal.environment; + try { + await wordpressApi.updateResourceLimits(id, env.id, limits); + toast.success('Resource limits updated, containers restarting'); + setResourceLimitsModal(null); + loadPipeline(); + } catch (err) { + toast.error(err.message || 'Failed to update resource limits'); + } + }, [id, resourceLimitsModal, toast]); + + const handleBasicAuth = useCallback((env) => { + setBasicAuthModal({ environment: env }); + }, []); + + const handleWpCli = useCallback((env) => { + setWpCliModal({ environment: env }); + }, []); + + const handleAutoSync = useCallback((env) => { + setAutoSyncModal({ environment: env }); + }, []); + + const handleHealthCheck = useCallback(async (env) => { + try { + const data = await wordpressApi.getEnvironmentHealth(id, env.id); + if (data.success) { + setHealthData(prev => ({ ...prev, [env.id]: data })); + toast.info(`${env.name}: ${data.overall_status}`); + } + } catch (err) { + toast.error('Health check failed'); + } + }, [id, toast]); + + const handleBulkToggle = useCallback((envId) => { + setBulkSelected(prev => + prev.includes(envId) + ? prev.filter(id => id !== envId) + : [...prev, envId] + ); + }, []); + + const handleBulkExecute = useCallback(async (action, envIds) => { + try { + await wordpressApi.executeBulkOperation(id, [{ action, env_ids: envIds }]); + toast.success(`Bulk ${action} completed`); + setBulkSelected([]); + loadPipeline(); + } catch (err) { + toast.error(err.message || `Bulk ${action} failed`); + } + }, [id, toast]); + + // Load health and disk usage data on pipeline load + useEffect(() => { + if (pipeline) { + loadHealthData(); + loadDiskUsageData(); + } + }, [pipeline]); + + async function loadHealthData() { + try { + const data = await wordpressApi.getProjectHealth(id); + if (data.success) { + setHealthData(data.environments || {}); + } + } catch { + // Health data is optional + } + } + + async function loadDiskUsageData() { + try { + const data = await wordpressApi.getProjectDiskUsage(id); + if (data.success) { + setDiskUsageData(data.environments || {}); + } + } catch { + // Disk usage data is optional + } + } + + const handleCreateEnvironment = useCallback(async (data) => { + toast.info('Creating environment...', { duration: 5000 }); + try { + await wordpressApi.createProjectEnvironment(id, data); + setShowCreateEnvModal(false); + } catch (err) { + toast.error(err.message || 'Failed to create environment'); + } + }, [id, toast]); + + if (loading) { + return ( +
+ +
+ ); + } + + if (!pipeline) { + return ( +
+

Project not found

+ +
+ ); + } + + const production = pipeline.production || pipeline; + const projectName = production.name || 'WordPress Project'; + const projectDomain = production.application?.domains?.[0] || production.url || ''; + + return ( +
+ {/* Top Bar */} +
+
+ Projects + / + {projectName} +
+
+ {projectDomain && ( + + + Visit Site + + )} + + +
+
+ + {/* Header */} +
+
+ + + +
+
+

+ {projectName} + + + {production.status === 'running' ? 'Running' : 'Stopped'} + +

+
+ {projectDomain && {projectDomain}} + {production.wp_version && ( + <> + • + WordPress {production.wp_version} + + )} + {pipeline.environments && ( + <> + • + {(pipeline.environments?.length || 0) + 1} environments + + )} +
+
+
+ + {/* Tabs */} +
+
setActiveTab('pipeline')} + > + Pipeline +
+
setActiveTab('activity')} + > + Activity +
+
setActiveTab('health')} + > + Health +
+
+ + {/* Tab Content */} +
+ {activeTab === 'pipeline' && ( +
+ {operationInProgress && ( +
+ +
+ + {operationInProgress === 'promotion_started' && 'Promotion in progress...'} + {operationInProgress === 'sync_started' && 'Sync in progress...'} + {operationInProgress === 'environment_creating' && 'Creating environment...'} + + {operationProgress && ( +
+
+
+
+ + Step {operationProgress.step}/{operationProgress.total}: {operationProgress.message} + +
+ )} +
+
+ )} + + {bulkSelected.length > 0 && ( + setBulkSelected([])} + onExecute={handleBulkExecute} + api={wordpressApi} + /> + )} + + { + setShowCreateEnvModal(true); + }} + onResourceLimits={handleResourceLimits} + onBasicAuth={handleBasicAuth} + onWpCli={handleWpCli} + onAutoSync={handleAutoSync} + onHealthCheck={handleHealthCheck} + operationInProgress={operationInProgress} + healthData={healthData} + diskUsageData={diskUsageData} + bulkSelected={bulkSelected} + onBulkToggle={handleBulkToggle} + /> + + {/* Recent Activity Preview */} +
+
+

Recent Activity

+ +
+ +
+
+ )} + + {activeTab === 'activity' && ( +
+
+

Activity Log

+ +
+ +
+ )} + + {activeTab === 'health' && ( +
+ +
+ )} +
+ + {/* Logs Panel */} + {logsPanel && ( +
+ setLogsPanel(null)} + /> +
+ )} + + {/* Modals */} + {promoteModal && ( + setPromoteModal(null)} + onPromote={handleDoPromote} + /> + )} + + {syncModal && ( + setSyncModal(null)} + onSync={handleDoSync} + /> + )} + + {showCreateEnvModal && ( + setShowCreateEnvModal(false)} + onCreate={handleCreateEnvironment} + productionDomain={projectDomain} + existingTypes={(pipeline.environments || []).map(e => e.environment_type)} + projectId={id} + /> + )} + + {compareModal && ( + setCompareModal(null)} + /> + )} + + {showSanitizationProfiles && ( + setShowSanitizationProfiles(false)} + onProfilesChange={() => {}} + /> + )} + + {resourceLimitsModal && ( + setResourceLimitsModal(null)} + onApply={handleApplyResourceLimits} + /> + )} + + {basicAuthModal && ( + setBasicAuthModal(null)} + api={wordpressApi} + /> + )} + + {wpCliModal && ( + setWpCliModal(null)} + api={wordpressApi} + /> + )} + + {autoSyncModal && ( + setAutoSyncModal(null)} + api={wordpressApi} + /> + )} + + setConfirmDialog(null))} + /> +
+ ); +}; + +// Create Environment Modal (Pipeline version) +const CreatePipelineEnvModal = ({ onClose, onCreate, productionDomain, existingTypes, projectId }) => { + const [formData, setFormData] = useState({ + type: existingTypes.includes('development') ? 'staging' : 'development', + name: '', + branch: '', + clone_db: true + }); + const [loading, setLoading] = useState(false); + const [branches, setBranches] = useState([]); + const [branchesLoading, setBranchesLoading] = useState(false); + const [branchSearch, setBranchSearch] = useState(''); + const [useCustomBranch, setUseCustomBranch] = useState(false); + + const availableTypes = [ + { value: 'development', label: 'Development', disabled: existingTypes.includes('development') }, + { value: 'staging', label: 'Staging', disabled: existingTypes.includes('staging') }, + { value: 'multidev', label: 'Multidev (branch-based)', disabled: false } + ]; + + useEffect(() => { + if (formData.type === 'multidev' && branches.length === 0 && !branchesLoading) { + loadBranches(); + } + }, [formData.type]); + + async function loadBranches() { + setBranchesLoading(true); + try { + const data = await wordpressApi.getBranches(projectId); + setBranches(data.branches || []); + } catch { + setBranches([]); + } finally { + setBranchesLoading(false); + } + } + + function handleChange(e) { + const { name, value, type, checked } = e.target; + setFormData(prev => ({ + ...prev, + [name]: type === 'checkbox' ? checked : value + })); + } + + function selectBranch(branchName) { + setFormData(prev => ({ ...prev, branch: branchName })); + setBranchSearch(''); + } + + async function handleSubmit(e) { + e.preventDefault(); + setLoading(true); + try { + await onCreate(formData); + } finally { + setLoading(false); + } + } + + const filteredBranches = branches.filter(b => { + if (!branchSearch) return true; + return b.name.toLowerCase().includes(branchSearch.toLowerCase()); + }); + + return ( +
+
e.stopPropagation()}> +
+

Create Environment

+ +
+ +
+
+ + +
+ + {formData.type === 'multidev' && ( +
+ + + {formData.branch && !useCustomBranch && ( +
+ + {formData.branch} + +
+ )} + + {!formData.branch && !useCustomBranch && ( + <> + {branchesLoading ? ( +
+ + Loading branches... +
+ ) : branches.length > 0 ? ( +
+
+ + setBranchSearch(e.target.value)} + placeholder="Search branches..." + autoFocus + /> +
+
+ {filteredBranches.map(b => ( + + ))} + {filteredBranches.length === 0 && ( +
+ No branches match "{branchSearch}" +
+ )} +
+ +
+ ) : ( +
+ + No git repo connected or no branches found. Enter branch name manually. +
+ )} + + )} + + {useCustomBranch && ( +
+ + {branches.length > 0 && ( + + )} +
+ )} +
+ )} + +
+ + + Leave empty to auto-generate +
+ +
+ + Creates a copy of the production database for this environment +
+ +
+ + +
+
+
+
+ ); +}; + +export default WordPressProject; diff --git a/frontend/src/pages/WordPressProjects.jsx b/frontend/src/pages/WordPressProjects.jsx new file mode 100644 index 00000000..97a658e2 --- /dev/null +++ b/frontend/src/pages/WordPressProjects.jsx @@ -0,0 +1,139 @@ +import React, { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { ExternalLink, Plus, GitBranch, Layers } from 'lucide-react'; +import wordpressApi from '../services/wordpress'; +import { useToast } from '../contexts/ToastContext'; +import Spinner from '../components/Spinner'; + +const WordPressProjects = () => { + const [projects, setProjects] = useState([]); + const [loading, setLoading] = useState(true); + const navigate = useNavigate(); + const toast = useToast(); + + useEffect(() => { + loadProjects(); + }, []); + + async function loadProjects() { + setLoading(true); + try { + const data = await wordpressApi.getProjects(); + setProjects(data.projects || []); + } catch (err) { + console.error('Failed to load projects:', err); + toast.error('Failed to load WordPress projects'); + } finally { + setLoading(false); + } + } + + if (loading) { + return ( +
+ +
+ ); + } + + return ( +
+
+
+

WordPress Projects

+

Manage WordPress sites with environment pipelines

+
+
+ + {projects.length === 0 ? ( +
+
+ +
+

No WordPress Projects

+

WordPress projects with environment pipelines will appear here. Create a WordPress site with environments enabled to get started.

+
+ ) : ( +
+ {projects.map(project => ( + navigate(`/wordpress/projects/${project.id}`)} + /> + ))} +
+ )} +
+ ); +}; + +const ProjectCard = ({ project, onClick }) => { + const isRunning = project.status === 'running'; + const envCount = project.environment_count || 0; + const envTypes = project.environment_types || []; + const domain = project.application?.domains?.[0] || project.url || ''; + + return ( +
+
+
+ + + +
+
+

{project.name}

+ {domain && ( + {domain} + )} +
+ + + {isRunning ? 'Running' : 'Stopped'} + +
+ +
+
+
+ + {envCount + 1} environment{envCount !== 0 ? 's' : ''} +
+ {envTypes.length > 0 && ( +
+ PROD + {envTypes.includes('staging') && ( + STG + )} + {envTypes.includes('development') && ( + DEV + )} + {envTypes.includes('multidev') && ( + MD + )} +
+ )} + {project.wp_version && ( +
+ WordPress {project.wp_version} +
+ )} + {project.git_repo_url && ( +
+ + Git connected +
+ )} +
+
+ +
+ View Pipeline + +
+
+ ); +}; + +export default WordPressProjects; diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.js index cf267e05..884dcf23 100644 --- a/frontend/src/services/wordpress.js +++ b/frontend/src/services/wordpress.js @@ -99,6 +99,164 @@ const wordpressApi = { cloneDatabase: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/clone-db`, { method: 'POST', body: data + }), + + // ========================================= + // Pipeline API (Environment Management v2) + // ========================================= + PIPELINE_PATH: '/wordpress/projects', + + // Project listing + getProjects: () => api.request('/wordpress/projects'), + + // Pipeline dashboard + getProjectPipeline: (prodId) => api.request(`/wordpress/projects/${prodId}/pipeline`), + + // Environment CRUD + createProjectEnvironment: (prodId, data) => api.request(`/wordpress/projects/${prodId}/environments`, { + method: 'POST', + body: data + }), + + getProjectEnvironment: (prodId, envId) => api.request(`/wordpress/projects/${prodId}/environments/${envId}`), + + deleteProjectEnvironment: (prodId, envId) => api.request(`/wordpress/projects/${prodId}/environments/${envId}`, { + method: 'DELETE' + }), + + // Container lifecycle + startEnvironment: (prodId, envId) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/start`, { + method: 'POST' + }), + + stopEnvironment: (prodId, envId) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/stop`, { + method: 'POST' + }), + + restartEnvironment: (prodId, envId) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/restart`, { + method: 'POST' + }), + + // Promotion + promoteEnvironment: (prodId, data) => api.request(`/wordpress/projects/${prodId}/promote`, { + method: 'POST', + body: data + }), + + // Sync from production + syncProjectEnvironment: (prodId, envId, data) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/sync`, { + method: 'POST', + body: data + }), + + // Compare environments + compareEnvironments: (prodId, envAId, envBId) => + api.request(`/wordpress/projects/${prodId}/compare?env_a=${envAId}&env_b=${envBId}`), + + // Locking + lockEnvironment: (prodId, envId, data) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/lock`, { + method: 'POST', + body: data + }), + + unlockEnvironment: (prodId, envId) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/lock`, { + method: 'DELETE' + }), + + // Activity log + getProjectActivity: (prodId, params = {}) => { + const query = new URLSearchParams(params).toString(); + return api.request(`/wordpress/projects/${prodId}/activity${query ? `?${query}` : ''}`); + }, + + // Container logs + getEnvironmentLogs: (prodId, envId, params = {}) => { + const query = new URLSearchParams(params).toString(); + return api.request(`/wordpress/projects/${prodId}/environments/${envId}/logs${query ? `?${query}` : ''}`); + }, + + // Promotion history + getPromotionHistory: (prodId, params = {}) => { + const query = new URLSearchParams(params).toString(); + return api.request(`/wordpress/projects/${prodId}/promotions${query ? `?${query}` : ''}`); + }, + + // Git branches (for multidev) + getBranches: (prodId) => api.request(`/wordpress/projects/${prodId}/git/branches`), + + // Multidev cleanup + cleanupMultidevs: (prodId, dryRun = true) => api.request(`/wordpress/projects/${prodId}/multidev/cleanup`, { + method: 'POST', + body: { dry_run: dryRun } + }), + + // Sanitization Profiles + getSanitizationProfiles: () => api.request('/wordpress/projects/sanitization-profiles'), + + createSanitizationProfile: (data) => api.request('/wordpress/projects/sanitization-profiles', { + method: 'POST', + body: data + }), + + updateSanitizationProfile: (profileId, data) => api.request(`/wordpress/projects/sanitization-profiles/${profileId}`, { + method: 'PUT', + body: data + }), + + deleteSanitizationProfile: (profileId) => api.request(`/wordpress/projects/sanitization-profiles/${profileId}`, { + method: 'DELETE' + }), + + // ========================================= + // Phase 7: Advanced Features + // ========================================= + + // Resource Limits + updateResourceLimits: (prodId, envId, limits) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/resources`, { + method: 'PUT', + body: limits + }), + + // Basic Auth + enableBasicAuth: (prodId, envId, data = {}) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/auth`, { + method: 'POST', + body: data + }), + + disableBasicAuth: (prodId, envId) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/auth`, { + method: 'DELETE' + }), + + getBasicAuthStatus: (prodId, envId) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/auth`), + + // WP-CLI + executeWpCli: (prodId, envId, command) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/exec`, { + method: 'POST', + body: { command } + }), + + // Health + getEnvironmentHealth: (prodId, envId) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/health`), + + getProjectHealth: (prodId) => api.request(`/wordpress/projects/${prodId}/health`), + + // Disk Usage + getEnvironmentDiskUsage: (prodId, envId) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/disk-usage`), + + getProjectDiskUsage: (prodId) => api.request(`/wordpress/projects/${prodId}/disk-usage`), + + // Bulk Operations + executeBulkOperation: (prodId, operations) => api.request(`/wordpress/projects/${prodId}/bulk`, { + method: 'POST', + body: { operations } + }), + + // Auto-Sync + getAutoSyncSchedule: (prodId, envId) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/auto-sync`), + + updateAutoSyncSchedule: (prodId, envId, config) => api.request(`/wordpress/projects/${prodId}/environments/${envId}/auto-sync`, { + method: 'PUT', + body: config }) }; diff --git a/frontend/src/styles/components/_metrics-graph.less b/frontend/src/styles/components/_metrics-graph.less index ae19fdfe..5511c1dc 100644 --- a/frontend/src/styles/components/_metrics-graph.less +++ b/frontend/src/styles/components/_metrics-graph.less @@ -85,7 +85,7 @@ // Chart Container .metrics-chart-container { margin-bottom: @space-4; - background: linear-gradient(180deg, rgba(39, 39, 42, 0.3) 0%, transparent 100%); + background: linear-gradient(180deg, var(--bg-hover) 0%, transparent 100%); border-radius: @radius-lg; padding: @space-2 0; diff --git a/frontend/src/styles/components/_modals.less b/frontend/src/styles/components/_modals.less index e41736ee..f3c621ab 100644 --- a/frontend/src/styles/components/_modals.less +++ b/frontend/src/styles/components/_modals.less @@ -73,6 +73,14 @@ border-top: 1px solid @border-subtle; } +.modal-footer { + display: flex; + gap: @space-3; + justify-content: flex-end; + padding: @space-4 @space-6; + border-top: 1px solid @border-subtle; +} + // Type selection grid (used in create app modal) .app-type-grid { display: grid; diff --git a/frontend/src/styles/layout/_sidebar.less b/frontend/src/styles/layout/_sidebar.less index e6e89aa6..403fef2e 100644 --- a/frontend/src/styles/layout/_sidebar.less +++ b/frontend/src/styles/layout/_sidebar.less @@ -440,6 +440,12 @@ } } +// Sub Navigation Item (indented under parent) +.nav-sub-item { + padding-left: 2.25rem; + font-size: 0.8rem; +} + // Navigation Icon .nav-icon { width: 18px; diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.less index 70f486a7..d32bc796 100644 --- a/frontend/src/styles/main.less +++ b/frontend/src/styles/main.less @@ -76,4 +76,5 @@ @import 'pages/_servers'; @import 'pages/_downloads'; @import 'pages/_wordpress'; +@import 'pages/_wordpress-pipeline'; @import 'pages/_ssl'; diff --git a/frontend/src/styles/pages/_wordpress-pipeline.less b/frontend/src/styles/pages/_wordpress-pipeline.less new file mode 100644 index 00000000..b069f115 --- /dev/null +++ b/frontend/src/styles/pages/_wordpress-pipeline.less @@ -0,0 +1,2342 @@ +// ============================================ +// WORDPRESS PIPELINE STYLES +// ============================================ + +// Page Loading +.page-loading { + display: flex; + align-items: center; + justify-content: center; + min-height: 400px; +} + +// Projects Page +.wp-projects-page { + padding: @space-4; + + .page-header { + margin-bottom: @space-6; + } + + .page-header-content { + h1 { + font-size: @font-size-xl; + font-weight: @font-weight-bold; + color: @text-primary; + margin: 0 0 @space-1; + } + } + + .page-description { + font-size: @font-size-sm; + color: @text-tertiary; + margin: 0; + } + + .empty-state-large { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 60px @space-6; + background: @bg-card; + border-radius: @radius-xl; + text-align: center; + + .empty-icon { + color: @text-tertiary; + margin-bottom: @space-4; + } + + h2 { + font-size: @font-size-lg; + font-weight: @font-weight-semibold; + color: @text-primary; + margin: 0 0 @space-2; + } + + p { + font-size: @font-size-sm; + color: @text-secondary; + max-width: 460px; + margin: 0; + } + } +} + +.wp-projects-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); + gap: @space-4; +} + +.wp-project-card { + background: @bg-card; + border: 1px solid @border-subtle; + border-radius: @radius-lg; + cursor: pointer; + transition: all 0.15s ease; + + &:hover { + border-color: @border-hover; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); + } +} + +.wp-project-card-header { + display: flex; + align-items: center; + gap: @space-3; + padding: @space-4; + border-bottom: 1px solid @border-subtle; +} + +.wp-project-info { + flex: 1; + min-width: 0; +} + +.wp-project-name { + font-size: @font-size-base; + font-weight: @font-weight-semibold; + color: @text-primary; + margin: 0; +} + +.wp-project-domain { + font-size: @font-size-xs; + color: @text-tertiary; + font-family: @font-family-mono; +} + +.wp-project-card-body { + padding: @space-4; +} + +.wp-project-meta { + display: flex; + flex-wrap: wrap; + gap: @space-3; + align-items: center; +} + +.wp-project-meta-item { + display: flex; + align-items: center; + gap: 4px; + font-size: @font-size-sm; + color: @text-secondary; + + svg { + color: @text-tertiary; + } +} + +.wp-project-env-badges { + display: flex; + gap: @space-1; +} + +.wp-project-card-footer { + display: flex; + align-items: center; + justify-content: space-between; + padding: @space-3 @space-4; + border-top: 1px solid @border-subtle; + background: @bg-tertiary; + border-radius: 0 0 @radius-lg @radius-lg; +} + +.wp-project-card-cta { + font-size: @font-size-sm; + font-weight: @font-weight-medium; + color: @color-primary; +} + +// ============================================ +// PIPELINE DASHBOARD +// ============================================ + +.wp-project-page { + .wp-icon { + background: linear-gradient(135deg, #21759b 0%, #1a5f7f 100%) !important; + } +} + +// Pipeline Tab +.pipeline-tab { + padding: @space-4 0; +} + +.pipeline-operation-banner { + display: flex; + align-items: center; + gap: @space-3; + padding: @space-3 @space-4; + background: fade(@color-info, 10%); + border: 1px solid fade(@color-info, 25%); + border-radius: @radius-md; + margin-bottom: @space-4; + font-size: @font-size-sm; + color: @color-info; +} + +// Pipeline View +.pipeline-view { + margin-bottom: @space-6; +} + +.pipeline-row { + display: flex; + align-items: stretch; + gap: 0; + overflow-x: auto; + padding-bottom: @space-2; +} + +.pipeline-card { + flex: 1; + min-width: 220px; + max-width: 320px; + background: @bg-card; + border: 1px solid @border-subtle; + border-radius: @radius-lg; + display: flex; + flex-direction: column; + position: relative; + + &.production { + border-color: fade(@color-danger, 30%); + border-left: 3px solid @color-danger; + } + + &.locked { + opacity: 0.85; + } + + &.empty { + border-style: dashed; + border-color: @border-subtle; + display: flex; + align-items: center; + justify-content: center; + min-height: 180px; + } +} + +.pipeline-empty-content { + text-align: center; + color: @text-tertiary; + + p { + margin: @space-2 0 0; + font-size: @font-size-sm; + } +} + +.pipeline-card-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: @space-3 @space-4; + border-bottom: 1px solid @border-subtle; +} + +.env-status-badge-group { + display: flex; + align-items: center; + gap: @space-2; +} + +.env-locked-badge { + display: flex; + align-items: center; + padding: 2px 4px; + background: fade(@color-warning, 15%); + color: @color-warning; + border-radius: @radius-sm; +} + +.pipeline-card-menu-wrapper { + position: relative; +} + +.pipeline-card-menu-btn { + padding: 4px !important; +} + +.pipeline-card-menu { + position: absolute; + right: 0; + top: 100%; + background: @bg-elevated; + border: 1px solid @border-subtle; + border-radius: @radius-md; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2); + z-index: 100; + min-width: 140px; + padding: @space-1; + + button { + display: flex; + align-items: center; + gap: @space-2; + width: 100%; + padding: @space-2 @space-3; + border: none; + background: none; + color: @text-secondary; + font-size: @font-size-sm; + cursor: pointer; + border-radius: @radius-sm; + text-align: left; + + &:hover { + background: @bg-hover; + color: @text-primary; + } + + &.danger { + color: @color-danger; + + &:hover { + background: fade(@color-danger, 10%); + } + } + } +} + +.pipeline-card-body { + flex: 1; + padding: @space-4; +} + +.pipeline-card-name { + font-size: @font-size-base; + font-weight: @font-weight-semibold; + color: @text-primary; + margin: 0 0 @space-2; +} + +.pipeline-card-domain { + display: block; + font-size: @font-size-xs; + font-family: @font-family-mono; + color: @color-primary; + margin-bottom: @space-2; + text-decoration: none; + + &:hover { + text-decoration: underline; + } +} + +.pipeline-card-meta { + display: flex; + flex-wrap: wrap; + gap: @space-2; +} + +.pipeline-meta-item { + font-size: @font-size-xs; + color: @text-tertiary; +} + +.pipeline-card-footer { + display: flex; + gap: @space-2; + padding: @space-2 @space-3; + border-top: 1px solid @border-subtle; + background: @bg-tertiary; + border-radius: 0 0 @radius-lg @radius-lg; +} + +.pipeline-card-lock-banner { + display: flex; + align-items: center; + gap: @space-1; + padding: @space-2 @space-3; + background: fade(@color-warning, 10%); + font-size: @font-size-xs; + color: @color-warning; + border-radius: 0 0 @radius-lg @radius-lg; +} + +// Pipeline Arrows +.pipeline-arrow { + display: flex; + align-items: center; + justify-content: center; + min-width: 80px; + padding: 0 @space-2; + + &.disabled { + opacity: 0.3; + pointer-events: none; + } +} + +.pipeline-arrow-btn { + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; + padding: @space-2 @space-3; + border: 1px solid @border-subtle; + background: @bg-card; + border-radius: @radius-md; + cursor: pointer; + color: @text-secondary; + transition: all 0.15s ease; + + &:hover:not(:disabled) { + border-color: @color-primary; + color: @color-primary; + background: fade(@color-primary, 5%); + } + + &:disabled { + cursor: not-allowed; + opacity: 0.4; + } +} + +.pipeline-arrow-label { + font-size: 10px; + font-weight: @font-weight-medium; + text-transform: uppercase; + letter-spacing: 0.5px; +} + +// Pipeline Sync Row +.pipeline-sync-row { + display: flex; + gap: 0; + margin-top: @space-2; + + .pipeline-sync-action { + flex: 1; + min-width: 220px; + max-width: 320px; + display: flex; + justify-content: center; + } +} + +// Multidev Section +.pipeline-multidev-section { + margin-top: @space-6; + padding-top: @space-4; + border-top: 1px solid @border-subtle; +} + +.pipeline-section-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: @space-3; +} + +.pipeline-section-title { + display: flex; + align-items: center; + gap: @space-2; + font-size: @font-size-sm; + font-weight: @font-weight-semibold; + color: @text-secondary; + text-transform: uppercase; + letter-spacing: 0.5px; + margin: 0; +} + +.pipeline-section-count { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 20px; + height: 20px; + padding: 0 6px; + background: fade(@color-primary, 12%); + color: @color-primary; + border-radius: 10px; + font-size: 11px; + font-weight: @font-weight-bold; + text-transform: none; + letter-spacing: 0; +} + +.pipeline-multidev-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + gap: @space-3; +} + +.pipeline-multidev-empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: @space-8 @space-4; + background: @bg-card; + border: 1px dashed @border-subtle; + border-radius: @radius-lg; + text-align: center; + + > svg { + color: @text-tertiary; + margin-bottom: @space-3; + } + + p { + font-size: @font-size-base; + font-weight: @font-weight-medium; + color: @text-secondary; + margin: 0 0 @space-1; + } + + > span { + font-size: @font-size-sm; + color: @text-tertiary; + margin-bottom: @space-4; + } +} + +.multidev-card { + background: @bg-card; + border: 1px solid @border-subtle; + border-radius: @radius-lg; + transition: border-color 0.15s ease; + + &:hover { + border-color: @border-hover; + } + + &.locked { + opacity: 0.85; + } +} + +.multidev-card-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: @space-3 @space-4; + border-bottom: 1px solid @border-subtle; +} + +.multidev-card-header-left { + display: flex; + align-items: center; + gap: @space-2; +} + +.multidev-lock-icon { + color: @color-warning; +} + +.multidev-card-menu-wrapper { + position: relative; +} + +.multidev-card-body { + padding: @space-3 @space-4; +} + +.multidev-card-name { + font-size: @font-size-sm; + font-weight: @font-weight-semibold; + color: @text-primary; + margin: 0 0 @space-2; +} + +.multidev-branch { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: @font-size-xs; + font-family: @font-family-mono; + color: @text-tertiary; + background: @bg-tertiary; + padding: 2px 8px; + border-radius: @radius-sm; + margin-bottom: @space-2; +} + +.multidev-domain { + display: block; + font-size: @font-size-xs; + font-family: @font-family-mono; + color: @color-primary; + text-decoration: none; + margin-bottom: @space-2; + + &:hover { + text-decoration: underline; + } +} + +.multidev-card-meta { + display: flex; + flex-wrap: wrap; + gap: @space-2; +} + +.multidev-meta-item { + font-size: @font-size-xs; + color: @text-tertiary; +} + +.multidev-card-footer { + display: flex; + gap: @space-2; + padding: @space-2 @space-3; + border-top: 1px solid @border-subtle; + background: @bg-tertiary; + border-radius: 0 0 @radius-lg @radius-lg; +} + +.wp-env-badge.env-multidev { + background: fade(@color-primary, 12%); + color: @color-primary; +} + +// ============================================ +// BRANCH PICKER +// ============================================ + +.branch-selected { + display: flex; + align-items: center; + gap: @space-2; + padding: @space-3; + background: fade(@color-primary, 8%); + border: 1px solid fade(@color-primary, 25%); + border-radius: @radius-md; + + svg { + color: @color-primary; + flex-shrink: 0; + } +} + +.branch-selected-name { + flex: 1; + font-family: @font-family-mono; + font-size: @font-size-sm; + font-weight: @font-weight-medium; + color: @text-primary; +} + +.branch-picker-loading { + display: flex; + align-items: center; + gap: @space-2; + padding: @space-4; + justify-content: center; + color: @text-tertiary; + font-size: @font-size-sm; +} + +.branch-picker { + border: 1px solid @border-subtle; + border-radius: @radius-md; + overflow: hidden; +} + +.branch-picker-search { + display: flex; + align-items: center; + gap: @space-2; + padding: @space-2 @space-3; + border-bottom: 1px solid @border-subtle; + background: @bg-tertiary; + + svg { + color: @text-tertiary; + flex-shrink: 0; + } + + input { + flex: 1; + border: none; + background: none; + font-size: @font-size-sm; + color: @text-primary; + outline: none; + padding: 0; + + &::placeholder { + color: @text-tertiary; + } + } +} + +.branch-picker-list { + max-height: 240px; + overflow-y: auto; +} + +.branch-picker-item { + display: flex; + flex-direction: column; + gap: 2px; + width: 100%; + padding: @space-2 @space-3; + border: none; + border-bottom: 1px solid @border-subtle; + background: @bg-card; + cursor: pointer; + text-align: left; + transition: background 0.1s ease; + + &:last-child { + border-bottom: none; + } + + &:hover:not(:disabled) { + background: @bg-hover; + } + + &:disabled { + opacity: 0.5; + cursor: not-allowed; + } + + &.has-env { + background: fade(@text-tertiary-raw, 3%); + } +} + +.branch-picker-item-main { + display: flex; + align-items: center; + gap: @space-2; + font-size: @font-size-sm; + color: @text-primary; + + svg { + color: @text-tertiary; + flex-shrink: 0; + } +} + +.branch-name { + font-family: @font-family-mono; + font-weight: @font-weight-medium; +} + +.branch-tag { + font-size: 10px; + font-weight: @font-weight-medium; + padding: 1px 6px; + border-radius: @radius-sm; + background: fade(@text-tertiary-raw, 10%); + color: @text-tertiary; + + &.env { + background: fade(@color-primary, 10%); + color: @color-primary; + } +} + +.branch-picker-item-meta { + display: flex; + align-items: center; + gap: @space-2; + padding-left: 20px; + + .branch-sha { + font-family: @font-family-mono; + font-size: 11px; + color: @text-tertiary; + } + + .branch-msg { + font-size: 11px; + color: @text-tertiary; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } +} + +.branch-picker-empty { + padding: @space-4; + text-align: center; + font-size: @font-size-sm; + color: @text-tertiary; +} + +.branch-picker-custom { + width: 100%; + border-top: 1px solid @border-subtle; + border-radius: 0 0 @radius-md @radius-md; + justify-content: center; + color: @color-primary !important; +} + +// ============================================ +// PROMOTE / SYNC MODALS +// ============================================ + +.promote-direction, +.sync-direction { + display: flex; + align-items: center; + justify-content: center; + gap: @space-3; + padding: @space-4; + background: @bg-tertiary; + border-radius: @radius-md; + margin-bottom: @space-4; +} + +.promote-env-pill { + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; + padding: @space-3 @space-4; + background: @bg-card; + border: 1px solid @border-subtle; + border-radius: @radius-md; + min-width: 120px; + + .promote-env-type { + font-size: @font-size-xs; + font-weight: @font-weight-bold; + text-transform: uppercase; + letter-spacing: 0.5px; + } + + .promote-env-name { + font-size: @font-size-sm; + color: @text-secondary; + max-width: 150px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + &.production .promote-env-type { color: @color-danger; } + &.staging .promote-env-type { color: @color-warning; } + &.development .promote-env-type { color: @color-info; } + &.multidev .promote-env-type { color: @color-primary; } +} + +.promote-arrow { + color: @text-tertiary; + flex-shrink: 0; +} + +.promote-warning, +.sync-warning { + display: flex; + align-items: flex-start; + gap: @space-3; + padding: @space-3 @space-4; + background: fade(@color-warning, 8%); + border: 1px solid fade(@color-warning, 20%); + border-radius: @radius-md; + margin-top: @space-4; + font-size: @font-size-sm; + color: @text-secondary; + + > svg { + color: @color-warning; + flex-shrink: 0; + margin-top: 2px; + } + + strong { + color: @text-primary; + } + + p { + margin: @space-1 0 0; + } +} + +// Radio Group for promotion/sync type selection +.radio-group { + display: flex; + flex-direction: column; + gap: @space-2; +} + +.radio-label { + display: flex; + align-items: flex-start; + gap: @space-3; + padding: @space-3; + border: 1px solid @border-subtle; + border-radius: @radius-md; + cursor: pointer; + transition: all 0.15s ease; + + &:hover { + border-color: @border-hover; + background: @bg-hover; + } + + &:has(input:checked) { + border-color: @color-primary; + background: fade(@color-primary, 5%); + } + + input[type="radio"] { + margin-top: 4px; + accent-color: var(--color-primary, #3b82f6); + } +} + +.radio-content { + display: flex; + flex-direction: column; + gap: 2px; + + strong { + font-size: @font-size-sm; + color: @text-primary; + } + + span { + font-size: @font-size-xs; + color: @text-tertiary; + } +} + +.checkbox-group { + display: flex; + flex-direction: column; + gap: @space-2; +} + +// ============================================ +// ACTIVITY FEED +// ============================================ + +.activity-feed { + display: flex; + flex-direction: column; + gap: 1px; + background: @border-subtle; + border: 1px solid @border-subtle; + border-radius: @radius-lg; + overflow: hidden; + + &.compact .activity-item { + padding: @space-2 @space-3; + } +} + +.activity-feed-empty { + padding: @space-6; + text-align: center; + color: @text-tertiary; + font-size: @font-size-sm; +} + +.activity-item { + display: flex; + align-items: center; + gap: @space-3; + padding: @space-3 @space-4; + background: @bg-card; +} + +.activity-item-skeleton { + display: flex; + align-items: center; + gap: @space-3; + padding: @space-3 @space-4; +} + +.activity-icon { + display: flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + border-radius: 50%; + flex-shrink: 0; + + &.success { + background: fade(@color-success, 12%); + color: @color-success; + } + &.danger { + background: fade(@color-danger, 12%); + color: @color-danger; + } + &.warning { + background: fade(@color-warning, 12%); + color: @color-warning; + } + &.info { + background: fade(@color-info, 12%); + color: @color-info; + } + &.primary { + background: fade(@color-primary, 12%); + color: @color-primary; + } + &.default { + background: fade(@text-tertiary-raw, 12%); + color: @text-tertiary; + } +} + +.activity-content { + flex: 1; + min-width: 0; +} + +.activity-description { + font-size: @font-size-sm; + color: @text-primary; + display: block; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.activity-error { + font-size: @font-size-xs; + color: @color-danger; + display: block; + margin-top: 2px; +} + +.activity-meta { + display: flex; + align-items: center; + gap: @space-2; + flex-shrink: 0; +} + +.activity-time { + font-size: @font-size-xs; + color: @text-tertiary; + white-space: nowrap; +} + +.activity-status-badge { + font-size: 10px; + font-weight: @font-weight-medium; + padding: 2px 6px; + border-radius: @radius-sm; + + &.failed { + background: fade(@color-danger, 12%); + color: @color-danger; + } + + &.running { + background: fade(@color-info, 12%); + color: @color-info; + } +} + +.activity-load-more { + background: @bg-card; + padding: @space-3; + text-align: center; + width: 100%; + justify-content: center; +} + +// Pipeline Activity Preview +.pipeline-activity-preview { + margin-top: @space-6; +} + +// ============================================ +// CONTAINER LOGS +// ============================================ + +.pipeline-logs-overlay { + position: fixed; + bottom: 0; + right: 0; + width: 600px; + max-width: 100%; + height: 400px; + z-index: 200; + box-shadow: -4px -4px 24px rgba(0, 0, 0, 0.3); + border-radius: @radius-lg @radius-lg 0 0; + overflow: hidden; + + @media (max-width: 768px) { + width: 100%; + } +} + +.container-logs-panel { + display: flex; + flex-direction: column; + height: 100%; + background: @bg-body; + border: 1px solid @border-subtle; + border-radius: @radius-lg @radius-lg 0 0; +} + +.container-logs-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: @space-3 @space-4; + border-bottom: 1px solid @border-subtle; + background: @bg-elevated; +} + +.container-logs-title { + display: flex; + align-items: center; + gap: @space-2; + font-size: @font-size-sm; + font-weight: @font-weight-semibold; + color: @text-primary; +} + +.container-logs-controls { + display: flex; + align-items: center; + gap: @space-2; +} + +.logs-service-select, +.logs-lines-select { + padding: 4px 8px; + font-size: @font-size-xs; + border: 1px solid @border-subtle; + border-radius: @radius-sm; + background: @bg-card; + color: @text-primary; +} + +.container-logs-body { + flex: 1; + overflow-y: auto; + background: @bg-body; +} + +.logs-loading, +.logs-empty { + padding: @space-6; + text-align: center; + color: @text-tertiary; + font-size: @font-size-sm; +} + +.logs-content { + margin: 0; + padding: @space-3; + font-family: @font-family-mono; + font-size: 12px; + line-height: 1.6; + color: @text-secondary; + white-space: pre-wrap; + word-break: break-all; +} + +.log-line { + padding: 1px 0; + + &:hover { + background: fade(@text-primary-raw, 5%); + } +} + +// ============================================ +// COMPARE VIEW +// ============================================ + +.compare-header { + display: flex; + align-items: center; + justify-content: center; + gap: @space-3; + padding: @space-4; + background: @bg-tertiary; + margin: 0 -@space-5; + padding: @space-4 @space-5; +} + +.compare-env-pill { + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; + padding: @space-3 @space-4; + background: @bg-card; + border: 1px solid @border-subtle; + border-radius: @radius-md; + min-width: 120px; + + .compare-env-type { + font-size: @font-size-xs; + font-weight: @font-weight-bold; + text-transform: uppercase; + letter-spacing: 0.5px; + } + + .compare-env-name { + font-size: @font-size-sm; + color: @text-secondary; + max-width: 150px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + &.production .compare-env-type { color: @color-danger; } + &.staging .compare-env-type { color: @color-warning; } + &.development .compare-env-type { color: @color-info; } + &.multidev .compare-env-type { color: @color-primary; } +} + +.compare-vs-icon { + color: @text-tertiary; + flex-shrink: 0; +} + +.compare-body { + padding: @space-4 0; + max-height: 60vh; + overflow-y: auto; +} + +.compare-loading { + display: flex; + flex-direction: column; + align-items: center; + gap: @space-3; + padding: @space-8; + color: @text-tertiary; + font-size: @font-size-sm; +} + +.compare-error { + text-align: center; + padding: @space-6; + + p { + color: @color-danger; + margin: 0 0 @space-3; + } +} + +.compare-section { + margin-bottom: @space-4; + + &:last-child { + margin-bottom: 0; + } +} + +.compare-section-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: @space-2 @space-3; + background: @bg-tertiary; + border-radius: @radius-md; + margin-bottom: @space-2; + + h4 { + margin: 0; + font-size: @font-size-sm; + font-weight: @font-weight-semibold; + color: @text-primary; + } +} + +.compare-section-summary { + font-size: @font-size-xs; + color: @text-tertiary; +} + +.compare-table { + border: 1px solid @border-subtle; + border-radius: @radius-md; + overflow: hidden; +} + +.compare-row { + display: grid; + grid-template-columns: 1fr 1fr 1fr; + gap: @space-2; + padding: @space-2 @space-3; + border-bottom: 1px solid @border-subtle; + font-size: @font-size-sm; + align-items: center; + + &:last-child { + border-bottom: none; + } + + &.match { + .compare-row-icon { color: @color-success; } + } + + &.different { + background: fade(@color-danger, 5%); + .compare-row-icon { color: @color-danger; } + .compare-row-value-a, + .compare-row-value-b { + font-weight: @font-weight-medium; + } + } + + &.only-a { + .compare-row-icon { color: @color-warning; } + .compare-row-value-b { opacity: 0.4; } + } + + &.only-b { + .compare-row-icon { color: @color-warning; } + .compare-row-value-a { opacity: 0.4; } + } +} + +.compare-row-label { + display: flex; + align-items: center; + gap: @space-2; + font-weight: @font-weight-medium; + color: @text-primary; +} + +.compare-row-icon { + flex-shrink: 0; +} + +.compare-row-value-a, +.compare-row-value-b { + font-size: @font-size-xs; + color: @text-secondary; + font-family: @font-family-mono; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.compare-na { + color: @text-tertiary; + font-style: italic; +} + +.compare-empty-row { + padding: @space-4; + text-align: center; + font-size: @font-size-sm; + color: @text-tertiary; +} + +// Pipeline Compare Row +.pipeline-compare-row { + display: flex; + gap: @space-3; + justify-content: center; + margin-top: @space-2; + padding: @space-2 0; +} + +.pipeline-compare-btn { + color: @text-tertiary !important; + font-size: @font-size-xs !important; + + &:hover { + color: @color-primary !important; + } +} + +// ============================================ +// SANITIZATION PROFILES +// ============================================ + +.sanitization-profiles-body { + padding: @space-4 0; + max-height: 60vh; + overflow-y: auto; +} + +.sanitization-loading { + display: flex; + align-items: center; + justify-content: center; + padding: @space-8; +} + +.sanitization-profile-list { + display: flex; + flex-direction: column; + gap: @space-3; + margin-bottom: @space-4; +} + +.sanitization-profile-card { + background: @bg-card; + border: 1px solid @border-subtle; + border-radius: @radius-md; + padding: @space-3 @space-4; + transition: border-color 0.15s ease; + + &:hover { + border-color: @border-hover; + } + + &.default { + border-color: fade(@color-primary, 30%); + border-left: 3px solid @color-primary; + } +} + +.sanitization-profile-card-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: @space-2; +} + +.sanitization-profile-card-title { + display: flex; + align-items: center; + gap: @space-2; + + h5 { + margin: 0; + font-size: @font-size-sm; + font-weight: @font-weight-semibold; + color: @text-primary; + } +} + +.sanitization-tag { + font-size: 10px; + font-weight: @font-weight-medium; + padding: 1px 6px; + border-radius: @radius-sm; + + &.builtin { + background: fade(@text-tertiary-raw, 10%); + color: @text-tertiary; + } + + &.default { + background: fade(@color-primary, 12%); + color: @color-primary; + } +} + +.sanitization-profile-card-actions { + display: flex; + gap: @space-1; +} + +.sanitization-profile-desc { + font-size: @font-size-xs; + color: @text-secondary; + margin: 0 0 @space-2; +} + +.sanitization-rule-tags { + display: flex; + flex-wrap: wrap; + gap: 4px; +} + +.sanitization-rule-tag { + font-size: 10px; + padding: 2px 8px; + background: @bg-tertiary; + border-radius: @radius-sm; + color: @text-tertiary; + + &.empty { + font-style: italic; + } +} + +.sanitization-add-btn { + width: 100%; + justify-content: center; +} + +// Profile Editor +.sanitization-editor { + background: @bg-tertiary; + border: 1px solid @border-subtle; + border-radius: @radius-md; + padding: @space-4; + margin-top: @space-3; + + h4 { + margin: 0 0 @space-3; + font-size: @font-size-sm; + font-weight: @font-weight-semibold; + color: @text-primary; + } + + .form-group { + margin-bottom: @space-3; + + &:last-of-type { + margin-bottom: @space-4; + } + } +} + +.sanitization-editor-actions { + display: flex; + justify-content: flex-end; + gap: @space-2; + padding-top: @space-3; + border-top: 1px solid @border-subtle; +} + +// ============================================ +// RESPONSIVE +// ============================================ + +// ============================================ +// PIPELINE CARD ADDITIONS (Phase 7) +// ============================================ + +.pipeline-card-checkbox { + margin-right: @space-1; + accent-color: var(--color-primary, #3b82f6); +} + +.pipeline-card-menu-divider { + height: 1px; + background: @border-subtle; + margin: @space-1 0; +} + +// ============================================ +// RESOURCE LIMITS MODAL +// ============================================ + +.resource-limits-modal { + max-width: 480px; +} + +.resource-limits-env-name { + font-size: @font-size-sm; + font-weight: @font-weight-semibold; + color: @text-primary; + padding-bottom: @space-3; + border-bottom: 1px solid @border-subtle; + margin-bottom: @space-3; +} + +.resource-limits-presets { + display: flex; + align-items: center; + gap: @space-2; + margin-bottom: @space-4; +} + +.resource-limits-presets-label { + font-size: @font-size-sm; + color: @text-secondary; +} + +.resource-preset-btn { + text-transform: capitalize; +} + +.resource-limits-section { + margin-bottom: @space-4; + + h4 { + display: flex; + align-items: center; + gap: @space-2; + font-size: @font-size-sm; + font-weight: @font-weight-semibold; + color: @text-secondary; + margin: 0 0 @space-3; + } +} + +.resource-limits-row { + display: flex; + align-items: center; + justify-content: space-between; + padding: @space-2 0; + + label { + font-size: @font-size-sm; + color: @text-primary; + } + + select { + width: 120px; + padding: @space-1 @space-2; + font-size: @font-size-sm; + border: 1px solid @border-subtle; + border-radius: @radius-sm; + background: @bg-card; + color: @text-primary; + } +} + +.resource-limits-warning { + display: flex; + align-items: center; + gap: @space-2; + padding: @space-3; + background: fade(@color-warning, 8%); + border: 1px solid fade(@color-warning, 20%); + border-radius: @radius-md; + margin-top: @space-3; + margin-bottom: @space-3; + font-size: @font-size-xs; + color: @color-warning; +} + +// ============================================ +// BASIC AUTH MODAL +// ============================================ + +.basic-auth-modal { + max-width: 460px; +} + +.basic-auth-body { + padding: @space-4 0; +} + +.basic-auth-env-name { + font-size: @font-size-sm; + font-weight: @font-weight-semibold; + color: @text-primary; + padding-bottom: @space-3; + border-bottom: 1px solid @border-subtle; + margin-bottom: @space-3; +} + +.basic-auth-loading { + display: flex; + align-items: center; + gap: @space-2; + justify-content: center; + padding: @space-4; + color: @text-tertiary; + font-size: @font-size-sm; +} + +.basic-auth-toggle { + margin-bottom: @space-4; +} + +.basic-auth-toggle-label { + display: flex; + align-items: center; + justify-content: space-between; + cursor: pointer; + + span { + font-size: @font-size-sm; + font-weight: @font-weight-medium; + color: @text-primary; + } +} + +.basic-auth-description { + font-size: @font-size-xs; + color: @text-tertiary; + margin: @space-1 0 0; +} + +.toggle-switch { + position: relative; + width: 44px; + height: 24px; + border: none; + border-radius: 12px; + background: @bg-tertiary; + cursor: pointer; + transition: background 0.2s ease; + padding: 0; + + &.active { + background: var(--color-primary, #3b82f6); + } +} + +.toggle-switch-slider { + position: absolute; + top: 2px; + left: 2px; + width: 20px; + height: 20px; + border-radius: 50%; + background: white; + transition: transform 0.2s ease; + + .toggle-switch.active & { + transform: translateX(20px); + } +} + +.basic-auth-current { + padding: @space-3; + background: @bg-tertiary; + border-radius: @radius-md; +} + +.basic-auth-credentials { + display: flex; + flex-direction: column; + gap: @space-3; +} + +.basic-auth-credential-warning { + display: flex; + align-items: center; + gap: @space-2; + padding: @space-2 @space-3; + background: fade(@color-warning, 10%); + border: 1px solid fade(@color-warning, 20%); + border-radius: @radius-md; + font-size: @font-size-xs; + color: @color-warning; +} + +.basic-auth-field { + display: flex; + flex-direction: column; + gap: @space-1; + + label { + font-size: @font-size-xs; + font-weight: @font-weight-medium; + color: @text-tertiary; + text-transform: uppercase; + letter-spacing: 0.5px; + } +} + +.basic-auth-value { + display: flex; + align-items: center; + gap: @space-2; + padding: @space-2 @space-3; + background: @bg-tertiary; + border-radius: @radius-sm; + + code { + flex: 1; + font-family: @font-family-mono; + font-size: @font-size-sm; + color: @text-primary; + } +} + +.basic-auth-hint { + font-size: @font-size-xs; + color: @text-tertiary; + margin-top: @space-2; +} + +// ============================================ +// WP-CLI TERMINAL +// ============================================ + +.wpcli-terminal-modal { + max-width: 700px; + height: 560px; + display: flex; + flex-direction: column; +} + +.wpcli-quick-actions { + display: flex; + flex-wrap: wrap; + gap: @space-1; + padding: @space-2 @space-4; + border-bottom: 1px solid @border-subtle; + background: @bg-tertiary; +} + +.wpcli-history { + border-bottom: 1px solid @border-subtle; + max-height: 200px; + overflow-y: auto; +} + +.wpcli-history-item { + display: block; + width: 100%; + padding: @space-2 @space-4; + border: none; + background: none; + text-align: left; + cursor: pointer; + border-bottom: 1px solid @border-subtle; + + &:last-child { + border-bottom: none; + } + + &:hover { + background: @bg-hover; + } + + code { + font-family: @font-family-mono; + font-size: @font-size-xs; + color: @text-primary; + } +} + +.wpcli-output { + flex: 1; + overflow-y: auto; + padding: @space-3; + background: @bg-body; + font-family: @font-family-mono; + font-size: 12px; + line-height: 1.6; +} + +.wpcli-output-empty { + color: @text-tertiary; + text-align: center; + padding: @space-6; + font-size: @font-size-sm; +} + +.wpcli-output-command { + display: flex; + gap: @space-2; + color: @color-primary; + margin-top: @space-2; + + &:first-child { + margin-top: 0; + } +} + +.wpcli-output-text { + margin: 0; + color: @text-secondary; + white-space: pre-wrap; + word-break: break-all; +} + +.wpcli-output-error { + margin: 0; + color: @color-danger; + white-space: pre-wrap; + word-break: break-all; +} + +.wpcli-prompt { + color: @color-success; + font-weight: @font-weight-bold; + user-select: none; +} + +.wpcli-executing { + display: flex; + align-items: center; + gap: @space-2; + padding: @space-2 0; + color: @text-tertiary; + font-size: @font-size-xs; +} + +.wpcli-input-row { + display: flex; + align-items: center; + gap: @space-2; + padding: @space-2 @space-3; + border-top: 1px solid @border-subtle; + background: @bg-elevated; +} + +.wpcli-input { + flex: 1; + border: none; + background: none; + font-family: @font-family-mono; + font-size: @font-size-sm; + color: @text-primary; + outline: none; + padding: @space-1 0; + + &::placeholder { + color: @text-tertiary; + } +} + +// ============================================ +// HEALTH STATUS PANEL +// ============================================ + +.health-status-panel { + background: @bg-card; + border: 1px solid @border-subtle; + border-radius: @radius-lg; + padding: @space-4; +} + +.health-panel-loading { + display: flex; + align-items: center; + justify-content: center; + gap: @space-2; + padding: @space-6; + color: @text-tertiary; + font-size: @font-size-sm; +} + +.health-panel-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: @space-4; + + h4 { + display: flex; + align-items: center; + gap: @space-2; + margin: 0; + font-size: @font-size-base; + font-weight: @font-weight-semibold; + color: @text-primary; + } +} + +.health-panel-grid { + display: flex; + flex-direction: column; + gap: @space-3; +} + +.health-panel-env { + padding: @space-3; + background: @bg-tertiary; + border-radius: @radius-md; +} + +.health-panel-env-header { + display: flex; + align-items: center; + gap: @space-2; + margin-bottom: @space-2; +} + +.health-panel-env-name { + flex: 1; + font-size: @font-size-sm; + font-weight: @font-weight-semibold; + color: @text-primary; +} + +.health-panel-overall { + font-size: @font-size-xs; + font-weight: @font-weight-medium; + padding: 2px 8px; + border-radius: @radius-sm; + + &.health-healthy { + background: fade(@color-success, 12%); + color: @color-success; + } + &.health-degraded { + background: fade(@color-warning, 12%); + color: @color-warning; + } + &.health-unhealthy { + background: fade(@color-danger, 12%); + color: @color-danger; + } + &.health-unknown { + background: fade(@text-tertiary-raw, 12%); + color: @text-tertiary; + } +} + +.health-panel-checks { + display: flex; + flex-direction: column; + gap: @space-1; +} + +.health-panel-check { + display: flex; + align-items: center; + gap: @space-2; + padding: @space-1 0; + font-size: @font-size-xs; +} + +.health-panel-check-name { + font-weight: @font-weight-medium; + color: @text-secondary; + min-width: 80px; +} + +.health-panel-check-msg { + color: @text-tertiary; +} + +.health-panel-empty { + text-align: center; + padding: @space-6; + color: @text-tertiary; + font-size: @font-size-sm; +} + +.health-dot { + flex-shrink: 0; +} + +// ============================================ +// DISK USAGE BAR +// ============================================ + +.disk-usage-compact { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: @font-size-xs; + color: @text-tertiary; +} + +.disk-usage-compact-text { + font-family: @font-family-mono; +} + +.disk-usage-bar-container { + padding: @space-3; + background: @bg-card; + border: 1px solid @border-subtle; + border-radius: @radius-md; +} + +.disk-usage-header { + display: flex; + align-items: center; + gap: @space-2; + margin-bottom: @space-2; + font-size: @font-size-sm; + color: @text-primary; +} + +.disk-usage-total { + font-weight: @font-weight-semibold; + font-family: @font-family-mono; +} + +.disk-usage-bar { + display: flex; + height: 8px; + border-radius: 4px; + overflow: hidden; + background: @bg-tertiary; +} + +.disk-usage-segment { + height: 100%; + transition: width 0.3s ease; + + &.wordpress { + &.green { background: @color-success; } + &.yellow { background: @color-warning; } + &.red { background: @color-danger; } + } + + &.mysql { + background: @color-info; + } + + &.snapshots { + background: fade(@text-tertiary-raw, 30%); + } +} + +.disk-usage-legend { + display: flex; + flex-wrap: wrap; + gap: @space-3; + margin-top: @space-2; +} + +.disk-usage-legend-item { + display: flex; + align-items: center; + gap: 4px; + font-size: @font-size-xs; + color: @text-tertiary; +} + +.disk-usage-legend-dot { + width: 8px; + height: 8px; + border-radius: 2px; + + &.wordpress { background: @color-success; } + &.mysql { background: @color-info; } + &.snapshots { background: fade(@text-tertiary-raw, 30%); } +} + +// ============================================ +// AUTO-SYNC MODAL +// ============================================ + +.auto-sync-modal { + max-width: 480px; +} + +.auto-sync-loading { + display: flex; + align-items: center; + justify-content: center; + gap: @space-2; + padding: @space-6; + color: @text-tertiary; + font-size: @font-size-sm; +} + +.auto-sync-body { + padding: @space-4 0; +} + +.auto-sync-env-name { + font-size: @font-size-sm; + font-weight: @font-weight-semibold; + color: @text-primary; + padding-bottom: @space-3; + border-bottom: 1px solid @border-subtle; + margin-bottom: @space-3; +} + +.auto-sync-toggle { + margin-bottom: @space-4; +} + +.auto-sync-toggle-label { + display: flex; + align-items: center; + justify-content: space-between; + cursor: pointer; + + span { + font-size: @font-size-sm; + font-weight: @font-weight-medium; + color: @text-primary; + } +} + +.auto-sync-description { + font-size: @font-size-xs; + color: @text-tertiary; + margin: @space-1 0 0; +} + +.auto-sync-presets { + display: flex; + flex-direction: column; + gap: @space-2; +} + +.auto-sync-cron-display { + font-family: @font-family-mono; + font-size: @font-size-xs; + color: @text-tertiary; +} + +.auto-sync-cron-input { + font-family: @font-family-mono; +} + +.auto-sync-next-runs { + margin-top: @space-4; + padding: @space-3; + background: @bg-tertiary; + border-radius: @radius-md; + + h5 { + margin: 0 0 @space-2; + font-size: @font-size-xs; + font-weight: @font-weight-semibold; + color: @text-secondary; + text-transform: uppercase; + letter-spacing: 0.5px; + } + + ul { + list-style: none; + margin: 0; + padding: 0; + } + + li { + display: flex; + align-items: center; + gap: @space-2; + padding: @space-1 0; + font-size: @font-size-xs; + color: @text-secondary; + + svg { + color: @text-tertiary; + } + } +} + +// ============================================ +// BULK ACTIONS BAR +// ============================================ + +.bulk-actions-bar { + display: flex; + align-items: center; + gap: @space-3; + padding: @space-3 @space-4; + background: fade(@color-primary, 8%); + border: 1px solid fade(@color-primary, 20%); + border-radius: @radius-md; + margin-bottom: @space-4; +} + +.bulk-actions-info { + display: flex; + align-items: center; + gap: @space-1; + font-size: @font-size-sm; + color: @text-secondary; +} + +.bulk-actions-count { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 24px; + height: 24px; + padding: 0 6px; + background: @color-primary; + color: white; + border-radius: 12px; + font-size: @font-size-xs; + font-weight: @font-weight-bold; +} + +.bulk-actions-buttons { + display: flex; + gap: @space-1; + flex: 1; +} + +.bulk-actions-clear { + color: @text-tertiary !important; +} + +.bulk-actions-confirm { + display: flex; + align-items: center; + gap: @space-3; + width: 100%; + + span { + flex: 1; + font-size: @font-size-sm; + color: @text-primary; + font-weight: @font-weight-medium; + } +} + +// ============================================ +// OPERATION PROGRESS +// ============================================ + +.operation-progress-content { + flex: 1; + display: flex; + flex-direction: column; + gap: @space-2; +} + +.operation-progress { + display: flex; + flex-direction: column; + gap: @space-1; +} + +.operation-progress-bar { + height: 4px; + background: fade(@color-info, 20%); + border-radius: 2px; + overflow: hidden; +} + +.operation-progress-fill { + height: 100%; + background: @color-info; + border-radius: 2px; + transition: width 0.3s ease; +} + +.operation-progress-step { + font-size: @font-size-xs; + color: @text-tertiary; +} + +// ============================================ +// HEALTH TAB +// ============================================ + +.health-tab { + padding: @space-4 0; +} + +// ============================================ +// RESPONSIVE +// ============================================ + +@media (max-width: 900px) { + .pipeline-row { + flex-direction: column; + align-items: stretch; + + .pipeline-card { + max-width: none; + } + } + + .pipeline-arrow { + min-width: auto; + padding: @space-2 0; + + .pipeline-arrow-btn { + flex-direction: row; + } + + svg { + transform: rotate(90deg); + } + } + + .pipeline-sync-row { + flex-direction: column; + + .pipeline-sync-action { + max-width: none; + } + } + + .bulk-actions-bar { + flex-wrap: wrap; + } + + .bulk-actions-buttons { + flex-wrap: wrap; + } +}