Skip to content

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

Add build and deployment API with models and services

Juan Denisf696faedccb2
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 0a8c8586..b69a6a7d 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -109,6 +109,10 @@ def create_app(config_name=None):
from app.api.deploy import deploy_bp
app.register_blueprint(deploy_bp, url_prefix='/api/v1/deploy')
+ # Register blueprints - Builds & Deployments
+ from app.api.builds import builds_bp
+ app.register_blueprint(builds_bp, url_prefix='/api/v1/builds')
+
# Register blueprints - File Manager
from app.api.files import files_bp
app.register_blueprint(files_bp, url_prefix='/api/v1/files')
diff --git a/backend/app/api/builds.py b/backend/app/api/builds.py
new file mode 100644
index 00000000..934d1bb3
--- /dev/null
+++ b/backend/app/api/builds.py
@@ -0,0 +1,349 @@
+"""
+Build and Deployment API Endpoints
+
+Provides REST endpoints for:
+- Build configuration
+- Build triggering and monitoring
+- Deployment management
+- Rollback functionality
+"""
+
+from flask import Blueprint, request, jsonify
+from flask_jwt_extended import jwt_required, get_jwt_identity
+from app.models import User, Application, Deployment
+from app.services.build_service import BuildService
+from app.services.deployment_service import DeploymentService
+
+builds_bp = Blueprint('builds', __name__)
+
+
+def admin_required(fn):
+ """Decorator to require admin role."""
+ from functools import wraps
+
+ @wraps(fn)
+ def wrapper(*args, **kwargs):
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ if not user or user.role != 'admin':
+ return jsonify({'error': 'Admin access required'}), 403
+ return fn(*args, **kwargs)
+ return wrapper
+
+
+# ==================== BUILD CONFIGURATION ====================
+
+@builds_bp.route('/apps/<int:app_id>/build-config', methods=['GET'])
+@jwt_required()
+def get_build_config(app_id):
+ """Get build configuration for an app."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ config = BuildService.get_app_build_config(app_id)
+ if not config:
+ return jsonify({'configured': False}), 200
+
+ return jsonify({'configured': True, 'config': config}), 200
+
+
+@builds_bp.route('/apps/<int:app_id>/build-config', methods=['POST'])
+@jwt_required()
+@admin_required
+def configure_build(app_id):
+ """Configure build settings for an app."""
+ app = Application.query.get(app_id)
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ data = request.get_json()
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ result = BuildService.configure_build(
+ app_id=app_id,
+ app_path=app.root_path or app.path,
+ build_method=data.get('build_method', 'auto'),
+ dockerfile_path=data.get('dockerfile_path'),
+ custom_build_cmd=data.get('custom_build_cmd'),
+ custom_start_cmd=data.get('custom_start_cmd'),
+ build_args=data.get('build_args'),
+ env_vars=data.get('env_vars'),
+ cache_enabled=data.get('cache_enabled', True),
+ timeout=data.get('timeout'),
+ keep_deployments=data.get('keep_deployments', 5)
+ )
+
+ return jsonify(result), 201 if result.get('success') else 400
+
+
+@builds_bp.route('/apps/<int:app_id>/build-config', methods=['DELETE'])
+@jwt_required()
+@admin_required
+def remove_build_config(app_id):
+ """Remove build configuration for an app."""
+ config = BuildService.get_config()
+ if str(app_id) in config.get('apps', {}):
+ del config['apps'][str(app_id)]
+ BuildService.save_config(config)
+ return jsonify({'success': True}), 200
+ return jsonify({'success': False, 'error': 'Build not configured'}), 404
+
+
+# ==================== BUILD DETECTION ====================
+
+@builds_bp.route('/apps/<int:app_id>/detect', methods=['GET'])
+@jwt_required()
+def detect_build_method(app_id):
+ """Auto-detect build method for an app."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ detection = BuildService.detect_build_method(app.root_path or app.path)
+ return jsonify(detection), 200
+
+
+@builds_bp.route('/apps/<int:app_id>/nixpacks-plan', methods=['GET'])
+@jwt_required()
+def get_nixpacks_plan(app_id):
+ """Get Nixpacks build plan for an app."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ result = BuildService.get_nixpacks_plan(app.root_path or app.path)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+# ==================== BUILD EXECUTION ====================
+
+@builds_bp.route('/apps/<int:app_id>/build', methods=['POST'])
+@jwt_required()
+def trigger_build(app_id):
+ """Trigger a build for an app."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ data = request.get_json() or {}
+ no_cache = data.get('no_cache', False)
+
+ result = BuildService.build(app_id, no_cache=no_cache)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@builds_bp.route('/apps/<int:app_id>/build-logs', methods=['GET'])
+@jwt_required()
+def get_build_logs(app_id):
+ """Get build log history for an app."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ limit = request.args.get('limit', 20, type=int)
+ logs = BuildService.get_build_logs(app_id, limit)
+ return jsonify({'logs': logs}), 200
+
+
+@builds_bp.route('/apps/<int:app_id>/build-logs/<timestamp>', methods=['GET'])
+@jwt_required()
+def get_build_log_detail(app_id, timestamp):
+ """Get detailed build log including output."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ log = BuildService.get_build_log_detail(app_id, timestamp)
+ if log:
+ return jsonify(log), 200
+ return jsonify({'error': 'Build log not found'}), 404
+
+
+@builds_bp.route('/apps/<int:app_id>/clear-cache', methods=['POST'])
+@jwt_required()
+@admin_required
+def clear_build_cache(app_id):
+ """Clear build cache for an app."""
+ result = BuildService.clear_build_cache(app_id)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+# ==================== DEPLOYMENTS ====================
+
+@builds_bp.route('/apps/<int:app_id>/deploy', methods=['POST'])
+@jwt_required()
+def deploy_app(app_id):
+ """Deploy an application (build + deploy)."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ data = request.get_json() or {}
+
+ result = DeploymentService.deploy(
+ app_id=app_id,
+ user_id=current_user_id,
+ no_cache=data.get('no_cache', False),
+ trigger='manual',
+ version_tag=data.get('version_tag')
+ )
+
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@builds_bp.route('/apps/<int:app_id>/deployments', methods=['GET'])
+@jwt_required()
+def get_deployments(app_id):
+ """Get deployment history for an app."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ limit = request.args.get('limit', 20, type=int)
+ offset = request.args.get('offset', 0, type=int)
+
+ deployments = DeploymentService.get_deployments(app_id, limit, offset)
+ current = DeploymentService.get_current_deployment(app_id)
+
+ return jsonify({
+ 'deployments': deployments,
+ 'current': current
+ }), 200
+
+
+@builds_bp.route('/deployments/<int:deployment_id>', methods=['GET'])
+@jwt_required()
+def get_deployment(deployment_id):
+ """Get a specific deployment."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+
+ deployment = Deployment.query.get(deployment_id)
+ if not deployment:
+ return jsonify({'error': 'Deployment not found'}), 404
+
+ app = Application.query.get(deployment.app_id)
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ include_logs = request.args.get('include_logs', 'false').lower() == 'true'
+ return jsonify(deployment.to_dict(include_logs=include_logs)), 200
+
+
+@builds_bp.route('/deployments/<int:deployment_id>/diff', methods=['GET'])
+@jwt_required()
+def get_deployment_diff(deployment_id):
+ """Get diff for a deployment."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+
+ deployment = Deployment.query.get(deployment_id)
+ if not deployment:
+ return jsonify({'error': 'Deployment not found'}), 404
+
+ app = Application.query.get(deployment.app_id)
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ diff = DeploymentService.get_deployment_diff(deployment_id)
+ if diff:
+ return jsonify(diff), 200
+ return jsonify({'error': 'No diff available'}), 404
+
+
+# ==================== ROLLBACK ====================
+
+@builds_bp.route('/apps/<int:app_id>/rollback', methods=['POST'])
+@jwt_required()
+def rollback(app_id):
+ """Rollback to a previous deployment."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ data = request.get_json() or {}
+ target_version = data.get('version') # Optional - if not provided, rolls back to previous
+
+ result = DeploymentService.rollback(
+ app_id=app_id,
+ target_version=target_version,
+ user_id=current_user_id
+ )
+
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@builds_bp.route('/apps/<int:app_id>/current-deployment', methods=['GET'])
+@jwt_required()
+def get_current_deployment(app_id):
+ """Get the currently live deployment."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ deployment = DeploymentService.get_current_deployment(app_id)
+ if deployment:
+ return jsonify(deployment), 200
+ return jsonify({'error': 'No live deployment'}), 404
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index ca62af82..8095630d 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -3,5 +3,6 @@ from app.models.application import Application
from app.models.domain import Domain
from app.models.env_variable import EnvironmentVariable, EnvironmentVariableHistory
from app.models.notification_preferences import NotificationPreferences
+from app.models.deployment import Deployment, DeploymentDiff
-__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory', 'NotificationPreferences']
+__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory', 'NotificationPreferences', 'Deployment', 'DeploymentDiff']
diff --git a/backend/app/models/deployment.py b/backend/app/models/deployment.py
new file mode 100644
index 00000000..ebdb5909
--- /dev/null
+++ b/backend/app/models/deployment.py
@@ -0,0 +1,208 @@
+"""
+Deployment Model - Tracks versioned deployments for applications.
+
+Supports:
+- Deployment history with versions
+- Rollback to previous versions
+- Deployment status tracking
+- Build artifacts (image tags, commit hashes)
+"""
+
+from datetime import datetime
+from app import db
+import json
+
+
+class Deployment(db.Model):
+ """Represents a single deployment of an application."""
+ __tablename__ = 'deployments'
+
+ id = db.Column(db.Integer, primary_key=True)
+ app_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=False)
+
+ # Version info
+ version = db.Column(db.Integer, nullable=False) # Sequential version number per app
+ version_tag = db.Column(db.String(100), nullable=True) # Optional semantic version
+
+ # Status: pending, building, deploying, live, failed, rolled_back
+ status = db.Column(db.String(20), default='pending')
+
+ # Build info
+ build_method = db.Column(db.String(20), nullable=True) # dockerfile, nixpacks, custom
+ image_tag = db.Column(db.String(255), nullable=True) # Docker image tag
+ commit_hash = db.Column(db.String(40), nullable=True) # Git commit if applicable
+ commit_message = db.Column(db.Text, nullable=True)
+
+ # Container info (for running deployment)
+ container_id = db.Column(db.String(100), nullable=True)
+
+ # Deployment details
+ deployed_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
+ deploy_trigger = db.Column(db.String(20), default='manual') # manual, webhook, rollback
+
+ # Build/deploy output
+ build_log_path = db.Column(db.String(500), nullable=True)
+
+ # Timing
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ build_started_at = db.Column(db.DateTime, nullable=True)
+ build_completed_at = db.Column(db.DateTime, nullable=True)
+ deploy_started_at = db.Column(db.DateTime, nullable=True)
+ deploy_completed_at = db.Column(db.DateTime, nullable=True)
+
+ # Error info
+ error_message = db.Column(db.Text, nullable=True)
+
+ # Metadata (JSON for flexibility)
+ metadata = db.Column(db.Text, default='{}')
+
+ # Relationships
+ app = db.relationship('Application', backref=db.backref('deployments', lazy='dynamic', order_by='Deployment.version.desc()'))
+ deployer = db.relationship('User', backref='deployments')
+
+ def get_metadata(self):
+ """Get metadata as dict."""
+ try:
+ return json.loads(self.metadata) if self.metadata else {}
+ except (json.JSONDecodeError, TypeError):
+ return {}
+
+ def set_metadata(self, data):
+ """Set metadata from dict."""
+ self.metadata = json.dumps(data)
+
+ def update_metadata(self, key, value):
+ """Update a single metadata field."""
+ meta = self.get_metadata()
+ meta[key] = value
+ self.metadata = json.dumps(meta)
+
+ @property
+ def duration(self):
+ """Calculate total deployment duration in seconds."""
+ if self.deploy_completed_at and self.build_started_at:
+ return (self.deploy_completed_at - self.build_started_at).total_seconds()
+ return None
+
+ @property
+ def build_duration(self):
+ """Calculate build duration in seconds."""
+ if self.build_completed_at and self.build_started_at:
+ return (self.build_completed_at - self.build_started_at).total_seconds()
+ return None
+
+ def to_dict(self, include_logs=False):
+ """Convert to dictionary for API response."""
+ result = {
+ 'id': self.id,
+ 'app_id': self.app_id,
+ 'version': self.version,
+ 'version_tag': self.version_tag,
+ 'status': self.status,
+ 'build_method': self.build_method,
+ 'image_tag': self.image_tag,
+ 'commit_hash': self.commit_hash,
+ 'commit_message': self.commit_message,
+ 'container_id': self.container_id,
+ 'deployed_by': self.deployed_by,
+ 'deploy_trigger': self.deploy_trigger,
+ 'error_message': self.error_message,
+ 'metadata': self.get_metadata(),
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'build_started_at': self.build_started_at.isoformat() if self.build_started_at else None,
+ 'build_completed_at': self.build_completed_at.isoformat() if self.build_completed_at else None,
+ 'deploy_started_at': self.deploy_started_at.isoformat() if self.deploy_started_at else None,
+ 'deploy_completed_at': self.deploy_completed_at.isoformat() if self.deploy_completed_at else None,
+ 'duration': self.duration,
+ 'build_duration': self.build_duration
+ }
+
+ if include_logs and self.build_log_path:
+ try:
+ import os
+ if os.path.exists(self.build_log_path):
+ with open(self.build_log_path, 'r') as f:
+ log_data = json.load(f)
+ result['build_logs'] = log_data.get('logs', [])
+ except Exception:
+ pass
+
+ return result
+
+ @classmethod
+ def get_next_version(cls, app_id):
+ """Get next version number for an app."""
+ latest = cls.query.filter_by(app_id=app_id).order_by(cls.version.desc()).first()
+ return (latest.version + 1) if latest else 1
+
+ @classmethod
+ def get_current(cls, app_id):
+ """Get currently live deployment for an app."""
+ return cls.query.filter_by(app_id=app_id, status='live').order_by(cls.version.desc()).first()
+
+ @classmethod
+ def get_previous(cls, app_id, before_version):
+ """Get previous successful deployment before a version."""
+ return cls.query.filter(
+ cls.app_id == app_id,
+ cls.version < before_version,
+ cls.status == 'live'
+ ).order_by(cls.version.desc()).first()
+
+ @classmethod
+ def cleanup_old_deployments(cls, app_id, keep_count=5):
+ """Delete old deployments, keeping the last N."""
+ # Get all deployments except the latest N
+ deployments = cls.query.filter_by(app_id=app_id).order_by(
+ cls.version.desc()
+ ).offset(keep_count).all()
+
+ deleted = 0
+ for deployment in deployments:
+ # Don't delete currently live deployments
+ if deployment.status != 'live':
+ db.session.delete(deployment)
+ deleted += 1
+
+ if deleted > 0:
+ db.session.commit()
+
+ return deleted
+
+ def __repr__(self):
+ return f'<Deployment app={self.app_id} v{self.version} status={self.status}>'
+
+
+class DeploymentDiff(db.Model):
+ """Stores diff information between deployments."""
+ __tablename__ = 'deployment_diffs'
+
+ id = db.Column(db.Integer, primary_key=True)
+ deployment_id = db.Column(db.Integer, db.ForeignKey('deployments.id'), nullable=False)
+ previous_deployment_id = db.Column(db.Integer, db.ForeignKey('deployments.id'), nullable=True)
+
+ # Diff content (JSON)
+ files_added = db.Column(db.Text, default='[]')
+ files_removed = db.Column(db.Text, default='[]')
+ files_modified = db.Column(db.Text, default='[]')
+
+ # Summary
+ additions = db.Column(db.Integer, default=0)
+ deletions = db.Column(db.Integer, default=0)
+
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ deployment = db.relationship('Deployment', foreign_keys=[deployment_id], backref='diff')
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'deployment_id': self.deployment_id,
+ 'previous_deployment_id': self.previous_deployment_id,
+ 'files_added': json.loads(self.files_added) if self.files_added else [],
+ 'files_removed': json.loads(self.files_removed) if self.files_removed else [],
+ 'files_modified': json.loads(self.files_modified) if self.files_modified else [],
+ 'additions': self.additions,
+ 'deletions': self.deletions,
+ 'created_at': self.created_at.isoformat() if self.created_at else None
+ }
diff --git a/backend/app/services/build_service.py b/backend/app/services/build_service.py
new file mode 100644
index 00000000..13c5c1b7
--- /dev/null
+++ b/backend/app/services/build_service.py
@@ -0,0 +1,700 @@
+"""
+Build Service - Handles application building with multiple strategies.
+
+Supports:
+- Dockerfile detection and building
+- Nixpacks (Heroku-style auto-detection)
+- Custom build commands
+- Build log streaming
+- Build caching
+- Build timeout handling
+"""
+
+import os
+import subprocess
+import json
+import shutil
+import hashlib
+import threading
+import queue
+from datetime import datetime
+from typing import Dict, List, Optional, Callable, Generator
+from pathlib import Path
+
+
+class BuildService:
+ """Service for building applications from source code."""
+
+ CONFIG_DIR = '/etc/serverkit'
+ BUILD_CONFIG = os.path.join(CONFIG_DIR, 'builds.json')
+ BUILD_LOG_DIR = '/var/log/serverkit/builds'
+ BUILD_CACHE_DIR = '/var/cache/serverkit/builds'
+
+ # Default build timeout (10 minutes)
+ DEFAULT_TIMEOUT = 600
+
+ # Nixpacks language detection patterns
+ LANGUAGE_PATTERNS = {
+ 'node': ['package.json'],
+ 'python': ['requirements.txt', 'Pipfile', 'pyproject.toml', 'setup.py'],
+ 'ruby': ['Gemfile'],
+ 'go': ['go.mod', 'go.sum'],
+ 'rust': ['Cargo.toml'],
+ 'php': ['composer.json'],
+ 'java': ['pom.xml', 'build.gradle', 'build.gradle.kts'],
+ 'dotnet': ['*.csproj', '*.fsproj', '*.sln'],
+ 'elixir': ['mix.exs'],
+ 'static': ['index.html'],
+ }
+
+ # Framework detection for better build configs
+ FRAMEWORK_PATTERNS = {
+ 'nextjs': ['next.config.js', 'next.config.mjs', 'next.config.ts'],
+ 'nuxt': ['nuxt.config.js', 'nuxt.config.ts'],
+ 'remix': ['remix.config.js'],
+ 'astro': ['astro.config.mjs'],
+ 'sveltekit': ['svelte.config.js'],
+ 'vite': ['vite.config.js', 'vite.config.ts'],
+ 'django': ['manage.py', 'wsgi.py'],
+ 'flask': ['app.py', 'wsgi.py'],
+ 'fastapi': ['main.py'],
+ 'rails': ['config.ru', 'Rakefile'],
+ 'laravel': ['artisan'],
+ 'express': ['app.js', 'server.js', 'index.js'],
+ }
+
+ @classmethod
+ def get_config(cls) -> Dict:
+ """Get build configuration."""
+ if os.path.exists(cls.BUILD_CONFIG):
+ try:
+ with open(cls.BUILD_CONFIG, 'r') as f:
+ return json.load(f)
+ except Exception:
+ pass
+ return {'apps': {}}
+
+ @classmethod
+ def save_config(cls, config: Dict) -> Dict:
+ """Save build configuration."""
+ try:
+ os.makedirs(cls.CONFIG_DIR, exist_ok=True)
+ with open(cls.BUILD_CONFIG, 'w') as f:
+ json.dump(config, f, indent=2)
+ return {'success': True}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_app_build_config(cls, app_id: int) -> Optional[Dict]:
+ """Get build config for an app."""
+ config = cls.get_config()
+ return config.get('apps', {}).get(str(app_id))
+
+ @classmethod
+ def configure_build(cls, app_id: int, app_path: str,
+ build_method: str = 'auto',
+ dockerfile_path: str = None,
+ custom_build_cmd: str = None,
+ custom_start_cmd: str = None,
+ build_args: Dict = None,
+ env_vars: Dict = None,
+ cache_enabled: bool = True,
+ timeout: int = None,
+ keep_deployments: int = 5) -> Dict:
+ """Configure build settings for an app.
+
+ Args:
+ app_id: Application ID
+ app_path: Path to application source code
+ build_method: 'auto', 'dockerfile', 'nixpacks', 'custom'
+ dockerfile_path: Path to Dockerfile (relative to app_path)
+ custom_build_cmd: Custom build command
+ custom_start_cmd: Custom start command
+ build_args: Docker build arguments
+ env_vars: Environment variables for build
+ cache_enabled: Enable build caching
+ timeout: Build timeout in seconds
+ keep_deployments: Number of deployments to keep for rollback
+ """
+ config = cls.get_config()
+
+ app_config = {
+ 'app_id': app_id,
+ 'app_path': app_path,
+ 'build_method': build_method,
+ 'dockerfile_path': dockerfile_path or 'Dockerfile',
+ 'custom_build_cmd': custom_build_cmd,
+ 'custom_start_cmd': custom_start_cmd,
+ 'build_args': build_args or {},
+ 'env_vars': env_vars or {},
+ 'cache_enabled': cache_enabled,
+ 'timeout': timeout or cls.DEFAULT_TIMEOUT,
+ 'keep_deployments': keep_deployments,
+ 'created_at': datetime.now().isoformat(),
+ 'last_build': None,
+ 'build_count': 0
+ }
+
+ config.setdefault('apps', {})[str(app_id)] = app_config
+ result = cls.save_config(config)
+
+ if result.get('success'):
+ return {'success': True, 'config': app_config}
+ return result
+
+ @classmethod
+ def detect_build_method(cls, app_path: str) -> Dict:
+ """Auto-detect the best build method for an application.
+
+ Returns detected language, framework, and recommended build method.
+ """
+ result = {
+ 'language': None,
+ 'framework': None,
+ 'build_method': 'custom',
+ 'has_dockerfile': False,
+ 'has_docker_compose': False,
+ 'detected_files': []
+ }
+
+ if not os.path.exists(app_path):
+ return result
+
+ files = os.listdir(app_path)
+ result['detected_files'] = files
+
+ # Check for Dockerfile
+ if 'Dockerfile' in files:
+ result['has_dockerfile'] = True
+ result['build_method'] = 'dockerfile'
+
+ # Check for docker-compose
+ if 'docker-compose.yml' in files or 'docker-compose.yaml' in files:
+ result['has_docker_compose'] = True
+
+ # Detect language
+ for lang, patterns in cls.LANGUAGE_PATTERNS.items():
+ for pattern in patterns:
+ if '*' in pattern:
+ # Glob pattern
+ import fnmatch
+ if any(fnmatch.fnmatch(f, pattern) for f in files):
+ result['language'] = lang
+ break
+ elif pattern in files:
+ result['language'] = lang
+ break
+ if result['language']:
+ break
+
+ # Detect framework
+ for framework, patterns in cls.FRAMEWORK_PATTERNS.items():
+ for pattern in patterns:
+ if pattern in files:
+ result['framework'] = framework
+ break
+ # Check in subdirectories for some patterns
+ for subdir in ['src', 'app', 'config']:
+ subpath = os.path.join(app_path, subdir, pattern)
+ if os.path.exists(subpath):
+ result['framework'] = framework
+ break
+ if result['framework']:
+ break
+
+ # Determine build method
+ if result['has_dockerfile']:
+ result['build_method'] = 'dockerfile'
+ elif result['language']:
+ result['build_method'] = 'nixpacks'
+ else:
+ result['build_method'] = 'custom'
+
+ return result
+
+ @classmethod
+ def _compute_build_hash(cls, app_path: str) -> str:
+ """Compute a hash of the source code for cache invalidation."""
+ hasher = hashlib.sha256()
+
+ for root, dirs, files in os.walk(app_path):
+ # Skip common non-source directories
+ dirs[:] = [d for d in dirs if d not in [
+ 'node_modules', '.git', '__pycache__', '.venv',
+ 'venv', 'vendor', 'target', 'dist', 'build'
+ ]]
+
+ for filename in sorted(files):
+ filepath = os.path.join(root, filename)
+ try:
+ with open(filepath, 'rb') as f:
+ hasher.update(f.read())
+ except (IOError, PermissionError):
+ pass
+
+ return hasher.hexdigest()[:16]
+
+ @classmethod
+ def _get_cache_key(cls, app_id: int, app_path: str) -> str:
+ """Get cache key for a build."""
+ source_hash = cls._compute_build_hash(app_path)
+ return f"app-{app_id}-{source_hash}"
+
+ @classmethod
+ def build_with_dockerfile(cls, app_id: int, app_path: str,
+ dockerfile_path: str = 'Dockerfile',
+ image_tag: str = None,
+ build_args: Dict = None,
+ no_cache: bool = False,
+ timeout: int = None,
+ log_callback: Callable[[str], None] = None) -> Dict:
+ """Build application using Dockerfile.
+
+ Args:
+ app_id: Application ID
+ app_path: Path to application source
+ dockerfile_path: Path to Dockerfile (relative to app_path)
+ image_tag: Docker image tag
+ build_args: Build arguments
+ no_cache: Disable Docker build cache
+ timeout: Build timeout in seconds
+ log_callback: Callback function for streaming logs
+ """
+ if not image_tag:
+ image_tag = f"serverkit-app-{app_id}:latest"
+
+ dockerfile_full = os.path.join(app_path, dockerfile_path)
+ if not os.path.exists(dockerfile_full):
+ return {'success': False, 'error': f'Dockerfile not found: {dockerfile_path}'}
+
+ build_log = {
+ 'app_id': app_id,
+ 'started_at': datetime.now().isoformat(),
+ 'build_method': 'dockerfile',
+ 'status': 'building',
+ 'logs': []
+ }
+
+ try:
+ cmd = ['docker', 'build', '-t', image_tag]
+
+ if dockerfile_path != 'Dockerfile':
+ cmd.extend(['-f', dockerfile_full])
+
+ if no_cache:
+ cmd.append('--no-cache')
+
+ if build_args:
+ for key, value in build_args.items():
+ cmd.extend(['--build-arg', f'{key}={value}'])
+
+ cmd.append(app_path)
+
+ # Run build with streaming output
+ process = subprocess.Popen(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ bufsize=1
+ )
+
+ output_lines = []
+ try:
+ for line in process.stdout:
+ output_lines.append(line)
+ build_log['logs'].append(line.rstrip())
+ if log_callback:
+ log_callback(line.rstrip())
+
+ process.wait(timeout=timeout or cls.DEFAULT_TIMEOUT)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ build_log['status'] = 'timeout'
+ build_log['error'] = 'Build timed out'
+ build_log['completed_at'] = datetime.now().isoformat()
+ cls._save_build_log(app_id, build_log)
+ return {'success': False, 'error': 'Build timed out', 'build_log': build_log}
+
+ if process.returncode == 0:
+ build_log['status'] = 'success'
+ build_log['image_tag'] = image_tag
+ build_log['completed_at'] = datetime.now().isoformat()
+ cls._save_build_log(app_id, build_log)
+ cls._update_build_stats(app_id)
+
+ return {
+ 'success': True,
+ 'image_tag': image_tag,
+ 'build_log': build_log
+ }
+ else:
+ build_log['status'] = 'failed'
+ build_log['error'] = 'Build failed'
+ build_log['completed_at'] = datetime.now().isoformat()
+ cls._save_build_log(app_id, build_log)
+
+ return {
+ 'success': False,
+ 'error': 'Docker build failed',
+ 'output': '\n'.join(output_lines),
+ 'build_log': build_log
+ }
+
+ except Exception as e:
+ build_log['status'] = 'error'
+ build_log['error'] = str(e)
+ build_log['completed_at'] = datetime.now().isoformat()
+ cls._save_build_log(app_id, build_log)
+ return {'success': False, 'error': str(e), 'build_log': build_log}
+
+ @classmethod
+ def build_with_nixpacks(cls, app_id: int, app_path: str,
+ image_tag: str = None,
+ env_vars: Dict = None,
+ build_cmd: str = None,
+ start_cmd: str = None,
+ no_cache: bool = False,
+ timeout: int = None,
+ log_callback: Callable[[str], None] = None) -> Dict:
+ """Build application using Nixpacks (Heroku-style auto-detection).
+
+ Nixpacks automatically detects the language and framework,
+ then builds an optimized Docker image.
+ """
+ if not image_tag:
+ image_tag = f"serverkit-app-{app_id}:latest"
+
+ # Check if nixpacks is installed
+ try:
+ subprocess.run(['nixpacks', '--version'], capture_output=True, check=True)
+ except (subprocess.CalledProcessError, FileNotFoundError):
+ return {
+ 'success': False,
+ 'error': 'Nixpacks not installed. Install with: curl -sSL https://nixpacks.com/install.sh | bash'
+ }
+
+ build_log = {
+ 'app_id': app_id,
+ 'started_at': datetime.now().isoformat(),
+ 'build_method': 'nixpacks',
+ 'status': 'building',
+ 'logs': []
+ }
+
+ try:
+ cmd = ['nixpacks', 'build', app_path, '--name', image_tag]
+
+ if env_vars:
+ for key, value in env_vars.items():
+ cmd.extend(['--env', f'{key}={value}'])
+
+ if build_cmd:
+ cmd.extend(['--build-cmd', build_cmd])
+
+ if start_cmd:
+ cmd.extend(['--start-cmd', start_cmd])
+
+ if no_cache:
+ cmd.append('--no-cache')
+
+ # Run build with streaming output
+ process = subprocess.Popen(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ bufsize=1
+ )
+
+ output_lines = []
+ try:
+ for line in process.stdout:
+ output_lines.append(line)
+ build_log['logs'].append(line.rstrip())
+ if log_callback:
+ log_callback(line.rstrip())
+
+ process.wait(timeout=timeout or cls.DEFAULT_TIMEOUT)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ build_log['status'] = 'timeout'
+ build_log['error'] = 'Build timed out'
+ build_log['completed_at'] = datetime.now().isoformat()
+ cls._save_build_log(app_id, build_log)
+ return {'success': False, 'error': 'Build timed out', 'build_log': build_log}
+
+ if process.returncode == 0:
+ build_log['status'] = 'success'
+ build_log['image_tag'] = image_tag
+ build_log['completed_at'] = datetime.now().isoformat()
+ cls._save_build_log(app_id, build_log)
+ cls._update_build_stats(app_id)
+
+ return {
+ 'success': True,
+ 'image_tag': image_tag,
+ 'build_log': build_log
+ }
+ else:
+ build_log['status'] = 'failed'
+ build_log['error'] = 'Build failed'
+ build_log['completed_at'] = datetime.now().isoformat()
+ cls._save_build_log(app_id, build_log)
+
+ return {
+ 'success': False,
+ 'error': 'Nixpacks build failed',
+ 'output': '\n'.join(output_lines),
+ 'build_log': build_log
+ }
+
+ except Exception as e:
+ build_log['status'] = 'error'
+ build_log['error'] = str(e)
+ build_log['completed_at'] = datetime.now().isoformat()
+ cls._save_build_log(app_id, build_log)
+ return {'success': False, 'error': str(e), 'build_log': build_log}
+
+ @classmethod
+ def build_with_custom_command(cls, app_id: int, app_path: str,
+ build_cmd: str,
+ env_vars: Dict = None,
+ timeout: int = None,
+ log_callback: Callable[[str], None] = None) -> Dict:
+ """Build application using custom commands."""
+ build_log = {
+ 'app_id': app_id,
+ 'started_at': datetime.now().isoformat(),
+ 'build_method': 'custom',
+ 'build_cmd': build_cmd,
+ 'status': 'building',
+ 'logs': []
+ }
+
+ try:
+ env = os.environ.copy()
+ if env_vars:
+ env.update(env_vars)
+
+ process = subprocess.Popen(
+ build_cmd,
+ shell=True,
+ cwd=app_path,
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ bufsize=1
+ )
+
+ output_lines = []
+ try:
+ for line in process.stdout:
+ output_lines.append(line)
+ build_log['logs'].append(line.rstrip())
+ if log_callback:
+ log_callback(line.rstrip())
+
+ process.wait(timeout=timeout or cls.DEFAULT_TIMEOUT)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ build_log['status'] = 'timeout'
+ build_log['error'] = 'Build timed out'
+ build_log['completed_at'] = datetime.now().isoformat()
+ cls._save_build_log(app_id, build_log)
+ return {'success': False, 'error': 'Build timed out', 'build_log': build_log}
+
+ if process.returncode == 0:
+ build_log['status'] = 'success'
+ build_log['completed_at'] = datetime.now().isoformat()
+ cls._save_build_log(app_id, build_log)
+ cls._update_build_stats(app_id)
+
+ return {
+ 'success': True,
+ 'build_log': build_log
+ }
+ else:
+ build_log['status'] = 'failed'
+ build_log['error'] = f'Build command exited with code {process.returncode}'
+ build_log['completed_at'] = datetime.now().isoformat()
+ cls._save_build_log(app_id, build_log)
+
+ return {
+ 'success': False,
+ 'error': 'Custom build failed',
+ 'output': '\n'.join(output_lines),
+ 'build_log': build_log
+ }
+
+ except Exception as e:
+ build_log['status'] = 'error'
+ build_log['error'] = str(e)
+ build_log['completed_at'] = datetime.now().isoformat()
+ cls._save_build_log(app_id, build_log)
+ return {'success': False, 'error': str(e), 'build_log': build_log}
+
+ @classmethod
+ def build(cls, app_id: int, no_cache: bool = False,
+ log_callback: Callable[[str], None] = None) -> Dict:
+ """Build an application using configured method.
+
+ Auto-detects build method if set to 'auto'.
+ """
+ build_config = cls.get_app_build_config(app_id)
+ if not build_config:
+ return {'success': False, 'error': 'Build not configured for this app'}
+
+ app_path = build_config['app_path']
+ build_method = build_config.get('build_method', 'auto')
+ timeout = build_config.get('timeout', cls.DEFAULT_TIMEOUT)
+
+ # Auto-detect if needed
+ if build_method == 'auto':
+ detection = cls.detect_build_method(app_path)
+ build_method = detection['build_method']
+
+ # Build based on method
+ if build_method == 'dockerfile':
+ return cls.build_with_dockerfile(
+ app_id=app_id,
+ app_path=app_path,
+ dockerfile_path=build_config.get('dockerfile_path', 'Dockerfile'),
+ build_args=build_config.get('build_args'),
+ no_cache=no_cache or not build_config.get('cache_enabled', True),
+ timeout=timeout,
+ log_callback=log_callback
+ )
+ elif build_method == 'nixpacks':
+ return cls.build_with_nixpacks(
+ app_id=app_id,
+ app_path=app_path,
+ env_vars=build_config.get('env_vars'),
+ build_cmd=build_config.get('custom_build_cmd'),
+ start_cmd=build_config.get('custom_start_cmd'),
+ no_cache=no_cache or not build_config.get('cache_enabled', True),
+ timeout=timeout,
+ log_callback=log_callback
+ )
+ elif build_method == 'custom':
+ custom_cmd = build_config.get('custom_build_cmd')
+ if not custom_cmd:
+ return {'success': False, 'error': 'No custom build command configured'}
+ return cls.build_with_custom_command(
+ app_id=app_id,
+ app_path=app_path,
+ build_cmd=custom_cmd,
+ env_vars=build_config.get('env_vars'),
+ timeout=timeout,
+ log_callback=log_callback
+ )
+ else:
+ return {'success': False, 'error': f'Unknown build method: {build_method}'}
+
+ @classmethod
+ def _save_build_log(cls, app_id: int, build_log: Dict) -> None:
+ """Save build log to file."""
+ try:
+ log_dir = os.path.join(cls.BUILD_LOG_DIR, str(app_id))
+ os.makedirs(log_dir, exist_ok=True)
+
+ timestamp = build_log.get('started_at', datetime.now().isoformat())
+ filename = f"build-{timestamp.replace(':', '-')}.json"
+ filepath = os.path.join(log_dir, filename)
+
+ with open(filepath, 'w') as f:
+ json.dump(build_log, f, indent=2)
+ except Exception:
+ pass
+
+ @classmethod
+ def _update_build_stats(cls, app_id: int) -> None:
+ """Update build statistics in config."""
+ config = cls.get_config()
+ if str(app_id) in config.get('apps', {}):
+ config['apps'][str(app_id)]['last_build'] = datetime.now().isoformat()
+ config['apps'][str(app_id)]['build_count'] = config['apps'][str(app_id)].get('build_count', 0) + 1
+ cls.save_config(config)
+
+ @classmethod
+ def get_build_logs(cls, app_id: int, limit: int = 20) -> List[Dict]:
+ """Get build logs for an application."""
+ logs = []
+ log_dir = os.path.join(cls.BUILD_LOG_DIR, str(app_id))
+
+ if not os.path.exists(log_dir):
+ return logs
+
+ try:
+ files = sorted(os.listdir(log_dir), reverse=True)[:limit]
+ for filename in files:
+ filepath = os.path.join(log_dir, filename)
+ try:
+ with open(filepath, 'r') as f:
+ log_entry = json.load(f)
+ # Don't include full log output in list
+ log_entry['log_count'] = len(log_entry.get('logs', []))
+ log_entry.pop('logs', None)
+ logs.append(log_entry)
+ except (json.JSONDecodeError, IOError):
+ pass
+ except Exception:
+ pass
+
+ return logs
+
+ @classmethod
+ def get_build_log_detail(cls, app_id: int, timestamp: str) -> Optional[Dict]:
+ """Get detailed build log including output."""
+ log_dir = os.path.join(cls.BUILD_LOG_DIR, str(app_id))
+ filename = f"build-{timestamp.replace(':', '-')}.json"
+ filepath = os.path.join(log_dir, filename)
+
+ if os.path.exists(filepath):
+ try:
+ with open(filepath, 'r') as f:
+ return json.load(f)
+ except (json.JSONDecodeError, IOError):
+ pass
+ return None
+
+ @classmethod
+ def cancel_build(cls, app_id: int) -> Dict:
+ """Cancel a running build (if possible)."""
+ # This would need process tracking to implement fully
+ # For now, just return a placeholder
+ return {'success': False, 'error': 'Build cancellation not yet implemented'}
+
+ @classmethod
+ def clear_build_cache(cls, app_id: int = None) -> Dict:
+ """Clear build cache for an app or all apps."""
+ try:
+ if app_id:
+ cache_dir = os.path.join(cls.BUILD_CACHE_DIR, str(app_id))
+ if os.path.exists(cache_dir):
+ shutil.rmtree(cache_dir)
+ else:
+ if os.path.exists(cls.BUILD_CACHE_DIR):
+ shutil.rmtree(cls.BUILD_CACHE_DIR)
+ return {'success': True}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_nixpacks_plan(cls, app_path: str) -> Dict:
+ """Get Nixpacks build plan for an application."""
+ try:
+ result = subprocess.run(
+ ['nixpacks', 'plan', app_path, '--format', 'json'],
+ capture_output=True,
+ text=True
+ )
+ if result.returncode == 0:
+ return {'success': True, 'plan': json.loads(result.stdout)}
+ return {'success': False, 'error': result.stderr}
+ except FileNotFoundError:
+ return {'success': False, 'error': 'Nixpacks not installed'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
diff --git a/backend/app/services/deployment_service.py b/backend/app/services/deployment_service.py
new file mode 100644
index 00000000..ce030167
--- /dev/null
+++ b/backend/app/services/deployment_service.py
@@ -0,0 +1,597 @@
+"""
+Deployment Service - Orchestrates build and deploy workflows.
+
+Supports:
+- Full deployment workflow (build -> deploy)
+- Deployment status tracking
+- One-click rollback
+- Deployment retention policies
+- Diff generation between deployments
+"""
+
+import os
+import subprocess
+import json
+import shutil
+from datetime import datetime
+from typing import Dict, List, Optional, Callable
+
+from app import db
+from app.models.deployment import Deployment, DeploymentDiff
+from app.models.application import Application
+from app.services.build_service import BuildService
+from app.services.docker_service import DockerService
+from app.services.git_service import GitService
+
+
+class DeploymentService:
+ """Service for orchestrating deployments."""
+
+ DEPLOYMENT_DIR = '/var/serverkit/deployments'
+
+ @classmethod
+ def create_deployment(cls, app_id: int, user_id: int = None,
+ trigger: str = 'manual', version_tag: str = None) -> Dict:
+ """Create a new deployment record."""
+ app = Application.query.get(app_id)
+ if not app:
+ return {'success': False, 'error': 'Application not found'}
+
+ # Get git commit info if available
+ commit_hash = None
+ commit_message = None
+ if app.root_path:
+ git_info = GitService.get_commit_info(app.root_path)
+ if git_info:
+ commit_hash = git_info.get('hash')
+ commit_message = git_info.get('message')
+
+ # Get build config
+ build_config = BuildService.get_app_build_config(app_id)
+ build_method = None
+ if build_config:
+ build_method = build_config.get('build_method', 'auto')
+ if build_method == 'auto':
+ detection = BuildService.detect_build_method(app.root_path or app.path)
+ build_method = detection.get('build_method')
+
+ # Create deployment record
+ version = Deployment.get_next_version(app_id)
+ deployment = Deployment(
+ app_id=app_id,
+ version=version,
+ version_tag=version_tag or f"v{version}",
+ status='pending',
+ build_method=build_method,
+ commit_hash=commit_hash,
+ commit_message=commit_message,
+ deployed_by=user_id,
+ deploy_trigger=trigger
+ )
+ db.session.add(deployment)
+ db.session.commit()
+
+ return {
+ 'success': True,
+ 'deployment': deployment.to_dict()
+ }
+
+ @classmethod
+ def deploy(cls, app_id: int, user_id: int = None,
+ no_cache: bool = False,
+ trigger: str = 'manual',
+ version_tag: str = None,
+ log_callback: Callable[[str], None] = None) -> Dict:
+ """Execute a full deployment (build + deploy).
+
+ This is the main entry point for deployments.
+ """
+ # Create deployment record
+ result = cls.create_deployment(app_id, user_id, trigger, version_tag)
+ if not result.get('success'):
+ return result
+
+ deployment_id = result['deployment']['id']
+ deployment = Deployment.query.get(deployment_id)
+
+ app = Application.query.get(app_id)
+ build_config = BuildService.get_app_build_config(app_id)
+
+ try:
+ # Update app status
+ app.status = 'deploying'
+ db.session.commit()
+
+ # Step 1: Build
+ deployment.status = 'building'
+ deployment.build_started_at = datetime.utcnow()
+ db.session.commit()
+
+ if log_callback:
+ log_callback(f"Starting build for {app.name}...")
+
+ build_result = BuildService.build(
+ app_id,
+ no_cache=no_cache,
+ log_callback=log_callback
+ )
+
+ deployment.build_completed_at = datetime.utcnow()
+
+ if not build_result.get('success'):
+ deployment.status = 'failed'
+ deployment.error_message = build_result.get('error', 'Build failed')
+ app.status = 'error'
+ db.session.commit()
+ return {
+ 'success': False,
+ 'error': deployment.error_message,
+ 'deployment': deployment.to_dict()
+ }
+
+ # Store build artifacts
+ if build_result.get('image_tag'):
+ deployment.image_tag = build_result['image_tag']
+
+ if build_result.get('build_log'):
+ # Store build log path for later retrieval
+ log_dir = f"/var/log/serverkit/builds/{app_id}"
+ log_file = f"build-{deployment.created_at.isoformat().replace(':', '-')}.json"
+ deployment.build_log_path = os.path.join(log_dir, log_file)
+
+ db.session.commit()
+
+ # Step 2: Deploy
+ deployment.status = 'deploying'
+ deployment.deploy_started_at = datetime.utcnow()
+ db.session.commit()
+
+ if log_callback:
+ log_callback("Build successful, starting deployment...")
+
+ deploy_result = cls._deploy_application(app, deployment, log_callback)
+
+ if not deploy_result.get('success'):
+ deployment.status = 'failed'
+ deployment.error_message = deploy_result.get('error', 'Deploy failed')
+ app.status = 'error'
+ db.session.commit()
+ return {
+ 'success': False,
+ 'error': deployment.error_message,
+ 'deployment': deployment.to_dict()
+ }
+
+ # Mark previous live deployment as rolled_back
+ current = Deployment.get_current(app_id)
+ if current and current.id != deployment.id:
+ current.status = 'rolled_back'
+
+ # Update deployment status
+ deployment.status = 'live'
+ deployment.deploy_completed_at = datetime.utcnow()
+ deployment.container_id = deploy_result.get('container_id')
+
+ # Update app
+ app.status = 'running'
+ app.last_deployed_at = datetime.utcnow()
+ if deployment.image_tag:
+ app.docker_image = deployment.image_tag
+ if deploy_result.get('container_id'):
+ app.container_id = deploy_result.get('container_id')
+
+ db.session.commit()
+
+ # Generate diff with previous deployment
+ cls._generate_diff(deployment)
+
+ # Cleanup old deployments
+ if build_config:
+ keep_count = build_config.get('keep_deployments', 5)
+ Deployment.cleanup_old_deployments(app_id, keep_count)
+
+ if log_callback:
+ log_callback(f"Deployment successful! Version {deployment.version} is now live.")
+
+ return {
+ 'success': True,
+ 'deployment': deployment.to_dict()
+ }
+
+ except Exception as e:
+ deployment.status = 'failed'
+ deployment.error_message = str(e)
+ app.status = 'error'
+ db.session.commit()
+ return {
+ 'success': False,
+ 'error': str(e),
+ 'deployment': deployment.to_dict()
+ }
+
+ @classmethod
+ def _deploy_application(cls, app: Application, deployment: Deployment,
+ log_callback: Callable[[str], None] = None) -> Dict:
+ """Deploy the application based on app type."""
+ try:
+ if deployment.image_tag:
+ # Docker-based deployment
+ return cls._deploy_docker(app, deployment, log_callback)
+ else:
+ # Non-Docker deployment (use existing deployment mechanisms)
+ return cls._deploy_traditional(app, deployment, log_callback)
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _deploy_docker(cls, app: Application, deployment: Deployment,
+ log_callback: Callable[[str], None] = None) -> Dict:
+ """Deploy a Docker-based application."""
+ image_tag = deployment.image_tag
+ container_name = f"serverkit-app-{app.id}"
+
+ if log_callback:
+ log_callback(f"Deploying Docker image: {image_tag}")
+
+ # Stop and remove existing container
+ existing = DockerService.get_container(container_name)
+ if existing:
+ if log_callback:
+ log_callback("Stopping existing container...")
+ DockerService.stop_container(container_name)
+ DockerService.remove_container(container_name)
+
+ # Configure container
+ ports = []
+ if app.port:
+ ports.append(f"{app.port}:{app.port}")
+
+ env = {}
+ # Get env vars from app config if available
+ from app.services.env_service import EnvService
+ env_vars = EnvService.get_env_vars(app.id)
+ if env_vars.get('success'):
+ for var in env_vars.get('variables', []):
+ env[var['key']] = var['value']
+
+ # Run new container
+ if log_callback:
+ log_callback(f"Starting container {container_name}...")
+
+ result = DockerService.run_container(
+ image=image_tag,
+ name=container_name,
+ ports=ports if ports else None,
+ env=env if env else None,
+ restart_policy='unless-stopped',
+ detach=True
+ )
+
+ if result.get('success'):
+ return {
+ 'success': True,
+ 'container_id': result.get('container_id')
+ }
+ return result
+
+ @classmethod
+ def _deploy_traditional(cls, app: Application, deployment: Deployment,
+ log_callback: Callable[[str], None] = None) -> Dict:
+ """Deploy using traditional methods (git pull, service restart, etc.)."""
+ from app.services.git_service import GitService
+
+ # If git is configured, pull latest
+ deploy_config = GitService.get_app_config(app.id)
+ if deploy_config:
+ if log_callback:
+ log_callback("Pulling latest changes...")
+
+ pull_result = GitService.pull_changes(
+ app.root_path or app.path,
+ deploy_config.get('branch')
+ )
+
+ if not pull_result.get('success'):
+ return pull_result
+
+ # Run post-deploy scripts
+ if deploy_config.get('post_deploy_script'):
+ if log_callback:
+ log_callback("Running post-deploy script...")
+
+ script_result = GitService._run_script(
+ deploy_config['post_deploy_script'],
+ app.root_path or app.path
+ )
+
+ if not script_result.get('success'):
+ return script_result
+
+ # Restart the application service if applicable
+ if app.app_type in ['flask', 'django']:
+ if log_callback:
+ log_callback("Restarting application service...")
+
+ service_name = f"serverkit-{app.name}"
+ try:
+ subprocess.run(
+ ['systemctl', 'restart', service_name],
+ capture_output=True,
+ check=True
+ )
+ except subprocess.CalledProcessError as e:
+ return {'success': False, 'error': f'Service restart failed: {e.stderr}'}
+
+ return {'success': True}
+
+ @classmethod
+ def rollback(cls, app_id: int, target_version: int = None,
+ user_id: int = None,
+ log_callback: Callable[[str], None] = None) -> Dict:
+ """Rollback to a previous deployment.
+
+ If target_version is not specified, rolls back to the previous successful deployment.
+ """
+ app = Application.query.get(app_id)
+ if not app:
+ return {'success': False, 'error': 'Application not found'}
+
+ current = Deployment.get_current(app_id)
+ if not current:
+ return {'success': False, 'error': 'No current deployment to rollback from'}
+
+ # Find target deployment
+ if target_version:
+ target = Deployment.query.filter_by(
+ app_id=app_id,
+ version=target_version
+ ).first()
+ else:
+ target = Deployment.get_previous(app_id, current.version)
+
+ if not target:
+ return {'success': False, 'error': 'No previous deployment found to rollback to'}
+
+ if not target.image_tag and not target.commit_hash:
+ return {
+ 'success': False,
+ 'error': 'Target deployment has no artifacts to rollback to'
+ }
+
+ if log_callback:
+ log_callback(f"Rolling back from v{current.version} to v{target.version}...")
+
+ try:
+ app.status = 'deploying'
+ db.session.commit()
+
+ # Create new deployment record for the rollback
+ version = Deployment.get_next_version(app_id)
+ rollback_deployment = Deployment(
+ app_id=app_id,
+ version=version,
+ version_tag=f"v{version}-rollback-from-v{current.version}",
+ status='deploying',
+ build_method=target.build_method,
+ image_tag=target.image_tag,
+ commit_hash=target.commit_hash,
+ deployed_by=user_id,
+ deploy_trigger='rollback'
+ )
+ rollback_deployment.update_metadata('rolled_back_to', target.version)
+ rollback_deployment.deploy_started_at = datetime.utcnow()
+ db.session.add(rollback_deployment)
+ db.session.commit()
+
+ # Deploy the previous version
+ if target.image_tag:
+ # Docker rollback
+ deploy_result = cls._deploy_docker(app, rollback_deployment, log_callback)
+ else:
+ # Git rollback
+ deploy_result = cls._rollback_git(app, target, log_callback)
+
+ if not deploy_result.get('success'):
+ rollback_deployment.status = 'failed'
+ rollback_deployment.error_message = deploy_result.get('error')
+ app.status = 'error'
+ db.session.commit()
+ return {
+ 'success': False,
+ 'error': deploy_result.get('error'),
+ 'deployment': rollback_deployment.to_dict()
+ }
+
+ # Update statuses
+ current.status = 'rolled_back'
+ rollback_deployment.status = 'live'
+ rollback_deployment.deploy_completed_at = datetime.utcnow()
+ rollback_deployment.container_id = deploy_result.get('container_id')
+
+ app.status = 'running'
+ app.last_deployed_at = datetime.utcnow()
+
+ db.session.commit()
+
+ if log_callback:
+ log_callback(f"Rollback successful! Now running v{target.version} code as v{version}")
+
+ return {
+ 'success': True,
+ 'deployment': rollback_deployment.to_dict(),
+ 'rolled_back_to': target.to_dict()
+ }
+
+ except Exception as e:
+ app.status = 'error'
+ db.session.commit()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _rollback_git(cls, app: Application, target: Deployment,
+ log_callback: Callable[[str], None] = None) -> Dict:
+ """Rollback to a specific git commit."""
+ if not target.commit_hash:
+ return {'success': False, 'error': 'No commit hash to rollback to'}
+
+ app_path = app.root_path or app.path
+
+ try:
+ if log_callback:
+ log_callback(f"Checking out commit {target.commit_hash[:8]}...")
+
+ # Checkout the specific commit
+ result = subprocess.run(
+ ['git', '-C', app_path, 'checkout', target.commit_hash],
+ capture_output=True,
+ text=True
+ )
+
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr}
+
+ # Run post-deploy script if configured
+ deploy_config = GitService.get_app_config(app.id)
+ if deploy_config and deploy_config.get('post_deploy_script'):
+ if log_callback:
+ log_callback("Running post-deploy script...")
+
+ script_result = GitService._run_script(
+ deploy_config['post_deploy_script'],
+ app_path
+ )
+
+ if not script_result.get('success'):
+ return script_result
+
+ # Restart service
+ if app.app_type in ['flask', 'django']:
+ service_name = f"serverkit-{app.name}"
+ subprocess.run(['systemctl', 'restart', service_name], check=True)
+
+ return {'success': True}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _generate_diff(cls, deployment: Deployment) -> None:
+ """Generate diff between this deployment and the previous one."""
+ try:
+ previous = Deployment.get_previous(deployment.app_id, deployment.version)
+ if not previous or not deployment.commit_hash or not previous.commit_hash:
+ return
+
+ app = Application.query.get(deployment.app_id)
+ app_path = app.root_path or app.path
+
+ # Get git diff
+ result = subprocess.run(
+ ['git', '-C', app_path, 'diff', '--name-status',
+ previous.commit_hash, deployment.commit_hash],
+ capture_output=True,
+ text=True
+ )
+
+ if result.returncode != 0:
+ return
+
+ files_added = []
+ files_removed = []
+ files_modified = []
+
+ for line in result.stdout.strip().split('\n'):
+ if not line:
+ continue
+ parts = line.split('\t')
+ if len(parts) >= 2:
+ status, filepath = parts[0], parts[1]
+ if status == 'A':
+ files_added.append(filepath)
+ elif status == 'D':
+ files_removed.append(filepath)
+ elif status.startswith('M') or status.startswith('R'):
+ files_modified.append(filepath)
+
+ # Get diff stats
+ stat_result = subprocess.run(
+ ['git', '-C', app_path, 'diff', '--shortstat',
+ previous.commit_hash, deployment.commit_hash],
+ capture_output=True,
+ text=True
+ )
+
+ additions = 0
+ deletions = 0
+ if stat_result.returncode == 0 and stat_result.stdout:
+ import re
+ add_match = re.search(r'(\d+) insertion', stat_result.stdout)
+ del_match = re.search(r'(\d+) deletion', stat_result.stdout)
+ if add_match:
+ additions = int(add_match.group(1))
+ if del_match:
+ deletions = int(del_match.group(1))
+
+ # Create diff record
+ diff = DeploymentDiff(
+ deployment_id=deployment.id,
+ previous_deployment_id=previous.id,
+ files_added=json.dumps(files_added),
+ files_removed=json.dumps(files_removed),
+ files_modified=json.dumps(files_modified),
+ additions=additions,
+ deletions=deletions
+ )
+ db.session.add(diff)
+ db.session.commit()
+
+ except Exception:
+ pass
+
+ @classmethod
+ def get_deployments(cls, app_id: int, limit: int = 20, offset: int = 0) -> List[Dict]:
+ """Get deployment history for an app."""
+ deployments = Deployment.query.filter_by(app_id=app_id).order_by(
+ Deployment.version.desc()
+ ).offset(offset).limit(limit).all()
+
+ return [d.to_dict() for d in deployments]
+
+ @classmethod
+ def get_deployment(cls, deployment_id: int, include_logs: bool = False) -> Optional[Dict]:
+ """Get a specific deployment."""
+ deployment = Deployment.query.get(deployment_id)
+ if deployment:
+ return deployment.to_dict(include_logs=include_logs)
+ return None
+
+ @classmethod
+ def get_deployment_diff(cls, deployment_id: int) -> Optional[Dict]:
+ """Get diff for a deployment."""
+ diff = DeploymentDiff.query.filter_by(deployment_id=deployment_id).first()
+ if diff:
+ return diff.to_dict()
+ return None
+
+ @classmethod
+ def get_current_deployment(cls, app_id: int) -> Optional[Dict]:
+ """Get the currently live deployment."""
+ deployment = Deployment.get_current(app_id)
+ if deployment:
+ return deployment.to_dict()
+ return None
+
+ @classmethod
+ def update_deployment_status(cls, deployment_id: int, status: str,
+ error_message: str = None) -> Dict:
+ """Update deployment status."""
+ deployment = Deployment.query.get(deployment_id)
+ if not deployment:
+ return {'success': False, 'error': 'Deployment not found'}
+
+ deployment.status = status
+ if error_message:
+ deployment.error_message = error_message
+
+ db.session.commit()
+ return {'success': True, 'deployment': deployment.to_dict()}
diff --git a/backend/app/sockets.py b/backend/app/sockets.py
index 260f3f83..95af98e9 100644
--- a/backend/app/sockets.py
+++ b/backend/app/sockets.py
@@ -3,6 +3,7 @@ from flask_jwt_extended import decode_token
from flask import request
import threading
import time
+import queue
from app.services.system_service import SystemService
from app.services.log_service import LogService, LogStreamer
@@ -15,6 +16,10 @@ metric_subscribers = set()
metric_thread = None
metric_stop_event = threading.Event()
+# Store active build subscriptions
+build_subscribers = {} # sid -> app_id
+build_log_queues = {} # app_id -> queue
+
def init_socketio(app):
"""Initialize SocketIO with the Flask app."""
@@ -151,3 +156,71 @@ def handle_leave_room(data):
if room:
leave_room(room)
emit('left', {'room': room})
+
+
+# ==================== BUILD LOG STREAMING ====================
+
[email protected]('subscribe_build')
+def handle_subscribe_build(data):
+ """Subscribe to build log streaming for an app."""
+ sid = request.sid
+ app_id = data.get('app_id')
+
+ if not app_id:
+ emit('error', {'message': 'app_id required'})
+ return
+
+ # Store subscription
+ build_subscribers[sid] = app_id
+
+ # Join a room for this app's builds
+ join_room(f'build_{app_id}')
+
+ emit('subscribed', {'channel': 'build', 'app_id': app_id})
+
+
[email protected]('unsubscribe_build')
+def handle_unsubscribe_build():
+ """Unsubscribe from build log streaming."""
+ sid = request.sid
+
+ if sid in build_subscribers:
+ app_id = build_subscribers[sid]
+ leave_room(f'build_{app_id}')
+ del build_subscribers[sid]
+
+ emit('unsubscribed', {'channel': 'build'})
+
+
+def emit_build_log(app_id: int, message: str, level: str = 'info'):
+ """Emit a build log message to all subscribers.
+
+ This function is called from the build service to stream logs.
+ """
+ socketio.emit('build_log', {
+ 'app_id': app_id,
+ 'message': message,
+ 'level': level,
+ 'timestamp': time.time()
+ }, room=f'build_{app_id}')
+
+
+def emit_build_status(app_id: int, status: str, details: dict = None):
+ """Emit a build status update to all subscribers."""
+ socketio.emit('build_status', {
+ 'app_id': app_id,
+ 'status': status,
+ 'details': details or {},
+ 'timestamp': time.time()
+ }, room=f'build_{app_id}')
+
+
+def create_build_log_callback(app_id: int):
+ """Create a log callback function for the build service.
+
+ Returns a function that can be passed to BuildService.build()
+ to stream logs in real-time via WebSocket.
+ """
+ def log_callback(message: str):
+ emit_build_log(app_id, message)
+ return log_callback
diff --git a/frontend/src/pages/ApplicationDetail.jsx b/frontend/src/pages/ApplicationDetail.jsx
index 913ee3de..f0e18e6c 100644
--- a/frontend/src/pages/ApplicationDetail.jsx
+++ b/frontend/src/pages/ApplicationDetail.jsx
@@ -185,6 +185,12 @@ const ApplicationDetail = () => {
</button>
</>
)}
+ <button
+ className={`tab ${activeTab === 'build' ? 'active' : ''}`}
+ onClick={() => setActiveTab('build')}
+ >
+ Build
+ </button>
<button
className={`tab ${activeTab === 'deploy' ? 'active' : ''}`}
onClick={() => setActiveTab('deploy')}
@@ -214,6 +220,7 @@ const ApplicationDetail = () => {
{activeTab === 'plugins' && isWordPressApp && <PluginsTab appId={app.id} />}
{activeTab === 'themes' && isWordPressApp && <ThemesTab appId={app.id} />}
{activeTab === 'backups' && isWordPressApp && <BackupsTab appId={app.id} />}
+ {activeTab === 'build' && <BuildTab appId={app.id} appPath={app.path} />}
{activeTab === 'deploy' && <DeployTab appId={app.id} appPath={app.path} />}
{activeTab === 'logs' && <LogsTab app={app} />}
{activeTab === 'settings' && <SettingsTab app={app} onUpdate={loadApp} />}
@@ -860,6 +867,543 @@ const BackupsTab = ({ appId }) => {
);
};
+const BuildTab = ({ appId, appPath }) => {
+ const toast = useToast();
+ const [buildConfig, setBuildConfig] = useState(null);
+ const [detection, setDetection] = useState(null);
+ const [deployments, setDeployments] = useState([]);
+ const [currentDeployment, setCurrentDeployment] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [building, setBuilding] = useState(false);
+ const [deploying, setDeploying] = useState(false);
+ const [showConfigModal, setShowConfigModal] = useState(false);
+ const [showLogsModal, setShowLogsModal] = useState(false);
+ const [selectedLog, setSelectedLog] = useState(null);
+ const [buildLogs, setBuildLogs] = useState([]);
+ const [error, setError] = useState(null);
+
+ // Config form state
+ const [configForm, setConfigForm] = useState({
+ buildMethod: 'auto',
+ dockerfilePath: 'Dockerfile',
+ customBuildCmd: '',
+ customStartCmd: '',
+ cacheEnabled: true,
+ timeout: 600,
+ keepDeployments: 5
+ });
+
+ useEffect(() => {
+ loadData();
+ }, [appId]);
+
+ async function loadData() {
+ try {
+ setLoading(true);
+ const [configRes, detectRes, deploymentsRes] = await Promise.all([
+ api.getBuildConfig(appId),
+ api.detectBuildMethod(appId),
+ api.getDeployments(appId, 10)
+ ]);
+
+ setDetection(detectRes);
+
+ if (configRes.configured) {
+ setBuildConfig(configRes.config);
+ setConfigForm({
+ buildMethod: configRes.config.build_method || 'auto',
+ dockerfilePath: configRes.config.dockerfile_path || 'Dockerfile',
+ customBuildCmd: configRes.config.custom_build_cmd || '',
+ customStartCmd: configRes.config.custom_start_cmd || '',
+ cacheEnabled: configRes.config.cache_enabled !== false,
+ timeout: configRes.config.timeout || 600,
+ keepDeployments: configRes.config.keep_deployments || 5
+ });
+ }
+
+ setDeployments(deploymentsRes.deployments || []);
+ setCurrentDeployment(deploymentsRes.current);
+
+ } catch (err) {
+ setError(err.message);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function handleConfigureBuild(e) {
+ e.preventDefault();
+ try {
+ await api.configureBuild(appId, {
+ build_method: configForm.buildMethod,
+ dockerfile_path: configForm.dockerfilePath,
+ custom_build_cmd: configForm.customBuildCmd || null,
+ custom_start_cmd: configForm.customStartCmd || null,
+ cache_enabled: configForm.cacheEnabled,
+ timeout: configForm.timeout,
+ keep_deployments: configForm.keepDeployments
+ });
+ setShowConfigModal(false);
+ toast.success('Build configuration saved');
+ loadData();
+ } catch (err) {
+ setError(err.message);
+ }
+ }
+
+ async function handleBuild(noCache = false) {
+ setBuilding(true);
+ setError(null);
+ try {
+ const result = await api.triggerBuild(appId, noCache);
+ if (result.success) {
+ toast.success('Build completed successfully');
+ } else {
+ setError(result.error || 'Build failed');
+ }
+ loadData();
+ } catch (err) {
+ setError(err.message);
+ } finally {
+ setBuilding(false);
+ }
+ }
+
+ async function handleDeploy(noCache = false) {
+ setDeploying(true);
+ setError(null);
+ try {
+ const result = await api.deployApp(appId, { no_cache: noCache });
+ if (result.success) {
+ toast.success(`Deployment v${result.deployment.version} successful!`);
+ } else {
+ setError(result.error || 'Deployment failed');
+ }
+ loadData();
+ } catch (err) {
+ setError(err.message);
+ } finally {
+ setDeploying(false);
+ }
+ }
+
+ async function handleRollback(version = null) {
+ if (!confirm(version
+ ? `Rollback to version ${version}? This will replace the current deployment.`
+ : 'Rollback to previous deployment?'
+ )) return;
+
+ setDeploying(true);
+ setError(null);
+ try {
+ const result = await api.rollback(appId, version);
+ if (result.success) {
+ toast.success('Rollback successful');
+ } else {
+ setError(result.error || 'Rollback failed');
+ }
+ loadData();
+ } catch (err) {
+ setError(err.message);
+ } finally {
+ setDeploying(false);
+ }
+ }
+
+ async function loadBuildLogs() {
+ try {
+ const result = await api.getBuildLogs(appId);
+ setBuildLogs(result.logs || []);
+ } catch (err) {
+ console.error('Failed to load build logs:', err);
+ }
+ }
+
+ async function viewBuildLog(timestamp) {
+ try {
+ const log = await api.getBuildLogDetail(appId, timestamp);
+ setSelectedLog(log);
+ setShowLogsModal(true);
+ } catch (err) {
+ toast.error('Failed to load build log');
+ }
+ }
+
+ function getStatusBadgeClass(status) {
+ switch (status) {
+ case 'live': return 'badge-success';
+ case 'building':
+ case 'deploying':
+ case 'pending': return 'badge-warning';
+ case 'failed': return 'badge-danger';
+ case 'rolled_back': return 'badge-secondary';
+ default: return 'badge-default';
+ }
+ }
+
+ function formatDuration(seconds) {
+ if (!seconds) return '-';
+ if (seconds < 60) return `${Math.round(seconds)}s`;
+ return `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
+ }
+
+ if (loading) {
+ return <div className="loading">Loading build configuration...</div>;
+ }
+
+ return (
+ <div className="build-tab">
+ {error && (
+ <div className="alert alert-danger">
+ {error}
+ <button onClick={() => setError(null)} className="alert-close">&times;</button>
+ </div>
+ )}
+
+ {/* Detection Results */}
+ {detection && (
+ <div className="card">
+ <h3>Auto-Detection Results</h3>
+ <div className="detection-results">
+ <div className="detection-item">
+ <span className="detection-label">Language</span>
+ <span className="detection-value">{detection.language || 'Unknown'}</span>
+ </div>
+ <div className="detection-item">
+ <span className="detection-label">Framework</span>
+ <span className="detection-value">{detection.framework || 'Unknown'}</span>
+ </div>
+ <div className="detection-item">
+ <span className="detection-label">Recommended</span>
+ <span className="detection-value">{detection.build_method}</span>
+ </div>
+ <div className="detection-item">
+ <span className="detection-label">Dockerfile</span>
+ <span className={`detection-value ${detection.has_dockerfile ? 'text-success' : ''}`}>
+ {detection.has_dockerfile ? 'Found' : 'Not found'}
+ </span>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Build Configuration */}
+ <div className="card">
+ <div className="section-header">
+ <h3>Build Configuration</h3>
+ <button className="btn btn-secondary btn-sm" onClick={() => setShowConfigModal(true)}>
+ {buildConfig ? 'Edit' : 'Configure'}
+ </button>
+ </div>
+
+ {buildConfig ? (
+ <div className="info-list">
+ <div className="info-item">
+ <span className="info-label">Build Method</span>
+ <span className="info-value">{buildConfig.build_method}</span>
+ </div>
+ {buildConfig.dockerfile_path && buildConfig.build_method === 'dockerfile' && (
+ <div className="info-item">
+ <span className="info-label">Dockerfile</span>
+ <span className="info-value mono">{buildConfig.dockerfile_path}</span>
+ </div>
+ )}
+ <div className="info-item">
+ <span className="info-label">Cache</span>
+ <span className="info-value">{buildConfig.cache_enabled ? 'Enabled' : 'Disabled'}</span>
+ </div>
+ <div className="info-item">
+ <span className="info-label">Timeout</span>
+ <span className="info-value">{buildConfig.timeout}s</span>
+ </div>
+ <div className="info-item">
+ <span className="info-label">Build Count</span>
+ <span className="info-value">{buildConfig.build_count || 0}</span>
+ </div>
+ </div>
+ ) : (
+ <p className="hint">No build configuration. Click Configure to set up builds.</p>
+ )}
+
+ {buildConfig && (
+ <div className="build-actions">
+ <button
+ className="btn btn-secondary"
+ onClick={() => handleBuild(false)}
+ disabled={building || deploying}
+ >
+ {building ? 'Building...' : 'Build Only'}
+ </button>
+ <button
+ className="btn btn-primary"
+ onClick={() => handleDeploy(false)}
+ disabled={building || deploying}
+ >
+ {deploying ? 'Deploying...' : 'Build & Deploy'}
+ </button>
+ </div>
+ )}
+ </div>
+
+ {/* Current Deployment */}
+ {currentDeployment && (
+ <div className="card current-deployment">
+ <h3>Current Deployment</h3>
+ <div className="deployment-current-info">
+ <div className="deployment-version">
+ <span className="version-number">v{currentDeployment.version}</span>
+ <span className={`badge ${getStatusBadgeClass(currentDeployment.status)}`}>
+ {currentDeployment.status}
+ </span>
+ </div>
+ {currentDeployment.commit_hash && (
+ <div className="deployment-commit">
+ <span className="commit-hash mono">{currentDeployment.commit_hash.substring(0, 8)}</span>
+ {currentDeployment.commit_message && (
+ <span className="commit-message">{currentDeployment.commit_message}</span>
+ )}
+ </div>
+ )}
+ <div className="deployment-meta">
+ <span>Deployed {new Date(currentDeployment.deploy_completed_at).toLocaleString()}</span>
+ {currentDeployment.duration && (
+ <span>Duration: {formatDuration(currentDeployment.duration)}</span>
+ )}
+ </div>
+ </div>
+ <div className="deployment-actions">
+ <button
+ className="btn btn-secondary btn-sm"
+ onClick={() => handleRollback()}
+ disabled={deploying || deployments.length < 2}
+ >
+ Rollback to Previous
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Deployment History */}
+ <div className="card">
+ <div className="section-header">
+ <h3>Deployment History</h3>
+ <button className="btn btn-secondary btn-sm" onClick={loadData}>
+ Refresh
+ </button>
+ </div>
+
+ {deployments.length === 0 ? (
+ <p className="hint">No deployments yet.</p>
+ ) : (
+ <table className="table">
+ <thead>
+ <tr>
+ <th>Version</th>
+ <th>Status</th>
+ <th>Commit</th>
+ <th>Deployed</th>
+ <th>Duration</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {deployments.map(deployment => (
+ <tr key={deployment.id}>
+ <td>
+ <span className="version-tag">{deployment.version_tag || `v${deployment.version}`}</span>
+ </td>
+ <td>
+ <span className={`badge ${getStatusBadgeClass(deployment.status)}`}>
+ {deployment.status}
+ </span>
+ </td>
+ <td className="mono">
+ {deployment.commit_hash ? deployment.commit_hash.substring(0, 8) : '-'}
+ </td>
+ <td>
+ {deployment.deploy_completed_at
+ ? new Date(deployment.deploy_completed_at).toLocaleString()
+ : '-'}
+ </td>
+ <td>{formatDuration(deployment.duration)}</td>
+ <td>
+ {deployment.status !== 'live' && deployment.image_tag && (
+ <button
+ className="btn btn-secondary btn-xs"
+ onClick={() => handleRollback(deployment.version)}
+ disabled={deploying}
+ >
+ Rollback
+ </button>
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+
+ {/* Build Logs */}
+ <div className="card">
+ <div className="section-header">
+ <h3>Build Logs</h3>
+ <button className="btn btn-secondary btn-sm" onClick={loadBuildLogs}>
+ Load Logs
+ </button>
+ </div>
+
+ {buildLogs.length === 0 ? (
+ <p className="hint">Click "Load Logs" to view build history.</p>
+ ) : (
+ <div className="build-logs-list">
+ {buildLogs.map((log, index) => (
+ <div key={index} className="build-log-item" onClick={() => viewBuildLog(log.started_at)}>
+ <span className={`badge ${getStatusBadgeClass(log.status)}`}>{log.status}</span>
+ <span className="build-log-method">{log.build_method}</span>
+ <span className="build-log-time">{new Date(log.started_at).toLocaleString()}</span>
+ <span className="build-log-lines">{log.log_count} lines</span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Configure Build Modal */}
+ {showConfigModal && (
+ <div className="modal-overlay" onClick={() => setShowConfigModal(false)}>
+ <div className="modal" onClick={e => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Configure Build</h2>
+ <button className="modal-close" onClick={() => setShowConfigModal(false)}>&times;</button>
+ </div>
+ <form onSubmit={handleConfigureBuild}>
+ <div className="modal-body">
+ <div className="form-group">
+ <label>Build Method</label>
+ <select
+ value={configForm.buildMethod}
+ onChange={(e) => setConfigForm({...configForm, buildMethod: e.target.value})}
+ >
+ <option value="auto">Auto-detect</option>
+ <option value="dockerfile">Dockerfile</option>
+ <option value="nixpacks">Nixpacks</option>
+ <option value="custom">Custom Command</option>
+ </select>
+ </div>
+
+ {configForm.buildMethod === 'dockerfile' && (
+ <div className="form-group">
+ <label>Dockerfile Path</label>
+ <input
+ type="text"
+ value={configForm.dockerfilePath}
+ onChange={(e) => setConfigForm({...configForm, dockerfilePath: e.target.value})}
+ placeholder="Dockerfile"
+ />
+ </div>
+ )}
+
+ {(configForm.buildMethod === 'custom' || configForm.buildMethod === 'nixpacks') && (
+ <>
+ <div className="form-group">
+ <label>Custom Build Command</label>
+ <textarea
+ value={configForm.customBuildCmd}
+ onChange={(e) => setConfigForm({...configForm, customBuildCmd: e.target.value})}
+ placeholder="npm install && npm run build"
+ rows={2}
+ />
+ </div>
+ <div className="form-group">
+ <label>Custom Start Command</label>
+ <textarea
+ value={configForm.customStartCmd}
+ onChange={(e) => setConfigForm({...configForm, customStartCmd: e.target.value})}
+ placeholder="npm start"
+ rows={2}
+ />
+ </div>
+ </>
+ )}
+
+ <div className="form-group">
+ <label className="checkbox-label">
+ <input
+ type="checkbox"
+ checked={configForm.cacheEnabled}
+ onChange={(e) => setConfigForm({...configForm, cacheEnabled: e.target.checked})}
+ />
+ <span>Enable Build Cache</span>
+ </label>
+ </div>
+
+ <div className="form-row">
+ <div className="form-group">
+ <label>Timeout (seconds)</label>
+ <input
+ type="number"
+ value={configForm.timeout}
+ onChange={(e) => setConfigForm({...configForm, timeout: parseInt(e.target.value)})}
+ min={60}
+ max={3600}
+ />
+ </div>
+ <div className="form-group">
+ <label>Keep Deployments</label>
+ <input
+ type="number"
+ value={configForm.keepDeployments}
+ onChange={(e) => setConfigForm({...configForm, keepDeployments: parseInt(e.target.value)})}
+ min={1}
+ max={50}
+ />
+ </div>
+ </div>
+ </div>
+ <div className="modal-footer">
+ <button type="button" className="btn btn-secondary" onClick={() => setShowConfigModal(false)}>
+ Cancel
+ </button>
+ <button type="submit" className="btn btn-primary">
+ Save Configuration
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ )}
+
+ {/* Build Log Detail Modal */}
+ {showLogsModal && selectedLog && (
+ <div className="modal-overlay" onClick={() => setShowLogsModal(false)}>
+ <div className="modal modal-lg" onClick={e => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Build Log - {selectedLog.build_method}</h2>
+ <button className="modal-close" onClick={() => setShowLogsModal(false)}>&times;</button>
+ </div>
+ <div className="modal-body">
+ <div className="build-log-meta">
+ <span className={`badge ${getStatusBadgeClass(selectedLog.status)}`}>{selectedLog.status}</span>
+ <span>Started: {new Date(selectedLog.started_at).toLocaleString()}</span>
+ {selectedLog.completed_at && (
+ <span>Completed: {new Date(selectedLog.completed_at).toLocaleString()}</span>
+ )}
+ </div>
+ {selectedLog.error && (
+ <div className="alert alert-danger">{selectedLog.error}</div>
+ )}
+ <pre className="build-log-output">
+ {(selectedLog.logs || []).join('\n')}
+ </pre>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
+
const LogsTab = ({ app }) => {
const [logs, setLogs] = useState('');
const [loading, setLoading] = useState(true);
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 1ab2c026..14ac307b 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -1222,6 +1222,81 @@ class ApiService {
return this.request(`/deploy/webhook-logs?${params}`);
}
+ // ========================================
+ // Build & Deployment endpoints
+ // ========================================
+ async getBuildConfig(appId) {
+ return this.request(`/builds/apps/${appId}/build-config`);
+ }
+
+ async configureBuild(appId, config) {
+ return this.request(`/builds/apps/${appId}/build-config`, {
+ method: 'POST',
+ body: config
+ });
+ }
+
+ async removeBuildConfig(appId) {
+ return this.request(`/builds/apps/${appId}/build-config`, { method: 'DELETE' });
+ }
+
+ async detectBuildMethod(appId) {
+ return this.request(`/builds/apps/${appId}/detect`);
+ }
+
+ async getNixpacksPlan(appId) {
+ return this.request(`/builds/apps/${appId}/nixpacks-plan`);
+ }
+
+ async triggerBuild(appId, noCache = false) {
+ return this.request(`/builds/apps/${appId}/build`, {
+ method: 'POST',
+ body: { no_cache: noCache }
+ });
+ }
+
+ async getBuildLogs(appId, limit = 20) {
+ return this.request(`/builds/apps/${appId}/build-logs?limit=${limit}`);
+ }
+
+ async getBuildLogDetail(appId, timestamp) {
+ return this.request(`/builds/apps/${appId}/build-logs/${timestamp}`);
+ }
+
+ async clearBuildCache(appId) {
+ return this.request(`/builds/apps/${appId}/clear-cache`, { method: 'POST' });
+ }
+
+ async deployApp(appId, options = {}) {
+ return this.request(`/builds/apps/${appId}/deploy`, {
+ method: 'POST',
+ body: options
+ });
+ }
+
+ async getDeployments(appId, limit = 20, offset = 0) {
+ return this.request(`/builds/apps/${appId}/deployments?limit=${limit}&offset=${offset}`);
+ }
+
+ async getDeploymentDetail(deploymentId, includeLogs = false) {
+ return this.request(`/builds/deployments/${deploymentId}?include_logs=${includeLogs}`);
+ }
+
+ async getDeploymentDiff(deploymentId) {
+ return this.request(`/builds/deployments/${deploymentId}/diff`);
+ }
+
+ async rollback(appId, targetVersion = null) {
+ return this.request(`/builds/apps/${appId}/rollback`, {
+ method: 'POST',
+ body: targetVersion ? { version: targetVersion } : {}
+ });
+ }
+
+ async getCurrentDeployment(appId) {
+ return this.request(`/builds/apps/${appId}/current-deployment`);
+ }
+
// ========================================
// File Manager endpoints
// ========================================
diff --git a/frontend/src/styles/components/_build.less b/frontend/src/styles/components/_build.less
new file mode 100644
index 00000000..9f48d01f
--- /dev/null
+++ b/frontend/src/styles/components/_build.less
@@ -0,0 +1,272 @@
+// ============================================
+// BUILD TAB STYLES
+// ============================================
+
+// Build Tab Container
+.build-tab {
+ display: flex;
+ flex-direction: column;
+ gap: @space-6;
+}
+
+// Detection Results
+.detection-results {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
+ gap: @space-4;
+ margin-top: @space-4;
+}
+
+.detection-item {
+ display: flex;
+ flex-direction: column;
+ gap: @space-1;
+}
+
+.detection-label {
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+}
+
+.detection-value {
+ font-size: @font-size-md;
+ font-weight: @font-weight-medium;
+ color: @text-primary;
+ text-transform: capitalize;
+
+ &.text-success {
+ color: @success;
+ }
+}
+
+// Build Actions
+.build-actions {
+ display: flex;
+ gap: @space-3;
+ margin-top: @space-4;
+ padding-top: @space-4;
+ border-top: 1px solid @border-subtle;
+}
+
+// Info List
+.info-list {
+ display: flex;
+ flex-direction: column;
+ gap: @space-3;
+}
+
+.info-item {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: @space-2 0;
+ border-bottom: 1px solid @border-subtle;
+
+ &:last-child {
+ border-bottom: none;
+ }
+}
+
+.info-label {
+ font-size: @font-size-sm;
+ color: @text-secondary;
+}
+
+.info-value {
+ font-size: @font-size-sm;
+ font-weight: @font-weight-medium;
+ color: @text-primary;
+
+ &.mono {
+ font-family: @font-mono;
+ }
+}
+
+// Current Deployment Card
+.current-deployment {
+ background: linear-gradient(135deg, fade(@success, 5%), fade(@accent-primary, 5%));
+ border-color: fade(@success, 30%);
+
+ .deployment-current-info {
+ display: flex;
+ flex-direction: column;
+ gap: @space-3;
+ margin-top: @space-4;
+ }
+
+ .deployment-version {
+ display: flex;
+ align-items: center;
+ gap: @space-3;
+ }
+
+ .version-number {
+ font-size: @font-size-2xl;
+ font-weight: @font-weight-bold;
+ color: @text-primary;
+ }
+
+ .deployment-commit {
+ display: flex;
+ align-items: center;
+ gap: @space-2;
+ }
+
+ .commit-hash {
+ font-family: @font-mono;
+ font-size: @font-size-sm;
+ padding: @space-1 @space-2;
+ background: @bg-hover;
+ border-radius: @radius-sm;
+ }
+
+ .commit-message {
+ font-size: @font-size-sm;
+ color: @text-secondary;
+ max-width: 400px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .deployment-meta {
+ display: flex;
+ gap: @space-4;
+ font-size: @font-size-sm;
+ color: @text-tertiary;
+ }
+
+ .deployment-actions {
+ margin-top: @space-4;
+ padding-top: @space-4;
+ border-top: 1px solid @border-subtle;
+ }
+}
+
+// Deployment History Table
+.version-tag {
+ font-family: @font-mono;
+ font-size: @font-size-sm;
+ font-weight: @font-weight-medium;
+}
+
+// Build Logs List
+.build-logs-list {
+ display: flex;
+ flex-direction: column;
+ gap: @space-2;
+}
+
+.build-log-item {
+ display: flex;
+ align-items: center;
+ gap: @space-3;
+ padding: @space-3;
+ background: @bg-hover;
+ border-radius: @radius-md;
+ cursor: pointer;
+ transition: all @transition-fast;
+
+ &:hover {
+ background: @bg-card;
+ box-shadow: @shadow-sm;
+ }
+
+ .build-log-method {
+ font-size: @font-size-sm;
+ font-weight: @font-weight-medium;
+ color: @text-primary;
+ text-transform: capitalize;
+ }
+
+ .build-log-time {
+ font-size: @font-size-sm;
+ color: @text-secondary;
+ }
+
+ .build-log-lines {
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+ margin-left: auto;
+ }
+}
+
+// Build Log Modal
+.build-log-meta {
+ display: flex;
+ align-items: center;
+ gap: @space-4;
+ margin-bottom: @space-4;
+ padding-bottom: @space-4;
+ border-bottom: 1px solid @border-subtle;
+ flex-wrap: wrap;
+
+ span {
+ font-size: @font-size-sm;
+ color: @text-secondary;
+ }
+}
+
+.build-log-output {
+ margin: 0;
+ padding: @space-4;
+ background: @bg-body;
+ border-radius: @radius-md;
+ font-family: @font-mono;
+ font-size: @font-size-sm;
+ line-height: @line-height-relaxed;
+ color: @text-primary;
+ max-height: 500px;
+ overflow: auto;
+ white-space: pre-wrap;
+ word-break: break-all;
+}
+
+// Modal Large
+.modal-lg {
+ max-width: 900px;
+ width: 90%;
+}
+
+// Alert with close button
+.alert {
+ position: relative;
+ padding: @space-4;
+ border-radius: @radius-md;
+ margin-bottom: @space-4;
+
+ &-danger {
+ background: @danger-bg;
+ border: 1px solid @danger-border;
+ color: @danger;
+ }
+
+ &-close {
+ position: absolute;
+ top: @space-2;
+ right: @space-3;
+ background: none;
+ border: none;
+ font-size: @font-size-lg;
+ color: inherit;
+ opacity: 0.6;
+ cursor: pointer;
+
+ &:hover {
+ opacity: 1;
+ }
+ }
+}
+
+// Button extra small
+.btn-xs {
+ padding: @space-1 @space-2;
+ font-size: @font-size-xs;
+}
+
+// Utility classes
+.mono {
+ font-family: @font-mono;
+}
diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.less
index c84ca9b3..5848fdb1 100644
--- a/frontend/src/styles/main.less
+++ b/frontend/src/styles/main.less
@@ -45,6 +45,7 @@
@import 'components/_notifications';
@import 'components/_query-runner';
@import 'components/_deploy';
+@import 'components/_build';
// --------------------------------------------
// 5. PAGE-SPECIFIC STYLES