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 remote Docker Compose management support

Juan Denis4a34349ed406
diff --git a/agent/agent.exe b/agent/agent.exe
new file mode 100644
index 00000000..0f316df4
Binary files /dev/null and b/agent/agent.exe differ
diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.go
index a4115038..3cc50354 100644
--- a/agent/internal/agent/agent.go
+++ b/agent/internal/agent/agent.go
@@ -105,6 +105,15 @@ func (a *Agent) registerHandlers() {
// Docker network commands
a.handlers[protocol.ActionDockerNetworkList] = a.handleDockerNetworkList
+
+ // Docker compose commands
+ a.handlers[protocol.ActionDockerComposeList] = a.handleDockerComposeList
+ a.handlers[protocol.ActionDockerComposePs] = a.handleDockerComposePs
+ a.handlers[protocol.ActionDockerComposeUp] = a.handleDockerComposeUp
+ a.handlers[protocol.ActionDockerComposeDown] = a.handleDockerComposeDown
+ a.handlers[protocol.ActionDockerComposeLogs] = a.handleDockerComposeLogs
+ a.handlers[protocol.ActionDockerComposeRestart] = a.handleDockerComposeRestart
+ a.handlers[protocol.ActionDockerComposePull] = a.handleDockerComposePull
}
// System commands
@@ -554,3 +563,147 @@ func (a *Agent) handleSystemInfo(ctx context.Context, params json.RawMessage) (i
func (a *Agent) handleSystemProcesses(ctx context.Context, params json.RawMessage) (interface{}, error) {
return a.metrics.ListProcesses(ctx)
}
+
+// Docker Compose command handlers
+
+func (a *Agent) handleDockerComposeList(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ return a.docker.ComposeList(ctx)
+}
+
+func (a *Agent) handleDockerComposePs(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ProjectPath string `json:"project_path"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ return a.docker.ComposePsProject(ctx, p.ProjectPath)
+}
+
+func (a *Agent) handleDockerComposeUp(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ProjectPath string `json:"project_path"`
+ Detach bool `json:"detach"`
+ Build bool `json:"build"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+
+ // Default to detached mode
+ if !p.Detach {
+ p.Detach = true
+ }
+
+ output, err := a.docker.ComposeUp(ctx, p.ProjectPath, p.Detach, p.Build)
+ if err != nil {
+ return map[string]interface{}{
+ "success": false,
+ "output": output,
+ "error": err.Error(),
+ }, nil
+ }
+
+ return map[string]interface{}{
+ "success": true,
+ "output": output,
+ }, nil
+}
+
+func (a *Agent) handleDockerComposeDown(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ProjectPath string `json:"project_path"`
+ Volumes bool `json:"volumes"`
+ RemoveOrphans bool `json:"remove_orphans"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+
+ output, err := a.docker.ComposeDown(ctx, p.ProjectPath, p.Volumes, p.RemoveOrphans)
+ if err != nil {
+ return map[string]interface{}{
+ "success": false,
+ "output": output,
+ "error": err.Error(),
+ }, nil
+ }
+
+ return map[string]interface{}{
+ "success": true,
+ "output": output,
+ }, nil
+}
+
+func (a *Agent) handleDockerComposeLogs(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ProjectPath string `json:"project_path"`
+ Service string `json:"service"`
+ Tail int `json:"tail"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+
+ // Default tail to 100
+ if p.Tail == 0 {
+ p.Tail = 100
+ }
+
+ logs, err := a.docker.ComposeLogs(ctx, p.ProjectPath, p.Service, p.Tail)
+ if err != nil {
+ return nil, err
+ }
+
+ return map[string]interface{}{
+ "logs": logs,
+ }, nil
+}
+
+func (a *Agent) handleDockerComposeRestart(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ProjectPath string `json:"project_path"`
+ Service string `json:"service"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+
+ output, err := a.docker.ComposeRestart(ctx, p.ProjectPath, p.Service)
+ if err != nil {
+ return map[string]interface{}{
+ "success": false,
+ "output": output,
+ "error": err.Error(),
+ }, nil
+ }
+
+ return map[string]interface{}{
+ "success": true,
+ "output": output,
+ }, nil
+}
+
+func (a *Agent) handleDockerComposePull(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ProjectPath string `json:"project_path"`
+ Service string `json:"service"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+
+ output, err := a.docker.ComposePull(ctx, p.ProjectPath, p.Service)
+ if err != nil {
+ return map[string]interface{}{
+ "success": false,
+ "output": output,
+ "error": err.Error(),
+ }, nil
+ }
+
+ return map[string]interface{}{
+ "success": true,
+ "output": output,
+ }, nil
+}
diff --git a/agent/internal/docker/client.go b/agent/internal/docker/client.go
index 8f5d0ea6..beaf28bc 100644
--- a/agent/internal/docker/client.go
+++ b/agent/internal/docker/client.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
+ "os/exec"
"strings"
"github.com/docker/docker/api/types"
@@ -447,3 +448,206 @@ func calculateCPUPercent(stats *types.StatsJSON) float64 {
return 0.0
}
+// ==================== Docker Compose ====================
+
+// ComposeProject represents a Docker Compose project
+type ComposeProject struct {
+ Name string `json:"name"`
+ Status string `json:"status"`
+ ConfigFiles string `json:"config_files"`
+}
+
+// ComposeContainer represents a container in a compose project
+type ComposeContainer struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Service string `json:"service"`
+ State string `json:"state"`
+ Status string `json:"status"`
+ Ports string `json:"ports"`
+}
+
+// ComposeList lists all compose projects
+func (c *Client) ComposeList(ctx context.Context) ([]ComposeProject, error) {
+ cmd := exec.CommandContext(ctx, "docker", "compose", "ls", "--format", "json")
+ output, err := cmd.Output()
+ if err != nil {
+ return nil, fmt.Errorf("failed to list compose projects: %w", err)
+ }
+
+ var projects []ComposeProject
+ if err := json.Unmarshal(output, &projects); err != nil {
+ return nil, fmt.Errorf("failed to parse compose projects: %w", err)
+ }
+
+ return projects, nil
+}
+
+// ComposePsProject lists containers for a specific compose project
+func (c *Client) ComposePsProject(ctx context.Context, projectPath string) ([]ComposeContainer, error) {
+ if err := validateProjectPath(projectPath); err != nil {
+ return nil, err
+ }
+
+ cmd := exec.CommandContext(ctx, "docker", "compose", "-f", projectPath, "ps", "--format", "json", "-a")
+ output, err := cmd.Output()
+ if err != nil {
+ return nil, fmt.Errorf("failed to list compose containers: %w", err)
+ }
+
+ // Handle empty output
+ if len(output) == 0 {
+ return []ComposeContainer{}, nil
+ }
+
+ // Docker compose ps can return either a JSON array or line-delimited JSON objects
+ var containers []ComposeContainer
+
+ // Try parsing as JSON array first
+ if err := json.Unmarshal(output, &containers); err != nil {
+ // Try line-by-line JSON parsing
+ lines := strings.Split(string(output), "\n")
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
+ if line == "" {
+ continue
+ }
+ var container ComposeContainer
+ if err := json.Unmarshal([]byte(line), &container); err != nil {
+ continue
+ }
+ containers = append(containers, container)
+ }
+ }
+
+ return containers, nil
+}
+
+// ComposeUp starts a compose project
+func (c *Client) ComposeUp(ctx context.Context, projectPath string, detach, build bool) (string, error) {
+ if err := validateProjectPath(projectPath); err != nil {
+ return "", err
+ }
+
+ args := []string{"compose", "-f", projectPath, "up"}
+ if detach {
+ args = append(args, "-d")
+ }
+ if build {
+ args = append(args, "--build")
+ }
+
+ cmd := exec.CommandContext(ctx, "docker", args...)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ return string(output), fmt.Errorf("compose up failed: %w: %s", err, output)
+ }
+
+ return string(output), nil
+}
+
+// ComposeDown stops a compose project
+func (c *Client) ComposeDown(ctx context.Context, projectPath string, volumes, removeOrphans bool) (string, error) {
+ if err := validateProjectPath(projectPath); err != nil {
+ return "", err
+ }
+
+ args := []string{"compose", "-f", projectPath, "down"}
+ if volumes {
+ args = append(args, "-v")
+ }
+ if removeOrphans {
+ args = append(args, "--remove-orphans")
+ }
+
+ cmd := exec.CommandContext(ctx, "docker", args...)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ return string(output), fmt.Errorf("compose down failed: %w: %s", err, output)
+ }
+
+ return string(output), nil
+}
+
+// ComposeLogs gets logs from a compose project
+func (c *Client) ComposeLogs(ctx context.Context, projectPath, service string, tail int) (string, error) {
+ if err := validateProjectPath(projectPath); err != nil {
+ return "", err
+ }
+
+ args := []string{"compose", "-f", projectPath, "logs", "--no-color"}
+ if tail > 0 {
+ args = append(args, "--tail", fmt.Sprintf("%d", tail))
+ }
+ if service != "" {
+ args = append(args, service)
+ }
+
+ cmd := exec.CommandContext(ctx, "docker", args...)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ return string(output), fmt.Errorf("compose logs failed: %w: %s", err, output)
+ }
+
+ return string(output), nil
+}
+
+// ComposeRestart restarts a compose project or specific service
+func (c *Client) ComposeRestart(ctx context.Context, projectPath, service string) (string, error) {
+ if err := validateProjectPath(projectPath); err != nil {
+ return "", err
+ }
+
+ args := []string{"compose", "-f", projectPath, "restart"}
+ if service != "" {
+ args = append(args, service)
+ }
+
+ cmd := exec.CommandContext(ctx, "docker", args...)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ return string(output), fmt.Errorf("compose restart failed: %w: %s", err, output)
+ }
+
+ return string(output), nil
+}
+
+// ComposePull pulls images for a compose project
+func (c *Client) ComposePull(ctx context.Context, projectPath, service string) (string, error) {
+ if err := validateProjectPath(projectPath); err != nil {
+ return "", err
+ }
+
+ args := []string{"compose", "-f", projectPath, "pull"}
+ if service != "" {
+ args = append(args, service)
+ }
+
+ cmd := exec.CommandContext(ctx, "docker", args...)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ return string(output), fmt.Errorf("compose pull failed: %w: %s", err, output)
+ }
+
+ return string(output), nil
+}
+
+// validateProjectPath validates the project path to prevent path traversal attacks
+func validateProjectPath(projectPath string) error {
+ if projectPath == "" {
+ return fmt.Errorf("project path is required")
+ }
+
+ // Check for path traversal attempts
+ if strings.Contains(projectPath, "..") {
+ return fmt.Errorf("invalid project path: path traversal not allowed")
+ }
+
+ // Check if path is absolute
+ if !strings.HasPrefix(projectPath, "/") {
+ return fmt.Errorf("invalid project path: must be absolute path")
+ }
+
+ return nil
+}
+
diff --git a/agent/pkg/protocol/messages.go b/agent/pkg/protocol/messages.go
index 74644a2a..e713f81f 100644
--- a/agent/pkg/protocol/messages.go
+++ b/agent/pkg/protocol/messages.go
@@ -180,9 +180,13 @@ const (
ActionDockerNetworkRemove = "docker:network:remove"
// Docker compose actions
- ActionDockerComposeList = "docker:compose:list"
- ActionDockerComposeUp = "docker:compose:up"
- ActionDockerComposeDown = "docker:compose:down"
+ ActionDockerComposeList = "docker:compose:list"
+ ActionDockerComposePs = "docker:compose:ps"
+ ActionDockerComposeUp = "docker:compose:up"
+ ActionDockerComposeDown = "docker:compose:down"
+ ActionDockerComposeLogs = "docker:compose:logs"
+ ActionDockerComposeRestart = "docker:compose:restart"
+ ActionDockerComposePull = "docker:compose:pull"
// System actions
ActionSystemMetrics = "system:metrics"
diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py
index 9a25218b..28cf76ec 100644
--- a/backend/app/api/servers.py
+++ b/backend/app/api/servers.py
@@ -866,6 +866,166 @@ def get_remote_system_info(server_id):
return jsonify(result.get('data'))
+# ==================== Remote Docker Compose Operations ====================
+
+@servers_bp.route('/<server_id>/docker/compose/projects', methods=['GET'])
+@jwt_required()
+def list_remote_compose_projects(server_id):
+ """List compose projects on a remote server"""
+ user_id = get_jwt_identity()
+
+ result = RemoteDockerService.compose_list(server_id, user_id=user_id)
+
+ if not result.get('success'):
+ return jsonify(result), 500 if result.get('code') != 'AGENT_OFFLINE' else 503
+
+ return jsonify(result.get('data', []))
+
+
+@servers_bp.route('/<server_id>/docker/compose/ps', methods=['POST'])
+@jwt_required()
+def remote_compose_ps(server_id):
+ """List containers for a compose project"""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ if not data or not data.get('project_path'):
+ return jsonify({'error': 'project_path is required'}), 400
+
+ result = RemoteDockerService.compose_ps(
+ server_id,
+ data['project_path'],
+ user_id=user_id
+ )
+
+ if not result.get('success'):
+ return jsonify(result), 500
+
+ return jsonify(result.get('data', []))
+
+
+@servers_bp.route('/<server_id>/docker/compose/up', methods=['POST'])
+@jwt_required()
+@developer_required
+def remote_compose_up(server_id):
+ """Start a compose project"""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ if not data or not data.get('project_path'):
+ return jsonify({'error': 'project_path is required'}), 400
+
+ result = RemoteDockerService.compose_up(
+ server_id,
+ data['project_path'],
+ detach=data.get('detach', True),
+ build=data.get('build', False),
+ user_id=user_id
+ )
+
+ if not result.get('success'):
+ return jsonify(result), 500
+
+ return jsonify(result)
+
+
+@servers_bp.route('/<server_id>/docker/compose/down', methods=['POST'])
+@jwt_required()
+@developer_required
+def remote_compose_down(server_id):
+ """Stop a compose project"""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ if not data or not data.get('project_path'):
+ return jsonify({'error': 'project_path is required'}), 400
+
+ result = RemoteDockerService.compose_down(
+ server_id,
+ data['project_path'],
+ volumes=data.get('volumes', False),
+ remove_orphans=data.get('remove_orphans', True),
+ user_id=user_id
+ )
+
+ if not result.get('success'):
+ return jsonify(result), 500
+
+ return jsonify(result)
+
+
+@servers_bp.route('/<server_id>/docker/compose/logs', methods=['POST'])
+@jwt_required()
+def remote_compose_logs(server_id):
+ """Get logs from a compose project"""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ if not data or not data.get('project_path'):
+ return jsonify({'error': 'project_path is required'}), 400
+
+ result = RemoteDockerService.compose_logs(
+ server_id,
+ data['project_path'],
+ service=data.get('service'),
+ tail=data.get('tail', 100),
+ user_id=user_id
+ )
+
+ if not result.get('success'):
+ return jsonify(result), 500
+
+ return jsonify(result.get('data'))
+
+
+@servers_bp.route('/<server_id>/docker/compose/restart', methods=['POST'])
+@jwt_required()
+@developer_required
+def remote_compose_restart(server_id):
+ """Restart a compose project or specific service"""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ if not data or not data.get('project_path'):
+ return jsonify({'error': 'project_path is required'}), 400
+
+ result = RemoteDockerService.compose_restart(
+ server_id,
+ data['project_path'],
+ service=data.get('service'),
+ user_id=user_id
+ )
+
+ if not result.get('success'):
+ return jsonify(result), 500
+
+ return jsonify(result)
+
+
+@servers_bp.route('/<server_id>/docker/compose/pull', methods=['POST'])
+@jwt_required()
+@developer_required
+def remote_compose_pull(server_id):
+ """Pull images for a compose project"""
+ user_id = get_jwt_identity()
+ data = request.get_json()
+
+ if not data or not data.get('project_path'):
+ return jsonify({'error': 'project_path is required'}), 400
+
+ result = RemoteDockerService.compose_pull(
+ server_id,
+ data['project_path'],
+ service=data.get('service'),
+ user_id=user_id
+ )
+
+ if not result.get('success'):
+ return jsonify(result), 500
+
+ return jsonify(result)
+
+
# ==================== Installation Scripts ====================
def _get_scripts_dir():
diff --git a/backend/app/services/remote_docker_service.py b/backend/app/services/remote_docker_service.py
index b51369a7..3affcce8 100644
--- a/backend/app/services/remote_docker_service.py
+++ b/backend/app/services/remote_docker_service.py
@@ -412,3 +412,235 @@ class RemoteDockerService:
})
return servers
+
+ # ==================== Docker Compose ====================
+
+ @staticmethod
+ def compose_list(server_id: str, user_id: int = None) -> Dict[str, Any]:
+ """
+ List compose projects on a remote server.
+
+ Args:
+ server_id: Target server ID
+ user_id: User ID for audit logging
+
+ Returns:
+ dict: {success, data: [projects], error}
+ """
+ if not server_id or server_id == 'local':
+ from app.services.docker_service import DockerService
+ try:
+ projects = DockerService.compose_list()
+ return {'success': True, 'data': projects}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ return agent_registry.send_command(
+ server_id=server_id,
+ action='docker:compose:list',
+ params={},
+ user_id=user_id
+ )
+
+ @staticmethod
+ def compose_ps(server_id: str, project_path: str, user_id: int = None) -> Dict[str, Any]:
+ """
+ List containers for a compose project.
+
+ Args:
+ server_id: Target server ID
+ project_path: Path to docker-compose.yml
+ user_id: User ID for audit logging
+
+ Returns:
+ dict: {success, data: [containers], error}
+ """
+ if not server_id or server_id == 'local':
+ from app.services.docker_service import DockerService
+ try:
+ containers = DockerService.compose_ps(project_path)
+ return {'success': True, 'data': containers}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ return agent_registry.send_command(
+ server_id=server_id,
+ action='docker:compose:ps',
+ params={'project_path': project_path},
+ user_id=user_id
+ )
+
+ @staticmethod
+ def compose_up(server_id: str, project_path: str, detach: bool = True,
+ build: bool = False, user_id: int = None) -> Dict[str, Any]:
+ """
+ Start a compose project.
+
+ Args:
+ server_id: Target server ID
+ project_path: Path to docker-compose.yml
+ detach: Run in detached mode
+ build: Build images before starting
+ user_id: User ID for audit logging
+
+ Returns:
+ dict: {success, output, error}
+ """
+ if not server_id or server_id == 'local':
+ from app.services.docker_service import DockerService
+ try:
+ result = DockerService.compose_up(project_path, detach=detach, build=build)
+ return {'success': True, 'data': result}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ return agent_registry.send_command(
+ server_id=server_id,
+ action='docker:compose:up',
+ params={
+ 'project_path': project_path,
+ 'detach': detach,
+ 'build': build
+ },
+ timeout=300.0, # 5 minutes for compose up
+ user_id=user_id
+ )
+
+ @staticmethod
+ def compose_down(server_id: str, project_path: str, volumes: bool = False,
+ remove_orphans: bool = True, user_id: int = None) -> Dict[str, Any]:
+ """
+ Stop a compose project.
+
+ Args:
+ server_id: Target server ID
+ project_path: Path to docker-compose.yml
+ volumes: Remove volumes
+ remove_orphans: Remove orphan containers
+ user_id: User ID for audit logging
+
+ Returns:
+ dict: {success, output, error}
+ """
+ if not server_id or server_id == 'local':
+ from app.services.docker_service import DockerService
+ try:
+ result = DockerService.compose_down(project_path, volumes=volumes, remove_orphans=remove_orphans)
+ return {'success': True, 'data': result}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ return agent_registry.send_command(
+ server_id=server_id,
+ action='docker:compose:down',
+ params={
+ 'project_path': project_path,
+ 'volumes': volumes,
+ 'remove_orphans': remove_orphans
+ },
+ timeout=120.0, # 2 minutes for compose down
+ user_id=user_id
+ )
+
+ @staticmethod
+ def compose_logs(server_id: str, project_path: str, service: str = None,
+ tail: int = 100, user_id: int = None) -> Dict[str, Any]:
+ """
+ Get logs from a compose project.
+
+ Args:
+ server_id: Target server ID
+ project_path: Path to docker-compose.yml
+ service: Specific service name (optional)
+ tail: Number of lines to retrieve
+ user_id: User ID for audit logging
+
+ Returns:
+ dict: {success, data: {logs: str}, error}
+ """
+ if not server_id or server_id == 'local':
+ from app.services.docker_service import DockerService
+ try:
+ logs = DockerService.compose_logs(project_path, service=service, tail=tail)
+ return {'success': True, 'data': {'logs': logs}}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ return agent_registry.send_command(
+ server_id=server_id,
+ action='docker:compose:logs',
+ params={
+ 'project_path': project_path,
+ 'service': service or '',
+ 'tail': tail
+ },
+ timeout=30.0,
+ user_id=user_id
+ )
+
+ @staticmethod
+ def compose_restart(server_id: str, project_path: str, service: str = None,
+ user_id: int = None) -> Dict[str, Any]:
+ """
+ Restart a compose project or specific service.
+
+ Args:
+ server_id: Target server ID
+ project_path: Path to docker-compose.yml
+ service: Specific service name (optional)
+ user_id: User ID for audit logging
+
+ Returns:
+ dict: {success, output, error}
+ """
+ if not server_id or server_id == 'local':
+ from app.services.docker_service import DockerService
+ try:
+ result = DockerService.compose_restart(project_path, service=service)
+ return {'success': True, 'data': result}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ return agent_registry.send_command(
+ server_id=server_id,
+ action='docker:compose:restart',
+ params={
+ 'project_path': project_path,
+ 'service': service or ''
+ },
+ user_id=user_id
+ )
+
+ @staticmethod
+ def compose_pull(server_id: str, project_path: str, service: str = None,
+ user_id: int = None) -> Dict[str, Any]:
+ """
+ Pull images for a compose project.
+
+ Args:
+ server_id: Target server ID
+ project_path: Path to docker-compose.yml
+ service: Specific service name (optional)
+ user_id: User ID for audit logging
+
+ Returns:
+ dict: {success, output, error}
+ """
+ if not server_id or server_id == 'local':
+ from app.services.docker_service import DockerService
+ try:
+ result = DockerService.compose_pull(project_path, service=service)
+ return {'success': True, 'data': result}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ return agent_registry.send_command(
+ server_id=server_id,
+ action='docker:compose:pull',
+ params={
+ 'project_path': project_path,
+ 'service': service or ''
+ },
+ timeout=300.0, # 5 minutes for pull
+ user_id=user_id
+ )
diff --git a/frontend/src/pages/Docker.jsx b/frontend/src/pages/Docker.jsx
index 2d87c39d..88142784 100644
--- a/frontend/src/pages/Docker.jsx
+++ b/frontend/src/pages/Docker.jsx
@@ -188,6 +188,7 @@ const Docker = () => {
const tabs = [
{ id: 'containers', label: 'Containers' },
+ { id: 'compose', label: 'Compose' },
{ id: 'images', label: 'Images' },
{ id: 'volumes', label: 'Volumes' },
{ id: 'networks', label: 'Networks' }
@@ -277,6 +278,7 @@ const Docker = () => {
<div className="docker-panel-content">
{activeTab === 'containers' && <ContainersTab onStatsChange={loadStats} />}
+ {activeTab === 'compose' && <ComposeTab onStatsChange={loadStats} />}
{activeTab === 'images' && <ImagesTab onStatsChange={loadStats} />}
{activeTab === 'networks' && <NetworksTab onStatsChange={loadStats} />}
{activeTab === 'volumes' && <VolumesTab onStatsChange={loadStats} />}
@@ -1012,6 +1014,332 @@ const VolumesTab = ({ onStatsChange }) => {
);
};
+// Compose Tab
+const ComposeTab = ({ onStatsChange }) => {
+ const toast = useToast();
+ const { serverId, isRemote } = useServer();
+ const [projects, setProjects] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [selectedProject, setSelectedProject] = useState(null);
+ const [logsProject, setLogsProject] = useState(null);
+ const [actionLoading, setActionLoading] = useState({});
+
+ useEffect(() => {
+ loadProjects();
+ }, [serverId]);
+
+ async function loadProjects() {
+ setLoading(true);
+ try {
+ let data;
+ if (isRemote) {
+ data = await api.getRemoteComposeProjects(serverId);
+ } else {
+ data = await api.request('/docker/compose/list');
+ }
+ setProjects(Array.isArray(data) ? data : data.projects || []);
+ } catch (err) {
+ console.error('Failed to load compose projects:', err);
+ setProjects([]);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function handleAction(project, action) {
+ const projectPath = project.ConfigFiles || project.config_files;
+ if (!projectPath) {
+ toast.error('Project path not found');
+ return;
+ }
+
+ setActionLoading(prev => ({ ...prev, [project.Name || project.name]: true }));
+
+ try {
+ let result;
+ if (action === 'up') {
+ if (isRemote) {
+ result = await api.remoteComposeUp(serverId, projectPath);
+ } else {
+ result = await api.composeUp(projectPath, true, false);
+ }
+ toast.success('Project started');
+ } else if (action === 'down') {
+ if (!confirm('Stop this compose project? Containers will be removed.')) {
+ setActionLoading(prev => ({ ...prev, [project.Name || project.name]: false }));
+ return;
+ }
+ if (isRemote) {
+ result = await api.remoteComposeDown(serverId, projectPath);
+ } else {
+ result = await api.composeDown(projectPath, false, true);
+ }
+ toast.success('Project stopped');
+ } else if (action === 'restart') {
+ if (isRemote) {
+ result = await api.remoteComposeRestart(serverId, projectPath);
+ } else {
+ result = await api.composeRestart(projectPath);
+ }
+ toast.success('Project restarted');
+ } else if (action === 'pull') {
+ if (isRemote) {
+ result = await api.remoteComposePull(serverId, projectPath);
+ } else {
+ result = await api.composePull(projectPath);
+ }
+ toast.success('Images pulled');
+ }
+ loadProjects();
+ onStatsChange?.();
+ } catch (err) {
+ console.error(`Failed to ${action} project:`, err);
+ toast.error(err.message || `Failed to ${action} project`);
+ } finally {
+ setActionLoading(prev => ({ ...prev, [project.Name || project.name]: false }));
+ }
+ }
+
+ function getProjectStatus(project) {
+ const status = project.Status || project.status || '';
+ if (status.includes('running')) return 'running';
+ if (status.includes('exited') || status.includes('stopped')) return 'exited';
+ return 'unknown';
+ }
+
+ function parseRunningCount(status) {
+ // Parse status like "running(3)" or "exited(2), running(1)"
+ const match = status.match(/running\((\d+)\)/);
+ return match ? parseInt(match[1], 10) : 0;
+ }
+
+ if (loading) {
+ return <div className="docker-loading">Loading compose projects...</div>;
+ }
+
+ return (
+ <div>
+ <div className="docker-table-header">
+ <div className="docker-table-info">
+ {projects.length} project{projects.length !== 1 ? 's' : ''} found
+ </div>
+ <button className="btn btn-secondary btn-sm" onClick={loadProjects}>
+ Refresh
+ </button>
+ </div>
+
+ {projects.length === 0 ? (
+ <div className="docker-empty">
+ <h3>No Compose Projects</h3>
+ <p>No Docker Compose projects are running on this server.</p>
+ <p className="text-muted">
+ Start a compose project with <code>docker compose up -d</code>
+ </p>
+ </div>
+ ) : (
+ <table className="docker-table">
+ <thead>
+ <tr>
+ <th>Project</th>
+ <th>Status</th>
+ <th>Config File</th>
+ <th style={{ textAlign: 'right' }}>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {projects.map(project => {
+ const name = project.Name || project.name;
+ const status = project.Status || project.status || 'unknown';
+ const configFiles = project.ConfigFiles || project.config_files || '';
+ const isRunning = getProjectStatus(project) === 'running';
+ const runningCount = parseRunningCount(status);
+ const isLoading = actionLoading[name];
+
+ return (
+ <tr key={name}>
+ <td>
+ <span className="docker-container-name">{name}</span>
+ </td>
+ <td>
+ <span className={`docker-status-pill ${isRunning ? 'running' : 'exited'}`}>
+ <span className="docker-status-dot" />
+ {isRunning ? `Running (${runningCount})` : 'Stopped'}
+ </span>
+ <div className="docker-status-detail">{status}</div>
+ </td>
+ <td>
+ <span className="docker-container-id" style={{ maxWidth: '300px', display: 'inline-block', overflow: 'hidden', textOverflow: 'ellipsis' }}>
+ {configFiles}
+ </span>
+ </td>
+ <td className="docker-actions-cell">
+ <IconAction
+ title="Logs"
+ onClick={() => setLogsProject(project)}
+ disabled={isLoading}
+ >
+ <LogsIcon />
+ </IconAction>
+ {isRunning ? (
+ <>
+ <IconAction
+ title="Restart"
+ onClick={() => handleAction(project, 'restart')}
+ disabled={isLoading}
+ >
+ <RestartIcon />
+ </IconAction>
+ <IconAction
+ title="Stop"
+ onClick={() => handleAction(project, 'down')}
+ disabled={isLoading}
+ color="#EF4444"
+ >
+ <StopIcon />
+ </IconAction>
+ </>
+ ) : (
+ <IconAction
+ title="Start"
+ onClick={() => handleAction(project, 'up')}
+ disabled={isLoading}
+ color="#10B981"
+ >
+ <PlayIcon />
+ </IconAction>
+ )}
+ <IconAction
+ title="Pull Images"
+ onClick={() => handleAction(project, 'pull')}
+ disabled={isLoading}
+ >
+ <DownloadIcon />
+ </IconAction>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ )}
+
+ {logsProject && (
+ <ComposeLogsModal
+ project={logsProject}
+ onClose={() => setLogsProject(null)}
+ />
+ )}
+ </div>
+ );
+};
+
+// Download Icon for Compose Pull
+const DownloadIcon = () => (
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
+ <polyline points="7 10 12 15 17 10"/>
+ <line x1="12" y1="15" x2="12" y2="3"/>
+ </svg>
+);
+
+// Compose Logs Modal
+const ComposeLogsModal = ({ project, onClose }) => {
+ const { serverId, isRemote } = useServer();
+ const [logs, setLogs] = useState('');
+ const [loading, setLoading] = useState(true);
+ const [tail, setTail] = useState(200);
+ const [selectedService, setSelectedService] = useState('');
+ const [services, setServices] = useState([]);
+
+ const projectName = project.Name || project.name;
+ const projectPath = project.ConfigFiles || project.config_files || '';
+
+ useEffect(() => {
+ loadServices();
+ loadLogs();
+ }, [project, tail, selectedService]);
+
+ async function loadServices() {
+ try {
+ let containers;
+ if (isRemote) {
+ containers = await api.getRemoteComposePs(serverId, projectPath);
+ } else {
+ const result = await api.composePs(projectPath);
+ containers = result.containers || result || [];
+ }
+
+ // Extract unique service names
+ const serviceNames = [...new Set(
+ (Array.isArray(containers) ? containers : [])
+ .map(c => c.Service || c.service)
+ .filter(Boolean)
+ )];
+ setServices(serviceNames);
+ } catch (err) {
+ console.error('Failed to load services:', err);
+ }
+ }
+
+ async function loadLogs() {
+ setLoading(true);
+ try {
+ let data;
+ if (isRemote) {
+ data = await api.remoteComposeLogs(serverId, projectPath, selectedService || null, tail);
+ } else {
+ data = await api.composeLogs(projectPath, selectedService || null, tail);
+ }
+ setLogs(data.logs || 'No logs available');
+ } catch (err) {
+ setLogs('Failed to load logs: ' + (err.message || 'Unknown error'));
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ return (
+ <div className="modal-overlay" onClick={onClose}>
+ <div className="modal modal-lg" onClick={e => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Logs: {projectName}</h2>
+ <button className="modal-close" onClick={onClose}>&times;</button>
+ </div>
+ <div className="modal-body">
+ <div className="logs-controls" style={{ marginBottom: '10px', display: 'flex', gap: '10px', alignItems: 'center', flexWrap: 'wrap' }}>
+ <label>Service:</label>
+ <select
+ value={selectedService}
+ onChange={(e) => setSelectedService(e.target.value)}
+ style={{ padding: '4px 8px' }}
+ >
+ <option value="">All Services</option>
+ {services.map(service => (
+ <option key={service} value={service}>{service}</option>
+ ))}
+ </select>
+ <label>Lines:</label>
+ <select value={tail} onChange={(e) => setTail(Number(e.target.value))} style={{ padding: '4px 8px' }}>
+ <option value={50}>50</option>
+ <option value={100}>100</option>
+ <option value={200}>200</option>
+ <option value={500}>500</option>
+ <option value={1000}>1000</option>
+ </select>
+ </div>
+ <pre className="log-viewer">{loading ? 'Loading...' : logs}</pre>
+ </div>
+ <div className="modal-actions">
+ <button className="btn btn-secondary" onClick={loadLogs} disabled={loading}>
+ {loading ? 'Loading...' : 'Refresh'}
+ </button>
+ <button className="btn btn-primary" onClick={onClose}>Close</button>
+ </div>
+ </div>
+ </div>
+ );
+};
+
// Modals
const RunContainerModal = ({ onClose, onCreated }) => {
const [formData, setFormData] = useState({
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 247de7ea..7c80817e 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -2714,6 +2714,71 @@ class ApiService {
return this.request('/servers/available');
}
+ // Remote Docker Compose Operations
+ async getRemoteComposeProjects(serverId) {
+ return this.request(`/servers/${serverId}/docker/compose/projects`);
+ }
+
+ async getRemoteComposePs(serverId, projectPath) {
+ return this.request(`/servers/${serverId}/docker/compose/ps`, {
+ method: 'POST',
+ body: { project_path: projectPath }
+ });
+ }
+
+ async remoteComposeUp(serverId, projectPath, options = {}) {
+ return this.request(`/servers/${serverId}/docker/compose/up`, {
+ method: 'POST',
+ body: {
+ project_path: projectPath,
+ detach: options.detach !== false,
+ build: options.build || false
+ }
+ });
+ }
+
+ async remoteComposeDown(serverId, projectPath, options = {}) {
+ return this.request(`/servers/${serverId}/docker/compose/down`, {
+ method: 'POST',
+ body: {
+ project_path: projectPath,
+ volumes: options.volumes || false,
+ remove_orphans: options.removeOrphans !== false
+ }
+ });
+ }
+
+ async remoteComposeLogs(serverId, projectPath, service = null, tail = 100) {
+ return this.request(`/servers/${serverId}/docker/compose/logs`, {
+ method: 'POST',
+ body: {
+ project_path: projectPath,
+ service: service,
+ tail: tail
+ }
+ });
+ }
+
+ async remoteComposeRestart(serverId, projectPath, service = null) {
+ return this.request(`/servers/${serverId}/docker/compose/restart`, {
+ method: 'POST',
+ body: {
+ project_path: projectPath,
+ service: service
+ }
+ });
+ }
+
+ async remoteComposePull(serverId, projectPath, service = null) {
+ return this.request(`/servers/${serverId}/docker/compose/pull`, {
+ method: 'POST',
+ body: {
+ project_path: projectPath,
+ service: service
+ }
+ });
+ }
+
// Agent Downloads
async getAgentVersion() {
return this.request('/servers/agent/version');