From f4ed11ceafa45735962eef13054131da211abeab Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sun, 25 Jan 2026 16:47:04 -0500 Subject: [PATCH] Add WordPress site management API and models Introduces backend API endpoints for WordPress site management, including site creation, environment handling, database snapshots, sync, and Git integration. Adds new models for WordPressSite, DatabaseSnapshot, and SyncJob, and registers the new blueprint. Updates frontend with new WordPress pages, components, and styles to support these features. --- EXPLORATIONS_AND_FUTURE.md | 672 -------- backend/app/__init__.py | 2 + backend/app/api/wordpress_sites.py | 799 ++++++++++ backend/app/models/__init__.py | 4 +- backend/app/models/wordpress_site.py | 247 +++ backend/app/services/db_sync_service.py | 609 ++++++++ backend/app/services/git_wordpress_service.py | 536 +++++++ backend/app/services/wordpress_env_service.py | 486 ++++++ frontend/src/App.jsx | 6 + frontend/src/components/ConfirmDialog.jsx | 50 +- frontend/src/components/ErrorBoundary.jsx | 89 ++ frontend/src/components/Sidebar.jsx | 8 + .../src/components/wordpress/CommitList.jsx | 197 +++ .../components/wordpress/CreateSiteModal.jsx | 159 ++ .../components/wordpress/EnvironmentCard.jsx | 239 +++ .../components/wordpress/GitConnectForm.jsx | 188 +++ .../components/wordpress/SnapshotTable.jsx | 168 ++ .../wordpress/WordPressSiteCard.jsx | 148 ++ frontend/src/components/wordpress/index.js | 6 + frontend/src/pages/Applications.jsx | 3 +- frontend/src/pages/WordPress.jsx | 237 +++ frontend/src/pages/WordPressDetail.jsx | 1359 +++++++++++++++++ frontend/src/services/wordpress.js | 105 ++ frontend/src/styles/main.less | 1 + frontend/src/styles/pages/_wordpress.less | 1134 ++++++++++++++ 25 files changed, 6776 insertions(+), 676 deletions(-) delete mode 100644 EXPLORATIONS_AND_FUTURE.md create mode 100644 backend/app/api/wordpress_sites.py create mode 100644 backend/app/models/wordpress_site.py create mode 100644 backend/app/services/db_sync_service.py create mode 100644 backend/app/services/git_wordpress_service.py create mode 100644 backend/app/services/wordpress_env_service.py create mode 100644 frontend/src/components/ErrorBoundary.jsx create mode 100644 frontend/src/components/wordpress/CommitList.jsx create mode 100644 frontend/src/components/wordpress/CreateSiteModal.jsx create mode 100644 frontend/src/components/wordpress/EnvironmentCard.jsx create mode 100644 frontend/src/components/wordpress/GitConnectForm.jsx create mode 100644 frontend/src/components/wordpress/SnapshotTable.jsx create mode 100644 frontend/src/components/wordpress/WordPressSiteCard.jsx create mode 100644 frontend/src/components/wordpress/index.js create mode 100644 frontend/src/pages/WordPress.jsx create mode 100644 frontend/src/pages/WordPressDetail.jsx create mode 100644 frontend/src/services/wordpress.js create mode 100644 frontend/src/styles/pages/_wordpress.less diff --git a/EXPLORATIONS_AND_FUTURE.md b/EXPLORATIONS_AND_FUTURE.md deleted file mode 100644 index 87a67c7e..00000000 --- a/EXPLORATIONS_AND_FUTURE.md +++ /dev/null @@ -1,672 +0,0 @@ -# ServerKit: Explorations and Future Directions - -> A deep dive into where ServerKit stands, where it should go, and practical next steps. -> -> *Written: January 2026* - ---- - -## Table of Contents - -1. [Current State Assessment](#current-state-assessment) -2. [WordPress Dev/Prod Environment Architecture](#wordpress-devprod-environment-architecture) -3. [Testing the Go Agent Locally](#testing-the-go-agent-locally) -4. [Future of ServerKit](#future-of-serverkit) -5. [Recommended Next Steps](#recommended-next-steps) - ---- - -## Current State Assessment - -### What ServerKit Has Achieved - -ServerKit has matured into a **legitimate self-hosted server control panel** with impressive breadth: - -| Area | Maturity | Notes | -|------|----------|-------| -| **Multi-Server Agents** | Production-Ready | Go agent with WSS, HMAC auth, cross-platform builds | -| **Docker Management** | Complete | Full container lifecycle, compose support, logs streaming | -| **WordPress Support** | Good | WP-CLI, one-click install, security hardening | -| **Git Deployment** | Complete | Webhooks, rollback, zero-downtime deploys | -| **Security** | Strong | 2FA, encryption at rest, audit logging, ClamAV | -| **Monitoring** | Good | Real-time metrics, alerts, webhooks | -| **Multi-Environment** | Partial | UI exists, but workflow needs refinement | - -### What's Missing for Real-World Usage - -1. **Backup & Restore** - Critical gap. No automated backups = risky for production. -2. **Database Sync/Clone** - For dev/prod workflows, you need this. -3. **Team Permissions** - Single-user limits commercial viability. -4. **Agent Stress Testing** - No evidence of load testing at scale. - ---- - -## WordPress Dev/Prod Environment Architecture - -### The Vision - -You want to explore: -- **Dev and Prod WordPress instances** -- **Synced from GitHub** -- **Sharing the same DB (or a mini version of prod DB)** - -This is a real-world workflow that ServerKit should excel at. Let me break down the options: - -### Option A: Shared Database (Live Sync) - -``` -┌─────────────────────────────────────────────────────────────┐ -│ GitHub Repository │ -│ (wp-content/themes, wp-content/plugins) │ -└─────────────────────────────────────────────────────────────┘ - │ - ┌───────────────┴───────────────┐ - ▼ ▼ - ┌─────────────────┐ ┌─────────────────┐ - │ DEV Server │ │ PROD Server │ - │ (Agent #1) │ │ (Agent #2) │ - │ │ │ │ - │ ┌───────────┐ │ │ ┌───────────┐ │ - │ │ WordPress │ │ │ │ WordPress │ │ - │ │ (Dev) │ │ │ │ (Prod) │ │ - │ └─────┬─────┘ │ │ └─────┬─────┘ │ - └────────┼────────┘ └────────┼────────┘ - │ │ - └───────────┬───────────────────┘ - ▼ - ┌─────────────────┐ - │ Shared MySQL │ - │ (Prod Server) │ - │ │ - │ wp_* tables │ - └─────────────────┘ -``` - -**Pros:** -- Real-time content sync -- No data drift between environments -- Simple conceptually - -**Cons:** -- **Dangerous** - Dev changes affect prod data -- URL serialization issues in WordPress (siteurl, home options) -- Not recommended for real workflows - -**Verdict:** Avoid this pattern. WordPress stores serialized URLs in the database, making true DB sharing problematic. - -### Option B: Mini Prod Database (Recommended) - -``` -┌─────────────────────────────────────────────────────────────┐ -│ GitHub Repository │ -│ (wp-content/themes, wp-content/plugins) │ -└─────────────────────────────────────────────────────────────┘ - │ - ┌───────────────┴───────────────┐ - ▼ ▼ - ┌─────────────────┐ ┌─────────────────┐ - │ DEV Server │ │ PROD Server │ - │ (Agent #1) │ │ (Agent #2) │ - │ │ │ │ - │ ┌───────────┐ │ │ ┌───────────┐ │ - │ │ WordPress │ │ │ │ WordPress │ │ - │ │ (Dev) │ │ │ │ (Prod) │ │ - │ └─────┬─────┘ │ │ └─────┬─────┘ │ - │ │ │ │ │ │ - │ ┌─────┴─────┐ │ │ ┌─────┴─────┐ │ - │ │ MySQL │ │◄────────────│ │ MySQL │ │ - │ │ (Clone) │ │ Nightly │ │ (Prod) │ │ - │ └───────────┘ │ Sync │ └───────────┘ │ - └─────────────────┘ └─────────────────┘ -``` - -**How It Works:** - -1. **Prod runs normally** with live database -2. **Nightly job** creates a mysqldump of prod -3. **Sanitize the dump:** - - Run search-replace for URLs (`prod.example.com` → `dev.example.com`) - - Optionally anonymize user data - - Truncate large tables (logs, analytics) -4. **Import to dev** database -5. **Dev has fresh, realistic data** without affecting prod - -**Implementation in ServerKit:** - -This requires a new feature: **Database Sync Jobs** - -```python -# Proposed: backend/app/services/db_sync_service.py - -class DatabaseSyncService: - def create_sync_job(self, source_app_id, target_app_id, options): - """ - Create a scheduled database sync from source to target. - - Options: - - schedule: cron expression - - search_replace: dict of find/replace patterns - - anonymize: bool - anonymize user emails/names - - exclude_tables: list of tables to skip - - truncate_tables: list of tables to empty - """ - pass - - def run_sync(self, job_id): - """Execute a database sync job.""" - # 1. Dump source database - # 2. Apply transformations - # 3. Import to target - # 4. Run wp search-replace if WordPress - pass -``` - -### Option C: Read Replica (Advanced) - -``` - ┌─────────────────┐ ┌─────────────────┐ - │ DEV Server │ │ PROD Server │ - │ │ │ │ - │ ┌───────────┐ │ │ ┌───────────┐ │ - │ │ WordPress │ │ │ │ WordPress │ │ - │ └─────┬─────┘ │ │ └─────┬─────┘ │ - │ │ │ │ │ │ - │ ┌─────┴─────┐ │ │ ┌─────┴─────┐ │ - │ │ MySQL │ │ │ │ MySQL │ │ - │ │ (Replica) │◄─┼─────────────┼──│ (Primary) │ │ - │ └───────────┘ │ Binlog │ └───────────┘ │ - └─────────────────┘ Replication └─────────────────┘ -``` - -**Pros:** -- Near real-time sync (seconds) -- Dev sees exactly what prod sees - -**Cons:** -- Read-only dev database -- Complex to set up cross-server -- Still has URL serialization issues - -**Verdict:** Overkill for WordPress. Better for read-heavy APIs. - -### Recommended Architecture: GitHub-Driven Dev/Prod - -Here's what I'd actually build: - -``` -┌─────────────────────────────────────────────────────────────┐ -│ GitHub Repository │ -│ │ -│ ├── wp-content/ │ -│ │ ├── themes/my-theme/ │ -│ │ └── plugins/my-plugin/ │ -│ ├── .github/workflows/ │ -│ │ ├── deploy-dev.yml # On push to develop branch │ -│ │ └── deploy-prod.yml # On push to main branch │ -│ └── serverkit.yaml # Environment config │ -└─────────────────────────────────────────────────────────────┘ - │ - ┌────────────────────┴────────────────────┐ - │ │ - │ push to develop push to main │ - ▼ ▼ -┌─────────────────┐ ┌─────────────────┐ -│ ServerKit API │ │ ServerKit API │ -│ (Webhook) │ │ (Webhook) │ -└────────┬────────┘ └────────┬────────┘ - │ │ - ▼ ▼ -┌─────────────────┐ ┌─────────────────┐ -│ DEV Server │ │ PROD Server │ -│ │ │ │ -│ WordPress │ │ WordPress │ -│ dev.site.com │ │ www.site.com │ -│ │ │ │ -│ MySQL (local) │◄────── Weekly ──────│ MySQL (local) │ -│ Sanitized copy │ Sync │ Live data │ -└─────────────────┘ └─────────────────┘ -``` - -**The Workflow:** - -1. **Developer pushes to `develop` branch** -2. **GitHub Action** calls ServerKit webhook -3. **ServerKit pulls code** on dev server -4. **Runs `wp theme activate`, `wp plugin activate`** as needed -5. **Developer tests on dev.site.com** -6. **When ready, merge PR to `main`** -7. **Same process for production** - -**Weekly Database Sync:** - -```yaml -# serverkit.yaml in repo root -environments: - dev: - server: dev-server-id - app: wordpress-dev-id - domain: dev.site.com - db_sync: - source: prod - schedule: "0 3 * * 0" # Sunday 3 AM - search_replace: - - ["https://www.site.com", "https://dev.site.com"] - anonymize_users: true - truncate_tables: - - wp_statistics_* - - wp_actionscheduler_* - - prod: - server: prod-server-id - app: wordpress-prod-id - domain: www.site.com -``` - -### What ServerKit Needs to Support This - -| Feature | Current Status | Priority | -|---------|---------------|----------| -| Git webhook deployments | ✅ Done | - | -| Multi-environment app linking | ✅ Done | - | -| Database dump/export | ❌ Missing | **High** | -| Database import with transformations | ❌ Missing | **High** | -| WP-CLI search-replace integration | ⚠️ Partial | Medium | -| Scheduled sync jobs | ❌ Missing | Medium | -| Cross-server database operations | ❌ Missing | Medium | - ---- - -## Testing the Go Agent Locally - -### Your Goal - -Test the ServerKit Go agent on your Windows PC to understand: -- How it connects to the control plane -- How commands flow through -- What happens with Docker operations -- Whether it's stable - -### Setting Up the Test Environment - -#### Prerequisites - -1. **Go 1.21+** installed -2. **Docker Desktop** running (for Docker commands) -3. **ServerKit backend** running (localhost or remote) - -#### Step 1: Build the Agent - -```powershell -# Navigate to agent directory -cd C:\Users\Juan\Documents\GitHub\ServerKit\agent - -# Build for Windows -go build -o serverkit-agent.exe ./cmd/agent - -# Or use the Makefile (if you have make installed) -make build-windows -``` - -#### Step 2: Create Test Configuration - -Create `agent-config.yaml` in the agent directory: - -```yaml -# agent-config.yaml -server_url: "ws://localhost:5000" # Your ServerKit backend -# server_url: "wss://serverkit.yourdomain.com" # For production - -# Leave empty - will be populated on first registration -api_key: "" -api_secret: "" - -# Logging -log_level: "debug" -log_file: "agent.log" - -# Heartbeat interval (seconds) -heartbeat_interval: 30 - -# Enable Docker integration -docker_enabled: true -docker_socket: "npipe:////./pipe/docker_engine" # Windows Docker socket -``` - -#### Step 3: Register the Agent - -First, create a server in ServerKit UI to get a registration token, then: - -```powershell -# Register with the control plane -.\serverkit-agent.exe register --token YOUR_REGISTRATION_TOKEN - -# This will: -# 1. Connect to ServerKit backend -# 2. Exchange token for API credentials -# 3. Save credentials to config file -# 4. Print success message -``` - -#### Step 4: Run the Agent - -```powershell -# Run in foreground (for testing) -.\serverkit-agent.exe run --config agent-config.yaml - -# You should see: -# [INFO] Connecting to ws://localhost:5000/agent -# [INFO] Authenticated successfully -# [INFO] Starting heartbeat loop (30s interval) -# [DEBUG] Sending heartbeat with metrics... -``` - -### Testing Agent Functionality - -#### Test 1: Verify Connection - -In ServerKit UI: -- Go to Servers page -- Your test server should show as "Online" -- Last seen should update every 30 seconds - -#### Test 2: Docker Commands - -If Docker Desktop is running: - -```powershell -# In ServerKit UI, try: -# - View containers -# - Start/stop a container -# - View container logs - -# Agent logs should show: -# [DEBUG] Received command: docker:container:list -# [DEBUG] Executing Docker command... -# [DEBUG] Sending response with 5 containers -``` - -#### Test 3: System Metrics - -Check Monitoring page in ServerKit: -- CPU usage should show Windows Task Manager equivalent -- Memory should match your system -- Disk usage for C: drive - -#### Test 4: Terminal Access - -Try opening a terminal session to your test server: -- Should spawn PowerShell on Windows -- Commands should execute -- Output should stream back - -### Common Issues and Fixes - -| Issue | Cause | Fix | -|-------|-------|-----| -| "Connection refused" | Backend not running | Start Flask backend | -| "Docker not available" | Docker Desktop not running | Start Docker Desktop | -| "Authentication failed" | Invalid/expired token | Re-register agent | -| "TLS handshake error" | Self-signed cert | Use `ws://` for local testing | -| Metrics not updating | Heartbeat blocked | Check firewall rules | - -### Agent Architecture Deep Dive - -``` -┌─────────────────────────────────────────────────────────────┐ -│ ServerKit Go Agent │ -├─────────────────────────────────────────────────────────────┤ -│ │ -│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ -│ │ Config │ │ Logger │ │ Auth │ │ -│ │ Manager │ │ (Zerolog) │ │ (HMAC) │ │ -│ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │ -│ │ │ │ │ -│ └──────────────┼──────────────┘ │ -│ │ │ -│ ┌────────────────────┴────────────────────┐ │ -│ │ WebSocket Client │ │ -│ │ (gorilla/websocket + reconnect) │ │ -│ └────────────────────┬────────────────────┘ │ -│ │ │ -│ ┌──────────────┼──────────────┐ │ -│ │ │ │ │ -│ ▼ ▼ ▼ │ -│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ -│ │ Docker │ │ Metrics │ │ Terminal │ │ -│ │ Handler │ │ Collector │ │ PTY │ │ -│ │ │ │ │ │ │ │ -│ │ - List │ │ - CPU │ │ - Spawn │ │ -│ │ - Start │ │ - Memory │ │ - Resize │ │ -│ │ - Stop │ │ - Disk │ │ - Input │ │ -│ │ - Logs │ │ - Network │ │ - Output │ │ -│ │ - Stats │ │ │ │ │ │ -│ └───────────┘ └───────────┘ └───────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────┘ -``` - -### Agent Test Checklist - -- [ ] Agent builds without errors -- [ ] Agent connects to backend -- [ ] Heartbeat appears in server list -- [ ] Metrics show in monitoring page -- [ ] Docker containers list correctly -- [ ] Container start/stop works -- [ ] Container logs stream -- [ ] Terminal opens and accepts input -- [ ] Agent survives backend restart (reconnect) -- [ ] Agent handles network interruption gracefully - ---- - -## Future of ServerKit - -### My Honest Assessment - -ServerKit has grown from a simple control panel into something with real architectural depth. The Go agent is a significant investment that positions it for multi-server, enterprise-like features. But there are strategic decisions ahead. - -### Where ServerKit Sits in the Market - -``` - Complexity - ▲ - │ - Kubernetes ────┼──────────────● CloudPanel - Nomad │ ● Coolify - │ ● ServerKit (today) - │ ● Dokku - │ ● CapRover - ────────────────────────────────────────► Features - │ - Portainer ● - │ - Cockpit ● │ - │ -``` - -**Current Position:** ServerKit is between CapRover/Dokku (simple) and CloudPanel/Coolify (feature-rich). - -**Opportunity:** The multi-server Go agent puts ServerKit closer to what teams actually need for real production workloads. - -### Three Possible Futures - -#### Future A: WordPress Hosting Platform - -**Focus:** Become the best self-hosted WordPress management platform. - -**What to build:** -- Staging/production sync (database cloning) -- WordPress-specific monitoring (slow queries, plugin conflicts) -- One-click backup to S3/Backblaze -- Malware scanning with auto-remediation -- WordPress multisite support -- WP-CLI exposed as API - -**Target users:** WordPress agencies, freelancers with multiple client sites - -**Competitors:** GridPane, SpinupWP, RunCloud - -**My take:** This is a viable niche. WordPress agencies pay well for good tooling. But it limits ServerKit's appeal. - -#### Future B: Mini-Kubernetes Alternative - -**Focus:** Multi-server orchestration without Kubernetes complexity. - -**What to build:** -- Service mesh between agents (internal DNS) -- Load balancing across servers -- Container scheduling (deploy to least-loaded server) -- Cross-server networking -- Secrets management (Vault-like) -- Log aggregation (ship logs to central location) - -**Target users:** Small-medium teams who outgrew single servers but don't want Kubernetes - -**Competitors:** Nomad, Docker Swarm (dead), Coolify - -**My take:** This is the more ambitious path. The Go agent is already 70% of what's needed. The question is whether you want to compete at this level. - -#### Future C: Developer-First Homelab Manager - -**Focus:** Self-hosting for developers who want to own their infrastructure. - -**What to build:** -- One-click apps (like Umbrel, CasaOS) -- Personal cloud features (Nextcloud, Vaultwarden integration) -- Tunnel support (Cloudflare Tunnel, Tailscale) -- Mobile-friendly dashboard -- Simple DNS management -- Local SSL with mkcert/step-ca - -**Target users:** Developers, homelabbers, privacy-conscious users - -**Competitors:** Umbrel, CasaOS, Tipi - -**My take:** Growing market, but harder to monetize. Good for adoption, hard for revenue. - -### My Recommendation: Hybrid Approach - -Don't pick one future. Build the **foundation** that supports all three: - -``` - ┌─────────────────────────────────┐ - │ User-Facing Products │ - ├─────────┬───────────┬───────────┤ - │WordPress│ App │ Homelab │ - │Platform │ Platform │ Suite │ - ├─────────┴───────────┴───────────┤ - │ ServerKit Core Platform │ - │ │ - │ ┌─────┐ ┌─────┐ ┌───────────┐ │ - │ │Agents│ │Apps │ │ Templates │ │ - │ └─────┘ └─────┘ └───────────┘ │ - │ ┌─────┐ ┌─────┐ ┌───────────┐ │ - │ │ DB │ │ SSL │ │ Webhooks │ │ - │ └─────┘ └─────┘ └───────────┘ │ - └─────────────────────────────────┘ -``` - -**Core investments that pay off in all futures:** - -1. **Backup & Restore** - Everyone needs this -2. **Database Sync** - Dev/prod workflows are universal -3. **API Stability** - Third-party integrations -4. **Agent Reliability** - More agents = more value -5. **Plugin/Extension System** - Let community build - -### Roadmap Recommendation - -#### Q1 2026: Foundation (Now) - -| Priority | Feature | Why | -|----------|---------|-----| -| **P0** | Backup & Restore | Can't run production without backups | -| **P0** | Database sync/clone | Enables dev/prod workflows | -| **P1** | Agent stress testing | Prove multi-server works at scale | -| **P1** | WordPress staging sync | Popular request, differentiator | - -#### Q2 2026: Scale - -| Priority | Feature | Why | -|----------|---------|-----| -| **P0** | Team/user management | Required for teams | -| **P1** | Role-based permissions | Security requirement | -| **P1** | Cross-server log aggregation | Ops visibility | -| **P2** | Agent auto-update (production-grade) | Reduce maintenance burden | - -#### Q3 2026: Ecosystem - -| Priority | Feature | Why | -|----------|---------|-----| -| **P1** | Plugin/extension system | Community growth | -| **P1** | API v2 (stable, versioned) | Third-party integrations | -| **P2** | Template marketplace | Discoverability | -| **P2** | Tunnel support (Cloudflare/Tailscale) | Homelab market | - -#### Q4 2026: Differentiation - -Choose a direction based on traction: -- If WordPress is hot → WordPress-specific features -- If multi-server is hot → Orchestration features -- If homelab is hot → Personal cloud features - ---- - -## Recommended Next Steps - -### Immediate (This Week) - -1. **Build and test the Go agent locally** - - Follow the steps in Section 3 - - Document any issues you find - - Test Docker commands specifically - -2. **Prototype database sync** - - Manual mysqldump → transform → import - - Use WP-CLI for search-replace - - Prove the workflow works before automating - -3. **Set up a real dev/prod WordPress pair** - - Two Docker instances on same machine - - Different ports, different databases - - Test the GitHub webhook flow - -### Short-term (This Month) - -4. **Design the Database Sync feature** - - UI mockups - - API design - - Agent-side implementation - -5. **Backup & Restore MVP** - - Even if manual (cron + mysqldump + rsync) - - Restore must actually work - -### Medium-term (This Quarter) - -6. **Agent reliability improvements** - - Reconnection logic stress testing - - Memory leak detection - - Long-running connection stability - -7. **Documentation** - - Agent installation guide - - Multi-server setup tutorial - - WordPress dev/prod workflow guide - ---- - -## Final Thoughts - -ServerKit has the bones of something really useful. The Go agent is the right architectural choice for multi-server. The template system is flexible. The security features are more thorough than most open-source panels. - -The risk is feature sprawl - trying to be everything to everyone. The WordPress dev/prod workflow you want to explore is exactly the kind of **focused, real-world problem** that differentiates ServerKit from generic panels. - -Build for your own use case first. If you need WordPress staging with database sync, build that. You'll end up with something opinionated and useful rather than generic and forgettable. - -The market doesn't need another cPanel clone. It needs tools built by people who actually deploy and manage servers. - ---- - -*This document represents my analysis based on exploring the ServerKit codebase. These are recommendations, not requirements. Adjust based on your priorities and user feedback.* diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 959abd36..3137dcbd 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -84,8 +84,10 @@ def create_app(config_name=None): # Register blueprints - PHP & WordPress from app.api.php import php_bp from app.api.wordpress import wordpress_bp + from app.api.wordpress_sites import wordpress_sites_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') # Register blueprints - Python from app.api.python import python_bp diff --git a/backend/app/api/wordpress_sites.py b/backend/app/api/wordpress_sites.py new file mode 100644 index 00000000..b4f4f2be --- /dev/null +++ b/backend/app/api/wordpress_sites.py @@ -0,0 +1,799 @@ +""" +WordPress Sites API + +API endpoints for WordPress site management including: +- Site listing and creation +- Environment management (dev/staging) +- Database operations (snapshots, sync, clone) +- Git integration +""" + +from flask import Blueprint, request, jsonify +from flask_jwt_extended import jwt_required, get_jwt_identity +import json + +from app import db +from app.models.application import Application +from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob +from app.services.wordpress_service import WordPressService +from app.services.wordpress_env_service import WordPressEnvService +from app.services.db_sync_service import DatabaseSyncService +from app.services.git_wordpress_service import GitWordPressService + +wordpress_sites_bp = Blueprint('wordpress_sites', __name__) + + +# ============================================================================= +# Site Management +# ============================================================================= + +@wordpress_sites_bp.route('/sites', methods=['GET']) +@jwt_required() +def list_sites(): + """List all WordPress sites.""" + user_id = get_jwt_identity() + include_envs = request.args.get('include_environments', 'false').lower() == 'true' + + # Get all WordPress applications for this user + sites = WordPressSite.query.join(Application).filter( + Application.user_id == user_id, + Application.app_type == 'wordpress' + ).all() + + # Separate production and environment sites + production_sites = [s for s in sites if s.is_production] + + return jsonify({ + 'sites': [s.to_dict(include_environments=include_envs) for s in production_sites], + 'total': len(production_sites) + }) + + +@wordpress_sites_bp.route('/sites', methods=['POST']) +@jwt_required() +def create_site(): + """Create a new WordPress site.""" + user_id = get_jwt_identity() + data = request.get_json() + + # Validate required fields + required = ['name', 'domain', 'db_name', 'db_user', 'db_password', 'admin_email'] + missing = [f for f in required if not data.get(f)] + if missing: + return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400 + + try: + # Create Application record + app = Application( + name=data['name'], + app_type='wordpress', + status='deploying', + php_version=data.get('php_version', '8.2'), + port=data.get('port'), + root_path=data.get('root_path', f"/var/www/{data['name'].lower().replace(' ', '_')}"), + environment_type='production', + user_id=user_id + ) + db.session.add(app) + db.session.flush() + + # Create WordPressSite record + site = WordPressSite( + application_id=app.id, + admin_email=data['admin_email'], + admin_user=data.get('admin_user', 'admin'), + db_name=data['db_name'], + db_user=data['db_user'], + db_host=data.get('db_host', 'localhost'), + db_prefix=data.get('db_prefix', 'wp_'), + is_production=True + ) + db.session.add(site) + + # Install WordPress + install_result = WordPressService.install_wordpress( + path=app.root_path, + config={ + 'site_url': f"https://{data['domain']}", + 'site_title': data['name'], + 'admin_user': data.get('admin_user', 'admin'), + 'admin_password': data.get('admin_password'), + 'admin_email': data['admin_email'], + 'db_name': data['db_name'], + 'db_user': data['db_user'], + 'db_password': data['db_password'], + 'db_host': data.get('db_host', 'localhost'), + 'db_prefix': data.get('db_prefix', 'wp_') + } + ) + + if not install_result['success']: + db.session.rollback() + return jsonify({'error': install_result.get('error', 'Installation failed')}), 500 + + # Get WordPress version + wp_info = WordPressService.get_wordpress_info(app.root_path) + if wp_info: + site.wp_version = wp_info.get('version') + + app.status = 'running' + db.session.commit() + + return jsonify({ + 'success': True, + 'site': site.to_dict(), + 'admin_password': install_result.get('admin_password') + }), 201 + + except Exception as e: + db.session.rollback() + return jsonify({'error': str(e)}), 500 + + +@wordpress_sites_bp.route('/sites/', methods=['GET']) +@jwt_required() +def get_site(site_id): + """Get a WordPress site by ID.""" + user_id = get_jwt_identity() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + include_envs = request.args.get('include_environments', 'true').lower() == 'true' + include_snaps = request.args.get('include_snapshots', 'false').lower() == 'true' + + result = site.to_dict(include_environments=include_envs, include_snapshots=include_snaps) + + # Add WordPress info from WP-CLI + if site.application and site.application.root_path: + wp_info = WordPressService.get_wordpress_info(site.application.root_path) + if wp_info: + result['wp_info'] = wp_info + + return jsonify(result) + + +@wordpress_sites_bp.route('/sites/', methods=['DELETE']) +@jwt_required() +def delete_site(site_id): + """Delete a WordPress site.""" + user_id = get_jwt_identity() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + # Check if this is a production site with environments + if site.is_production and site.environments: + return jsonify({ + 'error': 'Cannot delete production site with active environments. Delete environments first.' + }), 400 + + try: + # Use environment service to clean up (handles files, database, etc.) + result = WordPressEnvService.delete_environment( + site_id, + delete_files=True, + delete_database=True + ) + + if not result['success']: + return jsonify(result), 500 + + return jsonify({'success': True, 'message': 'Site deleted'}) + + except Exception as e: + return jsonify({'error': str(e)}), 500 + + +# ============================================================================= +# Environment Management +# ============================================================================= + +@wordpress_sites_bp.route('/sites//environments', methods=['GET']) +@jwt_required() +def list_environments(site_id): + """List all environments for a production site.""" + user_id = get_jwt_identity() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + result = WordPressEnvService.get_environment_status(site_id) + return jsonify(result) + + +@wordpress_sites_bp.route('/sites//environments', methods=['POST']) +@jwt_required() +def create_environment(site_id): + """Create a new environment (dev/staging) for a production site.""" + user_id = get_jwt_identity() + data = request.get_json() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + env_type = data.get('type', 'development') + if env_type not in ['development', 'staging']: + return jsonify({'error': 'Invalid environment type'}), 400 + + result = WordPressEnvService.create_environment( + production_site_id=site_id, + env_type=env_type, + config=data, + user_id=user_id + ) + + if result['success']: + return jsonify(result), 201 + else: + return jsonify(result), 500 + + +@wordpress_sites_bp.route('/sites//environments/', methods=['DELETE']) +@jwt_required() +def delete_environment(site_id, env_id): + """Delete an environment.""" + user_id = get_jwt_identity() + + # Verify ownership + env_site = WordPressSite.query.join(Application).filter( + WordPressSite.id == env_id, + Application.user_id == user_id + ).first() + + if not env_site: + return jsonify({'error': 'Environment not found'}), 404 + + if env_site.production_site_id != site_id: + return jsonify({'error': 'Environment does not belong to this site'}), 400 + + result = WordPressEnvService.delete_environment(env_id) + if result['success']: + return jsonify(result) + else: + return jsonify(result), 500 + + +@wordpress_sites_bp.route('/sites//sync', methods=['POST']) +@jwt_required() +def sync_environment(site_id): + """Sync an environment from its production source.""" + user_id = get_jwt_identity() + data = request.get_json() or {} + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + if site.is_production: + return jsonify({'error': 'Cannot sync a production site'}), 400 + + result = WordPressEnvService.sync_environment(site_id, options=data) + if result['success']: + return jsonify(result) + else: + return jsonify(result), 500 + + +# ============================================================================= +# Database Operations +# ============================================================================= + +@wordpress_sites_bp.route('/sites//snapshots', methods=['GET']) +@jwt_required() +def list_snapshots(site_id): + """List database snapshots for a site.""" + user_id = get_jwt_identity() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + snapshots = DatabaseSnapshot.query.filter_by(site_id=site_id).order_by( + DatabaseSnapshot.created_at.desc() + ).all() + + return jsonify({ + 'snapshots': [s.to_dict() for s in snapshots], + 'total': len(snapshots) + }) + + +@wordpress_sites_bp.route('/sites//snapshots', methods=['POST']) +@jwt_required() +def create_snapshot(site_id): + """Create a database snapshot.""" + user_id = get_jwt_identity() + data = request.get_json() or {} + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + result = DatabaseSyncService.create_snapshot( + db_name=site.db_name, + name=data.get('name', f"{site.application.name}_{site.id}"), + tag=data.get('tag'), + commit_sha=site.last_deploy_commit, + host=site.db_host, + user=site.db_user, + password=WordPressEnvService._get_db_password(site), + exclude_tables=data.get('exclude_tables', []) + ) + + if result['success']: + # Save to database + snapshot = DatabaseSnapshot( + site_id=site_id, + name=result['snapshot']['name'], + tag=data.get('tag'), + file_path=result['snapshot']['file_path'], + size_bytes=result['snapshot']['size_bytes'], + compressed=result['snapshot']['compressed'], + commit_sha=site.last_deploy_commit, + tables_included=json.dumps(result['snapshot'].get('tables', [])), + row_count=result['snapshot'].get('row_count', 0), + status='completed' + ) + db.session.add(snapshot) + db.session.commit() + + return jsonify({ + 'success': True, + 'snapshot': snapshot.to_dict() + }), 201 + else: + return jsonify(result), 500 + + +@wordpress_sites_bp.route('/sites//snapshots//restore', methods=['POST']) +@jwt_required() +def restore_snapshot(site_id, snapshot_id): + """Restore a database snapshot.""" + user_id = get_jwt_identity() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + snapshot = DatabaseSnapshot.query.filter_by(id=snapshot_id, site_id=site_id).first() + if not snapshot: + return jsonify({'error': 'Snapshot not found'}), 404 + + # Create a backup before restoring + backup_result = DatabaseSyncService.create_snapshot( + db_name=site.db_name, + name=f"pre_restore_{snapshot_id}", + tag='pre-restore', + host=site.db_host, + user=site.db_user, + password=WordPressEnvService._get_db_password(site) + ) + + # Restore the snapshot + result = DatabaseSyncService.restore_snapshot( + file_path=snapshot.file_path, + target_db=site.db_name, + host=site.db_host, + user=site.db_user, + password=WordPressEnvService._get_db_password(site), + create_db=False + ) + + if result['success']: + return jsonify({ + 'success': True, + 'message': 'Snapshot restored', + 'backup_path': backup_result.get('snapshot', {}).get('file_path') if backup_result.get('success') else None + }) + else: + return jsonify(result), 500 + + +@wordpress_sites_bp.route('/sites//snapshots/', methods=['DELETE']) +@jwt_required() +def delete_snapshot(site_id, snapshot_id): + """Delete a database snapshot.""" + user_id = get_jwt_identity() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + snapshot = DatabaseSnapshot.query.filter_by(id=snapshot_id, site_id=site_id).first() + if not snapshot: + return jsonify({'error': 'Snapshot not found'}), 404 + + # Delete file + DatabaseSyncService.delete_snapshot(snapshot.file_path) + + # Delete record + db.session.delete(snapshot) + db.session.commit() + + return jsonify({'success': True, 'message': 'Snapshot deleted'}) + + +@wordpress_sites_bp.route('/sites//clone-db', methods=['POST']) +@jwt_required() +def clone_database(site_id): + """Clone the database to another environment.""" + user_id = get_jwt_identity() + data = request.get_json() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + target_site_id = data.get('target_site_id') + if not target_site_id: + return jsonify({'error': 'target_site_id is required'}), 400 + + target_site = WordPressSite.query.join(Application).filter( + WordPressSite.id == target_site_id, + Application.user_id == user_id + ).first() + + if not target_site: + return jsonify({'error': 'Target site not found'}), 404 + + result = DatabaseSyncService.clone_database( + source_db=site.db_name, + target_db=target_site.db_name, + source_host=site.db_host, + target_host=target_site.db_host, + source_user=site.db_user, + target_user=target_site.db_user, + source_password=WordPressEnvService._get_db_password(site), + target_password=WordPressEnvService._get_db_password(target_site), + options=data.get('options', {}) + ) + + if result['success']: + return jsonify(result) + else: + return jsonify(result), 500 + + +# ============================================================================= +# Git Integration +# ============================================================================= + +@wordpress_sites_bp.route('/sites//git', methods=['GET']) +@jwt_required() +def get_git_status(site_id): + """Get Git integration status for a site.""" + user_id = get_jwt_identity() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + result = GitWordPressService.get_git_status(site_id) + return jsonify(result) + + +@wordpress_sites_bp.route('/sites//git', methods=['POST']) +@jwt_required() +def connect_repo(site_id): + """Connect a Git repository to a site.""" + user_id = get_jwt_identity() + data = request.get_json() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + repo_url = data.get('repo_url') + if not repo_url: + return jsonify({'error': 'repo_url is required'}), 400 + + result = GitWordPressService.connect_repo( + site_id=site_id, + repo_url=repo_url, + branch=data.get('branch', 'main'), + paths=data.get('paths'), + auto_deploy=data.get('auto_deploy', False) + ) + + if result['success']: + return jsonify(result) + else: + return jsonify(result), 500 + + +@wordpress_sites_bp.route('/sites//git', methods=['DELETE']) +@jwt_required() +def disconnect_repo(site_id): + """Disconnect Git repository from a site.""" + user_id = get_jwt_identity() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + result = GitWordPressService.disconnect_repo(site_id) + if result['success']: + return jsonify(result) + else: + return jsonify(result), 500 + + +@wordpress_sites_bp.route('/sites//git/commits', methods=['GET']) +@jwt_required() +def get_commits(site_id): + """Get recent commits from the connected repository.""" + user_id = get_jwt_identity() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + limit = request.args.get('limit', 20, type=int) + result = GitWordPressService.get_recent_commits(site_id, limit=limit) + return jsonify(result) + + +@wordpress_sites_bp.route('/sites//git/deploy', methods=['POST']) +@jwt_required() +def deploy_commit(site_id): + """Deploy a specific commit or branch.""" + user_id = get_jwt_identity() + data = request.get_json() or {} + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + result = GitWordPressService.deploy_from_commit( + site_id=site_id, + commit_sha=data.get('commit_sha'), + branch=data.get('branch'), + create_snapshot=data.get('create_snapshot', True) + ) + + if result['success']: + return jsonify(result) + else: + return jsonify(result), 500 + + +@wordpress_sites_bp.route('/sites//git/dev-from-commit', methods=['POST']) +@jwt_required() +def create_dev_from_commit(site_id): + """Create a development environment for a specific commit.""" + user_id = get_jwt_identity() + data = request.get_json() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site: + return jsonify({'error': 'Site not found'}), 404 + + commit_sha = data.get('commit_sha') + if not commit_sha: + return jsonify({'error': 'commit_sha is required'}), 400 + + result = GitWordPressService.create_dev_for_commit( + production_site_id=site_id, + commit_sha=commit_sha, + config=data.get('config', {}), + user_id=user_id + ) + + if result['success']: + return jsonify(result), 201 + else: + return jsonify(result), 500 + + +# ============================================================================= +# WordPress Operations (Plugins, Themes, etc.) +# ============================================================================= + +@wordpress_sites_bp.route('/sites//plugins', methods=['GET']) +@jwt_required() +def get_plugins(site_id): + """Get installed plugins for a site.""" + user_id = get_jwt_identity() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site or not site.application: + return jsonify({'error': 'Site not found'}), 404 + + plugins = WordPressService.get_plugins(site.application.root_path) + return jsonify({'plugins': plugins}) + + +@wordpress_sites_bp.route('/sites//plugins', methods=['POST']) +@jwt_required() +def install_plugin(site_id): + """Install a plugin.""" + user_id = get_jwt_identity() + data = request.get_json() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site or not site.application: + return jsonify({'error': 'Site not found'}), 404 + + plugin = data.get('plugin') + if not plugin: + return jsonify({'error': 'plugin is required'}), 400 + + result = WordPressService.install_plugin( + site.application.root_path, + plugin, + activate=data.get('activate', True) + ) + + if result['success']: + return jsonify(result) + else: + return jsonify(result), 500 + + +@wordpress_sites_bp.route('/sites//themes', methods=['GET']) +@jwt_required() +def get_themes(site_id): + """Get installed themes for a site.""" + user_id = get_jwt_identity() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site or not site.application: + return jsonify({'error': 'Site not found'}), 404 + + themes = WordPressService.get_themes(site.application.root_path) + return jsonify({'themes': themes}) + + +@wordpress_sites_bp.route('/sites//themes', methods=['POST']) +@jwt_required() +def install_theme(site_id): + """Install a theme.""" + user_id = get_jwt_identity() + data = request.get_json() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site or not site.application: + return jsonify({'error': 'Site not found'}), 404 + + theme = data.get('theme') + if not theme: + return jsonify({'error': 'theme is required'}), 400 + + result = WordPressService.install_theme( + site.application.root_path, + theme, + activate=data.get('activate', False) + ) + + if result['success']: + return jsonify(result) + else: + return jsonify(result), 500 + + +@wordpress_sites_bp.route('/sites//update', methods=['POST']) +@jwt_required() +def update_wordpress(site_id): + """Update WordPress core.""" + user_id = get_jwt_identity() + + site = WordPressSite.query.join(Application).filter( + WordPressSite.id == site_id, + Application.user_id == user_id + ).first() + + if not site or not site.application: + return jsonify({'error': 'Site not found'}), 404 + + # Create snapshot before update + snapshot_result = DatabaseSyncService.create_snapshot( + db_name=site.db_name, + name=f"pre_update_{site.wp_version}", + tag='pre-update', + host=site.db_host, + user=site.db_user, + password=WordPressEnvService._get_db_password(site) + ) + + result = WordPressService.update_wordpress(site.application.root_path) + + if result['success']: + # Update version in database + wp_info = WordPressService.get_wordpress_info(site.application.root_path) + if wp_info: + site.wp_version = wp_info.get('version') + db.session.commit() + + return jsonify({ + 'success': True, + 'message': result.get('message'), + 'new_version': site.wp_version, + 'backup_snapshot': snapshot_result.get('snapshot', {}).get('file_path') if snapshot_result.get('success') else None + }) + else: + return jsonify(result), 500 diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 5d1950d2..b01c83c0 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -11,10 +11,12 @@ from app.models.workflow import Workflow 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 __all__ = [ 'User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory', 'NotificationPreferences', 'Deployment', 'DeploymentDiff', 'SystemSettings', 'AuditLog', 'MetricsHistory', 'Workflow', 'GitWebhook', 'WebhookLog', 'GitDeployment', - 'Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'SecurityAlert' + 'Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'SecurityAlert', + 'WordPressSite', 'DatabaseSnapshot', 'SyncJob' ] diff --git a/backend/app/models/wordpress_site.py b/backend/app/models/wordpress_site.py new file mode 100644 index 00000000..af9b886e --- /dev/null +++ b/backend/app/models/wordpress_site.py @@ -0,0 +1,247 @@ +""" +WordPress Site Models + +Extended models for WordPress-specific functionality including: +- WordPress site metadata +- Database snapshots for point-in-time recovery +- Sync jobs for scheduled database synchronization +""" + +from datetime import datetime +from app import db +import json + + +class WordPressSite(db.Model): + """Extended WordPress-specific data linked to Application.""" + + __tablename__ = 'wordpress_sites' + + id = db.Column(db.Integer, primary_key=True) + application_id = db.Column(db.Integer, db.ForeignKey('applications.id'), unique=True, nullable=False) + + # WordPress specifics + wp_version = db.Column(db.String(20)) + multisite = db.Column(db.Boolean, default=False) + admin_user = db.Column(db.String(100)) + admin_email = db.Column(db.String(200)) + + # Database info + db_name = db.Column(db.String(100)) + db_user = db.Column(db.String(100)) + db_host = db.Column(db.String(200), default='localhost') + db_prefix = db.Column(db.String(20), default='wp_') + + # Git integration + git_repo_url = db.Column(db.String(500)) + git_branch = db.Column(db.String(100), default='main') + git_paths = db.Column(db.Text) # JSON: paths to sync ['wp-content/themes', 'wp-content/plugins'] + auto_deploy = db.Column(db.Boolean, default=False) + last_deploy_commit = db.Column(db.String(40)) + last_deploy_at = db.Column(db.DateTime) + + # Environment info + is_production = db.Column(db.Boolean, default=True) + production_site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=True) + + # Sync settings (JSON) + sync_config = db.Column(db.Text) # schedule, search_replace, anonymize, etc. + + # Timestamps + created_at = db.Column(db.DateTime, default=datetime.utcnow) + updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) + + # Relationships + application = db.relationship('Application', backref=db.backref('wp_site', uselist=False)) + environments = db.relationship( + 'WordPressSite', + backref=db.backref('production_site', remote_side=[id]), + foreign_keys=[production_site_id] + ) + snapshots = db.relationship('DatabaseSnapshot', backref='site', lazy='dynamic', cascade='all, delete-orphan') + sync_jobs_as_source = db.relationship( + 'SyncJob', + foreign_keys='SyncJob.source_site_id', + backref='source_site', + lazy='dynamic' + ) + sync_jobs_as_target = db.relationship( + 'SyncJob', + foreign_keys='SyncJob.target_site_id', + backref='target_site', + lazy='dynamic' + ) + + def to_dict(self, include_environments=False, include_snapshots=False): + result = { + 'id': self.id, + 'application_id': self.application_id, + 'wp_version': self.wp_version, + 'multisite': self.multisite, + 'admin_user': self.admin_user, + 'admin_email': self.admin_email, + 'db_name': self.db_name, + 'db_user': self.db_user, + 'db_host': self.db_host, + 'db_prefix': self.db_prefix, + 'git_repo_url': self.git_repo_url, + 'git_branch': self.git_branch, + 'git_paths': json.loads(self.git_paths) if self.git_paths else None, + 'auto_deploy': self.auto_deploy, + 'last_deploy_commit': self.last_deploy_commit, + 'last_deploy_at': self.last_deploy_at.isoformat() if self.last_deploy_at else None, + '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, + 'created_at': self.created_at.isoformat() if self.created_at else None, + 'updated_at': self.updated_at.isoformat() if self.updated_at else None, + } + + # Include application data + if self.application: + result['application'] = { + 'id': self.application.id, + 'name': self.application.name, + 'status': self.application.status, + 'root_path': self.application.root_path, + 'port': self.application.port, + 'domains': [d.to_dict() for d in self.application.domains] + } + + if include_environments and self.is_production: + result['environments'] = [env.to_dict() for env in self.environments] + + if include_snapshots: + result['snapshots'] = [snap.to_dict() for snap in self.snapshots.order_by(DatabaseSnapshot.created_at.desc()).limit(10)] + + return result + + def __repr__(self): + return f'' + + +class DatabaseSnapshot(db.Model): + """Point-in-time database snapshots for WordPress sites.""" + + __tablename__ = 'database_snapshots' + + id = db.Column(db.Integer, primary_key=True) + site_id = db.Column(db.Integer, db.ForeignKey('wordpress_sites.id'), nullable=False) + + # Snapshot info + name = db.Column(db.String(200), nullable=False) + description = db.Column(db.Text) + tag = db.Column(db.String(100)) # e.g., 'pre-deploy', 'v1.2.0', 'auto-nightly' + + # File info + file_path = db.Column(db.String(500), nullable=False) + size_bytes = db.Column(db.BigInteger, default=0) + compressed = db.Column(db.Boolean, default=True) + + # Git context (optional) + commit_sha = db.Column(db.String(40)) # Git commit at snapshot time + commit_message = db.Column(db.Text) + + # Metadata + tables_included = db.Column(db.Text) # JSON list of tables + row_count = db.Column(db.Integer) + + # Status + status = db.Column(db.String(20), default='completed') # creating, completed, failed, deleted + error_message = db.Column(db.Text) + + # Timestamps + created_at = db.Column(db.DateTime, default=datetime.utcnow) + expires_at = db.Column(db.DateTime) # Auto-cleanup date + + def to_dict(self): + return { + 'id': self.id, + 'site_id': self.site_id, + 'name': self.name, + 'description': self.description, + 'tag': self.tag, + 'file_path': self.file_path, + 'size_bytes': self.size_bytes, + 'size_human': self._format_size(self.size_bytes), + 'compressed': self.compressed, + 'commit_sha': self.commit_sha, + 'commit_message': self.commit_message, + 'tables_included': json.loads(self.tables_included) if self.tables_included else None, + 'row_count': self.row_count, + 'status': self.status, + 'error_message': self.error_message, + 'created_at': self.created_at.isoformat() if self.created_at else None, + 'expires_at': self.expires_at.isoformat() if self.expires_at else None, + } + + @staticmethod + def _format_size(size_bytes): + 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' + + def __repr__(self): + return f'' + + +class SyncJob(db.Model): + """Scheduled database synchronization jobs between WordPress environments.""" + + __tablename__ = 'sync_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) + + # Job name + name = db.Column(db.String(200)) + + # Schedule (cron expression) + schedule = db.Column(db.String(100)) # e.g., "0 3 * * 0" = Sunday 3 AM + enabled = db.Column(db.Boolean, default=True) + + # Configuration (JSON) + config = db.Column(db.Text) # search_replace, anonymize, exclude_tables, truncate_tables + + # Execution tracking + last_run = db.Column(db.DateTime) + last_run_status = db.Column(db.String(20)) # success, failed, running + last_run_duration = db.Column(db.Integer) # seconds + last_run_error = db.Column(db.Text) + next_run = db.Column(db.DateTime) + run_count = db.Column(db.Integer, default=0) + + # Timestamps + created_at = db.Column(db.DateTime, default=datetime.utcnow) + updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) + + def to_dict(self): + return { + 'id': self.id, + 'name': self.name, + 'source_site_id': self.source_site_id, + 'target_site_id': self.target_site_id, + 'schedule': self.schedule, + 'enabled': self.enabled, + 'config': json.loads(self.config) if self.config else None, + 'last_run': self.last_run.isoformat() if self.last_run else None, + 'last_run_status': self.last_run_status, + 'last_run_duration': self.last_run_duration, + 'last_run_error': self.last_run_error, + 'next_run': self.next_run.isoformat() if self.next_run else None, + 'run_count': self.run_count, + 'created_at': self.created_at.isoformat() if self.created_at else None, + 'updated_at': self.updated_at.isoformat() if self.updated_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/services/db_sync_service.py b/backend/app/services/db_sync_service.py new file mode 100644 index 00000000..8c188547 --- /dev/null +++ b/backend/app/services/db_sync_service.py @@ -0,0 +1,609 @@ +""" +Database Sync Service + +Service for database cloning, transformation, and synchronization operations. +Supports WordPress-specific features like URL search-replace and data anonymization. +""" + +import os +import subprocess +import gzip +import shutil +import json +import re +from datetime import datetime, timedelta +from typing import Dict, List, Optional +from pathlib import Path + + +class DatabaseSyncService: + """Service for database cloning, transformation, and sync operations.""" + + SNAPSHOT_DIR = '/var/backups/serverkit/snapshots' + TEMP_DIR = '/tmp/serverkit_db_sync' + + @classmethod + def _ensure_dirs(cls): + """Ensure required directories exist.""" + for dir_path in [cls.SNAPSHOT_DIR, cls.TEMP_DIR]: + os.makedirs(dir_path, exist_ok=True) + + @classmethod + def _run_mysql(cls, command: str, database: str = None, host: str = 'localhost', + user: str = 'root', password: str = None) -> Dict: + """Execute a MySQL command.""" + try: + cmd = ['mysql', '-h', host, '-u', user] + if password: + cmd.append(f'-p{password}') + if database: + cmd.extend(['-D', database]) + cmd.extend(['-e', command]) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=300 + ) + + return { + 'success': result.returncode == 0, + 'output': result.stdout, + 'error': result.stderr if result.returncode != 0 else None + } + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Command timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def create_snapshot(cls, db_name: str, name: str = None, tag: str = None, + commit_sha: str = None, host: str = 'localhost', + user: str = 'root', password: str = None, + compress: bool = True, exclude_tables: List[str] = None) -> Dict: + """ + Create a point-in-time database snapshot. + + Args: + db_name: Database name to snapshot + name: Human-readable snapshot name + tag: Optional tag (e.g., 'pre-deploy', 'v1.2.0') + commit_sha: Git commit SHA at snapshot time + host: MySQL host + user: MySQL user + password: MySQL password + compress: Whether to gzip the dump + exclude_tables: List of tables to exclude + + Returns: + Dict with success status and snapshot info + """ + cls._ensure_dirs() + + timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') + snapshot_name = name or f'{db_name}_{timestamp}' + safe_name = re.sub(r'[^a-zA-Z0-9_-]', '_', snapshot_name) + + file_name = f'{safe_name}.sql' + if compress: + file_name += '.gz' + + file_path = os.path.join(cls.SNAPSHOT_DIR, file_name) + + try: + # Build mysqldump command + cmd = ['mysqldump', '-h', host, '-u', user] + if password: + cmd.append(f'-p{password}') + + # Add options for consistent snapshot + cmd.extend([ + '--single-transaction', + '--routines', + '--triggers', + '--add-drop-table', + ]) + + # Exclude tables if specified + if exclude_tables: + for table in exclude_tables: + cmd.extend(['--ignore-table', f'{db_name}.{table}']) + + cmd.append(db_name) + + # Execute dump + if compress: + # Pipe through gzip + dump_process = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE + ) + with gzip.open(file_path, 'wb') as f: + while True: + chunk = dump_process.stdout.read(8192) + if not chunk: + break + f.write(chunk) + + dump_process.wait() + if dump_process.returncode != 0: + error = dump_process.stderr.read().decode() + return {'success': False, 'error': f'mysqldump failed: {error}'} + else: + with open(file_path, 'w') as f: + result = subprocess.run(cmd, stdout=f, stderr=subprocess.PIPE, text=True) + if result.returncode != 0: + return {'success': False, 'error': f'mysqldump failed: {result.stderr}'} + + # Get file size + size_bytes = os.path.getsize(file_path) + + # Get table list and row count + tables_result = cls._run_mysql( + f"SELECT TABLE_NAME, TABLE_ROWS FROM information_schema.tables WHERE TABLE_SCHEMA = '{db_name}'", + host=host, user=user, password=password + ) + + tables = [] + total_rows = 0 + if tables_result['success']: + for line in tables_result['output'].strip().split('\n')[1:]: + parts = line.split('\t') + if len(parts) >= 2: + tables.append(parts[0]) + try: + total_rows += int(parts[1]) if parts[1] != 'NULL' else 0 + except ValueError: + pass + + return { + 'success': True, + 'snapshot': { + 'name': snapshot_name, + 'tag': tag, + 'file_path': file_path, + 'size_bytes': size_bytes, + 'compressed': compress, + 'commit_sha': commit_sha, + 'tables': tables, + 'row_count': total_rows, + 'created_at': datetime.now().isoformat() + } + } + + except Exception as e: + # Cleanup on failure + if os.path.exists(file_path): + os.remove(file_path) + return {'success': False, 'error': str(e)} + + @classmethod + def restore_snapshot(cls, file_path: str, target_db: str, + host: str = 'localhost', user: str = 'root', + password: str = None, create_db: bool = True) -> Dict: + """ + Restore a database snapshot. + + Args: + file_path: Path to snapshot file (.sql or .sql.gz) + target_db: Target database name + host: MySQL host + user: MySQL user + password: MySQL password + create_db: Create database if it doesn't exist + + Returns: + Dict with success status + """ + if not os.path.exists(file_path): + return {'success': False, 'error': f'Snapshot file not found: {file_path}'} + + try: + # Create database if needed + if create_db: + create_result = cls._run_mysql( + f"CREATE DATABASE IF NOT EXISTS `{target_db}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci", + host=host, user=user, password=password + ) + if not create_result['success']: + return create_result + + # Build mysql import command + cmd = ['mysql', '-h', host, '-u', user] + if password: + cmd.append(f'-p{password}') + cmd.append(target_db) + + # Handle compressed files + if file_path.endswith('.gz'): + with gzip.open(file_path, 'rb') as f: + result = subprocess.run( + cmd, + stdin=f, + capture_output=True, + timeout=1800 # 30 min timeout for large DBs + ) + else: + with open(file_path, 'r') as f: + result = subprocess.run( + cmd, + stdin=f, + capture_output=True, + timeout=1800 + ) + + if result.returncode != 0: + return {'success': False, 'error': result.stderr.decode() if result.stderr else 'Import failed'} + + return {'success': True, 'message': f'Snapshot restored to {target_db}'} + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Restore timed out (>30 minutes)'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def clone_database(cls, source_db: str, target_db: str, + source_host: str = 'localhost', target_host: str = 'localhost', + source_user: str = 'root', target_user: str = 'root', + source_password: str = None, target_password: str = None, + options: Dict = None) -> Dict: + """ + Clone a database with optional transformations. + + Args: + source_db: Source database name + target_db: Target database name + source_host/target_host: MySQL hosts + source_user/target_user: MySQL users + source_password/target_password: MySQL passwords + options: Dict with transformation options: + - search_replace: Dict of {search: replace} for URL/string replacement + - table_prefix: New table prefix (e.g., 'wp_dev_') + - anonymize: Bool - anonymize user data + - exclude_tables: List of tables to skip + - truncate_tables: List of tables to empty (keep structure) + + Returns: + Dict with success status and clone info + """ + options = options or {} + cls._ensure_dirs() + + try: + # Step 1: Create snapshot of source + snapshot_result = cls.create_snapshot( + db_name=source_db, + name=f'clone_{source_db}_to_{target_db}', + host=source_host, + user=source_user, + password=source_password, + compress=False, # Don't compress for transformation + exclude_tables=options.get('exclude_tables', []) + ) + + if not snapshot_result['success']: + return snapshot_result + + dump_file = snapshot_result['snapshot']['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: Drop and recreate target database + cls._run_mysql( + f"DROP DATABASE IF EXISTS `{target_db}`", + host=target_host, user=target_user, password=target_password + ) + + # Step 4: Restore to target + restore_result = cls.restore_snapshot( + file_path=import_file, + target_db=target_db, + host=target_host, + user=target_user, + password=target_password, + create_db=True + ) + + if not restore_result['success']: + return restore_result + + return { + 'success': True, + 'message': f'Database cloned from {source_db} to {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 _transform_dump(cls, input_file: str, output_file: str, options: Dict) -> Dict: + """ + Transform a SQL dump file with search-replace and other modifications. + + This handles WordPress serialized data properly using PHP-style serialization. + """ + search_replace = options.get('search_replace', {}) + new_prefix = options.get('table_prefix') + anonymize = options.get('anonymize', False) + truncate_tables = options.get('truncate_tables', []) + + try: + with open(input_file, 'r', encoding='utf-8', errors='replace') as infile: + with open(output_file, 'w', encoding='utf-8') as outfile: + current_table = None + + for line in infile: + # Track current table for truncation + if line.startswith('INSERT INTO'): + match = re.search(r'INSERT INTO `?(\w+)`?', line) + if match: + current_table = match.group(1) + + # Skip inserts for truncated tables + if current_table and truncate_tables: + table_name = current_table + if new_prefix: + # Check both old and new prefix versions + for prefix in ['wp_', new_prefix]: + for t in truncate_tables: + if table_name == f'{prefix}{t}' or table_name == t: + # Skip this INSERT + if line.startswith('INSERT INTO'): + continue + + # Table prefix replacement + if new_prefix and 'wp_' in line: + # Replace table references + line = re.sub(r'`wp_(\w+)`', f'`{new_prefix}\\1`', line) + # Replace in CREATE TABLE + line = line.replace('CREATE TABLE `wp_', f'CREATE TABLE `{new_prefix}') + # Replace in INSERT INTO + line = line.replace('INSERT INTO `wp_', f'INSERT INTO `{new_prefix}') + + # Search and replace (handles serialized data) + 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) + + outfile.write(line) + + return {'success': True} + + except Exception as e: + return {'success': False, 'error': f'Transform failed: {str(e)}'} + + @classmethod + def _safe_search_replace(cls, text: str, search: str, replace: str) -> str: + """ + Perform search-replace that handles WordPress serialized data. + + WordPress stores serialized PHP arrays in the database with string length prefixes. + e.g., s:23:"http://example.com/path"; + + When replacing URLs, we need to update these length prefixes. + """ + # Simple replacement first + if search not in text: + return text + + # Handle serialized string format: s:LENGTH:"VALUE"; + def replace_serialized(match): + original = match.group(2) + new_value = original.replace(search, replace) + new_length = len(new_value.encode('utf-8')) + return f's:{new_length}:"{new_value}"' + + # Pattern for serialized strings that contain the search term + pattern = r's:(\d+):"([^"]*' + re.escape(search) + r'[^"]*)"' + text = re.sub(pattern, replace_serialized, text) + + # Also do plain replacement for non-serialized occurrences + text = text.replace(search, replace) + + return text + + @classmethod + def _anonymize_line(cls, line: str) -> str: + """Anonymize user data in a SQL line.""" + # Replace email addresses + line = re.sub( + r"'([^']+@[^']+)'", + lambda m: f"'user{hash(m.group(1)) % 10000}@example.com'", + line + ) + return line + + @classmethod + def run_search_replace(cls, db_name: str, search: str, replace: str, + table_prefix: str = 'wp_', host: str = 'localhost', + user: str = 'root', password: str = None, + dry_run: bool = False) -> Dict: + """ + Run WordPress-aware search-replace on a database. + + This is a pure SQL approach without requiring WP-CLI. + For better serialized data handling, use WP-CLI if available. + + Args: + db_name: Database name + search: String to search for + replace: String to replace with + table_prefix: WordPress table prefix + host: MySQL host + user: MySQL user + password: MySQL password + dry_run: Only count replacements, don't apply + + Returns: + Dict with success status and replacement count + """ + try: + # Get list of tables + tables_result = cls._run_mysql( + f"SHOW TABLES LIKE '{table_prefix}%'", + database=db_name, host=host, user=user, password=password + ) + + if not tables_result['success']: + return tables_result + + tables = [line.strip() for line in tables_result['output'].strip().split('\n')[1:] if line.strip()] + total_replacements = 0 + + for table in tables: + # Get columns + cols_result = cls._run_mysql( + f"SHOW COLUMNS FROM `{table}`", + database=db_name, host=host, user=user, password=password + ) + + if not cols_result['success']: + continue + + # Find text/varchar columns + text_columns = [] + for line in cols_result['output'].strip().split('\n')[1:]: + parts = line.split('\t') + if len(parts) >= 2: + col_name = parts[0] + col_type = parts[1].lower() + if any(t in col_type for t in ['varchar', 'text', 'longtext', 'mediumtext']): + text_columns.append(col_name) + + # Count or replace in each column + for col in text_columns: + if dry_run: + count_query = f"SELECT COUNT(*) FROM `{table}` WHERE `{col}` LIKE '%{search}%'" + count_result = cls._run_mysql( + count_query, + database=db_name, host=host, user=user, password=password + ) + if count_result['success']: + try: + count = int(count_result['output'].strip().split('\n')[1]) + total_replacements += count + except (IndexError, ValueError): + pass + else: + # Note: This is basic replacement, doesn't handle serialized data perfectly + update_query = f"UPDATE `{table}` SET `{col}` = REPLACE(`{col}`, '{search}', '{replace}') WHERE `{col}` LIKE '%{search}%'" + cls._run_mysql( + update_query, + database=db_name, host=host, user=user, password=password + ) + + return { + 'success': True, + 'dry_run': dry_run, + 'replacements': total_replacements if dry_run else 'Applied to all matching rows', + 'tables_processed': len(tables) + } + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def delete_snapshot(cls, file_path: str) -> Dict: + """Delete a snapshot file.""" + try: + if os.path.exists(file_path): + os.remove(file_path) + return {'success': True, 'message': 'Snapshot deleted'} + return {'success': False, 'error': 'Snapshot file not found'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def list_snapshots(cls, site_name: str = None) -> List[Dict]: + """List available snapshots.""" + cls._ensure_dirs() + snapshots = [] + + try: + for filename in os.listdir(cls.SNAPSHOT_DIR): + if not filename.endswith(('.sql', '.sql.gz')): + continue + + if site_name and not filename.startswith(site_name): + continue + + file_path = os.path.join(cls.SNAPSHOT_DIR, filename) + stat = os.stat(file_path) + + snapshots.append({ + 'name': filename.replace('.sql.gz', '').replace('.sql', ''), + 'file_path': file_path, + 'size_bytes': stat.st_size, + 'compressed': filename.endswith('.gz'), + 'created_at': datetime.fromtimestamp(stat.st_mtime).isoformat() + }) + + return sorted(snapshots, key=lambda x: x['created_at'], reverse=True) + + except Exception: + return [] + + @classmethod + def cleanup_old_snapshots(cls, days: int = 30, keep_tagged: bool = True) -> Dict: + """ + Clean up snapshots older than specified days. + + Args: + days: Delete snapshots older than this many days + keep_tagged: Keep snapshots with tags (like 'v1.0.0') + + Returns: + Dict with deleted count + """ + cls._ensure_dirs() + cutoff = datetime.now() - timedelta(days=days) + deleted = 0 + + try: + for filename in os.listdir(cls.SNAPSHOT_DIR): + file_path = os.path.join(cls.SNAPSHOT_DIR, filename) + stat = os.stat(file_path) + file_time = datetime.fromtimestamp(stat.st_mtime) + + if file_time < cutoff: + # TODO: Check if tagged in database before deleting + os.remove(file_path) + deleted += 1 + + return {'success': True, 'deleted': deleted} + + except Exception as e: + return {'success': False, 'error': str(e), 'deleted': deleted} diff --git a/backend/app/services/git_wordpress_service.py b/backend/app/services/git_wordpress_service.py new file mode 100644 index 00000000..abfd91cd --- /dev/null +++ b/backend/app/services/git_wordpress_service.py @@ -0,0 +1,536 @@ +""" +Git WordPress Service + +Connect Git repositories to WordPress wp-content for theme/plugin management. +Supports deployment from specific commits and creating dev environments for any revision. +""" + +import os +import subprocess +import shutil +import json +from datetime import datetime +from typing import Dict, List, Optional + +from app import db +from app.models.wordpress_site import WordPressSite, DatabaseSnapshot +from app.services.db_sync_service import DatabaseSyncService +from app.services.wordpress_env_service import WordPressEnvService + + +class GitWordPressService: + """Connect Git repositories to WordPress wp-content.""" + + DEFAULT_PATHS = ['wp-content/themes', 'wp-content/plugins'] + + @classmethod + def connect_repo(cls, site_id: int, repo_url: str, branch: str = 'main', + paths: List[str] = None, auto_deploy: bool = False) -> Dict: + """ + Connect a Git repository to a WordPress site. + + Args: + site_id: ID of the WordPressSite + repo_url: Git repository URL (HTTPS or SSH) + branch: Branch to track (default: main) + paths: What to sync (default: ['wp-content/themes', 'wp-content/plugins']) + auto_deploy: Enable automatic deployment on push + + Returns: + Dict with success status + """ + site = WordPressSite.query.get(site_id) + if not site: + return {'success': False, 'error': 'Site not found'} + + if not site.application or not site.application.root_path: + return {'success': False, 'error': 'Site application path not found'} + + wp_path = site.application.root_path + paths = paths or cls.DEFAULT_PATHS + + try: + # Validate repository URL + if not cls._validate_repo_url(repo_url): + return {'success': False, 'error': 'Invalid repository URL'} + + # Test repository access + test_result = cls._test_repo_access(repo_url) + if not test_result['success']: + return test_result + + # Initialize git in wp-content if not exists + wp_content_path = os.path.join(wp_path, 'wp-content') + git_result = cls._init_git_tracking(wp_content_path, repo_url, branch) + if not git_result['success']: + return git_result + + # Update site record + site.git_repo_url = repo_url + site.git_branch = branch + site.git_paths = json.dumps(paths) + site.auto_deploy = auto_deploy + + db.session.commit() + + return { + 'success': True, + 'message': f'Repository connected successfully', + 'repo_url': repo_url, + 'branch': branch, + 'paths': paths + } + + except Exception as e: + db.session.rollback() + return {'success': False, 'error': str(e)} + + @classmethod + def disconnect_repo(cls, site_id: int) -> Dict: + """ + Disconnect a Git repository from a WordPress site. + + Args: + site_id: ID of the WordPressSite + + Returns: + Dict with success status + """ + site = WordPressSite.query.get(site_id) + if not site: + return {'success': False, 'error': 'Site not found'} + + try: + # Remove git tracking from wp-content + if site.application and site.application.root_path: + wp_content_path = os.path.join(site.application.root_path, 'wp-content') + git_dir = os.path.join(wp_content_path, '.git') + if os.path.exists(git_dir): + shutil.rmtree(git_dir) + + # Clear git settings + site.git_repo_url = None + site.git_branch = None + site.git_paths = None + site.auto_deploy = False + site.last_deploy_commit = None + site.last_deploy_at = None + + db.session.commit() + + return {'success': True, 'message': 'Repository disconnected'} + + except Exception as e: + db.session.rollback() + return {'success': False, 'error': str(e)} + + @classmethod + def deploy_from_commit(cls, site_id: int, commit_sha: str = None, + branch: str = None, create_snapshot: bool = True) -> Dict: + """ + Deploy a specific commit or branch to the WordPress site. + + Args: + site_id: ID of the WordPressSite + commit_sha: Specific commit SHA to deploy (optional) + branch: Branch name to deploy latest from (optional) + create_snapshot: Create a database snapshot before deploying + + Returns: + Dict with success status and deployment 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') + + try: + # Create pre-deploy snapshot + if create_snapshot: + snapshot_result = DatabaseSyncService.create_snapshot( + db_name=site.db_name, + name=f"pre_deploy_{datetime.now().strftime('%Y%m%d_%H%M%S')}", + tag='pre-deploy', + commit_sha=site.last_deploy_commit, + host=site.db_host, + user=site.db_user, + password=WordPressEnvService._get_db_password(site) + ) + + if snapshot_result['success']: + # Save snapshot to database + snapshot = DatabaseSnapshot( + site_id=site.id, + name=snapshot_result['snapshot']['name'], + tag='pre-deploy', + file_path=snapshot_result['snapshot']['file_path'], + size_bytes=snapshot_result['snapshot']['size_bytes'], + compressed=snapshot_result['snapshot']['compressed'], + commit_sha=site.last_deploy_commit, + tables_included=json.dumps(snapshot_result['snapshot'].get('tables', [])), + row_count=snapshot_result['snapshot'].get('row_count', 0), + status='completed' + ) + db.session.add(snapshot) + + # Fetch latest from remote + fetch_result = cls._run_git(wp_content_path, ['fetch', 'origin']) + if not fetch_result['success']: + return fetch_result + + # Determine what to checkout + if commit_sha: + target = commit_sha + elif branch: + target = f'origin/{branch}' + else: + target = f'origin/{site.git_branch}' + + # Checkout the target + checkout_result = cls._run_git(wp_content_path, ['checkout', target, '--force']) + if not checkout_result['success']: + return checkout_result + + # Get the actual commit SHA we deployed + rev_result = cls._run_git(wp_content_path, ['rev-parse', 'HEAD']) + deployed_sha = rev_result['output'].strip() if rev_result['success'] else commit_sha + + # Get commit message + msg_result = cls._run_git(wp_content_path, ['log', '-1', '--format=%s']) + commit_message = msg_result['output'].strip() if msg_result['success'] else '' + + # Update site record + site.last_deploy_commit = deployed_sha + site.last_deploy_at = datetime.utcnow() + + db.session.commit() + + return { + 'success': True, + 'message': 'Deployment successful', + 'commit_sha': deployed_sha, + 'commit_message': commit_message, + 'pre_deploy_snapshot': snapshot_result.get('snapshot', {}).get('file_path') if create_snapshot else None + } + + except Exception as e: + db.session.rollback() + return {'success': False, 'error': str(e)} + + @classmethod + def create_dev_for_commit(cls, production_site_id: int, commit_sha: str, + config: Dict, user_id: int) -> Dict: + """ + Create a development environment for a specific commit. + + This creates a full dev environment with: + - Database snapshot from nearest point in time (or current) + - Code checked out at the specified commit + - URL search-replace applied + + Args: + production_site_id: ID of the production WordPressSite + commit_sha: Git commit SHA to create dev for + config: Environment configuration (name, domain, etc.) + user_id: User ID creating the environment + + Returns: + Dict with success status and dev environment info + """ + 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: + return {'success': False, 'error': 'Source site is not a production site'} + + if not prod_site.git_repo_url: + return {'success': False, 'error': 'No repository connected to production site'} + + try: + # Get short SHA for naming + short_sha = commit_sha[:7] + + # Set defaults in config + if not config.get('name'): + config['name'] = f"{prod_site.application.name} @ {short_sha}" + + if not config.get('domain'): + # Try to create subdomain from production domain + if prod_site.application.domains: + prod_domain = prod_site.application.domains[0].domain + config['domain'] = f"{short_sha}.dev.{prod_domain}" + + # Create the environment using WordPressEnvService + env_result = WordPressEnvService.create_environment( + production_site_id=production_site_id, + env_type='development', + config=config, + user_id=user_id + ) + + if not env_result['success']: + return env_result + + env_site_id = env_result['environment']['id'] + env_site = WordPressSite.query.get(env_site_id) + + # Checkout the specific commit + if env_site and env_site.application: + wp_content_path = os.path.join(env_site.application.root_path, 'wp-content') + + # Initialize git in the new environment + init_result = cls._init_git_tracking( + wp_content_path, + prod_site.git_repo_url, + prod_site.git_branch + ) + + if init_result['success']: + # Fetch and checkout specific commit + cls._run_git(wp_content_path, ['fetch', 'origin']) + checkout_result = cls._run_git(wp_content_path, ['checkout', commit_sha, '--force']) + + if checkout_result['success']: + env_site.last_deploy_commit = commit_sha + env_site.last_deploy_at = datetime.utcnow() + db.session.commit() + + return { + 'success': True, + 'message': f'Development environment created for commit {short_sha}', + 'environment': env_site.to_dict() if env_site else env_result['environment'], + 'commit_sha': commit_sha, + 'url': f"https://{config.get('domain')}" if config.get('domain') else None + } + + except Exception as e: + db.session.rollback() + return {'success': False, 'error': str(e)} + + @classmethod + def get_recent_commits(cls, site_id: int, limit: int = 20) -> Dict: + """ + Get recent commits from the repository. + + Args: + site_id: ID of the WordPressSite + limit: Maximum number of commits to return + + Returns: + Dict with list of commits + """ + 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') + + try: + # Fetch latest + cls._run_git(wp_content_path, ['fetch', 'origin']) + + # Get commit log + log_format = '%H|%h|%s|%an|%ae|%ai' + log_result = cls._run_git(wp_content_path, [ + 'log', + f'origin/{site.git_branch}', + f'-{limit}', + f'--format={log_format}' + ]) + + if not log_result['success']: + return log_result + + commits = [] + for line in log_result['output'].strip().split('\n'): + if not line: + continue + parts = line.split('|') + if len(parts) >= 6: + commits.append({ + 'sha': parts[0], + 'short_sha': parts[1], + 'message': parts[2], + 'author_name': parts[3], + 'author_email': parts[4], + 'date': parts[5], + 'is_deployed': parts[0] == site.last_deploy_commit + }) + + return { + 'success': True, + 'commits': commits, + 'current_deploy': site.last_deploy_commit + } + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def rollback_to_commit(cls, site_id: int, commit_sha: str) -> Dict: + """ + Rollback a site to a previous commit. + + Args: + site_id: ID of the WordPressSite + commit_sha: Commit SHA to rollback to + + Returns: + Dict with success status + """ + # This is essentially the same as deploy_from_commit + return cls.deploy_from_commit(site_id, commit_sha=commit_sha, create_snapshot=True) + + @classmethod + def get_git_status(cls, site_id: int) -> Dict: + """ + Get the Git status for a site. + + Args: + site_id: ID of the WordPressSite + + Returns: + Dict with Git status information + """ + site = WordPressSite.query.get(site_id) + if not site: + return {'success': False, 'error': 'Site not found'} + + result = { + 'success': True, + 'connected': bool(site.git_repo_url), + 'repo_url': site.git_repo_url, + 'branch': site.git_branch, + 'auto_deploy': site.auto_deploy, + 'last_deploy_commit': site.last_deploy_commit, + 'last_deploy_at': site.last_deploy_at.isoformat() if site.last_deploy_at else None, + 'paths': json.loads(site.git_paths) if site.git_paths else None + } + + if site.git_repo_url and site.application and site.application.root_path: + wp_content_path = os.path.join(site.application.root_path, 'wp-content') + + # Check if there are uncommitted changes + status_result = cls._run_git(wp_content_path, ['status', '--porcelain']) + if status_result['success']: + result['has_local_changes'] = bool(status_result['output'].strip()) + + # Check if behind remote + cls._run_git(wp_content_path, ['fetch', 'origin']) + behind_result = cls._run_git(wp_content_path, [ + 'rev-list', + '--count', + f'HEAD..origin/{site.git_branch}' + ]) + if behind_result['success']: + result['commits_behind'] = int(behind_result['output'].strip() or 0) + + return result + + @classmethod + def _validate_repo_url(cls, url: str) -> bool: + """Validate a Git repository URL.""" + if not url: + return False + + # Accept HTTPS URLs + if url.startswith('https://'): + return True + + # Accept SSH URLs + if url.startswith('git@') or url.startswith('ssh://'): + return True + + return False + + @classmethod + def _test_repo_access(cls, repo_url: str) -> Dict: + """Test if we can access the repository.""" + try: + result = subprocess.run( + ['git', 'ls-remote', '--exit-code', repo_url], + capture_output=True, + text=True, + timeout=30 + ) + + if result.returncode == 0: + return {'success': True} + else: + return { + 'success': False, + 'error': f'Cannot access repository: {result.stderr or "Authentication failed or repository not found"}' + } + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Connection to repository timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def _init_git_tracking(cls, path: str, repo_url: str, branch: str) -> Dict: + """Initialize Git tracking in a directory.""" + try: + git_dir = os.path.join(path, '.git') + + if os.path.exists(git_dir): + # Already initialized, just update remote + cls._run_git(path, ['remote', 'set-url', 'origin', repo_url]) + else: + # Initialize new repo + init_result = cls._run_git(path, ['init']) + if not init_result['success']: + return init_result + + # Add remote + remote_result = cls._run_git(path, ['remote', 'add', 'origin', repo_url]) + if not remote_result['success']: + return remote_result + + # Fetch from remote + fetch_result = cls._run_git(path, ['fetch', 'origin']) + if not fetch_result['success']: + return fetch_result + + return {'success': True} + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def _run_git(cls, cwd: str, args: List[str]) -> Dict: + """Run a Git command.""" + try: + cmd = ['git'] + args + result = subprocess.run( + cmd, + cwd=cwd, + capture_output=True, + text=True, + timeout=120 + ) + + return { + 'success': result.returncode == 0, + 'output': result.stdout, + 'error': result.stderr if result.returncode != 0 else None + } + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Git command timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} diff --git a/backend/app/services/wordpress_env_service.py b/backend/app/services/wordpress_env_service.py new file mode 100644 index 00000000..ffb0b0b3 --- /dev/null +++ b/backend/app/services/wordpress_env_service.py @@ -0,0 +1,486 @@ +""" +WordPress Environment Service + +Manage WordPress production/development/staging environments. +Handles environment creation, database cloning, and synchronization. +""" + +import os +import json +import secrets +import string +import shutil +from datetime import datetime +from typing import Dict, List, Optional + +from app import db +from app.models.application import Application +from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob +from app.services.db_sync_service import DatabaseSyncService +from app.services.wordpress_service import WordPressService +from app.services.database_service import DatabaseService + + +class WordPressEnvService: + """Manage WordPress production/development/staging environments.""" + + @classmethod + def create_environment(cls, production_site_id: int, env_type: str, + config: Dict, user_id: int) -> Dict: + """ + Create a new environment linked to production. + + Args: + production_site_id: ID of the production WordPressSite + env_type: 'development' or 'staging' + config: Dict with: + - name: Environment name (e.g., 'My Site Dev') + - domain: Domain for the environment (e.g., 'dev.mysite.com') + - port: Optional custom port + - clone_db: Whether to clone the production database + - sync_schedule: Optional cron schedule for auto-sync + user_id: User ID creating the environment + + Returns: + Dict with success status and environment info + """ + # Validate environment type + if env_type not in ['development', 'staging']: + return {'success': False, 'error': 'Invalid environment type. Must be development or staging.'} + + # Get production site + 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: + return {'success': False, 'error': 'Source site is not a production site'} + + prod_app = prod_site.application + if not prod_app: + return {'success': False, 'error': 'Production application not found'} + + try: + # Generate names + env_name = config.get('name', f"{prod_app.name} ({env_type.title()})") + env_domain = config.get('domain') + + # Generate unique database name and prefix + short_id = secrets.token_hex(4) + env_db_name = f"{prod_site.db_name}_{env_type[:3]}_{short_id}" + env_db_prefix = f"wp_{env_type[:3]}_" + + # Determine root path for new environment + prod_path = prod_app.root_path + base_path = os.path.dirname(prod_path) + env_path = os.path.join(base_path, f"{os.path.basename(prod_path)}_{env_type}") + + # Step 1: Clone the database if requested + if config.get('clone_db', True): + # First create a snapshot + snapshot_result = DatabaseSyncService.create_snapshot( + db_name=prod_site.db_name, + name=f"pre_env_create_{env_type}", + tag=f"env-create-{env_type}", + host=prod_site.db_host, + user=prod_site.db_user, + password=cls._get_db_password(prod_site) + ) + + if not snapshot_result['success']: + return {'success': False, 'error': f"Failed to create snapshot: {snapshot_result.get('error')}"} + + # Clone with transformations + clone_options = { + 'table_prefix': env_db_prefix, + 'truncate_tables': config.get('truncate_tables', [ + 'actionscheduler_actions', + 'actionscheduler_logs', + ]) + } + + # Add search-replace for domain if provided + if env_domain and prod_app.domains: + prod_domain = prod_app.domains[0].domain if prod_app.domains else None + if prod_domain: + clone_options['search_replace'] = { + f'https://{prod_domain}': f'https://{env_domain}', + f'http://{prod_domain}': f'http://{env_domain}', + prod_domain: env_domain + } + + clone_result = DatabaseSyncService.clone_database( + source_db=prod_site.db_name, + target_db=env_db_name, + source_host=prod_site.db_host, + target_host=prod_site.db_host, + source_user=prod_site.db_user, + target_user=prod_site.db_user, + source_password=cls._get_db_password(prod_site), + target_password=cls._get_db_password(prod_site), + options=clone_options + ) + + if not clone_result['success']: + return {'success': False, 'error': f"Failed to clone database: {clone_result.get('error')}"} + + # Step 2: Create the Application record + env_app = Application( + name=env_name, + app_type='wordpress', + status='deploying', + php_version=prod_app.php_version, + port=config.get('port'), + root_path=env_path, + environment_type=env_type, + linked_app_id=prod_app.id, + user_id=user_id + ) + db.session.add(env_app) + db.session.flush() # Get the ID + + # Step 3: Create the 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_db_name, + db_user=prod_site.db_user, + db_host=prod_site.db_host, + db_prefix=env_db_prefix, + git_repo_url=prod_site.git_repo_url, + git_branch=config.get('git_branch', prod_site.git_branch), + git_paths=prod_site.git_paths, + auto_deploy=config.get('auto_deploy', False), + is_production=False, + production_site_id=production_site_id + ) + db.session.add(env_site) + + # Step 4: Copy WordPress files + copy_result = cls._copy_wordpress_files(prod_path, env_path) + if not copy_result['success']: + db.session.rollback() + return copy_result + + # Step 5: Update wp-config.php for new environment + config_result = cls._update_wp_config( + env_path, + db_name=env_db_name, + db_prefix=env_db_prefix, + site_url=f"https://{env_domain}" if env_domain else None + ) + + if not config_result['success']: + db.session.rollback() + return config_result + + # Step 6: Create sync job if schedule provided + if config.get('sync_schedule'): + sync_job = SyncJob( + source_site_id=production_site_id, + target_site_id=env_site.id, + name=f"Auto-sync {prod_app.name} to {env_name}", + schedule=config['sync_schedule'], + enabled=True, + config=json.dumps({ + 'search_replace': clone_options.get('search_replace', {}), + 'truncate_tables': clone_options.get('truncate_tables', []) + }) + ) + db.session.add(sync_job) + + # Update application status + env_app.status = 'running' + + db.session.commit() + + return { + 'success': True, + 'message': f'{env_type.title()} environment created successfully', + 'environment': env_site.to_dict(), + 'application': env_app.to_dict() + } + + except Exception as e: + db.session.rollback() + return {'success': False, 'error': str(e)} + + @classmethod + def sync_environment(cls, env_site_id: int, options: Dict = None) -> Dict: + """ + Sync an environment from its production source. + + Args: + env_site_id: ID of the environment WordPressSite to sync + options: Optional override options for 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: + return {'success': False, 'error': 'Cannot sync a production site'} + + prod_site = env_site.production_site + if not prod_site: + return {'success': False, 'error': 'Production site not found'} + + try: + # Get sync config + sync_config = json.loads(env_site.sync_config) if env_site.sync_config else {} + sync_config.update(options) + + # Create snapshot before sync + snapshot_result = DatabaseSyncService.create_snapshot( + db_name=env_site.db_name, + name=f"pre_sync_{datetime.now().strftime('%Y%m%d_%H%M%S')}", + tag='pre-sync', + host=env_site.db_host, + user=env_site.db_user, + password=cls._get_db_password(env_site) + ) + + # Clone production to environment + clone_options = { + 'table_prefix': env_site.db_prefix, + 'search_replace': sync_config.get('search_replace', {}), + 'truncate_tables': sync_config.get('truncate_tables', []), + 'anonymize': sync_config.get('anonymize', False) + } + + clone_result = DatabaseSyncService.clone_database( + source_db=prod_site.db_name, + target_db=env_site.db_name, + source_host=prod_site.db_host, + target_host=env_site.db_host, + source_user=prod_site.db_user, + target_user=env_site.db_user, + source_password=cls._get_db_password(prod_site), + target_password=cls._get_db_password(env_site), + options=clone_options + ) + + if not clone_result['success']: + return clone_result + + # Update sync timestamp + env_site.updated_at = datetime.utcnow() + db.session.commit() + + return { + 'success': True, + 'message': 'Environment synced successfully', + 'pre_sync_snapshot': snapshot_result.get('snapshot', {}).get('file_path') + } + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def get_environment_status(cls, production_site_id: int) -> Dict: + """ + Get status of all environments for a production site. + + Args: + production_site_id: ID of the production WordPressSite + + Returns: + Dict with production site and all environments + """ + prod_site = WordPressSite.query.get(production_site_id) + if not prod_site: + return {'success': False, 'error': 'Production site not found'} + + environments = [] + for env in prod_site.environments: + env_data = env.to_dict() + + # Get last sync info + last_sync_job = SyncJob.query.filter_by( + target_site_id=env.id + ).order_by(SyncJob.last_run.desc()).first() + + if last_sync_job: + env_data['last_sync'] = { + 'time': last_sync_job.last_run.isoformat() if last_sync_job.last_run else None, + 'status': last_sync_job.last_run_status, + 'next_scheduled': last_sync_job.next_run.isoformat() if last_sync_job.next_run else None + } + + environments.append(env_data) + + return { + 'success': True, + 'production': prod_site.to_dict(), + 'environments': environments + } + + @classmethod + def delete_environment(cls, env_site_id: int, delete_files: bool = True, + delete_database: bool = True) -> Dict: + """ + Delete an environment. + + Args: + env_site_id: ID of the environment WordPressSite + delete_files: Whether to delete WordPress files + delete_database: Whether to drop the database + + 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: + return {'success': False, 'error': 'Cannot delete a production site this way'} + + env_app = env_site.application + + try: + # Delete database + if delete_database and env_site.db_name: + DatabaseService.mysql_execute( + f"DROP DATABASE IF EXISTS `{env_site.db_name}`" + ) + + # Delete files + if delete_files and env_app and env_app.root_path: + if os.path.exists(env_app.root_path): + shutil.rmtree(env_app.root_path) + + # Delete related sync jobs + SyncJob.query.filter( + (SyncJob.source_site_id == env_site_id) | + (SyncJob.target_site_id == env_site_id) + ).delete() + + # Delete snapshots + for snapshot in env_site.snapshots: + if os.path.exists(snapshot.file_path): + os.remove(snapshot.file_path) + + # Delete records + db.session.delete(env_site) + if env_app: + db.session.delete(env_app) + + db.session.commit() + + return {'success': True, 'message': 'Environment deleted successfully'} + + except Exception as e: + db.session.rollback() + return {'success': False, 'error': str(e)} + + @classmethod + def _copy_wordpress_files(cls, source_path: str, target_path: str) -> Dict: + """Copy WordPress files from source to target.""" + try: + if os.path.exists(target_path): + shutil.rmtree(target_path) + + shutil.copytree(source_path, target_path) + + # Set permissions + import subprocess + subprocess.run(['sudo', 'chown', '-R', 'www-data:www-data', target_path], capture_output=True) + + return {'success': True} + + except Exception as e: + return {'success': False, 'error': f'Failed to copy files: {str(e)}'} + + @classmethod + def _update_wp_config(cls, wp_path: str, db_name: str = None, + db_prefix: str = None, site_url: str = None) -> Dict: + """Update wp-config.php for the new environment.""" + config_path = os.path.join(wp_path, 'wp-config.php') + + if not os.path.exists(config_path): + return {'success': False, 'error': 'wp-config.php not found'} + + try: + with open(config_path, 'r') as f: + content = f.read() + + # Update database name + if db_name: + content = cls._replace_define(content, 'DB_NAME', db_name) + + # Update table prefix + if db_prefix: + content = cls._replace_table_prefix(content, db_prefix) + + # Update site URL if provided + if site_url: + content = cls._replace_define(content, 'WP_HOME', site_url) + content = cls._replace_define(content, 'WP_SITEURL', site_url) + + # Add debug mode for non-production + if "define( 'WP_DEBUG'" not in content and "define('WP_DEBUG'" not in content: + content = content.replace( + "/* That's all", + "define('WP_DEBUG', true);\ndefine('WP_DEBUG_LOG', true);\n\n/* That's all" + ) + + with open(config_path, 'w') as f: + f.write(content) + + return {'success': True} + + except Exception as e: + return {'success': False, 'error': f'Failed to update wp-config.php: {str(e)}'} + + @staticmethod + def _replace_define(content: str, constant: str, value: str) -> str: + """Replace a define() statement in wp-config.php.""" + import re + # Match both styles: define('CONST', 'value') and define( 'CONST', 'value' ) + pattern = rf"define\s*\(\s*['\"]({constant})['\"]\s*,\s*['\"]([^'\"]*)['\"]" + replacement = f"define('{constant}', '{value}'" + return re.sub(pattern, replacement, content) + + @staticmethod + def _replace_table_prefix(content: str, prefix: str) -> str: + """Replace the table prefix in wp-config.php.""" + import re + pattern = r"\$table_prefix\s*=\s*['\"]([^'\"]*)['\"]" + replacement = f"$table_prefix = '{prefix}'" + return re.sub(pattern, replacement, content) + + @staticmethod + def _get_db_password(site: WordPressSite) -> Optional[str]: + """Get database password for a site 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: + with open(config_path, 'r') as f: + content = f.read() + + import re + match = re.search(r"define\s*\(\s*['\"]DB_PASSWORD['\"]\s*,\s*['\"]([^'\"]*)['\"]", content) + return match.group(1) if match else None + + except Exception: + return None + + @staticmethod + def _generate_password(length: int = 16) -> str: + """Generate a secure random password.""" + alphabet = string.ascii_letters + string.digits + '!@#$%^&*' + return ''.join(secrets.choice(alphabet) for _ in range(length)) diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index b62f2c23..b762641b 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -29,6 +29,8 @@ import WorkflowBuilder from './pages/WorkflowBuilder'; import Servers from './pages/Servers'; import ServerDetail from './pages/ServerDetail'; import Downloads from './pages/Downloads'; +import WordPress from './pages/WordPress'; +import WordPressDetail from './pages/WordPressDetail'; // Page title mapping const PAGE_TITLES = { @@ -37,6 +39,7 @@ const PAGE_TITLES = { '/register': 'Register', '/setup': 'Setup', '/apps': 'Applications', + '/wordpress': 'WordPress Sites', '/templates': 'Templates', '/workflow': 'Workflow Builder', '/domains': 'Domains', @@ -67,6 +70,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/')) title = 'WordPress Site'; else title = 'ServerKit'; } @@ -151,6 +155,8 @@ function AppRoutes() { } /> } /> } /> + } /> + } /> } /> } /> } /> diff --git a/frontend/src/components/ConfirmDialog.jsx b/frontend/src/components/ConfirmDialog.jsx index 1fcb123c..3e2e4b59 100644 --- a/frontend/src/components/ConfirmDialog.jsx +++ b/frontend/src/components/ConfirmDialog.jsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useState, useEffect } from 'react'; import { AlertTriangle, Info, AlertCircle } from 'lucide-react'; const iconMap = { @@ -11,15 +11,40 @@ export function ConfirmDialog({ isOpen, title, message, + details, confirmText = 'Confirm', cancelText = 'Cancel', variant = 'danger', + requireConfirmation, + confirmationPlaceholder, onConfirm, onCancel }) { + const [inputValue, setInputValue] = useState(''); + + // Reset input when dialog opens/closes + useEffect(() => { + if (isOpen) { + setInputValue(''); + } + }, [isOpen]); + if (!isOpen) return null; const Icon = iconMap[variant] || AlertTriangle; + const isConfirmDisabled = requireConfirmation && inputValue !== requireConfirmation; + + function handleConfirm() { + if (!isConfirmDisabled) { + onConfirm(); + } + } + + function handleKeyDown(e) { + if (e.key === 'Enter' && !isConfirmDisabled) { + handleConfirm(); + } + } return (
@@ -30,6 +55,26 @@ export function ConfirmDialog({

{title}

{message}

+ {details && ( +
+ {details} +
+ )} + {requireConfirmation && ( +
+ + setInputValue(e.target.value)} + onKeyDown={handleKeyDown} + placeholder={confirmationPlaceholder || requireConfirmation} + autoFocus + /> +
+ )}
diff --git a/frontend/src/components/ErrorBoundary.jsx b/frontend/src/components/ErrorBoundary.jsx new file mode 100644 index 00000000..35773ee0 --- /dev/null +++ b/frontend/src/components/ErrorBoundary.jsx @@ -0,0 +1,89 @@ +import React, { Component } from 'react'; +import { AlertTriangle, RefreshCw } from 'lucide-react'; + +// Class-based Error Boundary for catching React errors +export class ErrorBoundary extends Component { + constructor(props) { + super(props); + this.state = { hasError: false, error: null, errorInfo: null }; + } + + static getDerivedStateFromError(error) { + return { hasError: true, error }; + } + + componentDidCatch(error, errorInfo) { + this.setState({ errorInfo }); + console.error('ErrorBoundary caught an error:', error, errorInfo); + } + + handleRetry = () => { + this.setState({ hasError: false, error: null, errorInfo: null }); + this.props.onRetry?.(); + }; + + render() { + if (this.state.hasError) { + return ( +
+
+ +
+

Something went wrong

+

+ {this.state.error?.message || 'An unexpected error occurred'} +

+ +
+ ); + } + + return this.props.children; + } +} + +// Functional component for displaying API/fetch errors +export function ErrorState({ + title = 'Failed to load', + message, + error, + onRetry, + compact = false +}) { + const errorMessage = message || error?.message || 'An error occurred while loading data'; + + if (compact) { + return ( +
+ + {errorMessage} + {onRetry && ( + + )} +
+ ); + } + + return ( +
+
+ +
+

{title}

+

{errorMessage}

+ {onRetry && ( + + )} +
+ ); +} + +export default ErrorBoundary; diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx index 5afbe9d7..a4fd9d27 100644 --- a/frontend/src/components/Sidebar.jsx +++ b/frontend/src/components/Sidebar.jsx @@ -58,6 +58,14 @@ const Sidebar = () => { Applications + `nav-item ${isActive ? 'active' : ''}`}> + + + + + + WordPress + `nav-item ${isActive ? 'active' : ''}`}> diff --git a/frontend/src/components/wordpress/CommitList.jsx b/frontend/src/components/wordpress/CommitList.jsx new file mode 100644 index 00000000..ad8c47ba --- /dev/null +++ b/frontend/src/components/wordpress/CommitList.jsx @@ -0,0 +1,197 @@ +import React, { useState } from 'react'; +import { GitCommit, Rocket, Copy, CheckCircle } from 'lucide-react'; + +const CommitList = ({ commits, currentCommit, onDeploy, onCreateDev, loading = false }) => { + const [actionLoading, setActionLoading] = useState({}); + const [showDevModal, setShowDevModal] = useState(null); + + function formatDate(dateString) { + if (!dateString) return '-'; + const date = new Date(dateString); + const now = new Date(); + const diffMs = now - date; + const diffHours = Math.floor(diffMs / (1000 * 60 * 60)); + const diffDays = Math.floor(diffHours / 24); + + if (diffHours < 1) return 'Just now'; + if (diffHours < 24) return `${diffHours}h ago`; + if (diffDays < 7) return `${diffDays}d ago`; + return date.toLocaleDateString(); + } + + async function handleDeploy(commit) { + if (!confirm(`Deploy commit ${commit.sha.substring(0, 7)} to production?`)) { + return; + } + setActionLoading(prev => ({ ...prev, [`deploy-${commit.sha}`]: true })); + try { + await onDeploy?.({ commit_sha: commit.sha }); + } finally { + setActionLoading(prev => ({ ...prev, [`deploy-${commit.sha}`]: false })); + } + } + + async function handleCreateDev(commit, config) { + setActionLoading(prev => ({ ...prev, [`dev-${commit.sha}`]: true })); + try { + await onCreateDev?.({ + commit_sha: commit.sha, + config + }); + setShowDevModal(null); + } finally { + setActionLoading(prev => ({ ...prev, [`dev-${commit.sha}`]: false })); + } + } + + if (loading) { + return
Loading commits...
; + } + + if (!commits || commits.length === 0) { + return ( +
+

No commits found.

+

Push changes to your repository to see commits here.

+
+ ); + } + + return ( +
+ {commits.map(commit => { + const isCurrent = currentCommit === commit.sha; + const isDeploying = actionLoading[`deploy-${commit.sha}`]; + const isCreatingDev = actionLoading[`dev-${commit.sha}`]; + + return ( +
+
+ {isCurrent ? ( + + ) : ( + + )} +
+ +
+
+ {commit.sha.substring(0, 7)} + {isCurrent && Deployed} + {formatDate(commit.date)} +
+

{commit.message}

+ {commit.author && ( + {commit.author} + )} +
+ +
+ {!isCurrent && ( + + )} + +
+
+ ); + })} + + {showDevModal && ( + setShowDevModal(null)} + onCreate={(config) => handleCreateDev(showDevModal, config)} + loading={actionLoading[`dev-${showDevModal.sha}`]} + /> + )} +
+ ); +}; + +const CreateDevModal = ({ commit, onClose, onCreate, loading }) => { + const [formData, setFormData] = useState({ + name: `dev-${commit.sha.substring(0, 7)}`, + domain: '' + }); + + function handleChange(e) { + const { name, value } = e.target; + setFormData(prev => ({ ...prev, [name]: value })); + } + + function handleSubmit(e) { + e.preventDefault(); + onCreate(formData); + } + + return ( +
+
e.stopPropagation()}> +
+

Create Dev Environment

+ +
+ +
+

+ Create a development environment with code from commit{' '} + {commit.sha.substring(0, 7)} +

+

"{commit.message}"

+ +
+
+ + +
+ +
+ + + Leave empty to auto-generate +
+ +
+ + +
+
+
+
+
+ ); +}; + +export default CommitList; diff --git a/frontend/src/components/wordpress/CreateSiteModal.jsx b/frontend/src/components/wordpress/CreateSiteModal.jsx new file mode 100644 index 00000000..b645d255 --- /dev/null +++ b/frontend/src/components/wordpress/CreateSiteModal.jsx @@ -0,0 +1,159 @@ +import React, { useState } from 'react'; +import { X } from 'lucide-react'; + +const CreateSiteModal = ({ onClose, onCreate }) => { + const [formData, setFormData] = useState({ + name: '', + domain: '', + adminUser: 'admin', + adminEmail: '', + dbName: '', + createDatabase: true + }); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(''); + + function handleChange(e) { + const { name, value, type, checked } = e.target; + setFormData(prev => ({ + ...prev, + [name]: type === 'checkbox' ? checked : value + })); + } + + function generateDbName(siteName) { + return `wp_${siteName.toLowerCase().replace(/[^a-z0-9]/g, '_').substring(0, 20)}`; + } + + function handleNameChange(e) { + const name = e.target.value; + setFormData(prev => ({ + ...prev, + name, + dbName: prev.dbName || generateDbName(name) + })); + } + + async function handleSubmit(e) { + e.preventDefault(); + setError(''); + setLoading(true); + + try { + await onCreate({ + name: formData.name, + domain: formData.domain, + admin_user: formData.adminUser, + admin_email: formData.adminEmail, + db_name: formData.dbName, + create_database: formData.createDatabase + }); + onClose(); + } catch (err) { + setError(err.message || 'Failed to create WordPress site'); + } finally { + setLoading(false); + } + } + + return ( +
+
e.stopPropagation()}> +
+

Create WordPress Site

+ +
+ + {error &&
{error}
} + +
+
+ + +
+ +
+ + + Leave empty to use a local development URL +
+ +
+
+ + +
+ +
+ + +
+
+ +
+ + +
+ +
+ +
+ +
+ + +
+
+
+
+ ); +}; + +export default CreateSiteModal; diff --git a/frontend/src/components/wordpress/EnvironmentCard.jsx b/frontend/src/components/wordpress/EnvironmentCard.jsx new file mode 100644 index 00000000..08d0d582 --- /dev/null +++ b/frontend/src/components/wordpress/EnvironmentCard.jsx @@ -0,0 +1,239 @@ +import React, { useState } from 'react'; +import { ExternalLink, RefreshCw, Trash2, GitBranch, Clock, AlertTriangle, Calendar, FileText } from 'lucide-react'; +import { ConfirmDialog } from '../ConfirmDialog'; + +const EnvironmentCard = ({ environment, productionUrl, onSync, onDelete, onViewLogs, isProduction = false }) => { + const [syncing, setSyncing] = useState(false); + const [deleting, setDeleting] = useState(false); + const [showSyncConfirm, setShowSyncConfirm] = useState(false); + const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); + + const isRunning = environment.status === 'running'; + const envType = environment.type || (isProduction ? 'production' : 'development'); + + // Helper functions + function formatDate(dateString) { + if (!dateString) return null; + return new Date(dateString).toLocaleDateString(); + } + + 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 / (1000 * 60 * 60 * 24)); + + if (diffDays === 0) return 'Today'; + if (diffDays === 1) return 'Yesterday'; + if (diffDays < 7) return `${diffDays} days ago`; + if (diffDays < 30) return `${Math.floor(diffDays / 7)} week(s) ago`; + return `${Math.floor(diffDays / 30)} month(s) ago`; + } + + function isStale() { + if (!environment.last_sync || isProduction) return false; + const lastSync = new Date(environment.last_sync); + const now = new Date(); + const diffDays = Math.floor((now - lastSync) / (1000 * 60 * 60 * 24)); + return diffDays > 7; // Consider stale if not synced in 7 days + } + + function formatSchedule(schedule) { + if (!schedule) return null; + const scheduleMap = { + '0 3 * * 0': 'Weekly (Sunday 3am)', + '0 3 * * *': 'Daily (3am)', + '0 0 * * 0': 'Weekly (Sunday midnight)', + '0 0 * * *': 'Daily (midnight)' + }; + return scheduleMap[schedule] || schedule; + } + + const stale = isStale(); + + async function handleSync() { + setShowSyncConfirm(false); + setSyncing(true); + try { + await onSync?.(environment.id); + } finally { + setSyncing(false); + } + } + + async function handleDelete() { + setShowDeleteConfirm(false); + setDeleting(true); + try { + await onDelete?.(environment.id); + } finally { + setDeleting(false); + } + } + + function handleVisit() { + if (environment.url) { + window.open(environment.url, '_blank'); + } + } + + function getEnvBadgeClass() { + switch (envType) { + case 'production': return 'env-production'; + case 'staging': return 'env-staging'; + default: return 'env-development'; + } + } + + return ( +
+
+
+ + {envType.toUpperCase()} + +

{environment.name}

+
+
+ {stale && ( + + + Stale + + )} + + + {isRunning ? 'Running' : 'Stopped'} + +
+
+ +
+ {environment.url && ( + + )} + +
+ {environment.db_name && ( +
+ Database + {environment.db_name} +
+ )} + {environment.commit_sha && ( +
+ + Commit + + {environment.commit_sha.substring(0, 7)} +
+ )} + {!isProduction && environment.last_sync && ( +
+ + Last Sync + + + {formatRelativeTime(environment.last_sync)} + +
+ )} + {!isProduction && environment.sync_schedule && ( +
+ + Schedule + + + {formatSchedule(environment.sync_schedule)} + +
+ )} +
+
+ +
+ + + {!isProduction && ( + <> + + {onViewLogs && ( + + )} + + + )} +
+ + +
  • Warning: This will overwrite the current database
  • +
  • All data in this environment will be replaced with production data
  • +
  • URLs will be automatically updated for this environment
  • + + } + confirmText="Sync Now" + variant="warning" + onConfirm={handleSync} + onCancel={() => setShowSyncConfirm(false)} + /> + + +
  • All environment files will be permanently deleted
  • +
  • Database {environment.db_name || 'associated database'} will be removed
  • +
  • This action cannot be undone
  • + + } + confirmText="Delete Environment" + variant="danger" + onConfirm={handleDelete} + onCancel={() => setShowDeleteConfirm(false)} + /> +
    + ); +}; + +export default EnvironmentCard; diff --git a/frontend/src/components/wordpress/GitConnectForm.jsx b/frontend/src/components/wordpress/GitConnectForm.jsx new file mode 100644 index 00000000..109fd8ec --- /dev/null +++ b/frontend/src/components/wordpress/GitConnectForm.jsx @@ -0,0 +1,188 @@ +import React, { useState } from 'react'; +import { GitBranch, Link, Unlink } from 'lucide-react'; + +const GitConnectForm = ({ gitStatus, onConnect, onDisconnect }) => { + const [formData, setFormData] = useState({ + repoUrl: '', + branch: 'main', + paths: ['wp-content/themes', 'wp-content/plugins'], + autoDeploy: false + }); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(''); + + const isConnected = gitStatus?.connected; + + function handleChange(e) { + const { name, value, type, checked } = e.target; + setFormData(prev => ({ + ...prev, + [name]: type === 'checkbox' ? checked : value + })); + } + + function handlePathsChange(e) { + const paths = e.target.value.split('\n').filter(p => p.trim()); + setFormData(prev => ({ ...prev, paths })); + } + + async function handleConnect(e) { + e.preventDefault(); + setError(''); + setLoading(true); + + try { + await onConnect({ + repo_url: formData.repoUrl, + branch: formData.branch, + paths: formData.paths, + auto_deploy: formData.autoDeploy + }); + } catch (err) { + setError(err.message || 'Failed to connect repository'); + } finally { + setLoading(false); + } + } + + async function handleDisconnect() { + if (!confirm('Disconnect Git repository? This will not delete any files.')) { + return; + } + setLoading(true); + try { + await onDisconnect(); + } catch (err) { + setError(err.message || 'Failed to disconnect repository'); + } finally { + setLoading(false); + } + } + + if (isConnected) { + return ( +
    +
    + +
    +

    Repository Connected

    + + {gitStatus.repo_url} + +
    +
    + +
    +
    + Branch + {gitStatus.branch} +
    +
    + Auto Deploy + {gitStatus.auto_deploy ? 'Enabled' : 'Disabled'} +
    + {gitStatus.last_deploy_commit && ( +
    + Last Deploy + {gitStatus.last_deploy_commit.substring(0, 7)} +
    + )} + {gitStatus.last_deploy_at && ( +
    + Deployed At + + {new Date(gitStatus.last_deploy_at).toLocaleString()} + +
    + )} +
    + +
    + +
    +
    + ); + } + + return ( +
    +

    Connect Git Repository

    +

    + Connect a Git repository to manage themes and plugins via version control. +

    + + {error &&
    {error}
    } + +
    +
    + + +
    + +
    + + +
    + +
    + +