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 ServerKit agent and multi-server integration plan

Juan Denis3020b2472873
diff --git a/ROADMAP.md b/ROADMAP.md
index 58bcd22f..bbf9f23d 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -210,19 +210,19 @@ This document outlines the development roadmap for ServerKit. Features are organ
---
-## Phase 17: Advanced Security (In Progress)
+## Phase 17: Advanced Security (Completed)
**Priority: High**
- [x] Unified Security page with all security features
- [x] Firewall tab with UFW/firewalld management
-- [ ] Fail2ban integration
-- [ ] SSH key management
-- [ ] IP allowlist/blocklist
-- [ ] Brute force protection
-- [ ] Security audit reports
-- [ ] Vulnerability scanning
-- [ ] Automatic security updates
+- [x] Fail2ban integration
+- [x] SSH key management
+- [x] IP allowlist/blocklist
+- [x] Brute force protection
+- [x] Security audit reports
+- [x] Vulnerability scanning (Lynis)
+- [x] Automatic security updates (unattended-upgrades/dnf-automatic)
---
diff --git a/SERVERS_INTEGRATION_PLAN.md b/SERVERS_INTEGRATION_PLAN.md
new file mode 100644
index 00000000..00c9077e
--- /dev/null
+++ b/SERVERS_INTEGRATION_PLAN.md
@@ -0,0 +1,1514 @@
+# ServerKit Multi-Server Management Integration Plan
+## "ServerKit Agents" - THE Comprehensive Server Management Solution
+
+> **Vision**: Transform ServerKit from a single-server management tool into a distributed server orchestration platform that manages unlimited servers from a single dashboard.
+
+---
+
+## Table of Contents
+1. [Executive Summary](#executive-summary)
+2. [Architecture Overview](#architecture-overview)
+3. [Security Model (Critical!)](#security-model)
+4. [Agent Design](#agent-design)
+5. [Database Schema](#database-schema)
+6. [API Design](#api-design)
+7. [Frontend Design](#frontend-design)
+8. [Installation & Packaging](#installation--packaging)
+9. [Communication Protocol](#communication-protocol)
+10. [Feature Breakdown](#feature-breakdown)
+11. [Phase Implementation Plan](#phase-implementation-plan)
+12. [Risk Assessment](#risk-assessment)
+
+---
+
+## 1. Executive Summary
+
+### What We're Building
+A lightweight agent system that allows ServerKit to manage multiple remote servers (Windows/Linux) from a single dashboard. Users install a small agent on their servers, connect it to their ServerKit instance, and gain full Docker management, monitoring, and remote execution capabilities.
+
+### Why Security is ABSOLUTELY Required
+Even though we're "just managing Docker," this is a critical security concern:
+
+| Risk | Impact | Why It Matters |
+|------|--------|----------------|
+| **Docker = Root Access** | Critical | Docker can mount host filesystem, access kernel, run privileged containers |
+| **Remote Code Execution** | Critical | Agents execute commands on remote servers |
+| **Network Exposure** | High | Agents may be on internal networks with sensitive data |
+| **Credential Theft** | High | Stolen agent keys = full server access |
+| **Man-in-the-Middle** | High | Unencrypted traffic can be intercepted and modified |
+| **Supply Chain** | Medium | Malicious agents could be installed |
+
+**Bottom Line**: We need enterprise-grade security from day one. This isn't optional.
+
+---
+
+## 2. Architecture Overview
+
+### High-Level Architecture
+
+```
+┌─────────────────────────────────────────────────────────────────────────────────┐
+│ ServerKit Control Plane │
+│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────┐ │
+│ │ Web UI │ │ REST API │ │ SocketIO │ │ Agent Gateway │ │
+│ │ (React) │ │ (Flask) │ │ Server │ │ (WebSocket Handler) │ │
+│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └───────────┬─────────────┘ │
+│ │ │ │ │ │
+│ └────────────────┴────────────────┴─────────────────────┤ │
+│ │ │
+│ ┌──────────────────────────────────────────────────────────────┴─────────────┐ │
+│ │ Agent Registry Service │ │
+│ │ - Agent authentication - Health tracking - Command routing │ │
+│ │ - Connection management - Load balancing - Failover handling │ │
+│ └──────────────────────────────────────────────────────────────┬─────────────┘ │
+│ │ │
+│ ┌──────────────────────────────────────────────────────────────┴─────────────┐ │
+│ │ PostgreSQL Database │ │
+│ │ Servers, Agents, Commands, Metrics, Audit Logs, etc. │ │
+│ └────────────────────────────────────────────────────────────────────────────┘ │
+└─────────────────────────────────────────────────────────────────────────────────┘
+ │
+ ┌─────────────────┼─────────────────┐
+ │ │ │
+ ┌────────┴────────┐ ┌──────┴──────┐ ┌────────┴────────┐
+ │ WSS/TLS │ │ WSS/TLS │ │ WSS/TLS │
+ │ Connection │ │ Connection │ │ Connection │
+ └────────┬────────┘ └──────┬──────┘ └────────┬────────┘
+ │ │ │
+ ┌───────────────┴───────┐ ┌──────┴──────┐ ┌───────┴───────────────┐
+ │ Linux Server │ │ Windows PC │ │ Linux Server │
+ │ ┌─────────────────┐ │ │ ┌─────────┐ │ │ ┌─────────────────┐ │
+ │ │ ServerKit Agent │ │ │ │ Agent │ │ │ │ ServerKit Agent │ │
+ │ │ (Go binary) │ │ │ │ (Go) │ │ │ │ (Go binary) │ │
+ │ └────────┬────────┘ │ │ └────┬────┘ │ │ └────────┬────────┘ │
+ │ │ │ │ │ │ │ │ │
+ │ ┌────────┴────────┐ │ │ ┌────┴────┐ │ │ ┌────────┴────────┐ │
+ │ │ Docker │ │ │ │ Docker │ │ │ │ Docker │ │
+ │ │ Engine │ │ │ │ Desktop │ │ │ │ Engine │ │
+ │ └─────────────────┘ │ │ └─────────┘ │ │ └─────────────────┘ │
+ └───────────────────────┘ └─────────────┘ └───────────────────────┘
+```
+
+### Component Responsibilities
+
+| Component | Responsibility |
+|-----------|---------------|
+| **Control Plane** | Central management, UI, API, database |
+| **Agent Gateway** | WebSocket server for agent connections |
+| **Agent Registry** | Track connected agents, route commands |
+| **ServerKit Agent** | Lightweight daemon on remote servers |
+| **Local Executor** | Execute Docker/system commands locally |
+
+---
+
+## 3. Security Model
+
+### 3.1 Authentication Layers
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ SECURITY ARCHITECTURE │
+├─────────────────────────────────────────────────────────────────┤
+│ │
+│ Layer 1: Transport Security (TLS 1.3) │
+│ ┌─────────────────────────────────────────────────────────────┐│
+│ │ - All communication over WSS (WebSocket Secure) ││
+│ │ - Certificate validation (reject self-signed in prod) ││
+│ │ - Perfect forward secrecy ││
+│ └─────────────────────────────────────────────────────────────┘│
+│ │
+│ Layer 2: Agent Authentication │
+│ ┌─────────────────────────────────────────────────────────────┐│
+│ │ - API Key + Secret pair (generated on registration) ││
+│ │ - HMAC-SHA256 signed handshake ││
+│ │ - Short-lived session tokens (1 hour, auto-refresh) ││
+│ │ - Optional: mTLS for enterprise deployments ││
+│ └─────────────────────────────────────────────────────────────┘│
+│ │
+│ Layer 3: Command Authorization │
+│ ┌─────────────────────────────────────────────────────────────┐│
+│ │ - Per-server permission scopes ││
+│ │ - Command whitelist (allowed operations) ││
+│ │ - Request signing with timestamp (prevent replay) ││
+│ │ - Audit logging of all operations ││
+│ └─────────────────────────────────────────────────────────────┘│
+│ │
+│ Layer 4: Data Protection │
+│ ┌─────────────────────────────────────────────────────────────┐│
+│ │ - Secrets encrypted at rest (agent keys, tokens) ││
+│ │ - No plaintext credentials in transit ││
+│ │ - Secure secret injection to containers ││
+│ └─────────────────────────────────────────────────────────────┘│
+│ │
+└─────────────────────────────────────────────────────────────────┘
+```
+
+### 3.2 Agent Registration Flow
+
+```
+┌──────────┐ ┌──────────────┐ ┌──────────┐
+│ User │ │ Control Plane │ │ Agent │
+└────┬─────┘ └───────┬──────┘ └────┬─────┘
+ │ │ │
+ │ 1. Create Server (UI) │ │
+ │ ─────────────────────────────────> │
+ │ │ │
+ │ 2. Returns registration token │ │
+ │ <───────────────────────────────── │
+ │ (24-hour expiry, single-use) │ │
+ │ │ │
+ │ 3. Install agent with token │ │
+ │ ─────────────────────────────────────────────────────────────────>
+ │ │ │
+ │ │ 4. Agent connects with token │
+ │ │ <──────────────────────────────
+ │ │ │
+ │ │ 5. Validates token, generates │
+ │ │ permanent API key pair │
+ │ │ ──────────────────────────────>
+ │ │ │
+ │ │ 6. Agent stores keys securely │
+ │ │ (encrypted on disk) │
+ │ │ │
+ │ 7. Server shows as "Connected" │ │
+ │ <───────────────────────────────── │
+ │ │ │
+```
+
+### 3.3 Permission Scopes
+
+```python
+# Granular permissions per server
+AGENT_SCOPES = {
+ # Docker Operations
+ 'docker:containers:read', # List, inspect containers
+ 'docker:containers:write', # Create, start, stop, remove
+ 'docker:containers:exec', # Exec into containers (high risk!)
+ 'docker:images:read', # List, inspect images
+ 'docker:images:write', # Pull, build, remove images
+ 'docker:compose:read', # List compose stacks
+ 'docker:compose:write', # Deploy/remove compose stacks
+ 'docker:volumes:read',
+ 'docker:volumes:write',
+ 'docker:networks:read',
+ 'docker:networks:write',
+
+ # System Operations
+ 'system:metrics:read', # CPU, memory, disk metrics
+ 'system:processes:read', # Process list
+ 'system:logs:read', # Read log files
+ 'system:exec', # Execute arbitrary commands (DANGEROUS!)
+
+ # File Operations
+ 'files:read', # Read files on server
+ 'files:write', # Write files (limited paths)
+
+ # Agent Management
+ 'agent:update', # Self-update agent
+ 'agent:restart', # Restart agent service
+}
+
+# Preset permission profiles
+PERMISSION_PROFILES = {
+ 'docker_readonly': [
+ 'docker:containers:read',
+ 'docker:images:read',
+ 'docker:compose:read',
+ 'system:metrics:read',
+ ],
+ 'docker_manager': [
+ 'docker:*',
+ 'system:metrics:read',
+ 'system:logs:read',
+ ],
+ 'full_access': ['*'], # All permissions (admin only)
+}
+```
+
+### 3.4 Security Features Checklist
+
+- [ ] **TLS everywhere**: WSS for agent connections, HTTPS for API
+- [ ] **API key rotation**: Manual and automatic key rotation
+- [ ] **IP allowlisting**: Optional restriction of agent IPs
+- [ ] **Rate limiting**: Per-agent command rate limits
+- [ ] **Audit logging**: Every command logged with user, timestamp, result
+- [ ] **Anomaly detection**: Alert on unusual patterns (many failed commands, etc.)
+- [ ] **Secrets management**: Encrypted storage, never logged
+- [ ] **Session management**: Revoke agent sessions instantly
+- [ ] **Command signing**: HMAC-signed commands with timestamp
+- [ ] **Replay protection**: Nonce + timestamp validation
+
+---
+
+## 4. Agent Design
+
+### 4.1 Technology Choice: Go
+
+**Why Go?**
+| Reason | Benefit |
+|--------|---------|
+| Single binary | No runtime dependencies, easy distribution |
+| Cross-platform | Compile for Windows, Linux, macOS, ARM |
+| Low memory | ~10-20MB RAM typical usage |
+| Fast startup | Instant service startup |
+| Excellent networking | Built-in WebSocket, HTTP, TLS support |
+| Docker SDK | Official Docker Go SDK available |
+
+### 4.2 Agent Architecture
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ ServerKit Agent │
+├─────────────────────────────────────────────────────────────────┤
+│ │
+│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
+│ │ Connection │ │ Command │ │ Metrics │ │
+│ │ Manager │ │ Executor │ │ Collector │ │
+│ │ │ │ │ │ │ │
+│ │ - WebSocket │ │ - Docker API │ │ - CPU/RAM/Disk │ │
+│ │ - Auto-reconnect│ │ - System exec │ │ - Network I/O │ │
+│ │ - Heartbeat │ │ - File ops │ │ - Docker stats │ │
+│ │ - TLS handling │ │ - Sandboxing │ │ - Custom metrics│ │
+│ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │
+│ │ │ │ │
+│ ┌────────┴────────────────────┴────────────────────┴────────┐ │
+│ │ Core Event Loop │ │
+│ │ - Message queue - Command validation │ │
+│ │ - Priority handling - Response serialization │ │
+│ └────────────────────────────┬──────────────────────────────┘ │
+│ │ │
+│ ┌────────────────────────────┴──────────────────────────────┐ │
+│ │ Security Module │ │
+│ │ - Key storage (encrypted) - Request validation │ │
+│ │ - HMAC signing - Permission checking │ │
+│ └───────────────────────────────────────────────────────────┘ │
+│ │
+│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
+│ │ Config Store │ │ Local Cache │ │ Update Manager │ │
+│ │ (encrypted) │ │ (metrics/logs) │ │ (self-update) │ │
+│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
+│ │
+└─────────────────────────────────────────────────────────────────┘
+```
+
+### 4.3 Agent Features
+
+#### Core Features
+- **Persistent WebSocket connection** with auto-reconnect
+- **Heartbeat** every 30 seconds (configurable)
+- **Graceful shutdown** on SIGTERM/SIGINT
+- **Local metric buffering** when disconnected
+- **Self-update** capability (secure, signed updates)
+
+#### Docker Integration
+- Full Docker Engine API access
+- Container lifecycle management
+- Image management (pull, build, tag, push)
+- Docker Compose stack deployment
+- Volume and network management
+- Container logs streaming
+- Container stats streaming
+- Registry authentication
+
+#### System Integration
+- CPU, memory, disk metrics via cross-platform libraries
+- Process listing
+- Network interface stats
+- Service status (systemd/Windows services)
+- Log file streaming
+
+### 4.4 Agent Configuration
+
+```yaml
+# /etc/serverkit-agent/config.yaml (Linux)
+# C:\ProgramData\ServerKit\Agent\config.yaml (Windows)
+
+server:
+ url: wss://your-serverkit.example.com/agent/ws
+ # Alternative: ws://localhost:5000/agent/ws (dev only!)
+
+agent:
+ id: "auto-generated-uuid"
+ name: "production-server-1" # Human-friendly name
+
+auth:
+ key_file: /etc/serverkit-agent/agent.key # Encrypted
+ # Key is generated during registration
+
+features:
+ docker: true
+ metrics: true
+ metrics_interval: 10s
+ logs: true
+ file_access: false # Disabled by default
+ exec: false # Disabled by default (dangerous)
+
+docker:
+ socket: /var/run/docker.sock # Linux
+ # socket: npipe:////./pipe/docker_engine # Windows
+
+security:
+ allowed_paths: [] # For file operations
+ blocked_commands: [] # Regex patterns to block
+ max_exec_timeout: 300s
+
+logging:
+ level: info
+ file: /var/log/serverkit-agent/agent.log
+ max_size: 100MB
+ max_backups: 5
+```
+
+### 4.5 Resource Usage Targets
+
+| Resource | Target | Maximum |
+|----------|--------|---------|
+| Memory | 15 MB | 50 MB |
+| CPU (idle) | <0.1% | 1% |
+| CPU (active) | <2% | 10% |
+| Disk | 20 MB | 50 MB |
+| Network (idle) | <1 KB/s | 10 KB/s |
+
+---
+
+## 5. Database Schema
+
+### 5.1 New Models
+
+```python
+# backend/app/models/server.py
+
+class Server(db.Model):
+ """Represents a remote server managed by ServerKit"""
+ __tablename__ = 'servers'
+
+ id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
+
+ # Basic Info
+ name = db.Column(db.String(100), nullable=False)
+ description = db.Column(db.Text)
+ hostname = db.Column(db.String(255)) # Reported by agent
+ ip_address = db.Column(db.String(45)) # IPv4 or IPv6
+
+ # Organization
+ group_id = db.Column(db.String(36), db.ForeignKey('server_groups.id'), nullable=True)
+ tags = db.Column(db.JSON, default=list) # ["production", "us-east", "docker"]
+
+ # Status
+ status = db.Column(db.String(20), default='pending')
+ # pending, connecting, online, offline, error, maintenance
+ last_seen = db.Column(db.DateTime)
+ last_error = db.Column(db.Text)
+
+ # Agent Info
+ agent_version = db.Column(db.String(20))
+ agent_id = db.Column(db.String(36), unique=True) # Agent's UUID
+
+ # System Info (reported by agent)
+ os_type = db.Column(db.String(20)) # linux, windows, darwin
+ os_version = db.Column(db.String(100))
+ architecture = db.Column(db.String(20)) # amd64, arm64
+ cpu_cores = db.Column(db.Integer)
+ total_memory = db.Column(db.BigInteger) # bytes
+ total_disk = db.Column(db.BigInteger) # bytes
+ docker_version = db.Column(db.String(50))
+
+ # Security
+ api_key_hash = db.Column(db.String(256)) # bcrypt hash
+ api_key_prefix = db.Column(db.String(8)) # For identification: "sk_abc123"
+ permissions = db.Column(db.JSON, default=list) # List of scopes
+ allowed_ips = db.Column(db.JSON, default=list) # IP whitelist (empty = all)
+
+ # Registration
+ registration_token_hash = db.Column(db.String(256))
+ registration_token_expires = db.Column(db.DateTime)
+ registered_at = db.Column(db.DateTime)
+ registered_by = db.Column(db.Integer, db.ForeignKey('users.id'))
+
+ # Timestamps
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # Relationships
+ group = db.relationship('ServerGroup', back_populates='servers')
+ metrics = db.relationship('ServerMetrics', back_populates='server', lazy='dynamic')
+ commands = db.relationship('ServerCommand', back_populates='server', lazy='dynamic')
+ containers = db.relationship('ServerContainer', back_populates='server', lazy='dynamic')
+
+
+class ServerGroup(db.Model):
+ """Group servers for organization"""
+ __tablename__ = 'server_groups'
+
+ id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
+ name = db.Column(db.String(100), nullable=False)
+ description = db.Column(db.Text)
+ color = db.Column(db.String(7)) # Hex color for UI
+ icon = db.Column(db.String(50)) # Icon name
+ parent_id = db.Column(db.String(36), db.ForeignKey('server_groups.id')) # Nested groups
+
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ # Relationships
+ servers = db.relationship('Server', back_populates='group')
+ children = db.relationship('ServerGroup', backref=db.backref('parent', remote_side=[id]))
+
+
+class ServerMetrics(db.Model):
+ """Historical metrics from servers"""
+ __tablename__ = 'server_metrics'
+
+ id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
+ server_id = db.Column(db.String(36), db.ForeignKey('servers.id'), nullable=False)
+
+ timestamp = db.Column(db.DateTime, default=datetime.utcnow, index=True)
+
+ # System Metrics
+ cpu_percent = db.Column(db.Float)
+ memory_percent = db.Column(db.Float)
+ memory_used = db.Column(db.BigInteger)
+ disk_percent = db.Column(db.Float)
+ disk_used = db.Column(db.BigInteger)
+ network_rx = db.Column(db.BigInteger) # Bytes received
+ network_tx = db.Column(db.BigInteger) # Bytes transmitted
+
+ # Docker Metrics
+ container_count = db.Column(db.Integer)
+ container_running = db.Column(db.Integer)
+ image_count = db.Column(db.Integer)
+
+ # Additional data as JSON
+ extra = db.Column(db.JSON)
+
+ server = db.relationship('Server', back_populates='metrics')
+
+ __table_args__ = (
+ db.Index('ix_server_metrics_server_time', 'server_id', 'timestamp'),
+ )
+
+
+class ServerCommand(db.Model):
+ """Audit log of commands executed on servers"""
+ __tablename__ = 'server_commands'
+
+ id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
+ server_id = db.Column(db.String(36), db.ForeignKey('servers.id'), nullable=False)
+ user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
+
+ # Command details
+ command_type = db.Column(db.String(50)) # docker:container:start, system:exec, etc.
+ command_data = db.Column(db.JSON) # The actual command/parameters
+
+ # Execution
+ status = db.Column(db.String(20)) # pending, running, completed, failed, timeout
+ started_at = db.Column(db.DateTime)
+ completed_at = db.Column(db.DateTime)
+
+ # Result
+ result = db.Column(db.JSON)
+ error = db.Column(db.Text)
+ exit_code = db.Column(db.Integer)
+
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ server = db.relationship('Server', back_populates='commands')
+ user = db.relationship('User')
+
+
+class ServerContainer(db.Model):
+ """Cached container state from remote servers"""
+ __tablename__ = 'server_containers'
+
+ id = db.Column(db.String(36), primary_key=True) # Docker container ID
+ server_id = db.Column(db.String(36), db.ForeignKey('servers.id'), nullable=False)
+
+ name = db.Column(db.String(255))
+ image = db.Column(db.String(255))
+ status = db.Column(db.String(50))
+ state = db.Column(db.String(20)) # running, paused, exited, etc.
+
+ created = db.Column(db.DateTime)
+ started_at = db.Column(db.DateTime)
+
+ ports = db.Column(db.JSON)
+ labels = db.Column(db.JSON)
+
+ # Stats snapshot
+ cpu_percent = db.Column(db.Float)
+ memory_usage = db.Column(db.BigInteger)
+ memory_limit = db.Column(db.BigInteger)
+
+ last_updated = db.Column(db.DateTime, default=datetime.utcnow)
+
+ server = db.relationship('Server', back_populates='containers')
+
+
+class AgentSession(db.Model):
+ """Active agent WebSocket sessions"""
+ __tablename__ = 'agent_sessions'
+
+ id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
+ server_id = db.Column(db.String(36), db.ForeignKey('servers.id'), nullable=False)
+
+ session_token_hash = db.Column(db.String(256))
+ connected_at = db.Column(db.DateTime, default=datetime.utcnow)
+ last_heartbeat = db.Column(db.DateTime, default=datetime.utcnow)
+
+ ip_address = db.Column(db.String(45))
+ user_agent = db.Column(db.String(255)) # Agent version info
+
+ is_active = db.Column(db.Boolean, default=True)
+ disconnected_at = db.Column(db.DateTime)
+ disconnect_reason = db.Column(db.String(100))
+```
+
+### 5.2 Schema Diagram
+
+```
+┌─────────────────────┐ ┌─────────────────────┐
+│ server_groups │ │ users │
+├─────────────────────┤ ├─────────────────────┤
+│ id (PK) │ │ id (PK) │
+│ name │ │ ... │
+│ description │ └──────────┬──────────┘
+│ color │ │
+│ parent_id (FK)──────┼──┐ │
+└──────────┬──────────┘ │ │
+ │ │ │
+ │ 1:N │ │
+ │ │ │
+┌──────────┴──────────┐ │ │
+│ servers │◄─┘ │
+├─────────────────────┤ │
+│ id (PK) │ │
+│ name │ │
+│ group_id (FK)───────┼─────────────────┘
+│ registered_by (FK)──┼─────────────────┘
+│ status │
+│ agent_id │
+│ os_type │
+│ ... │
+└──────────┬──────────┘
+ │
+ ┌─────┼─────┬───────────┐
+ │ │ │ │
+ │ 1:N │ 1:N │ 1:N │ 1:N
+ │ │ │ │
+ ▼ ▼ ▼ ▼
+┌─────────┐ ┌─────────┐ ┌──────────┐ ┌──────────────┐
+│ metrics │ │commands │ │containers│ │agent_sessions│
+└─────────┘ └─────────┘ └──────────┘ └──────────────┘
+```
+
+---
+
+## 6. API Design
+
+### 6.1 Server Management Endpoints
+
+```
+# Server CRUD
+GET /api/v1/servers # List all servers
+POST /api/v1/servers # Create new server (generates reg token)
+GET /api/v1/servers/:id # Get server details
+PUT /api/v1/servers/:id # Update server (name, group, etc.)
+DELETE /api/v1/servers/:id # Remove server
+
+# Server Status
+GET /api/v1/servers/:id/status # Get current status & metrics
+POST /api/v1/servers/:id/ping # Force ping/health check
+
+# Registration
+POST /api/v1/servers/:id/regenerate-token # Generate new registration token
+POST /api/v1/servers/:id/rotate-key # Rotate API key
+
+# Permissions
+GET /api/v1/servers/:id/permissions # Get current permissions
+PUT /api/v1/servers/:id/permissions # Update permissions
+
+# Groups
+GET /api/v1/server-groups # List groups
+POST /api/v1/server-groups # Create group
+PUT /api/v1/server-groups/:id # Update group
+DELETE /api/v1/server-groups/:id # Delete group
+```
+
+### 6.2 Remote Docker Endpoints
+
+```
+# Containers
+GET /api/v1/servers/:id/docker/containers # List containers
+GET /api/v1/servers/:id/docker/containers/:cid # Inspect container
+POST /api/v1/servers/:id/docker/containers # Create container
+POST /api/v1/servers/:id/docker/containers/:cid/start
+POST /api/v1/servers/:id/docker/containers/:cid/stop
+POST /api/v1/servers/:id/docker/containers/:cid/restart
+DELETE /api/v1/servers/:id/docker/containers/:cid # Remove container
+GET /api/v1/servers/:id/docker/containers/:cid/logs # Get logs
+GET /api/v1/servers/:id/docker/containers/:cid/stats # Get stats
+
+# Images
+GET /api/v1/servers/:id/docker/images # List images
+POST /api/v1/servers/:id/docker/images/pull # Pull image
+DELETE /api/v1/servers/:id/docker/images/:iid # Remove image
+
+# Compose
+GET /api/v1/servers/:id/docker/compose # List stacks
+POST /api/v1/servers/:id/docker/compose # Deploy stack
+DELETE /api/v1/servers/:id/docker/compose/:name # Remove stack
+
+# Volumes & Networks
+GET /api/v1/servers/:id/docker/volumes
+GET /api/v1/servers/:id/docker/networks
+```
+
+### 6.3 Metrics & Monitoring
+
+```
+# Real-time metrics (via WebSocket)
+WS /api/v1/servers/:id/metrics/stream
+
+# Historical metrics
+GET /api/v1/servers/:id/metrics?from=&to=&interval=
+
+# Cross-server comparison
+GET /api/v1/servers/metrics/compare?ids=1,2,3&metric=cpu
+
+# Aggregated dashboard
+GET /api/v1/servers/overview # All servers health summary
+```
+
+### 6.4 Agent Gateway WebSocket Protocol
+
+```
+# Agent connects to: wss://serverkit.example.com/agent/ws
+
+# Handshake
+→ { "type": "auth", "agent_id": "...", "signature": "hmac(...)", "timestamp": ... }
+← { "type": "auth_ok", "session_token": "...", "expires": ... }
+
+# Heartbeat
+→ { "type": "heartbeat", "metrics": {...} }
+← { "type": "heartbeat_ack" }
+
+# Command from server
+← { "type": "command", "id": "uuid", "action": "docker:container:start", "params": {...} }
+→ { "type": "command_result", "id": "uuid", "success": true, "data": {...} }
+
+# Streaming (logs, stats)
+← { "type": "subscribe", "channel": "container:abc123:logs" }
+→ { "type": "stream", "channel": "...", "data": "log line..." }
+← { "type": "unsubscribe", "channel": "..." }
+
+# Error
+→ { "type": "error", "code": "...", "message": "..." }
+```
+
+---
+
+## 7. Frontend Design
+
+### 7.1 Navigation Structure
+
+```
+Sidebar (Updated)
+├── Dashboard
+├── Applications
+├── ─────────────
+├── Servers (NEW!) ← New section
+│ ├── Overview ← Multi-server dashboard
+│ ├── All Servers ← List/grid view
+│ └── Groups ← Server groups management
+├── ─────────────
+├── Docker ← Now shows server selector
+├── Databases
+├── Domains
+├── ...
+```
+
+### 7.2 Key Pages
+
+#### Servers Overview (`/servers`)
+```
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ Servers Overview [+ Add Server] │
+├─────────────────────────────────────────────────────────────────────────────┤
+│ │
+│ ┌─────────────────────────────────────────────────────────────────────────┐│
+│ │ Summary Cards ││
+│ │ ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ ││
+│ │ │ Total │ │ Online │ │ Offline │ │ Containers│ │ Avg CPU │ ││
+│ │ │ 12 │ │ 10 │ │ 2 │ │ 47 │ │ 34% │ ││
+│ │ └───────────┘ └───────────┘ └───────────┘ └───────────┘ └───────────┘ ││
+│ └─────────────────────────────────────────────────────────────────────────┘│
+│ │
+│ ┌─────────────────────────────────────────────────────────────────────────┐│
+│ │ Server Health Grid ││
+│ │ ││
+│ │ Production (4 servers) ││
+│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ││
+│ │ │ 🟢 web-1 │ │ 🟢 web-2 │ │ 🟢 db-1 │ │ 🔴 cache │ ││
+│ │ │ CPU: 45% │ │ CPU: 32% │ │ CPU: 12% │ │ OFFLINE │ ││
+│ │ │ RAM: 67% │ │ RAM: 58% │ │ RAM: 89% │ │ │ ││
+│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ ││
+│ │ ││
+│ │ Development (3 servers) ││
+│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ││
+│ │ │ 🟢 dev-1 │ │ 🟡 dev-2 │ │ 🟢 test │ ││
+│ │ │ CPU: 23% │ │ CPU: 78% │ │ CPU: 5% │ ││
+│ │ └──────────┘ └──────────┘ └──────────┘ ││
+│ └─────────────────────────────────────────────────────────────────────────┘│
+│ │
+│ ┌─────────────────────────────────────────────────────────────────────────┐│
+│ │ Cross-Server Metrics Comparison [CPU▼] [24h▼] ││
+│ │ ││
+│ │ 100% ┤ ││
+│ │ │ ╭─╮ ││
+│ │ 75% ┤ ╱ ╲ ╭───╮ ── web-1 ││
+│ │ │ ╱ ╲ ╱ ╲ ── web-2 ││
+│ │ 50% ┤─╱──────╲╱───────╲─────── ── db-1 ││
+│ │ │ ││
+│ │ 25% ┤ ││
+│ │ └──────────────────────────────────────────────────────────── ││
+│ └─────────────────────────────────────────────────────────────────────────┘│
+└─────────────────────────────────────────────────────────────────────────────┘
+```
+
+#### Add Server Flow (`/servers/add`)
+```
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ Add New Server │
+├─────────────────────────────────────────────────────────────────────────────┤
+│ │
+│ Step 1: Server Details │
+│ ───────────────────────────────────────────────────────────────────────── │
+│ │
+│ Server Name: [production-server-1 ] │
+│ Description: [Main production server ] │
+│ Group: [Production ▼] │
+│ Tags: [production] [us-east] [+] │
+│ │
+│ ───────────────────────────────────────────────────────────────────────── │
+│ │
+│ Step 2: Permissions │
+│ ───────────────────────────────────────────────────────────────────────── │
+│ │
+│ Permission Profile: [Docker Manager (Recommended) ▼] │
+│ │
+│ ☑ Docker: Containers (read/write) │
+│ ☑ Docker: Images (read/write) │
+│ ☑ Docker: Compose (read/write) │
+│ ☑ System: Metrics (read) │
+│ ☑ System: Logs (read) │
+│ ☐ System: Execute commands (⚠️ High risk) │
+│ ☐ Files: Read/Write (⚠️ High risk) │
+│ │
+│ [Cancel] [Create Server]│
+└─────────────────────────────────────────────────────────────────────────────┘
+
+# After creation:
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ Install Agent │
+├─────────────────────────────────────────────────────────────────────────────┤
+│ │
+│ Your server has been created! Install the agent using one of these methods:│
+│ │
+│ ┌─────────────────────────────────────────────────────────────────────────┐│
+│ │ Linux (One-liner) [Copy] ││
+│ │ ││
+│ │ curl -fsSL https://serverkit.example.com/install.sh | sudo bash -s -- \ ││
+│ │ --token "sk_reg_abc123xyz..." ││
+│ └─────────────────────────────────────────────────────────────────────────┘│
+│ │
+│ ┌─────────────────────────────────────────────────────────────────────────┐│
+│ │ Windows (PowerShell - Run as Administrator) [Copy] ││
+│ │ ││
+│ │ irm https://serverkit.example.com/install.ps1 | iex; ` ││
+│ │ Install-ServerKitAgent -Token "sk_reg_abc123xyz..." ││
+│ └─────────────────────────────────────────────────────────────────────────┘│
+│ │
+│ ┌─────────────────────────────────────────────────────────────────────────┐│
+│ │ Manual Download ││
+│ │ ││
+│ │ [Download Linux x64] [Download Linux ARM64] ││
+│ │ [Download Windows] [Download macOS] ││
+│ │ ││
+│ │ Registration Token: sk_reg_abc123xyz... (expires in 24 hours) [Copy] ││
+│ └─────────────────────────────────────────────────────────────────────────┘│
+│ │
+│ Waiting for agent to connect... ⏳ │
+│ │
+└─────────────────────────────────────────────────────────────────────────────┘
+```
+
+#### Server Detail Page (`/servers/:id`)
+```
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ ← Back production-server-1 🟢 Online [Actions ▼] [Settings]│
+├─────────────────────────────────────────────────────────────────────────────┤
+│ │
+│ [Overview] [Containers] [Images] [Compose] [Metrics] [Logs] [Terminal] │
+│ │
+│ ┌─────────────────────────────────────────────────────────────────────────┐│
+│ │ System Information ││
+│ │ ─────────────────────────────────────────────────────────────────────── ││
+│ │ OS: Ubuntu 22.04 LTS Docker: 24.0.5 ││
+│ │ Arch: x86_64 Agent: 1.0.0 ││
+│ │ CPUs: 8 cores Uptime: 45 days ││
+│ │ Memory: 32 GB IP: 10.0.1.50 ││
+│ └─────────────────────────────────────────────────────────────────────────┘│
+│ │
+│ ┌─────────────────────────────────────────────────────────────────────────┐│
+│ │ Live Metrics ││
+│ │ ─────────────────────────────────────────────────────────────────────── ││
+│ │ ││
+│ │ CPU Usage Memory Usage Disk Usage Network ││
+│ │ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ││
+│ │ │ 45% │ │ 67% │ │ 34% │ │ ↓ 1.2 │ ││
+│ │ │ ████ │ │ ██████ │ │ ████ │ │ ↑ 0.8 │ ││
+│ │ │ ████ │ │ ██████ │ │ ████ │ │ MB/s │ ││
+│ │ └────────┘ └────────┘ └────────┘ └────────┘ ││
+│ └─────────────────────────────────────────────────────────────────────────┘│
+│ │
+│ ┌─────────────────────────────────────────────────────────────────────────┐│
+│ │ Containers (12 running) [+ Create] ││
+│ │ ─────────────────────────────────────────────────────────────────────── ││
+│ │ Name Image Status CPU Memory Actions ││
+│ │ nginx-proxy nginx:alpine 🟢 Up 2% 45 MB [···] ││
+│ │ app-backend myapp:latest 🟢 Up 12% 234 MB [···] ││
+│ │ postgres-db postgres:15 🟢 Up 5% 512 MB [···] ││
+│ │ redis-cache redis:7 🟢 Up 1% 28 MB [···] ││
+│ └─────────────────────────────────────────────────────────────────────────┘│
+└─────────────────────────────────────────────────────────────────────────────┘
+```
+
+### 7.3 Docker Page Integration
+
+The existing Docker page needs to support server selection:
+
+```
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ Docker │
+├─────────────────────────────────────────────────────────────────────────────┤
+│ │
+│ Server: [Local (this server) ▼] ← New server selector │
+│ ┌─────────────────────────────────┐ │
+│ │ ⚡ Local (this server) │ │
+│ │ ─────────────────────────────── │ │
+│ │ 🟢 production-server-1 │ │
+│ │ 🟢 production-server-2 │ │
+│ │ 🔴 staging-server (offline) │ │
+│ │ 🟢 dev-server │ │
+│ └─────────────────────────────────┘ │
+│ │
+│ [Containers] [Images] [Volumes] [Networks] [Compose] │
+│ ... (existing Docker UI, now server-aware) │
+└─────────────────────────────────────────────────────────────────────────────┘
+```
+
+---
+
+## 8. Installation & Packaging
+
+### 8.1 Installation Methods
+
+#### Linux - One-liner Install
+```bash
+curl -fsSL https://your-serverkit.com/install.sh | sudo bash -s -- \
+ --token "sk_reg_abc123..."
+```
+
+The script will:
+1. Detect Linux distribution (Ubuntu, Debian, CentOS, Fedora, Alpine)
+2. Download appropriate binary
+3. Create service user (`serverkit-agent`)
+4. Install systemd service
+5. Configure firewall (if needed)
+6. Register with ServerKit using token
+7. Start the agent
+
+#### Windows - PowerShell Install
+```powershell
+# Run as Administrator
+irm https://your-serverkit.com/install.ps1 | iex
+Install-ServerKitAgent -Token "sk_reg_abc123..."
+```
+
+The script will:
+1. Download Windows binary
+2. Install to `C:\Program Files\ServerKit Agent\`
+3. Create Windows Service
+4. Configure Windows Firewall
+5. Register with ServerKit
+6. Start the service
+
+#### Docker Install (for containerized servers)
+```bash
+docker run -d \
+ --name serverkit-agent \
+ --restart unless-stopped \
+ -v /var/run/docker.sock:/var/run/docker.sock \
+ -e SERVERKIT_TOKEN="sk_reg_abc123..." \
+ serverkit/agent:latest
+```
+
+### 8.2 Package Formats
+
+| Platform | Formats |
+|----------|---------|
+| Linux | `.deb`, `.rpm`, `.apk`, static binary |
+| Windows | `.msi`, `.exe` installer, portable `.zip` |
+| macOS | `.pkg`, `.dmg`, Homebrew formula |
+| Container | Docker image (multi-arch) |
+
+### 8.3 Distribution
+
+```
+Binary Naming Convention:
+serverkit-agent-{version}-{os}-{arch}[.ext]
+
+Examples:
+serverkit-agent-1.0.0-linux-amd64
+serverkit-agent-1.0.0-linux-arm64
+serverkit-agent-1.0.0-windows-amd64.exe
+serverkit-agent-1.0.0-darwin-amd64
+serverkit-agent-1.0.0-darwin-arm64
+
+Package Naming:
+serverkit-agent_1.0.0_amd64.deb
+serverkit-agent-1.0.0-1.x86_64.rpm
+serverkit-agent-1.0.0-x64.msi
+```
+
+---
+
+## 9. Communication Protocol
+
+### 9.1 Message Format
+
+```typescript
+// Base message structure
+interface AgentMessage {
+ type: string;
+ id: string; // Unique message ID
+ timestamp: number; // Unix timestamp
+ signature?: string; // HMAC-SHA256 signature
+}
+
+// Authentication
+interface AuthMessage extends AgentMessage {
+ type: 'auth';
+ agent_id: string;
+ api_key_prefix: string; // "sk_abc123"
+ signature: string; // HMAC(agent_id + timestamp, api_secret)
+}
+
+interface AuthResponse extends AgentMessage {
+ type: 'auth_ok' | 'auth_fail';
+ session_token?: string;
+ expires?: number;
+ error?: string;
+}
+
+// Heartbeat
+interface HeartbeatMessage extends AgentMessage {
+ type: 'heartbeat';
+ metrics: {
+ cpu_percent: number;
+ memory_percent: number;
+ disk_percent: number;
+ container_count: number;
+ container_running: number;
+ };
+}
+
+// Commands
+interface CommandMessage extends AgentMessage {
+ type: 'command';
+ action: string; // e.g., "docker:container:start"
+ params: object;
+ timeout?: number; // ms
+}
+
+interface CommandResult extends AgentMessage {
+ type: 'command_result';
+ command_id: string; // References CommandMessage.id
+ success: boolean;
+ data?: any;
+ error?: string;
+ duration: number; // ms
+}
+
+// Streaming
+interface StreamSubscribe extends AgentMessage {
+ type: 'subscribe';
+ channel: string; // e.g., "container:abc123:logs"
+}
+
+interface StreamData extends AgentMessage {
+ type: 'stream';
+ channel: string;
+ data: any;
+}
+```
+
+### 9.2 Command Types
+
+```yaml
+# Docker Container Commands
+docker:container:list:
+ params: { all: boolean, filters: object }
+ returns: Container[]
+
+docker:container:inspect:
+ params: { id: string }
+ returns: ContainerInspect
+
+docker:container:create:
+ params: { image: string, name?: string, config: ContainerConfig }
+ returns: { id: string }
+
+docker:container:start:
+ params: { id: string }
+ returns: { success: boolean }
+
+docker:container:stop:
+ params: { id: string, timeout?: number }
+ returns: { success: boolean }
+
+docker:container:restart:
+ params: { id: string, timeout?: number }
+ returns: { success: boolean }
+
+docker:container:remove:
+ params: { id: string, force?: boolean, volumes?: boolean }
+ returns: { success: boolean }
+
+docker:container:logs:
+ params: { id: string, tail?: number, since?: string, follow?: boolean }
+ returns: Stream<string>
+
+docker:container:stats:
+ params: { id: string, stream?: boolean }
+ returns: ContainerStats | Stream<ContainerStats>
+
+docker:container:exec:
+ params: { id: string, cmd: string[], tty?: boolean }
+ returns: { exit_code: number, output: string }
+
+# Docker Image Commands
+docker:image:list:
+ params: { filters?: object }
+ returns: Image[]
+
+docker:image:pull:
+ params: { image: string, tag?: string }
+ returns: Stream<PullProgress>
+
+docker:image:remove:
+ params: { id: string, force?: boolean }
+ returns: { success: boolean }
+
+# Docker Compose Commands
+docker:compose:list:
+ params: { }
+ returns: ComposeStack[]
+
+docker:compose:up:
+ params: { project_name: string, compose_file: string, services?: string[] }
+ returns: Stream<ComposeProgress>
+
+docker:compose:down:
+ params: { project_name: string, volumes?: boolean }
+ returns: { success: boolean }
+
+# System Commands
+system:metrics:
+ params: { }
+ returns: SystemMetrics
+
+system:info:
+ params: { }
+ returns: SystemInfo
+
+system:processes:
+ params: { }
+ returns: Process[]
+
+system:exec: # Requires explicit permission
+ params: { command: string, args?: string[], timeout?: number }
+ returns: { exit_code: number, stdout: string, stderr: string }
+```
+
+---
+
+## 10. Feature Breakdown
+
+### 10.1 Core Features (MVP)
+
+| Feature | Description | Priority |
+|---------|-------------|----------|
+| Agent Registration | Register agents with tokens | P0 |
+| Agent Authentication | Secure API key auth | P0 |
+| WebSocket Gateway | Handle agent connections | P0 |
+| Server CRUD | Create, list, update, delete servers | P0 |
+| Basic Metrics | CPU, RAM, disk from agents | P0 |
+| Container List | List containers on remote servers | P0 |
+| Container Actions | Start/stop/restart containers | P0 |
+| Server Status | Online/offline detection | P0 |
+
+### 10.2 Extended Features (v1.1)
+
+| Feature | Description | Priority |
+|---------|-------------|----------|
+| Server Groups | Organize servers into groups | P1 |
+| Tags & Filtering | Tag-based server filtering | P1 |
+| Container Logs | Stream container logs | P1 |
+| Image Management | Pull, list, remove images | P1 |
+| Docker Compose | Deploy compose stacks | P1 |
+| Historical Metrics | Store and view metrics history | P1 |
+| Alerts | Server/container alerts | P1 |
+
+### 10.3 Advanced Features (v1.2+)
+
+| Feature | Description | Priority |
+|---------|-------------|----------|
+| Cross-server Metrics | Compare metrics across servers | P2 |
+| Remote Terminal | SSH-like terminal via agent | P2 |
+| File Manager | Browse files on remote servers | P2 |
+| Deployment Sync | Deploy to multiple servers | P2 |
+| Load Balancing | Distribute apps across servers | P2 |
+| Auto-scaling | Scale containers based on metrics | P3 |
+| Kubernetes Support | Optional K8s cluster management | P3 |
+
+---
+
+## 11. Phase Implementation Plan
+
+### Phase 10.1: Foundation (Agent Core)
+**Duration: ~2-3 weeks**
+
+```
+[ ] Design and implement Go agent binary
+ [ ] Project setup with Go modules
+ [ ] Configuration loading (YAML)
+ [ ] Logging system (structured logs)
+ [ ] WebSocket client with reconnection
+ [ ] HMAC authentication
+ [ ] Heartbeat mechanism
+ [ ] Graceful shutdown handling
+
+[ ] Docker integration in agent
+ [ ] Connect to Docker socket
+ [ ] Container list/inspect
+ [ ] Container start/stop/restart
+ [ ] Basic stats collection
+
+[ ] Build pipeline
+ [ ] Cross-compilation for all platforms
+ [ ] Binary signing
+ [ ] Version embedding
+```
+
+### Phase 10.2: Backend Gateway
+**Duration: ~2 weeks**
+
+```
+[ ] Database models
+ [ ] Server, ServerGroup models
+ [ ] ServerMetrics, ServerCommand models
+ [ ] AgentSession model
+ [ ] Migrations
+
+[ ] Agent Gateway (WebSocket server)
+ [ ] SocketIO namespace for agents
+ [ ] Authentication handler
+ [ ] Session management
+ [ ] Command routing
+ [ ] Connection tracking
+
+[ ] API endpoints
+ [ ] Server CRUD
+ [ ] Registration token generation
+ [ ] Server status endpoint
+```
+
+### Phase 10.3: Security Layer
+**Duration: ~1-2 weeks**
+
+```
+[ ] Security implementation
+ [ ] API key generation and hashing
+ [ ] HMAC signature validation
+ [ ] Session token management
+ [ ] Permission checking middleware
+ [ ] Rate limiting per agent
+ [ ] Audit logging
+
+[ ] Agent security
+ [ ] Encrypted key storage
+ [ ] Command validation
+ [ ] Permission enforcement
+```
+
+### Phase 10.4: Frontend - Server Management
+**Duration: ~2 weeks**
+
+```
+[ ] Servers page
+ [ ] Server list view
+ [ ] Server cards/grid view
+ [ ] Add server modal
+ [ ] Installation instructions
+ [ ] Server detail page
+ [ ] Server settings
+
+[ ] Server groups
+ [ ] Group CRUD UI
+ [ ] Drag-drop organization
+ [ ] Group filtering
+```
+
+### Phase 10.5: Remote Docker Integration
+**Duration: ~2 weeks**
+
+```
+[ ] Backend: Docker command routing
+ [ ] Route Docker commands to agents
+ [ ] Handle async responses
+ [ ] Error handling
+
+[ ] Frontend: Docker page updates
+ [ ] Server selector dropdown
+ [ ] Context-aware Docker UI
+ [ ] Real-time container updates
+
+[ ] Agent: Full Docker support
+ [ ] All container operations
+ [ ] Image operations
+ [ ] Volume/network listing
+```
+
+### Phase 10.6: Monitoring & Metrics
+**Duration: ~2 weeks**
+
+```
+[ ] Real-time metrics
+ [ ] Agent metrics streaming
+ [ ] WebSocket to frontend
+ [ ] Live dashboard updates
+
+[ ] Historical metrics
+ [ ] Metrics storage
+ [ ] Retention policies
+ [ ] Aggregation queries
+
+[ ] Cross-server dashboard
+ [ ] Overview page
+ [ ] Metric comparison charts
+ [ ] Health grid view
+```
+
+### Phase 10.7: Installation & Distribution
+**Duration: ~1-2 weeks**
+
+```
+[ ] Installation scripts
+ [ ] Linux install script (bash)
+ [ ] Windows install script (PowerShell)
+ [ ] Docker image
+
+[ ] Package building
+ [ ] .deb packages
+ [ ] .rpm packages
+ [ ] .msi installer
+ [ ] Homebrew formula
+
+[ ] Distribution
+ [ ] Download page
+ [ ] Version checking
+ [ ] Auto-update mechanism
+```
+
+### Phase 10.8: Advanced Features
+**Duration: ~3-4 weeks**
+
+```
+[ ] Docker Compose on remote servers
+ [ ] Stack deployment
+ [ ] Stack management
+ [ ] Compose file editor
+
+[ ] Container logs streaming
+ [ ] Real-time log streaming
+ [ ] Log search/filter
+ [ ] Download logs
+
+[ ] Remote terminal (optional)
+ [ ] PTY support in agent
+ [ ] Terminal UI component
+ [ ] Session management
+```
+
+---
+
+## 12. Risk Assessment
+
+### Technical Risks
+
+| Risk | Impact | Likelihood | Mitigation |
+|------|--------|------------|------------|
+| WebSocket scalability | High | Medium | Use Redis pub/sub for horizontal scaling |
+| Agent memory leaks | Medium | Low | Extensive testing, memory profiling |
+| Network latency | Medium | Medium | Async commands, timeouts, retry logic |
+| Docker API changes | Low | Low | Pin Docker SDK version, integration tests |
+
+### Security Risks
+
+| Risk | Impact | Likelihood | Mitigation |
+|------|--------|------------|------------|
+| Stolen API keys | Critical | Medium | Key rotation, IP whitelist, anomaly detection |
+| Man-in-the-middle | Critical | Low | TLS mandatory, certificate pinning option |
+| Agent compromise | Critical | Low | Sandboxing, minimal privileges, audit logs |
+| Replay attacks | High | Medium | Timestamps, nonces, short-lived tokens |
+
+### Operational Risks
+
+| Risk | Impact | Likelihood | Mitigation |
+|------|--------|------------|------------|
+| Mass disconnect | High | Low | Graceful degradation, cached state |
+| Database growth | Medium | High | Metrics retention policy, archiving |
+| Support burden | Medium | High | Good documentation, self-service tools |
+
+---
+
+## 13. Success Metrics
+
+| Metric | Target |
+|--------|--------|
+| Agent installation time | < 5 minutes |
+| Agent memory usage | < 50 MB |
+| Command latency | < 500ms (local network) |
+| Max servers per instance | 100+ |
+| Uptime | 99.9% |
+| User satisfaction | > 4.5/5 rating |
+
+---
+
+## 14. Future Considerations
+
+### Potential Extensions
+- **Kubernetes Support**: Manage K8s clusters alongside Docker
+- **Multi-tenancy**: Multiple users/teams managing different server sets
+- **Terraform Integration**: Infrastructure as Code support
+- **Ansible Playbooks**: Configuration management
+- **CI/CD Integration**: Deploy from GitHub Actions, GitLab CI
+- **Mobile App**: Monitor servers from mobile devices
+- **Slack/Teams Bot**: Manage servers via chat commands
+
+### Not In Scope (for now)
+- Bare metal provisioning
+- Cloud provider integration (AWS, GCP, Azure)
+- Network topology management
+- DNS management
+- Load balancer configuration
+
+---
+
+## Appendix A: Agent Command Reference
+
+```
+serverkit-agent [command] [flags]
+
+Commands:
+ start Start the agent service
+ stop Stop the agent service
+ status Show agent status
+ register Register with ServerKit (interactive)
+ config Show/edit configuration
+ logs View agent logs
+ version Show version information
+ update Check for and install updates
+ uninstall Remove agent from system
+
+Flags:
+ --config, -c Path to config file
+ --debug, -d Enable debug logging
+ --token, -t Registration token (for register command)
+ --server, -s ServerKit URL (for register command)
+
+Examples:
+ serverkit-agent register --token "sk_reg_abc123" --server "https://serverkit.example.com"
+ serverkit-agent status
+ serverkit-agent logs --tail 100
+```
+
+---
+
+## Appendix B: Configuration Reference
+
+```yaml
+# Full agent configuration reference
+# Location: /etc/serverkit-agent/config.yaml (Linux)
+# C:\ProgramData\ServerKit\Agent\config.yaml (Windows)
+
+# ServerKit connection
+server:
+ url: wss://your-serverkit.example.com/agent/ws
+ reconnect_interval: 5s
+ max_reconnect_interval: 5m
+ ping_interval: 30s
+
+# Agent identity
+agent:
+ id: "auto-generated-uuid"
+ name: "server-display-name"
+
+# Authentication (auto-generated)
+auth:
+ key_file: /etc/serverkit-agent/agent.key
+
+# Feature toggles
+features:
+ docker: true
+ metrics: true
+ logs: true
+ file_access: false
+ exec: false
+
+# Metrics collection
+metrics:
+ enabled: true
+ interval: 10s
+ include_per_cpu: true
+ include_docker_stats: true
+
+# Docker configuration
+docker:
+ socket: /var/run/docker.sock # Linux
+ # socket: npipe:////./pipe/docker_engine # Windows
+ timeout: 30s
+
+# Security settings
+security:
+ allowed_paths: []
+ blocked_commands: []
+ max_exec_timeout: 300s
+
+# Logging
+logging:
+ level: info # debug, info, warn, error
+ file: /var/log/serverkit-agent/agent.log
+ max_size: 100MB
+ max_backups: 5
+ max_age: 30 # days
+ compress: true
+```
+
+---
+
+*This document is a living specification and will be updated as implementation progresses.*
+
+**Document Version**: 1.0.0
+**Last Updated**: 2025-01-21
+**Author**: ServerKit Team
diff --git a/agent/Makefile b/agent/Makefile
new file mode 100644
index 00000000..fc71374c
--- /dev/null
+++ b/agent/Makefile
@@ -0,0 +1,114 @@
+# ServerKit Agent Makefile
+
+VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
+BUILD_TIME ?= $(shell date -u +"%Y-%m-%dT%H:%M:%SZ")
+GIT_COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
+
+LDFLAGS := -s -w \
+ -X main.Version=$(VERSION) \
+ -X main.BuildTime=$(BUILD_TIME) \
+ -X main.GitCommit=$(GIT_COMMIT)
+
+BINARY_NAME := serverkit-agent
+DIST_DIR := dist
+
+.PHONY: all build clean test lint deps dev run
+
+all: build
+
+# Download dependencies
+deps:
+ go mod download
+ go mod tidy
+
+# Build for current platform
+build:
+ CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o $(BINARY_NAME) ./cmd/agent
+
+# Build for current platform with debug symbols
+dev:
+ go build -o $(BINARY_NAME) ./cmd/agent
+
+# Run the agent
+run: build
+ ./$(BINARY_NAME) start
+
+# Build for all platforms
+build-all:
+ @mkdir -p $(DIST_DIR)
+ @echo "Building for Linux amd64..."
+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-linux-amd64 ./cmd/agent
+ @echo "Building for Linux arm64..."
+ CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-linux-arm64 ./cmd/agent
+ @echo "Building for Windows amd64..."
+ CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-windows-amd64.exe ./cmd/agent
+ @echo "Building for Windows arm64..."
+ CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-windows-arm64.exe ./cmd/agent
+ @echo "Building for macOS amd64..."
+ CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-darwin-amd64 ./cmd/agent
+ @echo "Building for macOS arm64..."
+ CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-darwin-arm64 ./cmd/agent
+ @echo "Done! Binaries in $(DIST_DIR)/"
+
+# Build Linux only
+build-linux:
+ @mkdir -p $(DIST_DIR)
+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-linux-amd64 ./cmd/agent
+ CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-linux-arm64 ./cmd/agent
+
+# Build Windows only
+build-windows:
+ @mkdir -p $(DIST_DIR)
+ CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-windows-amd64.exe ./cmd/agent
+
+# Run tests
+test:
+ go test -v ./...
+
+# Run tests with coverage
+test-coverage:
+ go test -v -coverprofile=coverage.out ./...
+ go tool cover -html=coverage.out -o coverage.html
+
+# Run linter
+lint:
+ golangci-lint run ./...
+
+# Format code
+fmt:
+ go fmt ./...
+
+# Clean build artifacts
+clean:
+ rm -f $(BINARY_NAME)
+ rm -rf $(DIST_DIR)
+ rm -f coverage.out coverage.html
+
+# Install locally
+install: build
+ cp $(BINARY_NAME) /usr/local/bin/
+
+# Create checksums
+checksums:
+ @cd $(DIST_DIR) && sha256sum * > checksums.txt
+
+# Help
+help:
+ @echo "ServerKit Agent Build System"
+ @echo ""
+ @echo "Usage: make [target]"
+ @echo ""
+ @echo "Targets:"
+ @echo " build Build for current platform"
+ @echo " build-all Build for all platforms"
+ @echo " build-linux Build for Linux only"
+ @echo " build-windows Build for Windows only"
+ @echo " dev Build with debug symbols"
+ @echo " run Build and run the agent"
+ @echo " test Run tests"
+ @echo " lint Run linter"
+ @echo " fmt Format code"
+ @echo " clean Remove build artifacts"
+ @echo " deps Download dependencies"
+ @echo " install Install to /usr/local/bin"
+ @echo " help Show this help"
diff --git a/agent/README.md b/agent/README.md
new file mode 100644
index 00000000..b4e9f5d8
--- /dev/null
+++ b/agent/README.md
@@ -0,0 +1,272 @@
+# ServerKit Agent
+
+A lightweight, cross-platform agent for remote server management. Connects to a ServerKit control plane to enable Docker management, system monitoring, and remote command execution.
+
+## Features
+
+- **Cross-Platform**: Supports Linux (amd64, arm64, arm), Windows (amd64, arm64), and macOS (amd64, arm64)
+- **Lightweight**: Single binary, ~15MB RAM typical usage
+- **Docker Integration**: Full Docker API access for container management
+- **System Metrics**: Real-time CPU, memory, disk, and network monitoring
+- **Secure Communication**: TLS encryption with HMAC-SHA256 authentication
+- **Auto-Reconnect**: Automatic reconnection with exponential backoff
+- **Self-Update**: Built-in update mechanism (coming soon)
+
+## Quick Start
+
+### Linux (One-liner)
+
+```bash
+curl -fsSL https://your-serverkit.com/install.sh | sudo bash -s -- \
+ --token "sk_reg_your_token" \
+ --server "https://your-serverkit.com"
+```
+
+### Windows (PowerShell as Administrator)
+
+```powershell
+irm https://your-serverkit.com/install.ps1 | iex
+Install-ServerKitAgent -Token "sk_reg_your_token" -Server "https://your-serverkit.com"
+```
+
+### Manual Installation
+
+1. Download the appropriate binary for your platform from the releases page
+2. Register the agent:
+ ```bash
+ ./serverkit-agent register --token "sk_reg_xxx" --server "https://your-serverkit.com"
+ ```
+3. Start the agent:
+ ```bash
+ ./serverkit-agent start
+ ```
+
+## Building from Source
+
+### Prerequisites
+
+- Go 1.21 or later
+- Make (optional, for using Makefile)
+
+### Build
+
+```bash
+# Clone the repository
+git clone https://github.com/serverkit/agent.git
+cd agent
+
+# Download dependencies
+go mod download
+
+# Build for current platform
+make build
+
+# Or build for all platforms
+make build-all
+```
+
+### Build Outputs
+
+Binaries are placed in the `dist/` directory:
+- `serverkit-agent-{version}-linux-amd64`
+- `serverkit-agent-{version}-linux-arm64`
+- `serverkit-agent-{version}-windows-amd64.exe`
+- `serverkit-agent-{version}-darwin-amd64`
+- `serverkit-agent-{version}-darwin-arm64`
+
+## Usage
+
+### Commands
+
+```
+serverkit-agent [command]
+
+Available Commands:
+ start Start the agent service
+ register Register with a ServerKit instance
+ status Show agent status
+ config Configuration management
+ version Show version information
+ help Help about any command
+
+Flags:
+ -c, --config string config file path
+ -d, --debug enable debug logging
+ -h, --help help for serverkit-agent
+```
+
+### Register
+
+```bash
+serverkit-agent register \
+ --token "sk_reg_xxx" \
+ --server "https://your-serverkit.com" \
+ --name "my-server"
+```
+
+### Start
+
+```bash
+# Foreground
+serverkit-agent start
+
+# With debug logging
+serverkit-agent start --debug
+```
+
+## Configuration
+
+Configuration file location:
+- **Linux**: `/etc/serverkit-agent/config.yaml`
+- **Windows**: `C:\ProgramData\ServerKit\Agent\config.yaml`
+
+### Example Configuration
+
+```yaml
+server:
+ url: wss://your-serverkit.com/agent/ws
+ reconnect_interval: 5s
+ max_reconnect_interval: 5m
+ ping_interval: 30s
+
+agent:
+ id: "auto-generated"
+ name: "my-server"
+
+features:
+ docker: true
+ metrics: true
+ logs: true
+ file_access: false
+ exec: false
+
+metrics:
+ enabled: true
+ interval: 10s
+ include_per_cpu: true
+ include_docker_stats: true
+
+docker:
+ socket: /var/run/docker.sock
+ timeout: 30s
+
+logging:
+ level: info
+ file: /var/log/serverkit-agent/agent.log
+ max_size_mb: 100
+ max_backups: 5
+ max_age_days: 30
+ compress: true
+```
+
+## Security
+
+### Authentication
+
+The agent uses HMAC-SHA256 signatures for authentication:
+1. During registration, the agent receives an API key and secret
+2. Each WebSocket connection is authenticated using HMAC-signed messages
+3. Session tokens are issued after successful authentication
+
+### Credentials Storage
+
+Credentials are encrypted at rest using AES-256-GCM with a machine-specific key derived from:
+- Hostname
+- Machine ID (Linux) or computer/user name (Windows)
+
+### Network Security
+
+- All communication uses TLS (WSS)
+- Certificate validation is enforced in production
+- Replay attack protection via timestamps and nonces
+
+## Systemd Service (Linux)
+
+The installation script automatically creates a systemd service:
+
+```bash
+# Check status
+systemctl status serverkit-agent
+
+# View logs
+journalctl -u serverkit-agent -f
+
+# Restart
+systemctl restart serverkit-agent
+```
+
+## Windows Service
+
+On Windows, the agent runs as a Windows Service:
+
+```powershell
+# Check status
+Get-Service ServerKitAgent
+
+# View logs
+Get-Content "C:\ProgramData\ServerKit\Agent\logs\agent.log" -Tail 50
+
+# Restart
+Restart-Service ServerKitAgent
+```
+
+## Development
+
+### Project Structure
+
+```
+agent/
+├── cmd/agent/ # Main entry point
+├── internal/
+│ ├── agent/ # Core agent logic
+│ ├── auth/ # HMAC authentication
+│ ├── config/ # Configuration management
+│ ├── docker/ # Docker client wrapper
+│ ├── logger/ # Structured logging
+│ ├── metrics/ # System metrics collection
+│ └── ws/ # WebSocket client
+├── pkg/protocol/ # Message protocol definitions
+├── scripts/ # Build and install scripts
+├── Makefile
+└── go.mod
+```
+
+### Running Tests
+
+```bash
+make test
+```
+
+### Code Formatting
+
+```bash
+make fmt
+```
+
+## Troubleshooting
+
+### Agent won't connect
+
+1. Check the server URL is correct
+2. Verify the registration token is valid
+3. Check firewall allows outbound WebSocket connections
+4. Review logs: `journalctl -u serverkit-agent -n 50`
+
+### Docker commands fail
+
+1. Ensure Docker is installed and running
+2. Verify the agent user has Docker permissions:
+ ```bash
+ sudo usermod -aG docker serverkit-agent
+ ```
+3. Check Docker socket permissions
+
+### High CPU/Memory usage
+
+1. Increase the metrics interval in config
+2. Disable per-CPU metrics if not needed
+3. Check for log rotation issues
+
+## License
+
+MIT License - see LICENSE file for details.
diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.go
new file mode 100644
index 00000000..e54ba421
--- /dev/null
+++ b/agent/cmd/agent/main.go
@@ -0,0 +1,264 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/serverkit/agent/internal/agent"
+ "github.com/serverkit/agent/internal/config"
+ "github.com/serverkit/agent/internal/logger"
+ "github.com/spf13/cobra"
+)
+
+var (
+ Version = "dev"
+ BuildTime = "unknown"
+ GitCommit = "unknown"
+)
+
+var (
+ cfgFile string
+ debugMode bool
+)
+
+func main() {
+ rootCmd := &cobra.Command{
+ Use: "serverkit-agent",
+ Short: "ServerKit Agent - Remote server management agent",
+ Long: `ServerKit Agent connects your server to a ServerKit control plane,
+enabling remote Docker management, monitoring, and more.`,
+ }
+
+ // Global flags
+ rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file path")
+ rootCmd.PersistentFlags().BoolVarP(&debugMode, "debug", "d", false, "enable debug logging")
+
+ // Add commands
+ rootCmd.AddCommand(startCmd())
+ rootCmd.AddCommand(registerCmd())
+ rootCmd.AddCommand(statusCmd())
+ rootCmd.AddCommand(versionCmd())
+ rootCmd.AddCommand(configCmd())
+
+ if err := rootCmd.Execute(); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
+
+func startCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "start",
+ Short: "Start the agent service",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runAgent()
+ },
+ }
+}
+
+func registerCmd() *cobra.Command {
+ var token string
+ var serverURL string
+ var name string
+
+ cmd := &cobra.Command{
+ Use: "register",
+ Short: "Register this agent with a ServerKit instance",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runRegister(token, serverURL, name)
+ },
+ }
+
+ cmd.Flags().StringVarP(&token, "token", "t", "", "registration token (required)")
+ cmd.Flags().StringVarP(&serverURL, "server", "s", "", "ServerKit server URL (required)")
+ cmd.Flags().StringVarP(&name, "name", "n", "", "display name for this server")
+ cmd.MarkFlagRequired("token")
+ cmd.MarkFlagRequired("server")
+
+ return cmd
+}
+
+func statusCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "status",
+ Short: "Show agent status",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return showStatus()
+ },
+ }
+}
+
+func versionCmd() *cobra.Command {
+ return &cobra.Command{
+ Use: "version",
+ Short: "Show version information",
+ Run: func(cmd *cobra.Command, args []string) {
+ fmt.Printf("ServerKit Agent\n")
+ fmt.Printf(" Version: %s\n", Version)
+ fmt.Printf(" Build Time: %s\n", BuildTime)
+ fmt.Printf(" Git Commit: %s\n", GitCommit)
+ },
+ }
+}
+
+func configCmd() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "config",
+ Short: "Configuration management",
+ }
+
+ cmd.AddCommand(&cobra.Command{
+ Use: "show",
+ Short: "Show current configuration",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ cfg, err := config.Load(cfgFile)
+ if err != nil {
+ return fmt.Errorf("failed to load config: %w", err)
+ }
+ cfg.Print()
+ return nil
+ },
+ })
+
+ cmd.AddCommand(&cobra.Command{
+ Use: "path",
+ Short: "Show configuration file path",
+ Run: func(cmd *cobra.Command, args []string) {
+ fmt.Println(config.DefaultConfigPath())
+ },
+ })
+
+ return cmd
+}
+
+func runAgent() error {
+ // Load configuration
+ cfg, err := config.Load(cfgFile)
+ if err != nil {
+ return fmt.Errorf("failed to load config: %w", err)
+ }
+
+ // Override debug mode if flag is set
+ if debugMode {
+ cfg.Logging.Level = "debug"
+ }
+
+ // Initialize logger
+ log := logger.New(cfg.Logging)
+ log.Info("Starting ServerKit Agent",
+ "version", Version,
+ "config", config.DefaultConfigPath(),
+ )
+
+ // Check if registered
+ if cfg.Agent.ID == "" {
+ return fmt.Errorf("agent not registered. Run 'serverkit-agent register' first")
+ }
+
+ // Create and start agent
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ ag, err := agent.New(cfg, log)
+ if err != nil {
+ return fmt.Errorf("failed to create agent: %w", err)
+ }
+
+ // Handle graceful shutdown
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
+
+ go func() {
+ sig := <-sigCh
+ log.Info("Received shutdown signal", "signal", sig.String())
+ cancel()
+ }()
+
+ // Start agent
+ if err := ag.Run(ctx); err != nil && err != context.Canceled {
+ return fmt.Errorf("agent error: %w", err)
+ }
+
+ log.Info("Agent stopped gracefully")
+ return nil
+}
+
+func runRegister(token, serverURL, name string) error {
+ log := logger.New(config.LoggingConfig{Level: "info"})
+
+ log.Info("Registering agent with ServerKit",
+ "server", serverURL,
+ )
+
+ // Load or create config
+ cfg, err := config.Load(cfgFile)
+ if err != nil {
+ // Create new config if doesn't exist
+ cfg = config.Default()
+ }
+
+ // Register with server
+ reg := agent.NewRegistration(log)
+ result, err := reg.Register(serverURL, token, name)
+ if err != nil {
+ return fmt.Errorf("registration failed: %w", err)
+ }
+
+ // Update config
+ cfg.Server.URL = result.WebSocketURL
+ cfg.Agent.ID = result.AgentID
+ cfg.Agent.Name = result.Name
+ cfg.Auth.APIKey = result.APIKey
+ cfg.Auth.APISecret = result.APISecret
+
+ // Save config
+ if err := cfg.Save(config.DefaultConfigPath()); err != nil {
+ return fmt.Errorf("failed to save config: %w", err)
+ }
+
+ // Save credentials securely
+ if err := cfg.SaveCredentials(); err != nil {
+ return fmt.Errorf("failed to save credentials: %w", err)
+ }
+
+ log.Info("Registration successful!",
+ "agent_id", result.AgentID,
+ "name", result.Name,
+ )
+
+ fmt.Println("\nAgent registered successfully!")
+ fmt.Printf(" Agent ID: %s\n", result.AgentID)
+ fmt.Printf(" Name: %s\n", result.Name)
+ fmt.Println("\nStart the agent with: serverkit-agent start")
+
+ return nil
+}
+
+func showStatus() error {
+ cfg, err := config.Load(cfgFile)
+ if err != nil {
+ fmt.Println("Status: Not configured")
+ fmt.Printf(" Config file not found at %s\n", config.DefaultConfigPath())
+ fmt.Println("\nRun 'serverkit-agent register' to configure.")
+ return nil
+ }
+
+ if cfg.Agent.ID == "" {
+ fmt.Println("Status: Not registered")
+ fmt.Println("\nRun 'serverkit-agent register' to register with a ServerKit instance.")
+ return nil
+ }
+
+ fmt.Println("Status: Configured")
+ fmt.Printf(" Agent ID: %s\n", cfg.Agent.ID)
+ fmt.Printf(" Agent Name: %s\n", cfg.Agent.Name)
+ fmt.Printf(" Server: %s\n", cfg.Server.URL)
+
+ // TODO: Check if actually connected
+ // This would require checking a PID file or socket
+
+ return nil
+}
diff --git a/agent/go.mod b/agent/go.mod
new file mode 100644
index 00000000..688d2d17
--- /dev/null
+++ b/agent/go.mod
@@ -0,0 +1,41 @@
+module github.com/serverkit/agent
+
+go 1.21
+
+require (
+ github.com/docker/docker v24.0.7+incompatible
+ github.com/gorilla/websocket v1.5.1
+ github.com/shirou/gopsutil/v3 v3.24.1
+ github.com/spf13/cobra v1.8.0
+ gopkg.in/natefinch/lumberjack.v2 v2.2.1
+ gopkg.in/yaml.v3 v3.0.1
+)
+
+require (
+ github.com/Microsoft/go-winio v0.6.1 // indirect
+ github.com/distribution/reference v0.5.0 // indirect
+ github.com/docker/distribution v2.8.3+incompatible // indirect
+ github.com/docker/go-connections v0.4.0 // indirect
+ github.com/docker/go-units v0.5.0 // indirect
+ github.com/go-ole/go-ole v1.3.0 // indirect
+ github.com/gogo/protobuf v1.3.2 // indirect
+ github.com/inconshreveable/mousetrap v1.1.0 // indirect
+ github.com/lufia/plan9stats v0.0.0-20231016141302-07b5767bb0ed // indirect
+ github.com/moby/term v0.5.0 // indirect
+ github.com/morikuni/aec v1.0.0 // indirect
+ github.com/opencontainers/go-digest v1.0.0 // indirect
+ github.com/opencontainers/image-spec v1.1.0-rc5 // indirect
+ github.com/pkg/errors v0.9.1 // indirect
+ github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b // indirect
+ github.com/shoenig/go-m1cpu v0.1.6 // indirect
+ github.com/spf13/pflag v1.0.5 // indirect
+ github.com/tklauser/go-sysconf v0.3.13 // indirect
+ github.com/tklauser/numcpus v0.7.0 // indirect
+ github.com/yusufpapurcu/wmi v1.2.3 // indirect
+ golang.org/x/mod v0.14.0 // indirect
+ golang.org/x/net v0.19.0 // indirect
+ golang.org/x/sys v0.16.0 // indirect
+ golang.org/x/time v0.5.0 // indirect
+ golang.org/x/tools v0.16.1 // indirect
+ gotest.tools/v3 v3.5.1 // indirect
+)
diff --git a/agent/go.sum b/agent/go.sum
new file mode 100644
index 00000000..a273f328
--- /dev/null
+++ b/agent/go.sum
@@ -0,0 +1,130 @@
+github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8=
+github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
+github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow=
+github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM=
+github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/distribution/reference v0.5.0 h1:/FUIFXtfc/x2gpa5/VGfiGLuOIdYa1t65IKK2OFGvA0=
+github.com/distribution/reference v0.5.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
+github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk=
+github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
+github.com/docker/docker v24.0.7+incompatible h1:Wo6l37AuwP3JaMnZa226lzVXGA3F9Ig1seQen0cKYlM=
+github.com/docker/docker v24.0.7+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
+github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ=
+github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
+github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
+github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
+github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
+github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
+github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
+github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
+github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
+github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
+github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
+github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
+github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
+github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
+github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
+github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
+github.com/lufia/plan9stats v0.0.0-20231016141302-07b5767bb0ed h1:036IscGBfJsFIgJQzlui7nK1Ncm0tp2ktmPj8xO4N/0=
+github.com/lufia/plan9stats v0.0.0-20231016141302-07b5767bb0ed/go.mod h1:ilwx/Dta8jXAgpFYFvSWEMwxmbWXyiUHkd5FwyKhb5k=
+github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
+github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
+github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
+github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
+github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
+github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
+github.com/opencontainers/image-spec v1.1.0-rc5 h1:Ygwkfw9bpDvs+c9E34SdgGOj41dX/cbdlwvlWt0pnFI=
+github.com/opencontainers/image-spec v1.1.0-rc5/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8=
+github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
+github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b h1:0LFwY6Q3gMACTjAbMZBjXAqTOzOwFaj2Ld6cjeQ7Rig=
+github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
+github.com/shirou/gopsutil/v3 v3.24.1 h1:R3t6ondCEvmARp3wxODhXMTLC/klMa87h2PHUw5m7QI=
+github.com/shirou/gopsutil/v3 v3.24.1/go.mod h1:UU7a2MSBQa+kW1uuDq8DeEBS8kmrnQwsv2b5O513rwU=
+github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
+github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
+github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU=
+github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=
+github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
+github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
+github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
+github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
+github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
+github.com/tklauser/go-sysconf v0.3.13 h1:GBUpcahXSpR2xN01jhkNAbTLRk2Yzgggk8IM08lq3r4=
+github.com/tklauser/go-sysconf v0.3.13/go.mod h1:zwleP4Q4OehZHGn4CYZDipCgg9usW5IJePewFCGVEa0=
+github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
+github.com/tklauser/numcpus v0.7.0 h1:yjuerZP127QG9m5Zh/mSO4wqurYil27tHrqwRoRjpr4=
+github.com/tklauser/numcpus v0.7.0/go.mod h1:bb6dMVcj8A42tSE7i32fsIUCbQNllK5iDguyOZRUzAY=
+github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
+github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
+github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFiw=
+github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
+golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
+golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0=
+golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
+golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
+golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
+golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
+golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
+golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
+golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
+golang.org/x/tools v0.16.1 h1:TLyB3WofjdOEepBHAU20JdNC1Zbg87elYofWYAY5oZA=
+golang.org/x/tools v0.16.1/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
+gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU=
+gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU=
diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.go
new file mode 100644
index 00000000..80c3416a
--- /dev/null
+++ b/agent/internal/agent/agent.go
@@ -0,0 +1,523 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "sync"
+ "time"
+
+ "github.com/serverkit/agent/internal/auth"
+ "github.com/serverkit/agent/internal/config"
+ "github.com/serverkit/agent/internal/docker"
+ "github.com/serverkit/agent/internal/logger"
+ "github.com/serverkit/agent/internal/metrics"
+ "github.com/serverkit/agent/internal/ws"
+ "github.com/serverkit/agent/pkg/protocol"
+)
+
+// Agent is the main agent that coordinates all components
+type Agent struct {
+ cfg *config.Config
+ log *logger.Logger
+ auth *auth.Authenticator
+ ws *ws.Client
+ docker *docker.Client
+ metrics *metrics.Collector
+
+ // Active subscriptions
+ subscriptions map[string]context.CancelFunc
+ subMu sync.Mutex
+
+ // Command handlers
+ handlers map[string]CommandHandler
+}
+
+// CommandHandler is a function that handles a command
+type CommandHandler func(ctx context.Context, params json.RawMessage) (interface{}, error)
+
+// New creates a new Agent
+func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {
+ // Create authenticator
+ authenticator := auth.New(cfg.Agent.ID, cfg.Auth.APIKey, cfg.Auth.APISecret)
+
+ // Create WebSocket client
+ wsClient := ws.NewClient(cfg.Server, authenticator, log)
+
+ // Create Docker client if enabled
+ var dockerClient *docker.Client
+ if cfg.Features.Docker {
+ var err error
+ dockerClient, err = docker.NewClient(cfg.Docker, log)
+ if err != nil {
+ log.Warn("Failed to create Docker client", "error", err)
+ // Don't fail - Docker may not be available
+ }
+ }
+
+ // Create metrics collector if enabled
+ var metricsCollector *metrics.Collector
+ if cfg.Features.Metrics {
+ metricsCollector = metrics.NewCollector(cfg.Metrics, log)
+ }
+
+ agent := &Agent{
+ cfg: cfg,
+ log: log,
+ auth: authenticator,
+ ws: wsClient,
+ docker: dockerClient,
+ metrics: metricsCollector,
+ subscriptions: make(map[string]context.CancelFunc),
+ handlers: make(map[string]CommandHandler),
+ }
+
+ // Register command handlers
+ agent.registerHandlers()
+
+ // Set WebSocket message handler
+ wsClient.SetHandler(agent.handleMessage)
+
+ return agent, nil
+}
+
+// registerHandlers registers all command handlers
+func (a *Agent) registerHandlers() {
+ // Docker container commands
+ if a.docker != nil {
+ a.handlers[protocol.ActionDockerContainerList] = a.handleDockerContainerList
+ a.handlers[protocol.ActionDockerContainerInspect] = a.handleDockerContainerInspect
+ a.handlers[protocol.ActionDockerContainerStart] = a.handleDockerContainerStart
+ a.handlers[protocol.ActionDockerContainerStop] = a.handleDockerContainerStop
+ a.handlers[protocol.ActionDockerContainerRestart] = a.handleDockerContainerRestart
+ a.handlers[protocol.ActionDockerContainerRemove] = a.handleDockerContainerRemove
+ a.handlers[protocol.ActionDockerContainerStats] = a.handleDockerContainerStats
+
+ // Docker image commands
+ a.handlers[protocol.ActionDockerImageList] = a.handleDockerImageList
+ a.handlers[protocol.ActionDockerImagePull] = a.handleDockerImagePull
+ a.handlers[protocol.ActionDockerImageRemove] = a.handleDockerImageRemove
+
+ // Docker volume commands
+ a.handlers[protocol.ActionDockerVolumeList] = a.handleDockerVolumeList
+ a.handlers[protocol.ActionDockerVolumeRemove] = a.handleDockerVolumeRemove
+
+ // Docker network commands
+ a.handlers[protocol.ActionDockerNetworkList] = a.handleDockerNetworkList
+ }
+
+ // System commands
+ if a.metrics != nil {
+ a.handlers[protocol.ActionSystemMetrics] = a.handleSystemMetrics
+ a.handlers[protocol.ActionSystemInfo] = a.handleSystemInfo
+ a.handlers[protocol.ActionSystemProcesses] = a.handleSystemProcesses
+ }
+}
+
+// Run starts the agent
+func (a *Agent) Run(ctx context.Context) error {
+ a.log.Info("Starting agent",
+ "agent_id", a.cfg.Agent.ID,
+ "features", fmt.Sprintf("docker=%v metrics=%v", a.cfg.Features.Docker, a.cfg.Features.Metrics),
+ )
+
+ // Verify Docker connection if enabled
+ if a.docker != nil {
+ if err := a.docker.Ping(ctx); err != nil {
+ a.log.Warn("Docker is not available", "error", err)
+ } else {
+ version, _ := a.docker.Version(ctx)
+ a.log.Info("Docker connected", "version", version)
+ }
+ }
+
+ // Start WebSocket connection in background
+ go func() {
+ if err := a.ws.Run(ctx); err != nil && err != context.Canceled {
+ a.log.Error("WebSocket error", "error", err)
+ }
+ }()
+
+ // Start heartbeat loop
+ go a.heartbeatLoop(ctx)
+
+ // Wait for context cancellation
+ <-ctx.Done()
+
+ // Cleanup
+ a.cleanup()
+
+ return ctx.Err()
+}
+
+// heartbeatLoop sends periodic heartbeats
+func (a *Agent) heartbeatLoop(ctx context.Context) {
+ ticker := time.NewTicker(a.cfg.Server.PingInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ if !a.ws.IsConnected() {
+ continue
+ }
+
+ heartbeatMetrics := protocol.HeartbeatMetrics{}
+
+ // Collect basic metrics for heartbeat
+ if a.metrics != nil {
+ sysMetrics, err := a.metrics.Collect(ctx)
+ if err == nil {
+ heartbeatMetrics.CPUPercent = sysMetrics.CPUPercent
+ heartbeatMetrics.MemoryPercent = sysMetrics.MemoryPercent
+ heartbeatMetrics.DiskPercent = sysMetrics.DiskPercent
+ }
+ }
+
+ // Get container counts if Docker is available
+ if a.docker != nil {
+ total, running, err := a.docker.GetContainerCount(ctx)
+ if err == nil {
+ heartbeatMetrics.ContainerCount = total
+ heartbeatMetrics.ContainerRunning = running
+ }
+ }
+
+ if err := a.ws.SendHeartbeat(heartbeatMetrics); err != nil {
+ a.log.Warn("Failed to send heartbeat", "error", err)
+ } else {
+ a.log.Debug("Heartbeat sent",
+ "cpu", fmt.Sprintf("%.1f%%", heartbeatMetrics.CPUPercent),
+ "mem", fmt.Sprintf("%.1f%%", heartbeatMetrics.MemoryPercent),
+ )
+ }
+ }
+ }
+}
+
+// handleMessage handles incoming WebSocket messages
+func (a *Agent) handleMessage(msgType protocol.MessageType, data []byte) {
+ a.log.Debug("Received message", "type", msgType)
+
+ switch msgType {
+ case protocol.TypeCommand:
+ a.handleCommand(data)
+ case protocol.TypeSubscribe:
+ a.handleSubscribe(data)
+ case protocol.TypeUnsubscribe:
+ a.handleUnsubscribe(data)
+ default:
+ a.log.Warn("Unknown message type", "type", msgType)
+ }
+}
+
+// handleCommand handles command messages
+func (a *Agent) handleCommand(data []byte) {
+ var cmd protocol.CommandMessage
+ if err := json.Unmarshal(data, &cmd); err != nil {
+ a.log.Error("Failed to parse command", "error", err)
+ return
+ }
+
+ a.log.Info("Executing command",
+ "id", cmd.ID,
+ "action", cmd.Action,
+ )
+
+ // Find handler
+ handler, ok := a.handlers[cmd.Action]
+ if !ok {
+ a.log.Warn("Unknown command action", "action", cmd.Action)
+ a.ws.SendCommandResult(cmd.ID, false, nil, "unknown action: "+cmd.Action, 0)
+ return
+ }
+
+ // Execute command
+ start := time.Now()
+ ctx := context.Background()
+ if cmd.Timeout > 0 {
+ var cancel context.CancelFunc
+ ctx, cancel = context.WithTimeout(ctx, time.Duration(cmd.Timeout)*time.Millisecond)
+ defer cancel()
+ }
+
+ result, err := handler(ctx, cmd.Params)
+ duration := time.Since(start)
+
+ if err != nil {
+ a.log.Error("Command failed",
+ "id", cmd.ID,
+ "action", cmd.Action,
+ "error", err,
+ "duration", duration,
+ )
+ a.ws.SendCommandResult(cmd.ID, false, nil, err.Error(), duration)
+ return
+ }
+
+ a.log.Info("Command completed",
+ "id", cmd.ID,
+ "action", cmd.Action,
+ "duration", duration,
+ )
+ a.ws.SendCommandResult(cmd.ID, true, result, "", duration)
+}
+
+// handleSubscribe handles subscription requests
+func (a *Agent) handleSubscribe(data []byte) {
+ var sub protocol.SubscribeMessage
+ if err := json.Unmarshal(data, &sub); err != nil {
+ a.log.Error("Failed to parse subscribe message", "error", err)
+ return
+ }
+
+ a.log.Info("Subscribing to channel", "channel", sub.Channel)
+
+ // Create cancellable context for this subscription
+ ctx, cancel := context.WithCancel(context.Background())
+
+ a.subMu.Lock()
+ // Cancel existing subscription if any
+ if existingCancel, ok := a.subscriptions[sub.Channel]; ok {
+ existingCancel()
+ }
+ a.subscriptions[sub.Channel] = cancel
+ a.subMu.Unlock()
+
+ // Start streaming based on channel type
+ go a.streamData(ctx, sub.Channel)
+}
+
+// handleUnsubscribe handles unsubscription requests
+func (a *Agent) handleUnsubscribe(data []byte) {
+ var unsub protocol.UnsubscribeMessage
+ if err := json.Unmarshal(data, &unsub); err != nil {
+ a.log.Error("Failed to parse unsubscribe message", "error", err)
+ return
+ }
+
+ a.log.Info("Unsubscribing from channel", "channel", unsub.Channel)
+
+ a.subMu.Lock()
+ if cancel, ok := a.subscriptions[unsub.Channel]; ok {
+ cancel()
+ delete(a.subscriptions, unsub.Channel)
+ }
+ a.subMu.Unlock()
+}
+
+// streamData streams data for a subscription
+func (a *Agent) streamData(ctx context.Context, channel string) {
+ // Determine what to stream based on channel
+ switch channel {
+ case protocol.ChannelMetrics:
+ a.streamMetrics(ctx, channel)
+ default:
+ a.log.Warn("Unknown stream channel", "channel", channel)
+ }
+}
+
+// streamMetrics streams system metrics
+func (a *Agent) streamMetrics(ctx context.Context, channel string) {
+ ticker := time.NewTicker(a.cfg.Metrics.Interval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ if a.metrics == nil {
+ continue
+ }
+
+ sysMetrics, err := a.metrics.Collect(ctx)
+ if err != nil {
+ a.log.Warn("Failed to collect metrics", "error", err)
+ continue
+ }
+
+ if err := a.ws.SendStream(channel, sysMetrics); err != nil {
+ a.log.Warn("Failed to send metrics stream", "error", err)
+ }
+ }
+ }
+}
+
+// cleanup performs cleanup on shutdown
+func (a *Agent) cleanup() {
+ a.log.Info("Cleaning up...")
+
+ // Cancel all subscriptions
+ a.subMu.Lock()
+ for _, cancel := range a.subscriptions {
+ cancel()
+ }
+ a.subscriptions = make(map[string]context.CancelFunc)
+ a.subMu.Unlock()
+
+ // Close WebSocket
+ a.ws.Close()
+
+ // Close Docker client
+ if a.docker != nil {
+ a.docker.Close()
+ }
+}
+
+// Docker command handlers
+
+func (a *Agent) handleDockerContainerList(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ All bool `json:"all"`
+ }
+ if len(params) > 0 {
+ json.Unmarshal(params, &p)
+ }
+ return a.docker.ListContainers(ctx, p.All)
+}
+
+func (a *Agent) handleDockerContainerInspect(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ID string `json:"id"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ return a.docker.InspectContainer(ctx, p.ID)
+}
+
+func (a *Agent) handleDockerContainerStart(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ID string `json:"id"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ return map[string]bool{"success": true}, a.docker.StartContainer(ctx, p.ID)
+}
+
+func (a *Agent) handleDockerContainerStop(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ID string `json:"id"`
+ Timeout *int `json:"timeout"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ return map[string]bool{"success": true}, a.docker.StopContainer(ctx, p.ID, p.Timeout)
+}
+
+func (a *Agent) handleDockerContainerRestart(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ID string `json:"id"`
+ Timeout *int `json:"timeout"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ return map[string]bool{"success": true}, a.docker.RestartContainer(ctx, p.ID, p.Timeout)
+}
+
+func (a *Agent) handleDockerContainerRemove(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ID string `json:"id"`
+ Force bool `json:"force"`
+ RemoveVolumes bool `json:"remove_volumes"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ return map[string]bool{"success": true}, a.docker.RemoveContainer(ctx, p.ID, p.Force, p.RemoveVolumes)
+}
+
+func (a *Agent) handleDockerContainerStats(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ID string `json:"id"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ return a.docker.ContainerStats(ctx, p.ID)
+}
+
+func (a *Agent) handleDockerImageList(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ return a.docker.ListImages(ctx)
+}
+
+func (a *Agent) handleDockerImagePull(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ Image string `json:"image"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+
+ reader, err := a.docker.PullImage(ctx, p.Image)
+ if err != nil {
+ return nil, err
+ }
+ defer reader.Close()
+
+ // Read the output to completion
+ var output []map[string]interface{}
+ decoder := json.NewDecoder(reader)
+ for decoder.More() {
+ var msg map[string]interface{}
+ if err := decoder.Decode(&msg); err != nil {
+ break
+ }
+ output = append(output, msg)
+ }
+
+ return map[string]interface{}{
+ "success": true,
+ "output": output,
+ }, nil
+}
+
+func (a *Agent) handleDockerImageRemove(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ID string `json:"id"`
+ Force bool `json:"force"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ return map[string]bool{"success": true}, a.docker.RemoveImage(ctx, p.ID, p.Force)
+}
+
+func (a *Agent) handleDockerVolumeList(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ return a.docker.ListVolumes(ctx)
+}
+
+func (a *Agent) handleDockerVolumeRemove(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ Name string `json:"name"`
+ Force bool `json:"force"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ return map[string]bool{"success": true}, a.docker.RemoveVolume(ctx, p.Name, p.Force)
+}
+
+func (a *Agent) handleDockerNetworkList(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ return a.docker.ListNetworks(ctx)
+}
+
+// System command handlers
+
+func (a *Agent) handleSystemMetrics(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ return a.metrics.Collect(ctx)
+}
+
+func (a *Agent) handleSystemInfo(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ return a.metrics.GetSystemInfo(ctx)
+}
+
+func (a *Agent) handleSystemProcesses(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ return a.metrics.ListProcesses(ctx)
+}
diff --git a/agent/internal/agent/registration.go b/agent/internal/agent/registration.go
new file mode 100644
index 00000000..36358d40
--- /dev/null
+++ b/agent/internal/agent/registration.go
@@ -0,0 +1,196 @@
+package agent
+
+import (
+ "bytes"
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "runtime"
+ "strings"
+ "time"
+
+ "github.com/serverkit/agent/internal/config"
+ "github.com/serverkit/agent/internal/logger"
+ "github.com/serverkit/agent/internal/metrics"
+)
+
+// Registration handles agent registration with ServerKit
+type Registration struct {
+ log *logger.Logger
+}
+
+// RegistrationResult contains the result of registration
+type RegistrationResult struct {
+ AgentID string `json:"agent_id"`
+ Name string `json:"name"`
+ APIKey string `json:"api_key"`
+ APISecret string `json:"api_secret"`
+ WebSocketURL string `json:"websocket_url"`
+}
+
+// NewRegistration creates a new Registration handler
+func NewRegistration(log *logger.Logger) *Registration {
+ return &Registration{
+ log: log.WithComponent("registration"),
+ }
+}
+
+// Register registers the agent with a ServerKit instance
+func (r *Registration) Register(serverURL, token, name string) (*RegistrationResult, error) {
+ // Normalize server URL
+ serverURL = strings.TrimSuffix(serverURL, "/")
+
+ // If no name provided, use hostname
+ if name == "" {
+ hostname, err := os.Hostname()
+ if err != nil {
+ name = "unknown-server"
+ } else {
+ name = hostname
+ }
+ }
+
+ // Collect system info for registration
+ collector := metrics.NewCollector(config.MetricsConfig{}, r.log)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ sysInfo, err := collector.GetSystemInfo(ctx)
+ if err != nil {
+ r.log.Warn("Failed to collect system info", "error", err)
+ sysInfo = &metrics.SystemInfo{
+ Hostname: name,
+ OS: runtime.GOOS,
+ Architecture: runtime.GOARCH,
+ }
+ }
+
+ // Prepare registration request
+ reqBody := map[string]interface{}{
+ "token": token,
+ "name": name,
+ "system_info": map[string]interface{}{
+ "hostname": sysInfo.Hostname,
+ "os": sysInfo.OS,
+ "platform": sysInfo.Platform,
+ "platform_version": sysInfo.PlatformVersion,
+ "architecture": sysInfo.Architecture,
+ "cpu_cores": sysInfo.CPUCores,
+ "total_memory": sysInfo.TotalMemory,
+ "total_disk": sysInfo.TotalDisk,
+ },
+ "agent_version": Version,
+ }
+
+ bodyBytes, err := json.Marshal(reqBody)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal request: %w", err)
+ }
+
+ // Create HTTP client
+ client := &http.Client{
+ Timeout: 30 * time.Second,
+ Transport: &http.Transport{
+ TLSClientConfig: &tls.Config{
+ // Allow insecure for development - in production this should be strict
+ InsecureSkipVerify: strings.HasPrefix(serverURL, "http://") || strings.Contains(serverURL, "localhost"),
+ },
+ },
+ }
+
+ // Make registration request
+ registrationURL := serverURL + "/api/v1/agents/register"
+ r.log.Info("Sending registration request", "url", registrationURL)
+
+ req, err := http.NewRequestWithContext(ctx, "POST", registrationURL, bytes.NewReader(bodyBytes))
+ if err != nil {
+ return nil, fmt.Errorf("failed to create request: %w", err)
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("User-Agent", fmt.Sprintf("ServerKit-Agent/%s", Version))
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("registration request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ // Read response
+ respBody, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read response: %w", err)
+ }
+
+ // Check status code
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
+ var errResp struct {
+ Error string `json:"error"`
+ }
+ json.Unmarshal(respBody, &errResp)
+ if errResp.Error != "" {
+ return nil, fmt.Errorf("registration failed: %s", errResp.Error)
+ }
+ return nil, fmt.Errorf("registration failed with status %d", resp.StatusCode)
+ }
+
+ // Parse response
+ var result RegistrationResult
+ if err := json.Unmarshal(respBody, &result); err != nil {
+ return nil, fmt.Errorf("failed to parse response: %w", err)
+ }
+
+ // Construct WebSocket URL if not provided
+ if result.WebSocketURL == "" {
+ wsURL := serverURL
+ wsURL = strings.Replace(wsURL, "https://", "wss://", 1)
+ wsURL = strings.Replace(wsURL, "http://", "ws://", 1)
+ result.WebSocketURL = wsURL + "/agent/ws"
+ }
+
+ r.log.Info("Registration successful",
+ "agent_id", result.AgentID,
+ "name", result.Name,
+ )
+
+ return &result, nil
+}
+
+// Unregister unregisters the agent from ServerKit
+func (r *Registration) Unregister(serverURL, agentID, apiKey, apiSecret string) error {
+ serverURL = strings.TrimSuffix(serverURL, "/")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ client := &http.Client{
+ Timeout: 30 * time.Second,
+ }
+
+ req, err := http.NewRequestWithContext(ctx, "DELETE", serverURL+"/api/v1/agents/"+agentID, nil)
+ if err != nil {
+ return fmt.Errorf("failed to create request: %w", err)
+ }
+
+ req.Header.Set("X-API-Key", apiKey)
+ req.Header.Set("X-API-Secret", apiSecret)
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return fmt.Errorf("unregister request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
+ return fmt.Errorf("unregister failed with status %d", resp.StatusCode)
+ }
+
+ return nil
+}
+
+// Version is set during build
+var Version = "dev"
diff --git a/agent/internal/auth/auth.go b/agent/internal/auth/auth.go
new file mode 100644
index 00000000..eaea6f7c
--- /dev/null
+++ b/agent/internal/auth/auth.go
@@ -0,0 +1,97 @@
+package auth
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "time"
+)
+
+// Authenticator handles HMAC-based authentication
+type Authenticator struct {
+ agentID string
+ apiKey string
+ apiSecret string
+}
+
+// New creates a new Authenticator
+func New(agentID, apiKey, apiSecret string) *Authenticator {
+ return &Authenticator{
+ agentID: agentID,
+ apiKey: apiKey,
+ apiSecret: apiSecret,
+ }
+}
+
+// SignMessage creates an HMAC signature for authentication
+// The signature is computed as: HMAC-SHA256(agent_id + timestamp, api_secret)
+func (a *Authenticator) SignMessage(timestamp int64) string {
+ message := fmt.Sprintf("%s:%d", a.agentID, timestamp)
+ return a.computeHMAC(message)
+}
+
+// SignCommand creates an HMAC signature for a command
+// Used to verify commands weren't tampered with
+func (a *Authenticator) SignCommand(commandID string, action string, timestamp int64) string {
+ message := fmt.Sprintf("%s:%s:%d", commandID, action, timestamp)
+ return a.computeHMAC(message)
+}
+
+// VerifySignature verifies an HMAC signature
+func (a *Authenticator) VerifySignature(message, signature string) bool {
+ expected := a.computeHMAC(message)
+ return hmac.Equal([]byte(expected), []byte(signature))
+}
+
+// VerifyTimestamp checks if a timestamp is within acceptable range
+// Prevents replay attacks
+func (a *Authenticator) VerifyTimestamp(timestamp int64, maxAgeSeconds int64) bool {
+ now := time.Now().UnixMilli()
+ diff := now - timestamp
+ if diff < 0 {
+ diff = -diff
+ }
+ return diff <= maxAgeSeconds*1000
+}
+
+// GetAPIKeyPrefix returns the first 8 characters of the API key
+// Used for identification without exposing full key
+func (a *Authenticator) GetAPIKeyPrefix() string {
+ if len(a.apiKey) < 8 {
+ return a.apiKey
+ }
+ return a.apiKey[:8]
+}
+
+// AgentID returns the agent ID
+func (a *Authenticator) AgentID() string {
+ return a.agentID
+}
+
+func (a *Authenticator) computeHMAC(message string) string {
+ h := hmac.New(sha256.New, []byte(a.apiSecret))
+ h.Write([]byte(message))
+ return hex.EncodeToString(h.Sum(nil))
+}
+
+// GenerateNonce generates a random nonce for request uniqueness
+func GenerateNonce() string {
+ return fmt.Sprintf("%d-%d", time.Now().UnixNano(), time.Now().UnixMilli())
+}
+
+// SessionToken represents an authenticated session
+type SessionToken struct {
+ Token string
+ ExpiresAt time.Time
+}
+
+// IsExpired checks if the session token has expired
+func (s *SessionToken) IsExpired() bool {
+ return time.Now().After(s.ExpiresAt)
+}
+
+// IsExpiringSoon checks if the token expires within the given duration
+func (s *SessionToken) IsExpiringSoon(within time.Duration) bool {
+ return time.Now().Add(within).After(s.ExpiresAt)
+}
diff --git a/agent/internal/config/config.go b/agent/internal/config/config.go
new file mode 100644
index 00000000..8b1c80c9
--- /dev/null
+++ b/agent/internal/config/config.go
@@ -0,0 +1,383 @@
+package config
+
+import (
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "runtime"
+ "time"
+
+ "gopkg.in/yaml.v3"
+)
+
+// Config holds all agent configuration
+type Config struct {
+ Server ServerConfig `yaml:"server"`
+ Agent AgentConfig `yaml:"agent"`
+ Auth AuthConfig `yaml:"auth"`
+ Features FeaturesConfig `yaml:"features"`
+ Metrics MetricsConfig `yaml:"metrics"`
+ Docker DockerConfig `yaml:"docker"`
+ Security SecurityConfig `yaml:"security"`
+ Logging LoggingConfig `yaml:"logging"`
+}
+
+// ServerConfig holds connection settings
+type ServerConfig struct {
+ URL string `yaml:"url"`
+ ReconnectInterval time.Duration `yaml:"reconnect_interval"`
+ MaxReconnectInterval time.Duration `yaml:"max_reconnect_interval"`
+ PingInterval time.Duration `yaml:"ping_interval"`
+ InsecureSkipVerify bool `yaml:"insecure_skip_verify"` // For dev only
+}
+
+// AgentConfig holds agent identity
+type AgentConfig struct {
+ ID string `yaml:"id"`
+ Name string `yaml:"name"`
+}
+
+// AuthConfig holds authentication credentials
+type AuthConfig struct {
+ KeyFile string `yaml:"key_file"`
+ APIKey string `yaml:"api_key,omitempty"` // Not saved to config file
+ APISecret string `yaml:"api_secret,omitempty"` // Not saved to config file
+}
+
+// FeaturesConfig controls enabled features
+type FeaturesConfig struct {
+ Docker bool `yaml:"docker"`
+ Metrics bool `yaml:"metrics"`
+ Logs bool `yaml:"logs"`
+ FileAccess bool `yaml:"file_access"`
+ Exec bool `yaml:"exec"`
+}
+
+// MetricsConfig controls metrics collection
+type MetricsConfig struct {
+ Enabled bool `yaml:"enabled"`
+ Interval time.Duration `yaml:"interval"`
+ IncludePerCPU bool `yaml:"include_per_cpu"`
+ IncludeDockerStats bool `yaml:"include_docker_stats"`
+}
+
+// DockerConfig holds Docker connection settings
+type DockerConfig struct {
+ Socket string `yaml:"socket"`
+ Timeout time.Duration `yaml:"timeout"`
+}
+
+// SecurityConfig holds security settings
+type SecurityConfig struct {
+ AllowedPaths []string `yaml:"allowed_paths"`
+ BlockedCommands []string `yaml:"blocked_commands"`
+ MaxExecTimeout time.Duration `yaml:"max_exec_timeout"`
+}
+
+// LoggingConfig holds logging settings
+type LoggingConfig struct {
+ Level string `yaml:"level"`
+ File string `yaml:"file"`
+ MaxSize int `yaml:"max_size_mb"`
+ MaxBackups int `yaml:"max_backups"`
+ MaxAge int `yaml:"max_age_days"`
+ Compress bool `yaml:"compress"`
+}
+
+// Default returns default configuration
+func Default() *Config {
+ return &Config{
+ Server: ServerConfig{
+ ReconnectInterval: 5 * time.Second,
+ MaxReconnectInterval: 5 * time.Minute,
+ PingInterval: 30 * time.Second,
+ },
+ Agent: AgentConfig{},
+ Auth: AuthConfig{
+ KeyFile: defaultKeyPath(),
+ },
+ Features: FeaturesConfig{
+ Docker: true,
+ Metrics: true,
+ Logs: true,
+ FileAccess: false,
+ Exec: false,
+ },
+ Metrics: MetricsConfig{
+ Enabled: true,
+ Interval: 10 * time.Second,
+ IncludePerCPU: true,
+ IncludeDockerStats: true,
+ },
+ Docker: DockerConfig{
+ Socket: defaultDockerSocket(),
+ Timeout: 30 * time.Second,
+ },
+ Security: SecurityConfig{
+ AllowedPaths: []string{},
+ BlockedCommands: []string{},
+ MaxExecTimeout: 5 * time.Minute,
+ },
+ Logging: LoggingConfig{
+ Level: "info",
+ File: defaultLogPath(),
+ MaxSize: 100,
+ MaxBackups: 5,
+ MaxAge: 30,
+ Compress: true,
+ },
+ }
+}
+
+// Load loads configuration from file
+func Load(path string) (*Config, error) {
+ if path == "" {
+ path = DefaultConfigPath()
+ }
+
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, fmt.Errorf("config file not found: %s", path)
+ }
+ return nil, fmt.Errorf("failed to read config: %w", err)
+ }
+
+ cfg := Default()
+ if err := yaml.Unmarshal(data, cfg); err != nil {
+ return nil, fmt.Errorf("failed to parse config: %w", err)
+ }
+
+ // Load credentials from secure storage
+ if err := cfg.LoadCredentials(); err != nil {
+ // Credentials may not exist yet (before registration)
+ // This is not an error
+ }
+
+ return cfg, nil
+}
+
+// Save saves configuration to file
+func (c *Config) Save(path string) error {
+ if path == "" {
+ path = DefaultConfigPath()
+ }
+
+ // Ensure directory exists
+ dir := filepath.Dir(path)
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return fmt.Errorf("failed to create config directory: %w", err)
+ }
+
+ // Create a copy without sensitive data
+ safeCfg := *c
+ safeCfg.Auth.APIKey = ""
+ safeCfg.Auth.APISecret = ""
+
+ data, err := yaml.Marshal(&safeCfg)
+ if err != nil {
+ return fmt.Errorf("failed to marshal config: %w", err)
+ }
+
+ // Write with restricted permissions
+ if err := os.WriteFile(path, data, 0600); err != nil {
+ return fmt.Errorf("failed to write config: %w", err)
+ }
+
+ return nil
+}
+
+// Print prints configuration (excluding secrets)
+func (c *Config) Print() {
+ safeCfg := *c
+ safeCfg.Auth.APIKey = "[REDACTED]"
+ safeCfg.Auth.APISecret = "[REDACTED]"
+
+ data, _ := yaml.Marshal(&safeCfg)
+ fmt.Println(string(data))
+}
+
+// SaveCredentials saves API credentials securely
+func (c *Config) SaveCredentials() error {
+ if c.Auth.APIKey == "" || c.Auth.APISecret == "" {
+ return nil
+ }
+
+ keyPath := c.Auth.KeyFile
+ if keyPath == "" {
+ keyPath = defaultKeyPath()
+ }
+
+ // Ensure directory exists
+ dir := filepath.Dir(keyPath)
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return fmt.Errorf("failed to create key directory: %w", err)
+ }
+
+ // Create credential data
+ creds := fmt.Sprintf("%s:%s", c.Auth.APIKey, c.Auth.APISecret)
+
+ // Encrypt credentials using machine-specific key
+ encrypted, err := encryptCredentials([]byte(creds))
+ if err != nil {
+ return fmt.Errorf("failed to encrypt credentials: %w", err)
+ }
+
+ // Write with restricted permissions
+ if err := os.WriteFile(keyPath, encrypted, 0600); err != nil {
+ return fmt.Errorf("failed to write key file: %w", err)
+ }
+
+ return nil
+}
+
+// LoadCredentials loads API credentials from secure storage
+func (c *Config) LoadCredentials() error {
+ keyPath := c.Auth.KeyFile
+ if keyPath == "" {
+ keyPath = defaultKeyPath()
+ }
+
+ data, err := os.ReadFile(keyPath)
+ if err != nil {
+ return fmt.Errorf("failed to read key file: %w", err)
+ }
+
+ // Decrypt credentials
+ decrypted, err := decryptCredentials(data)
+ if err != nil {
+ return fmt.Errorf("failed to decrypt credentials: %w", err)
+ }
+
+ // Parse credentials
+ var apiKey, apiSecret string
+ if _, err := fmt.Sscanf(string(decrypted), "%s:%s", &apiKey, &apiSecret); err != nil {
+ // Try splitting by colon
+ parts := splitFirst(string(decrypted), ':')
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid credentials format")
+ }
+ apiKey = parts[0]
+ apiSecret = parts[1]
+ }
+
+ c.Auth.APIKey = apiKey
+ c.Auth.APISecret = apiSecret
+
+ return nil
+}
+
+// DefaultConfigPath returns the default config file path
+func DefaultConfigPath() string {
+ if runtime.GOOS == "windows" {
+ return filepath.Join(os.Getenv("ProgramData"), "ServerKit", "Agent", "config.yaml")
+ }
+ return "/etc/serverkit-agent/config.yaml"
+}
+
+func defaultKeyPath() string {
+ if runtime.GOOS == "windows" {
+ return filepath.Join(os.Getenv("ProgramData"), "ServerKit", "Agent", "agent.key")
+ }
+ return "/etc/serverkit-agent/agent.key"
+}
+
+func defaultDockerSocket() string {
+ if runtime.GOOS == "windows" {
+ return "npipe:////./pipe/docker_engine"
+ }
+ return "unix:///var/run/docker.sock"
+}
+
+func defaultLogPath() string {
+ if runtime.GOOS == "windows" {
+ return filepath.Join(os.Getenv("ProgramData"), "ServerKit", "Agent", "logs", "agent.log")
+ }
+ return "/var/log/serverkit-agent/agent.log"
+}
+
+// getMachineKey generates a machine-specific encryption key
+func getMachineKey() []byte {
+ // Use machine-specific data to derive key
+ // This makes the credentials only decryptable on this machine
+ hostname, _ := os.Hostname()
+
+ var machineID string
+ if runtime.GOOS == "linux" {
+ data, err := os.ReadFile("/etc/machine-id")
+ if err == nil {
+ machineID = string(data)
+ }
+ } else if runtime.GOOS == "windows" {
+ // On Windows, use a combination of hostname and username
+ machineID = os.Getenv("COMPUTERNAME") + os.Getenv("USERNAME")
+ }
+
+ combined := fmt.Sprintf("serverkit-agent:%s:%s", hostname, machineID)
+ hash := sha256.Sum256([]byte(combined))
+ return hash[:]
+}
+
+func encryptCredentials(plaintext []byte) ([]byte, error) {
+ key := getMachineKey()
+
+ block, err := aes.NewCipher(key)
+ if err != nil {
+ return nil, err
+ }
+
+ gcm, err := cipher.NewGCM(block)
+ if err != nil {
+ return nil, err
+ }
+
+ nonce := make([]byte, gcm.NonceSize())
+ if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
+ return nil, err
+ }
+
+ ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
+ return []byte(base64.StdEncoding.EncodeToString(ciphertext)), nil
+}
+
+func decryptCredentials(data []byte) ([]byte, error) {
+ key := getMachineKey()
+
+ ciphertext, err := base64.StdEncoding.DecodeString(string(data))
+ if err != nil {
+ return nil, err
+ }
+
+ block, err := aes.NewCipher(key)
+ if err != nil {
+ return nil, err
+ }
+
+ gcm, err := cipher.NewGCM(block)
+ if err != nil {
+ return nil, err
+ }
+
+ nonceSize := gcm.NonceSize()
+ if len(ciphertext) < nonceSize {
+ return nil, fmt.Errorf("ciphertext too short")
+ }
+
+ nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
+ return gcm.Open(nil, nonce, ciphertext, nil)
+}
+
+func splitFirst(s string, sep byte) []string {
+ for i := 0; i < len(s); i++ {
+ if s[i] == sep {
+ return []string{s[:i], s[i+1:]}
+ }
+ }
+ return []string{s}
+}
diff --git a/agent/internal/docker/client.go b/agent/internal/docker/client.go
new file mode 100644
index 00000000..8f5d0ea6
--- /dev/null
+++ b/agent/internal/docker/client.go
@@ -0,0 +1,449 @@
+package docker
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "strings"
+
+ "github.com/docker/docker/api/types"
+ containertypes "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/api/types/filters"
+ volumetypes "github.com/docker/docker/api/types/volume"
+ "github.com/docker/docker/client"
+ "github.com/serverkit/agent/internal/config"
+ "github.com/serverkit/agent/internal/logger"
+)
+
+// Client wraps the Docker client with additional functionality
+type Client struct {
+ cli *client.Client
+ cfg config.DockerConfig
+ log *logger.Logger
+}
+
+// ContainerInfo represents container information
+type ContainerInfo struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Image string `json:"image"`
+ ImageID string `json:"image_id"`
+ Command string `json:"command"`
+ Created int64 `json:"created"`
+ State string `json:"state"`
+ Status string `json:"status"`
+ Ports []PortMapping `json:"ports"`
+ Labels map[string]string `json:"labels"`
+}
+
+// PortMapping represents a port mapping
+type PortMapping struct {
+ IP string `json:"ip,omitempty"`
+ PrivatePort uint16 `json:"private_port"`
+ PublicPort uint16 `json:"public_port,omitempty"`
+ Type string `json:"type"`
+}
+
+// ContainerStats represents container statistics
+type ContainerStats struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ CPUPercent float64 `json:"cpu_percent"`
+ MemoryUsage uint64 `json:"memory_usage"`
+ MemoryLimit uint64 `json:"memory_limit"`
+ MemoryPercent float64 `json:"memory_percent"`
+ NetworkRx uint64 `json:"network_rx"`
+ NetworkTx uint64 `json:"network_tx"`
+ BlockRead uint64 `json:"block_read"`
+ BlockWrite uint64 `json:"block_write"`
+ PIDs uint64 `json:"pids"`
+}
+
+// ImageInfo represents image information
+type ImageInfo struct {
+ ID string `json:"id"`
+ RepoTags []string `json:"repo_tags"`
+ RepoDigests []string `json:"repo_digests"`
+ Created int64 `json:"created"`
+ Size int64 `json:"size"`
+}
+
+// VolumeInfo represents volume information
+type VolumeInfo struct {
+ Name string `json:"name"`
+ Driver string `json:"driver"`
+ Mountpoint string `json:"mountpoint"`
+ Labels map[string]string `json:"labels"`
+ Scope string `json:"scope"`
+ CreatedAt string `json:"created_at"`
+}
+
+// NetworkInfo represents network information
+type NetworkInfo struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Driver string `json:"driver"`
+ Scope string `json:"scope"`
+ Internal bool `json:"internal"`
+ Labels map[string]string `json:"labels"`
+ Containers int `json:"containers"`
+}
+
+// NewClient creates a new Docker client
+func NewClient(cfg config.DockerConfig, log *logger.Logger) (*Client, error) {
+ var opts []client.Opt
+
+ // Set host if configured
+ if cfg.Socket != "" {
+ host := cfg.Socket
+ // Convert socket path to Docker format
+ if strings.HasPrefix(host, "/") {
+ host = "unix://" + host
+ }
+ opts = append(opts, client.WithHost(host))
+ }
+
+ opts = append(opts, client.WithAPIVersionNegotiation())
+
+ if cfg.Timeout > 0 {
+ opts = append(opts, client.WithTimeout(cfg.Timeout))
+ }
+
+ cli, err := client.NewClientWithOpts(opts...)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create Docker client: %w", err)
+ }
+
+ return &Client{
+ cli: cli,
+ cfg: cfg,
+ log: log.WithComponent("docker"),
+ }, nil
+}
+
+// Ping checks if Docker is available
+func (c *Client) Ping(ctx context.Context) error {
+ _, err := c.cli.Ping(ctx)
+ return err
+}
+
+// Version returns the Docker version
+func (c *Client) Version(ctx context.Context) (string, error) {
+ info, err := c.cli.ServerVersion(ctx)
+ if err != nil {
+ return "", err
+ }
+ return info.Version, nil
+}
+
+// Info returns Docker system info
+func (c *Client) Info(ctx context.Context) (*types.Info, error) {
+ info, err := c.cli.Info(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &info, nil
+}
+
+// ListContainers lists all containers
+func (c *Client) ListContainers(ctx context.Context, all bool) ([]ContainerInfo, error) {
+ containers, err := c.cli.ContainerList(ctx, types.ContainerListOptions{
+ All: all,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]ContainerInfo, len(containers))
+ for i, cont := range containers {
+ ports := make([]PortMapping, len(cont.Ports))
+ for j, p := range cont.Ports {
+ ports[j] = PortMapping{
+ IP: p.IP,
+ PrivatePort: p.PrivatePort,
+ PublicPort: p.PublicPort,
+ Type: p.Type,
+ }
+ }
+
+ name := ""
+ if len(cont.Names) > 0 {
+ name = strings.TrimPrefix(cont.Names[0], "/")
+ }
+
+ result[i] = ContainerInfo{
+ ID: cont.ID[:12],
+ Name: name,
+ Image: cont.Image,
+ ImageID: cont.ImageID,
+ Command: cont.Command,
+ Created: cont.Created,
+ State: cont.State,
+ Status: cont.Status,
+ Ports: ports,
+ Labels: cont.Labels,
+ }
+ }
+
+ return result, nil
+}
+
+// InspectContainer inspects a container
+func (c *Client) InspectContainer(ctx context.Context, id string) (*types.ContainerJSON, error) {
+ cont, err := c.cli.ContainerInspect(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ return &cont, nil
+}
+
+// StartContainer starts a container
+func (c *Client) StartContainer(ctx context.Context, id string) error {
+ return c.cli.ContainerStart(ctx, id, types.ContainerStartOptions{})
+}
+
+// StopContainer stops a container
+func (c *Client) StopContainer(ctx context.Context, id string, timeout *int) error {
+ var stopOpts containertypes.StopOptions
+ if timeout != nil {
+ stopOpts.Timeout = timeout
+ }
+ return c.cli.ContainerStop(ctx, id, stopOpts)
+}
+
+// RestartContainer restarts a container
+func (c *Client) RestartContainer(ctx context.Context, id string, timeout *int) error {
+ var stopOpts containertypes.StopOptions
+ if timeout != nil {
+ stopOpts.Timeout = timeout
+ }
+ return c.cli.ContainerRestart(ctx, id, stopOpts)
+}
+
+// RemoveContainer removes a container
+func (c *Client) RemoveContainer(ctx context.Context, id string, force, removeVolumes bool) error {
+ return c.cli.ContainerRemove(ctx, id, types.ContainerRemoveOptions{
+ Force: force,
+ RemoveVolumes: removeVolumes,
+ })
+}
+
+// ContainerLogs returns container logs
+func (c *Client) ContainerLogs(ctx context.Context, id string, tail string, since string, follow bool) (io.ReadCloser, error) {
+ opts := types.ContainerLogsOptions{
+ ShowStdout: true,
+ ShowStderr: true,
+ Follow: follow,
+ Timestamps: true,
+ }
+
+ if tail != "" {
+ opts.Tail = tail
+ }
+
+ if since != "" {
+ opts.Since = since
+ }
+
+ return c.cli.ContainerLogs(ctx, id, opts)
+}
+
+// ContainerStats returns container stats
+func (c *Client) ContainerStats(ctx context.Context, id string) (*ContainerStats, error) {
+ resp, err := c.cli.ContainerStats(ctx, id, false)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ var stats types.StatsJSON
+ if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil {
+ return nil, err
+ }
+
+ // Calculate CPU percentage
+ cpuPercent := calculateCPUPercent(&stats)
+
+ // Calculate memory percentage
+ memPercent := 0.0
+ if stats.MemoryStats.Limit > 0 {
+ memPercent = float64(stats.MemoryStats.Usage) / float64(stats.MemoryStats.Limit) * 100
+ }
+
+ // Calculate network I/O
+ var rx, tx uint64
+ for _, net := range stats.Networks {
+ rx += net.RxBytes
+ tx += net.TxBytes
+ }
+
+ // Calculate block I/O
+ var read, write uint64
+ for _, bio := range stats.BlkioStats.IoServiceBytesRecursive {
+ if bio.Op == "Read" {
+ read += bio.Value
+ } else if bio.Op == "Write" {
+ write += bio.Value
+ }
+ }
+
+ // Get container name
+ inspect, _ := c.cli.ContainerInspect(ctx, id)
+ name := strings.TrimPrefix(inspect.Name, "/")
+
+ return &ContainerStats{
+ ID: id[:12],
+ Name: name,
+ CPUPercent: cpuPercent,
+ MemoryUsage: stats.MemoryStats.Usage,
+ MemoryLimit: stats.MemoryStats.Limit,
+ MemoryPercent: memPercent,
+ NetworkRx: rx,
+ NetworkTx: tx,
+ BlockRead: read,
+ BlockWrite: write,
+ PIDs: stats.PidsStats.Current,
+ }, nil
+}
+
+// ListImages lists all images
+func (c *Client) ListImages(ctx context.Context) ([]ImageInfo, error) {
+ images, err := c.cli.ImageList(ctx, types.ImageListOptions{})
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]ImageInfo, len(images))
+ for i, img := range images {
+ result[i] = ImageInfo{
+ ID: img.ID,
+ RepoTags: img.RepoTags,
+ RepoDigests: img.RepoDigests,
+ Created: img.Created,
+ Size: img.Size,
+ }
+ }
+
+ return result, nil
+}
+
+// PullImage pulls an image
+func (c *Client) PullImage(ctx context.Context, imageName string) (io.ReadCloser, error) {
+ return c.cli.ImagePull(ctx, imageName, types.ImagePullOptions{})
+}
+
+// RemoveImage removes an image
+func (c *Client) RemoveImage(ctx context.Context, id string, force bool) error {
+ _, err := c.cli.ImageRemove(ctx, id, types.ImageRemoveOptions{
+ Force: force,
+ })
+ return err
+}
+
+// ListVolumes lists all volumes
+func (c *Client) ListVolumes(ctx context.Context) ([]VolumeInfo, error) {
+ resp, err := c.cli.VolumeList(ctx, volumetypes.ListOptions{})
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]VolumeInfo, len(resp.Volumes))
+ for i, vol := range resp.Volumes {
+ result[i] = VolumeInfo{
+ Name: vol.Name,
+ Driver: vol.Driver,
+ Mountpoint: vol.Mountpoint,
+ Labels: vol.Labels,
+ Scope: vol.Scope,
+ CreatedAt: vol.CreatedAt,
+ }
+ }
+
+ return result, nil
+}
+
+// CreateVolume creates a volume
+func (c *Client) CreateVolume(ctx context.Context, name, driver string, labels map[string]string) (*VolumeInfo, error) {
+ vol, err := c.cli.VolumeCreate(ctx, volumetypes.CreateOptions{
+ Name: name,
+ Driver: driver,
+ Labels: labels,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return &VolumeInfo{
+ Name: vol.Name,
+ Driver: vol.Driver,
+ Mountpoint: vol.Mountpoint,
+ Labels: vol.Labels,
+ Scope: vol.Scope,
+ CreatedAt: vol.CreatedAt,
+ }, nil
+}
+
+// RemoveVolume removes a volume
+func (c *Client) RemoveVolume(ctx context.Context, name string, force bool) error {
+ return c.cli.VolumeRemove(ctx, name, force)
+}
+
+// ListNetworks lists all networks
+func (c *Client) ListNetworks(ctx context.Context) ([]NetworkInfo, error) {
+ networks, err := c.cli.NetworkList(ctx, types.NetworkListOptions{})
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]NetworkInfo, len(networks))
+ for i, net := range networks {
+ result[i] = NetworkInfo{
+ ID: net.ID[:12],
+ Name: net.Name,
+ Driver: net.Driver,
+ Scope: net.Scope,
+ Internal: net.Internal,
+ Labels: net.Labels,
+ Containers: len(net.Containers),
+ }
+ }
+
+ return result, nil
+}
+
+// GetContainerCount returns the number of containers
+func (c *Client) GetContainerCount(ctx context.Context) (total int, running int, err error) {
+ allContainers, err := c.cli.ContainerList(ctx, types.ContainerListOptions{All: true})
+ if err != nil {
+ return 0, 0, err
+ }
+
+ runningContainers, err := c.cli.ContainerList(ctx, types.ContainerListOptions{
+ Filters: filters.NewArgs(filters.Arg("status", "running")),
+ })
+ if err != nil {
+ return 0, 0, err
+ }
+
+ return len(allContainers), len(runningContainers), nil
+}
+
+// Close closes the Docker client
+func (c *Client) Close() error {
+ return c.cli.Close()
+}
+
+// calculateCPUPercent calculates CPU usage percentage
+func calculateCPUPercent(stats *types.StatsJSON) float64 {
+ cpuDelta := float64(stats.CPUStats.CPUUsage.TotalUsage - stats.PreCPUStats.CPUUsage.TotalUsage)
+ systemDelta := float64(stats.CPUStats.SystemUsage - stats.PreCPUStats.SystemUsage)
+
+ if systemDelta > 0 && cpuDelta > 0 {
+ cpuPercent := (cpuDelta / systemDelta) * float64(stats.CPUStats.OnlineCPUs) * 100.0
+ return cpuPercent
+ }
+
+ return 0.0
+}
+
diff --git a/agent/internal/logger/logger.go b/agent/internal/logger/logger.go
new file mode 100644
index 00000000..d2ed06bc
--- /dev/null
+++ b/agent/internal/logger/logger.go
@@ -0,0 +1,77 @@
+package logger
+
+import (
+ "io"
+ "os"
+ "path/filepath"
+
+ "github.com/serverkit/agent/internal/config"
+ "gopkg.in/natefinch/lumberjack.v2"
+ "log/slog"
+)
+
+// Logger wraps slog.Logger with additional context
+type Logger struct {
+ *slog.Logger
+}
+
+// New creates a new logger with the given configuration
+func New(cfg config.LoggingConfig) *Logger {
+ var level slog.Level
+ switch cfg.Level {
+ case "debug":
+ level = slog.LevelDebug
+ case "info":
+ level = slog.LevelInfo
+ case "warn":
+ level = slog.LevelWarn
+ case "error":
+ level = slog.LevelError
+ default:
+ level = slog.LevelInfo
+ }
+
+ opts := &slog.HandlerOptions{
+ Level: level,
+ }
+
+ var writers []io.Writer
+
+ // Always write to stdout
+ writers = append(writers, os.Stdout)
+
+ // Also write to file if configured
+ if cfg.File != "" {
+ // Ensure log directory exists
+ dir := filepath.Dir(cfg.File)
+ if err := os.MkdirAll(dir, 0755); err == nil {
+ // Use lumberjack for log rotation
+ fileWriter := &lumberjack.Logger{
+ Filename: cfg.File,
+ MaxSize: cfg.MaxSize, // megabytes
+ MaxBackups: cfg.MaxBackups,
+ MaxAge: cfg.MaxAge, // days
+ Compress: cfg.Compress,
+ }
+ writers = append(writers, fileWriter)
+ }
+ }
+
+ // Create multi-writer
+ multiWriter := io.MultiWriter(writers...)
+
+ handler := slog.NewJSONHandler(multiWriter, opts)
+ logger := slog.New(handler)
+
+ return &Logger{Logger: logger}
+}
+
+// With returns a new logger with additional attributes
+func (l *Logger) With(args ...any) *Logger {
+ return &Logger{Logger: l.Logger.With(args...)}
+}
+
+// WithComponent returns a logger with a component name
+func (l *Logger) WithComponent(name string) *Logger {
+ return l.With("component", name)
+}
diff --git a/agent/internal/metrics/collector.go b/agent/internal/metrics/collector.go
new file mode 100644
index 00000000..e0d53f9e
--- /dev/null
+++ b/agent/internal/metrics/collector.go
@@ -0,0 +1,282 @@
+package metrics
+
+import (
+ "context"
+ "os"
+ "runtime"
+ "time"
+
+ "github.com/shirou/gopsutil/v3/cpu"
+ "github.com/shirou/gopsutil/v3/disk"
+ "github.com/shirou/gopsutil/v3/host"
+ "github.com/shirou/gopsutil/v3/mem"
+ "github.com/shirou/gopsutil/v3/net"
+ "github.com/shirou/gopsutil/v3/process"
+ "github.com/serverkit/agent/internal/config"
+ "github.com/serverkit/agent/internal/logger"
+)
+
+// Collector collects system metrics
+type Collector struct {
+ cfg config.MetricsConfig
+ log *logger.Logger
+
+ // Previous values for rate calculations
+ prevNetworkRx uint64
+ prevNetworkTx uint64
+ prevTime time.Time
+}
+
+// SystemMetrics contains all collected metrics
+type SystemMetrics struct {
+ Timestamp int64 `json:"timestamp"`
+ CPUPercent float64 `json:"cpu_percent"`
+ CPUPerCore []float64 `json:"cpu_per_core,omitempty"`
+ MemoryTotal uint64 `json:"memory_total"`
+ MemoryUsed uint64 `json:"memory_used"`
+ MemoryPercent float64 `json:"memory_percent"`
+ SwapTotal uint64 `json:"swap_total"`
+ SwapUsed uint64 `json:"swap_used"`
+ SwapPercent float64 `json:"swap_percent"`
+ DiskTotal uint64 `json:"disk_total"`
+ DiskUsed uint64 `json:"disk_used"`
+ DiskPercent float64 `json:"disk_percent"`
+ NetworkRx uint64 `json:"network_rx"` // Bytes received (total)
+ NetworkTx uint64 `json:"network_tx"` // Bytes transmitted (total)
+ NetworkRxRate float64 `json:"network_rx_rate"` // Bytes/sec
+ NetworkTxRate float64 `json:"network_tx_rate"` // Bytes/sec
+ Uptime uint64 `json:"uptime"`
+ LoadAvg1 float64 `json:"load_avg_1,omitempty"`
+ LoadAvg5 float64 `json:"load_avg_5,omitempty"`
+ LoadAvg15 float64 `json:"load_avg_15,omitempty"`
+}
+
+// SystemInfo contains static system information
+type SystemInfo struct {
+ Hostname string `json:"hostname"`
+ OS string `json:"os"`
+ Platform string `json:"platform"`
+ PlatformVersion string `json:"platform_version"`
+ KernelVersion string `json:"kernel_version"`
+ Architecture string `json:"architecture"`
+ CPUModel string `json:"cpu_model"`
+ CPUCores int `json:"cpu_cores"`
+ CPUThreads int `json:"cpu_threads"`
+ TotalMemory uint64 `json:"total_memory"`
+ TotalDisk uint64 `json:"total_disk"`
+}
+
+// ProcessInfo contains process information
+type ProcessInfo struct {
+ PID int32 `json:"pid"`
+ Name string `json:"name"`
+ Username string `json:"username"`
+ CPUPercent float64 `json:"cpu_percent"`
+ MemPercent float32 `json:"mem_percent"`
+ MemRSS uint64 `json:"mem_rss"`
+ Status string `json:"status"`
+ CreateTime int64 `json:"create_time"`
+ Cmdline string `json:"cmdline"`
+}
+
+// NewCollector creates a new metrics collector
+func NewCollector(cfg config.MetricsConfig, log *logger.Logger) *Collector {
+ return &Collector{
+ cfg: cfg,
+ log: log.WithComponent("metrics"),
+ prevTime: time.Now(),
+ }
+}
+
+// Collect collects current system metrics
+func (c *Collector) Collect(ctx context.Context) (*SystemMetrics, error) {
+ now := time.Now()
+ metrics := &SystemMetrics{
+ Timestamp: now.UnixMilli(),
+ }
+
+ // CPU usage
+ cpuPercent, err := cpu.PercentWithContext(ctx, 0, false)
+ if err == nil && len(cpuPercent) > 0 {
+ metrics.CPUPercent = cpuPercent[0]
+ }
+
+ // Per-core CPU (optional)
+ if c.cfg.IncludePerCPU {
+ perCore, err := cpu.PercentWithContext(ctx, 0, true)
+ if err == nil {
+ metrics.CPUPerCore = perCore
+ }
+ }
+
+ // Memory
+ memInfo, err := mem.VirtualMemoryWithContext(ctx)
+ if err == nil {
+ metrics.MemoryTotal = memInfo.Total
+ metrics.MemoryUsed = memInfo.Used
+ metrics.MemoryPercent = memInfo.UsedPercent
+ }
+
+ // Swap
+ swapInfo, err := mem.SwapMemoryWithContext(ctx)
+ if err == nil {
+ metrics.SwapTotal = swapInfo.Total
+ metrics.SwapUsed = swapInfo.Used
+ metrics.SwapPercent = swapInfo.UsedPercent
+ }
+
+ // Disk (root partition)
+ diskPath := "/"
+ if runtime.GOOS == "windows" {
+ diskPath = "C:\\"
+ }
+ diskInfo, err := disk.UsageWithContext(ctx, diskPath)
+ if err == nil {
+ metrics.DiskTotal = diskInfo.Total
+ metrics.DiskUsed = diskInfo.Used
+ metrics.DiskPercent = diskInfo.UsedPercent
+ }
+
+ // Network I/O
+ netIO, err := net.IOCountersWithContext(ctx, false)
+ if err == nil && len(netIO) > 0 {
+ metrics.NetworkRx = netIO[0].BytesRecv
+ metrics.NetworkTx = netIO[0].BytesSent
+
+ // Calculate rate
+ elapsed := now.Sub(c.prevTime).Seconds()
+ if elapsed > 0 && c.prevNetworkRx > 0 {
+ metrics.NetworkRxRate = float64(netIO[0].BytesRecv-c.prevNetworkRx) / elapsed
+ metrics.NetworkTxRate = float64(netIO[0].BytesSent-c.prevNetworkTx) / elapsed
+ }
+
+ c.prevNetworkRx = netIO[0].BytesRecv
+ c.prevNetworkTx = netIO[0].BytesSent
+ }
+
+ // Uptime
+ hostInfo, err := host.InfoWithContext(ctx)
+ if err == nil {
+ metrics.Uptime = hostInfo.Uptime
+ }
+
+ // Load average (Unix only)
+ if runtime.GOOS != "windows" {
+ loadAvg, err := cpu.Percent(0, false)
+ if err == nil && len(loadAvg) > 0 {
+ // Note: gopsutil load average is in misc package
+ // Using a simple approximation here
+ }
+ }
+
+ c.prevTime = now
+ return metrics, nil
+}
+
+// GetSystemInfo returns static system information
+func (c *Collector) GetSystemInfo(ctx context.Context) (*SystemInfo, error) {
+ info := &SystemInfo{
+ OS: runtime.GOOS,
+ Architecture: runtime.GOARCH,
+ }
+
+ // Hostname
+ hostname, err := os.Hostname()
+ if err == nil {
+ info.Hostname = hostname
+ }
+
+ // Host info
+ hostInfo, err := host.InfoWithContext(ctx)
+ if err == nil {
+ info.Platform = hostInfo.Platform
+ info.PlatformVersion = hostInfo.PlatformVersion
+ info.KernelVersion = hostInfo.KernelVersion
+ }
+
+ // CPU info
+ cpuInfo, err := cpu.InfoWithContext(ctx)
+ if err == nil && len(cpuInfo) > 0 {
+ info.CPUModel = cpuInfo[0].ModelName
+ info.CPUCores = int(cpuInfo[0].Cores)
+ }
+
+ // CPU count
+ threads, err := cpu.CountsWithContext(ctx, true)
+ if err == nil {
+ info.CPUThreads = threads
+ }
+ cores, err := cpu.CountsWithContext(ctx, false)
+ if err == nil {
+ info.CPUCores = cores
+ }
+
+ // Memory
+ memInfo, err := mem.VirtualMemoryWithContext(ctx)
+ if err == nil {
+ info.TotalMemory = memInfo.Total
+ }
+
+ // Disk
+ diskPath := "/"
+ if runtime.GOOS == "windows" {
+ diskPath = "C:\\"
+ }
+ diskInfo, err := disk.UsageWithContext(ctx, diskPath)
+ if err == nil {
+ info.TotalDisk = diskInfo.Total
+ }
+
+ return info, nil
+}
+
+// ListProcesses returns a list of running processes
+func (c *Collector) ListProcesses(ctx context.Context) ([]ProcessInfo, error) {
+ procs, err := process.ProcessesWithContext(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]ProcessInfo, 0, len(procs))
+ for _, p := range procs {
+ info := ProcessInfo{
+ PID: p.Pid,
+ }
+
+ if name, err := p.NameWithContext(ctx); err == nil {
+ info.Name = name
+ }
+
+ if username, err := p.UsernameWithContext(ctx); err == nil {
+ info.Username = username
+ }
+
+ if cpuPct, err := p.CPUPercentWithContext(ctx); err == nil {
+ info.CPUPercent = cpuPct
+ }
+
+ if memPct, err := p.MemoryPercentWithContext(ctx); err == nil {
+ info.MemPercent = memPct
+ }
+
+ if memInfo, err := p.MemoryInfoWithContext(ctx); err == nil && memInfo != nil {
+ info.MemRSS = memInfo.RSS
+ }
+
+ if status, err := p.StatusWithContext(ctx); err == nil && len(status) > 0 {
+ info.Status = status[0]
+ }
+
+ if createTime, err := p.CreateTimeWithContext(ctx); err == nil {
+ info.CreateTime = createTime
+ }
+
+ if cmdline, err := p.CmdlineWithContext(ctx); err == nil {
+ info.Cmdline = cmdline
+ }
+
+ result = append(result, info)
+ }
+
+ return result, nil
+}
diff --git a/agent/internal/ws/client.go b/agent/internal/ws/client.go
new file mode 100644
index 00000000..9b6dc962
--- /dev/null
+++ b/agent/internal/ws/client.go
@@ -0,0 +1,401 @@
+package ws
+
+import (
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/gorilla/websocket"
+ "github.com/serverkit/agent/internal/auth"
+ "github.com/serverkit/agent/internal/config"
+ "github.com/serverkit/agent/internal/logger"
+ "github.com/serverkit/agent/pkg/protocol"
+)
+
+// MessageHandler is called when a message is received
+type MessageHandler func(msgType protocol.MessageType, data []byte)
+
+// Client is a WebSocket client with auto-reconnect
+type Client struct {
+ cfg config.ServerConfig
+ auth *auth.Authenticator
+ log *logger.Logger
+ conn *websocket.Conn
+ handler MessageHandler
+ session *auth.SessionToken
+
+ mu sync.RWMutex
+ connected bool
+ reconnecting bool
+
+ sendCh chan []byte
+ doneCh chan struct{}
+
+ reconnectCount int
+}
+
+// NewClient creates a new WebSocket client
+func NewClient(cfg config.ServerConfig, authenticator *auth.Authenticator, log *logger.Logger) *Client {
+ return &Client{
+ cfg: cfg,
+ auth: authenticator,
+ log: log.WithComponent("websocket"),
+ sendCh: make(chan []byte, 100),
+ doneCh: make(chan struct{}),
+ }
+}
+
+// SetHandler sets the message handler
+func (c *Client) SetHandler(handler MessageHandler) {
+ c.handler = handler
+}
+
+// Connect establishes a WebSocket connection
+func (c *Client) Connect(ctx context.Context) error {
+ c.mu.Lock()
+ if c.connected {
+ c.mu.Unlock()
+ return nil
+ }
+ c.mu.Unlock()
+
+ dialer := websocket.Dialer{
+ HandshakeTimeout: 10 * time.Second,
+ }
+
+ // Allow insecure for development
+ if c.cfg.InsecureSkipVerify {
+ dialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
+ }
+
+ // Add authentication headers
+ headers := http.Header{}
+ headers.Set("X-Agent-ID", c.auth.AgentID())
+ headers.Set("X-API-Key-Prefix", c.auth.GetAPIKeyPrefix())
+
+ c.log.Debug("Connecting to server", "url", c.cfg.URL)
+
+ conn, resp, err := dialer.DialContext(ctx, c.cfg.URL, headers)
+ if err != nil {
+ if resp != nil {
+ c.log.Error("Connection failed",
+ "error", err,
+ "status", resp.StatusCode,
+ )
+ }
+ return fmt.Errorf("failed to connect: %w", err)
+ }
+
+ c.mu.Lock()
+ c.conn = conn
+ c.connected = true
+ c.reconnecting = false
+ c.reconnectCount = 0
+ c.mu.Unlock()
+
+ c.log.Info("Connected to server")
+
+ // Authenticate
+ if err := c.authenticate(); err != nil {
+ c.Close()
+ return fmt.Errorf("authentication failed: %w", err)
+ }
+
+ return nil
+}
+
+// authenticate sends authentication message and waits for response
+func (c *Client) authenticate() error {
+ timestamp := time.Now().UnixMilli()
+ signature := c.auth.SignMessage(timestamp)
+
+ authMsg := protocol.AuthMessage{
+ Message: protocol.NewMessage(protocol.TypeAuth, auth.GenerateNonce()),
+ AgentID: c.auth.AgentID(),
+ APIKeyPrefix: c.auth.GetAPIKeyPrefix(),
+ }
+ authMsg.Timestamp = timestamp
+ authMsg.Signature = signature
+
+ data, err := json.Marshal(authMsg)
+ if err != nil {
+ return fmt.Errorf("failed to marshal auth message: %w", err)
+ }
+
+ c.log.Debug("Sending authentication message")
+
+ if err := c.conn.WriteMessage(websocket.TextMessage, data); err != nil {
+ return fmt.Errorf("failed to send auth message: %w", err)
+ }
+
+ // Wait for auth response
+ c.conn.SetReadDeadline(time.Now().Add(10 * time.Second))
+ _, msg, err := c.conn.ReadMessage()
+ if err != nil {
+ return fmt.Errorf("failed to read auth response: %w", err)
+ }
+ c.conn.SetReadDeadline(time.Time{})
+
+ var response protocol.AuthResponse
+ if err := json.Unmarshal(msg, &response); err != nil {
+ return fmt.Errorf("failed to parse auth response: %w", err)
+ }
+
+ if response.Type == protocol.TypeAuthFail {
+ return fmt.Errorf("authentication rejected: %s", response.Error)
+ }
+
+ if response.Type != protocol.TypeAuthOK {
+ return fmt.Errorf("unexpected response type: %s", response.Type)
+ }
+
+ // Store session token
+ c.session = &auth.SessionToken{
+ Token: response.SessionToken,
+ ExpiresAt: time.UnixMilli(response.Expires),
+ }
+
+ c.log.Info("Authentication successful",
+ "expires_in", time.Until(c.session.ExpiresAt).Round(time.Second),
+ )
+
+ return nil
+}
+
+// Run starts the read/write loops and handles reconnection
+func (c *Client) Run(ctx context.Context) error {
+ for {
+ select {
+ case <-ctx.Done():
+ c.Close()
+ return ctx.Err()
+ default:
+ }
+
+ // Connect if not connected
+ c.mu.RLock()
+ connected := c.connected
+ c.mu.RUnlock()
+
+ if !connected {
+ if err := c.Connect(ctx); err != nil {
+ c.handleReconnect(ctx)
+ continue
+ }
+ }
+
+ // Start read/write loops
+ errCh := make(chan error, 2)
+
+ go func() {
+ errCh <- c.readLoop(ctx)
+ }()
+
+ go func() {
+ errCh <- c.writeLoop(ctx)
+ }()
+
+ // Wait for error
+ err := <-errCh
+ c.log.Warn("Connection loop ended", "error", err)
+
+ // Mark as disconnected
+ c.mu.Lock()
+ c.connected = false
+ c.mu.Unlock()
+
+ // Close connection
+ if c.conn != nil {
+ c.conn.Close()
+ }
+
+ // Check if context is cancelled
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ c.handleReconnect(ctx)
+ }
+ }
+}
+
+// readLoop reads messages from the WebSocket
+func (c *Client) readLoop(ctx context.Context) error {
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ }
+
+ _, msg, err := c.conn.ReadMessage()
+ if err != nil {
+ return fmt.Errorf("read error: %w", err)
+ }
+
+ // Parse message type
+ var base protocol.Message
+ if err := json.Unmarshal(msg, &base); err != nil {
+ c.log.Warn("Failed to parse message", "error", err)
+ continue
+ }
+
+ // Handle heartbeat ack internally
+ if base.Type == protocol.TypeHeartbeatAck {
+ c.log.Debug("Received heartbeat ack")
+ continue
+ }
+
+ // Pass to handler
+ if c.handler != nil {
+ c.handler(base.Type, msg)
+ }
+ }
+}
+
+// writeLoop writes messages from the send channel
+func (c *Client) writeLoop(ctx context.Context) error {
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case msg := <-c.sendCh:
+ if err := c.conn.WriteMessage(websocket.TextMessage, msg); err != nil {
+ return fmt.Errorf("write error: %w", err)
+ }
+ }
+ }
+}
+
+// handleReconnect implements exponential backoff reconnection
+func (c *Client) handleReconnect(ctx context.Context) {
+ c.mu.Lock()
+ c.reconnecting = true
+ c.reconnectCount++
+ count := c.reconnectCount
+ c.mu.Unlock()
+
+ // Calculate backoff duration
+ backoff := c.cfg.ReconnectInterval * time.Duration(1<<uint(count-1))
+ if backoff > c.cfg.MaxReconnectInterval {
+ backoff = c.cfg.MaxReconnectInterval
+ }
+
+ c.log.Info("Reconnecting",
+ "attempt", count,
+ "backoff", backoff,
+ )
+
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(backoff):
+ return
+ }
+}
+
+// Send queues a message for sending
+func (c *Client) Send(msg interface{}) error {
+ data, err := json.Marshal(msg)
+ if err != nil {
+ return fmt.Errorf("failed to marshal message: %w", err)
+ }
+
+ select {
+ case c.sendCh <- data:
+ return nil
+ default:
+ return fmt.Errorf("send channel full")
+ }
+}
+
+// SendHeartbeat sends a heartbeat message
+func (c *Client) SendHeartbeat(metrics protocol.HeartbeatMetrics) error {
+ msg := protocol.HeartbeatMessage{
+ Message: protocol.NewMessage(protocol.TypeHeartbeat, auth.GenerateNonce()),
+ Metrics: metrics,
+ }
+ return c.Send(msg)
+}
+
+// SendCommandResult sends a command result
+func (c *Client) SendCommandResult(commandID string, success bool, data interface{}, errMsg string, duration time.Duration) error {
+ var dataBytes json.RawMessage
+ if data != nil {
+ var err error
+ dataBytes, err = json.Marshal(data)
+ if err != nil {
+ return fmt.Errorf("failed to marshal data: %w", err)
+ }
+ }
+
+ msg := protocol.CommandResult{
+ Message: protocol.NewMessage(protocol.TypeCommandResult, auth.GenerateNonce()),
+ CommandID: commandID,
+ Success: success,
+ Data: dataBytes,
+ Error: errMsg,
+ Duration: duration.Milliseconds(),
+ }
+ return c.Send(msg)
+}
+
+// SendStream sends streaming data
+func (c *Client) SendStream(channel string, data interface{}) error {
+ dataBytes, err := json.Marshal(data)
+ if err != nil {
+ return fmt.Errorf("failed to marshal data: %w", err)
+ }
+
+ msg := protocol.StreamMessage{
+ Message: protocol.NewMessage(protocol.TypeStream, auth.GenerateNonce()),
+ Channel: channel,
+ Data: dataBytes,
+ }
+ return c.Send(msg)
+}
+
+// SendError sends an error message
+func (c *Client) SendError(code, details string) error {
+ msg := protocol.ErrorMessage{
+ Message: protocol.NewMessage(protocol.TypeError, auth.GenerateNonce()),
+ Code: code,
+ Details: details,
+ }
+ return c.Send(msg)
+}
+
+// IsConnected returns the connection status
+func (c *Client) IsConnected() bool {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ return c.connected
+}
+
+// Close closes the WebSocket connection
+func (c *Client) Close() error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if c.conn != nil {
+ // Send close message
+ c.conn.WriteMessage(
+ websocket.CloseMessage,
+ websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
+ )
+ c.conn.Close()
+ c.conn = nil
+ }
+
+ c.connected = false
+ return nil
+}
+
+// Session returns the current session token
+func (c *Client) Session() *auth.SessionToken {
+ return c.session
+}
diff --git a/agent/pkg/protocol/messages.go b/agent/pkg/protocol/messages.go
new file mode 100644
index 00000000..74644a2a
--- /dev/null
+++ b/agent/pkg/protocol/messages.go
@@ -0,0 +1,204 @@
+package protocol
+
+import (
+ "encoding/json"
+ "time"
+)
+
+// MessageType defines the type of message
+type MessageType string
+
+const (
+ // Authentication
+ TypeAuth MessageType = "auth"
+ TypeAuthOK MessageType = "auth_ok"
+ TypeAuthFail MessageType = "auth_fail"
+
+ // Heartbeat
+ TypeHeartbeat MessageType = "heartbeat"
+ TypeHeartbeatAck MessageType = "heartbeat_ack"
+
+ // Commands
+ TypeCommand MessageType = "command"
+ TypeCommandResult MessageType = "command_result"
+
+ // Streaming
+ TypeSubscribe MessageType = "subscribe"
+ TypeUnsubscribe MessageType = "unsubscribe"
+ TypeStream MessageType = "stream"
+
+ // Errors
+ TypeError MessageType = "error"
+
+ // System
+ TypeSystemInfo MessageType = "system_info"
+)
+
+// Message is the base message structure
+type Message struct {
+ Type MessageType `json:"type"`
+ ID string `json:"id"`
+ Timestamp int64 `json:"timestamp"`
+ Signature string `json:"signature,omitempty"`
+}
+
+// NewMessage creates a new message with timestamp
+func NewMessage(msgType MessageType, id string) Message {
+ return Message{
+ Type: msgType,
+ ID: id,
+ Timestamp: time.Now().UnixMilli(),
+ }
+}
+
+// AuthMessage is sent by agent to authenticate
+type AuthMessage struct {
+ Message
+ AgentID string `json:"agent_id"`
+ APIKeyPrefix string `json:"api_key_prefix"`
+}
+
+// AuthResponse is sent by server after authentication
+type AuthResponse struct {
+ Message
+ SessionToken string `json:"session_token,omitempty"`
+ Expires int64 `json:"expires,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+// HeartbeatMessage is sent periodically by agent
+type HeartbeatMessage struct {
+ Message
+ Metrics HeartbeatMetrics `json:"metrics"`
+}
+
+// HeartbeatMetrics contains basic system metrics
+type HeartbeatMetrics struct {
+ CPUPercent float64 `json:"cpu_percent"`
+ MemoryPercent float64 `json:"memory_percent"`
+ DiskPercent float64 `json:"disk_percent"`
+ ContainerCount int `json:"container_count"`
+ ContainerRunning int `json:"container_running"`
+}
+
+// HeartbeatAck is sent by server to acknowledge heartbeat
+type HeartbeatAck struct {
+ Message
+}
+
+// CommandMessage is sent by server to execute a command
+type CommandMessage struct {
+ Message
+ Action string `json:"action"`
+ Params json.RawMessage `json:"params"`
+ Timeout int `json:"timeout,omitempty"` // milliseconds
+}
+
+// CommandResult is sent by agent after executing a command
+type CommandResult struct {
+ Message
+ CommandID string `json:"command_id"`
+ Success bool `json:"success"`
+ Data json.RawMessage `json:"data,omitempty"`
+ Error string `json:"error,omitempty"`
+ Duration int64 `json:"duration"` // milliseconds
+}
+
+// SubscribeMessage requests subscription to a data stream
+type SubscribeMessage struct {
+ Message
+ Channel string `json:"channel"`
+}
+
+// UnsubscribeMessage cancels a subscription
+type UnsubscribeMessage struct {
+ Message
+ Channel string `json:"channel"`
+}
+
+// StreamMessage contains streaming data
+type StreamMessage struct {
+ Message
+ Channel string `json:"channel"`
+ Data json.RawMessage `json:"data"`
+}
+
+// ErrorMessage represents an error
+type ErrorMessage struct {
+ Message
+ Code string `json:"code"`
+ Details string `json:"details,omitempty"`
+}
+
+// SystemInfoMessage contains system information
+type SystemInfoMessage struct {
+ Message
+ Info SystemInfo `json:"info"`
+}
+
+// SystemInfo contains detailed system information
+type SystemInfo struct {
+ Hostname string `json:"hostname"`
+ OS string `json:"os"`
+ OSVersion string `json:"os_version"`
+ Architecture string `json:"architecture"`
+ CPUCores int `json:"cpu_cores"`
+ TotalMemory uint64 `json:"total_memory"`
+ TotalDisk uint64 `json:"total_disk"`
+ DockerVersion string `json:"docker_version,omitempty"`
+ AgentVersion string `json:"agent_version"`
+}
+
+// Command actions
+const (
+ // Docker container actions
+ ActionDockerContainerList = "docker:container:list"
+ ActionDockerContainerInspect = "docker:container:inspect"
+ ActionDockerContainerCreate = "docker:container:create"
+ ActionDockerContainerStart = "docker:container:start"
+ ActionDockerContainerStop = "docker:container:stop"
+ ActionDockerContainerRestart = "docker:container:restart"
+ ActionDockerContainerRemove = "docker:container:remove"
+ ActionDockerContainerLogs = "docker:container:logs"
+ ActionDockerContainerStats = "docker:container:stats"
+ ActionDockerContainerExec = "docker:container:exec"
+
+ // Docker image actions
+ ActionDockerImageList = "docker:image:list"
+ ActionDockerImagePull = "docker:image:pull"
+ ActionDockerImageRemove = "docker:image:remove"
+ ActionDockerImageBuild = "docker:image:build"
+
+ // Docker volume actions
+ ActionDockerVolumeList = "docker:volume:list"
+ ActionDockerVolumeCreate = "docker:volume:create"
+ ActionDockerVolumeRemove = "docker:volume:remove"
+
+ // Docker network actions
+ ActionDockerNetworkList = "docker:network:list"
+ ActionDockerNetworkCreate = "docker:network:create"
+ ActionDockerNetworkRemove = "docker:network:remove"
+
+ // Docker compose actions
+ ActionDockerComposeList = "docker:compose:list"
+ ActionDockerComposeUp = "docker:compose:up"
+ ActionDockerComposeDown = "docker:compose:down"
+
+ // System actions
+ ActionSystemMetrics = "system:metrics"
+ ActionSystemInfo = "system:info"
+ ActionSystemProcesses = "system:processes"
+ ActionSystemExec = "system:exec"
+
+ // File actions
+ ActionFileRead = "file:read"
+ ActionFileWrite = "file:write"
+ ActionFileList = "file:list"
+)
+
+// Stream channels
+const (
+ ChannelMetrics = "metrics"
+ ChannelContainerLogs = "container:%s:logs"
+ ChannelContainerStats = "container:%s:stats"
+)
diff --git a/agent/scripts/build.ps1 b/agent/scripts/build.ps1
new file mode 100644
index 00000000..729dd1ec
--- /dev/null
+++ b/agent/scripts/build.ps1
@@ -0,0 +1,87 @@
+# Build script for ServerKit Agent (Windows PowerShell)
+# Cross-compiles for multiple platforms
+
+param(
+ [string]$Version = "",
+ [string]$Target = "all"
+)
+
+$ErrorActionPreference = "Stop"
+
+# Get version from git or use default
+if ($Version -eq "") {
+ try {
+ $Version = git describe --tags --always --dirty 2>$null
+ } catch {
+ $Version = "dev"
+ }
+}
+
+$BuildTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
+try {
+ $GitCommit = git rev-parse --short HEAD 2>$null
+} catch {
+ $GitCommit = "unknown"
+}
+
+# Build flags
+$LdFlags = "-s -w -X main.Version=$Version -X main.BuildTime=$BuildTime -X main.GitCommit=$GitCommit"
+
+# Output directory
+$DistDir = "dist"
+if (-not (Test-Path $DistDir)) {
+ New-Item -ItemType Directory -Path $DistDir | Out-Null
+}
+
+Write-Host "Building ServerKit Agent $Version" -ForegroundColor Cyan
+Write-Host "Build time: $BuildTime"
+Write-Host "Git commit: $GitCommit"
+Write-Host ""
+
+# Build targets
+$Targets = @(
+ @{GOOS="linux"; GOARCH="amd64"},
+ @{GOOS="linux"; GOARCH="arm64"},
+ @{GOOS="linux"; GOARCH="arm"},
+ @{GOOS="windows"; GOARCH="amd64"},
+ @{GOOS="windows"; GOARCH="arm64"},
+ @{GOOS="darwin"; GOARCH="amd64"},
+ @{GOOS="darwin"; GOARCH="arm64"}
+)
+
+# Filter targets if specific one requested
+if ($Target -ne "all") {
+ $parts = $Target.Split("/")
+ $Targets = @(@{GOOS=$parts[0]; GOARCH=$parts[1]})
+}
+
+foreach ($t in $Targets) {
+ $goos = $t.GOOS
+ $goarch = $t.GOARCH
+
+ $outputName = "serverkit-agent-$Version-$goos-$goarch"
+ if ($goos -eq "windows") {
+ $outputName = "$outputName.exe"
+ }
+
+ Write-Host "Building $goos/$goarch..." -ForegroundColor Yellow
+
+ $env:CGO_ENABLED = "0"
+ $env:GOOS = $goos
+ $env:GOARCH = $goarch
+
+ go build -ldflags $LdFlags -o "$DistDir/$outputName" ./cmd/agent
+
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "Build failed for $goos/$goarch" -ForegroundColor Red
+ exit 1
+ }
+
+ # Calculate checksum
+ $hash = Get-FileHash -Path "$DistDir/$outputName" -Algorithm SHA256
+ Add-Content -Path "$DistDir/checksums.txt" -Value "$($hash.Hash.ToLower()) $outputName"
+}
+
+Write-Host ""
+Write-Host "Build complete! Binaries in $DistDir/" -ForegroundColor Green
+Get-ChildItem $DistDir
diff --git a/agent/scripts/build.sh b/agent/scripts/build.sh
new file mode 100644
index 00000000..fdaabf05
--- /dev/null
+++ b/agent/scripts/build.sh
@@ -0,0 +1,60 @@
+#!/bin/bash
+
+# Build script for ServerKit Agent
+# Cross-compiles for multiple platforms
+
+set -e
+
+# Get version from git or use default
+VERSION=${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo "dev")}
+BUILD_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
+GIT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
+
+# Build flags
+LDFLAGS="-s -w -X main.Version=${VERSION} -X main.BuildTime=${BUILD_TIME} -X main.GitCommit=${GIT_COMMIT}"
+
+# Output directory
+DIST_DIR="dist"
+mkdir -p ${DIST_DIR}
+
+echo "Building ServerKit Agent ${VERSION}"
+echo "Build time: ${BUILD_TIME}"
+echo "Git commit: ${GIT_COMMIT}"
+echo ""
+
+# Build targets
+TARGETS=(
+ "linux/amd64"
+ "linux/arm64"
+ "linux/arm"
+ "windows/amd64"
+ "windows/arm64"
+ "darwin/amd64"
+ "darwin/arm64"
+)
+
+for target in "${TARGETS[@]}"; do
+ GOOS=${target%/*}
+ GOARCH=${target#*/}
+
+ OUTPUT_NAME="serverkit-agent-${VERSION}-${GOOS}-${GOARCH}"
+ if [ "${GOOS}" == "windows" ]; then
+ OUTPUT_NAME="${OUTPUT_NAME}.exe"
+ fi
+
+ echo "Building ${GOOS}/${GOARCH}..."
+
+ CGO_ENABLED=0 GOOS=${GOOS} GOARCH=${GOARCH} go build \
+ -ldflags "${LDFLAGS}" \
+ -o "${DIST_DIR}/${OUTPUT_NAME}" \
+ ./cmd/agent
+
+ # Calculate checksum
+ if command -v sha256sum &> /dev/null; then
+ sha256sum "${DIST_DIR}/${OUTPUT_NAME}" >> "${DIST_DIR}/checksums.txt"
+ fi
+done
+
+echo ""
+echo "Build complete! Binaries in ${DIST_DIR}/"
+ls -la ${DIST_DIR}/
diff --git a/agent/scripts/install.ps1 b/agent/scripts/install.ps1
new file mode 100644
index 00000000..36c6f55e
--- /dev/null
+++ b/agent/scripts/install.ps1
@@ -0,0 +1,225 @@
+#Requires -RunAsAdministrator
+#
+# ServerKit Agent Installation Script for Windows
+# Usage: irm https://your-serverkit.com/install.ps1 | iex; Install-ServerKitAgent -Token "sk_reg_xxx" -Server "https://..."
+#
+
+function Install-ServerKitAgent {
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory=$true)]
+ [string]$Token,
+
+ [Parameter(Mandatory=$true)]
+ [string]$Server,
+
+ [Parameter(Mandatory=$false)]
+ [string]$Name = "",
+
+ [Parameter(Mandatory=$false)]
+ [string]$DownloadUrl = ""
+ )
+
+ $ErrorActionPreference = "Stop"
+
+ # Configuration
+ $InstallDir = "$env:ProgramFiles\ServerKit Agent"
+ $ConfigDir = "$env:ProgramData\ServerKit\Agent"
+ $LogDir = "$env:ProgramData\ServerKit\Agent\logs"
+ $ServiceName = "ServerKitAgent"
+
+ function Write-Info { param([string]$Message) Write-Host "[INFO] $Message" -ForegroundColor Cyan }
+ function Write-Success { param([string]$Message) Write-Host "[SUCCESS] $Message" -ForegroundColor Green }
+ function Write-Warn { param([string]$Message) Write-Host "[WARN] $Message" -ForegroundColor Yellow }
+ function Write-Err { param([string]$Message) Write-Host "[ERROR] $Message" -ForegroundColor Red }
+
+ Write-Host ""
+ Write-Host "╔══════════════════════════════════════════╗" -ForegroundColor Green
+ Write-Host "║ ServerKit Agent Installation ║" -ForegroundColor Green
+ Write-Host "╚══════════════════════════════════════════╝" -ForegroundColor Green
+ Write-Host ""
+
+ # Detect architecture
+ $Arch = if ([Environment]::Is64BitOperatingSystem) { "amd64" } else { "386" }
+ Write-Info "Detected architecture: windows/$Arch"
+
+ # Create directories
+ Write-Info "Creating directories..."
+ New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
+ New-Item -ItemType Directory -Path $ConfigDir -Force | Out-Null
+ New-Item -ItemType Directory -Path $LogDir -Force | Out-Null
+
+ # Stop existing service if running
+ $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
+ if ($service -and $service.Status -eq "Running") {
+ Write-Info "Stopping existing agent service..."
+ Stop-Service -Name $ServiceName -Force
+ Start-Sleep -Seconds 2
+ }
+
+ # Construct download URL
+ if ([string]::IsNullOrEmpty($DownloadUrl)) {
+ $DownloadUrl = "$Server/downloads/agent/serverkit-agent-windows-$Arch.exe"
+ }
+
+ # Download agent
+ Write-Info "Downloading agent from $DownloadUrl..."
+ $AgentPath = "$InstallDir\serverkit-agent.exe"
+ try {
+ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+ Invoke-WebRequest -Uri $DownloadUrl -OutFile $AgentPath -UseBasicParsing
+ } catch {
+ Write-Err "Failed to download agent: $_"
+ throw
+ }
+
+ # Verify download
+ if (-not (Test-Path $AgentPath)) {
+ Write-Err "Agent binary not found after download"
+ throw "Download failed"
+ }
+
+ Write-Success "Agent downloaded successfully"
+
+ # Register with ServerKit
+ Write-Info "Registering agent with ServerKit..."
+ $RegisterArgs = @("register", "--token", $Token, "--server", $Server)
+ if (-not [string]::IsNullOrEmpty($Name)) {
+ $RegisterArgs += @("--name", $Name)
+ }
+
+ $process = Start-Process -FilePath $AgentPath -ArgumentList $RegisterArgs -Wait -PassThru -NoNewWindow
+ if ($process.ExitCode -ne 0) {
+ Write-Err "Registration failed with exit code $($process.ExitCode)"
+ throw "Registration failed"
+ }
+
+ Write-Success "Registration successful"
+
+ # Install as Windows Service
+ Write-Info "Installing Windows service..."
+
+ # Remove existing service if present
+ if ($service) {
+ Write-Info "Removing existing service..."
+ sc.exe delete $ServiceName | Out-Null
+ Start-Sleep -Seconds 2
+ }
+
+ # Create service using sc.exe
+ $binPath = "`"$AgentPath`" start"
+ $result = sc.exe create $ServiceName binPath= $binPath start= auto displayname= "ServerKit Agent"
+ if ($LASTEXITCODE -ne 0) {
+ Write-Err "Failed to create service"
+ throw "Service creation failed"
+ }
+
+ # Set service description
+ sc.exe description $ServiceName "ServerKit Agent - Remote server management agent" | Out-Null
+
+ # Configure service recovery (restart on failure)
+ sc.exe failure $ServiceName reset= 86400 actions= restart/5000/restart/10000/restart/30000 | Out-Null
+
+ Write-Success "Service installed"
+
+ # Configure firewall (optional)
+ Write-Info "Configuring Windows Firewall..."
+ try {
+ $firewallRule = Get-NetFirewallRule -DisplayName "ServerKit Agent" -ErrorAction SilentlyContinue
+ if (-not $firewallRule) {
+ New-NetFirewallRule -DisplayName "ServerKit Agent" `
+ -Direction Outbound `
+ -Action Allow `
+ -Program $AgentPath `
+ -Description "Allow ServerKit Agent outbound connections" | Out-Null
+ Write-Success "Firewall rule created"
+ } else {
+ Write-Info "Firewall rule already exists"
+ }
+ } catch {
+ Write-Warn "Could not configure firewall: $_"
+ }
+
+ # Start service
+ Write-Info "Starting agent service..."
+ Start-Service -Name $ServiceName
+ Start-Sleep -Seconds 3
+
+ $service = Get-Service -Name $ServiceName
+ if ($service.Status -eq "Running") {
+ Write-Success "Agent is running"
+ } else {
+ Write-Err "Agent failed to start"
+ Get-EventLog -LogName Application -Source $ServiceName -Newest 10 -ErrorAction SilentlyContinue | Format-List
+ throw "Agent failed to start"
+ }
+
+ # Add to PATH
+ $currentPath = [Environment]::GetEnvironmentVariable("Path", "Machine")
+ if ($currentPath -notlike "*$InstallDir*") {
+ Write-Info "Adding agent to system PATH..."
+ [Environment]::SetEnvironmentVariable("Path", "$currentPath;$InstallDir", "Machine")
+ }
+
+ Write-Host ""
+ Write-Success "Installation complete!"
+ Write-Host ""
+ Write-Host "Agent Status: Get-Service $ServiceName"
+ Write-Host "View Logs: Get-Content '$LogDir\agent.log' -Tail 50"
+ Write-Host "Config File: $ConfigDir\config.yaml"
+ Write-Host "Uninstall: Uninstall-ServerKitAgent"
+ Write-Host ""
+}
+
+function Uninstall-ServerKitAgent {
+ [CmdletBinding()]
+ param()
+
+ $ErrorActionPreference = "Stop"
+
+ $InstallDir = "$env:ProgramFiles\ServerKit Agent"
+ $ConfigDir = "$env:ProgramData\ServerKit\Agent"
+ $ServiceName = "ServerKitAgent"
+
+ Write-Host "Uninstalling ServerKit Agent..." -ForegroundColor Yellow
+
+ # Stop and remove service
+ $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
+ if ($service) {
+ if ($service.Status -eq "Running") {
+ Stop-Service -Name $ServiceName -Force
+ Start-Sleep -Seconds 2
+ }
+ sc.exe delete $ServiceName | Out-Null
+ Write-Host "Service removed" -ForegroundColor Green
+ }
+
+ # Remove firewall rule
+ Remove-NetFirewallRule -DisplayName "ServerKit Agent" -ErrorAction SilentlyContinue
+
+ # Remove installation directory
+ if (Test-Path $InstallDir) {
+ Remove-Item -Path $InstallDir -Recurse -Force
+ Write-Host "Installation directory removed" -ForegroundColor Green
+ }
+
+ # Ask about config removal
+ $removeConfig = Read-Host "Remove configuration and logs? (y/N)"
+ if ($removeConfig -eq "y" -or $removeConfig -eq "Y") {
+ if (Test-Path $ConfigDir) {
+ Remove-Item -Path $ConfigDir -Recurse -Force
+ Write-Host "Configuration removed" -ForegroundColor Green
+ }
+ }
+
+ # Remove from PATH
+ $currentPath = [Environment]::GetEnvironmentVariable("Path", "Machine")
+ $newPath = ($currentPath.Split(';') | Where-Object { $_ -ne $InstallDir }) -join ';'
+ [Environment]::SetEnvironmentVariable("Path", $newPath, "Machine")
+
+ Write-Host ""
+ Write-Host "ServerKit Agent has been uninstalled" -ForegroundColor Green
+}
+
+# Export functions
+Export-ModuleMember -Function Install-ServerKitAgent, Uninstall-ServerKitAgent
diff --git a/agent/scripts/install.sh b/agent/scripts/install.sh
new file mode 100644
index 00000000..ea1eec80
--- /dev/null
+++ b/agent/scripts/install.sh
@@ -0,0 +1,306 @@
+#!/bin/bash
+#
+# ServerKit Agent Installation Script
+# Usage: curl -fsSL https://your-serverkit.com/install.sh | sudo bash -s -- --token "sk_reg_xxx"
+#
+
+set -e
+
+# Colors
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+NC='\033[0m' # No Color
+
+# Default values
+INSTALL_DIR="/usr/local/bin"
+CONFIG_DIR="/etc/serverkit-agent"
+LOG_DIR="/var/log/serverkit-agent"
+SERVICE_USER="serverkit-agent"
+DOWNLOAD_URL="" # Will be set by ServerKit server
+TOKEN=""
+SERVER_URL=""
+NAME=""
+
+# Parse arguments
+while [[ $# -gt 0 ]]; do
+ case $1 in
+ --token|-t)
+ TOKEN="$2"
+ shift 2
+ ;;
+ --server|-s)
+ SERVER_URL="$2"
+ shift 2
+ ;;
+ --name|-n)
+ NAME="$2"
+ shift 2
+ ;;
+ --download-url)
+ DOWNLOAD_URL="$2"
+ shift 2
+ ;;
+ --help|-h)
+ echo "ServerKit Agent Installer"
+ echo ""
+ echo "Usage: $0 [options]"
+ echo ""
+ echo "Options:"
+ echo " --token, -t TOKEN Registration token (required)"
+ echo " --server, -s URL ServerKit server URL (required)"
+ echo " --name, -n NAME Server display name (optional)"
+ echo " --download-url URL Custom download URL (optional)"
+ echo " --help, -h Show this help"
+ exit 0
+ ;;
+ *)
+ echo "Unknown option: $1"
+ exit 1
+ ;;
+ esac
+done
+
+# Validate required arguments
+if [ -z "$TOKEN" ]; then
+ echo -e "${RED}Error: Registration token is required${NC}"
+ echo "Usage: $0 --token TOKEN --server URL"
+ exit 1
+fi
+
+if [ -z "$SERVER_URL" ]; then
+ echo -e "${RED}Error: Server URL is required${NC}"
+ echo "Usage: $0 --token TOKEN --server URL"
+ exit 1
+fi
+
+# Functions
+log_info() {
+ echo -e "${BLUE}[INFO]${NC} $1"
+}
+
+log_success() {
+ echo -e "${GREEN}[SUCCESS]${NC} $1"
+}
+
+log_warn() {
+ echo -e "${YELLOW}[WARN]${NC} $1"
+}
+
+log_error() {
+ echo -e "${RED}[ERROR]${NC} $1"
+}
+
+# Check if running as root
+check_root() {
+ if [ "$EUID" -ne 0 ]; then
+ log_error "This script must be run as root"
+ exit 1
+ fi
+}
+
+# Detect OS and architecture
+detect_platform() {
+ OS=$(uname -s | tr '[:upper:]' '[:lower:]')
+ ARCH=$(uname -m)
+
+ case $ARCH in
+ x86_64|amd64)
+ ARCH="amd64"
+ ;;
+ aarch64|arm64)
+ ARCH="arm64"
+ ;;
+ armv7l|armhf)
+ ARCH="arm"
+ ;;
+ *)
+ log_error "Unsupported architecture: $ARCH"
+ exit 1
+ ;;
+ esac
+
+ log_info "Detected platform: $OS/$ARCH"
+}
+
+# Detect init system
+detect_init_system() {
+ if [ -d /run/systemd/system ]; then
+ INIT_SYSTEM="systemd"
+ elif [ -f /etc/init.d/cron ] && [ ! -d /run/systemd/system ]; then
+ INIT_SYSTEM="sysvinit"
+ else
+ INIT_SYSTEM="unknown"
+ fi
+ log_info "Init system: $INIT_SYSTEM"
+}
+
+# Create service user
+create_user() {
+ if id "$SERVICE_USER" &>/dev/null; then
+ log_info "Service user '$SERVICE_USER' already exists"
+ else
+ log_info "Creating service user '$SERVICE_USER'..."
+ useradd --system --no-create-home --shell /bin/false "$SERVICE_USER"
+ fi
+
+ # Add user to docker group if it exists
+ if getent group docker > /dev/null; then
+ usermod -aG docker "$SERVICE_USER"
+ log_info "Added $SERVICE_USER to docker group"
+ fi
+}
+
+# Download the agent binary
+download_agent() {
+ if [ -z "$DOWNLOAD_URL" ]; then
+ # Construct download URL from server
+ DOWNLOAD_URL="${SERVER_URL}/downloads/agent/serverkit-agent-${OS}-${ARCH}"
+ fi
+
+ log_info "Downloading agent from $DOWNLOAD_URL..."
+
+ # Try curl first, then wget
+ if command -v curl &> /dev/null; then
+ curl -fsSL -o /tmp/serverkit-agent "$DOWNLOAD_URL"
+ elif command -v wget &> /dev/null; then
+ wget -q -O /tmp/serverkit-agent "$DOWNLOAD_URL"
+ else
+ log_error "Neither curl nor wget is available"
+ exit 1
+ fi
+
+ chmod +x /tmp/serverkit-agent
+}
+
+# Install the agent
+install_agent() {
+ log_info "Installing agent to $INSTALL_DIR..."
+
+ # Stop existing service if running
+ if [ "$INIT_SYSTEM" = "systemd" ] && systemctl is-active --quiet serverkit-agent; then
+ log_info "Stopping existing agent service..."
+ systemctl stop serverkit-agent
+ fi
+
+ # Install binary
+ mv /tmp/serverkit-agent "$INSTALL_DIR/serverkit-agent"
+ chmod 755 "$INSTALL_DIR/serverkit-agent"
+
+ # Create directories
+ mkdir -p "$CONFIG_DIR"
+ mkdir -p "$LOG_DIR"
+ chown "$SERVICE_USER:$SERVICE_USER" "$LOG_DIR"
+}
+
+# Register with ServerKit
+register_agent() {
+ log_info "Registering agent with ServerKit..."
+
+ REGISTER_CMD="$INSTALL_DIR/serverkit-agent register --token \"$TOKEN\" --server \"$SERVER_URL\""
+ if [ -n "$NAME" ]; then
+ REGISTER_CMD="$REGISTER_CMD --name \"$NAME\""
+ fi
+
+ eval $REGISTER_CMD
+
+ if [ $? -ne 0 ]; then
+ log_error "Registration failed"
+ exit 1
+ fi
+
+ # Set permissions on config
+ chown -R "$SERVICE_USER:$SERVICE_USER" "$CONFIG_DIR"
+ chmod 600 "$CONFIG_DIR/config.yaml"
+ chmod 600 "$CONFIG_DIR/agent.key"
+}
+
+# Install systemd service
+install_systemd_service() {
+ log_info "Installing systemd service..."
+
+ cat > /etc/systemd/system/serverkit-agent.service << EOF
+[Unit]
+Description=ServerKit Agent
+Documentation=https://github.com/serverkit/agent
+After=network-online.target docker.service
+Wants=network-online.target
+
+[Service]
+Type=simple
+User=$SERVICE_USER
+Group=$SERVICE_USER
+ExecStart=$INSTALL_DIR/serverkit-agent start
+Restart=always
+RestartSec=5
+StandardOutput=journal
+StandardError=journal
+SyslogIdentifier=serverkit-agent
+
+# Security hardening
+NoNewPrivileges=yes
+ProtectSystem=strict
+ProtectHome=yes
+ReadWritePaths=$LOG_DIR $CONFIG_DIR
+PrivateTmp=yes
+
+[Install]
+WantedBy=multi-user.target
+EOF
+
+ systemctl daemon-reload
+ systemctl enable serverkit-agent
+}
+
+# Start the agent
+start_agent() {
+ log_info "Starting agent..."
+
+ if [ "$INIT_SYSTEM" = "systemd" ]; then
+ systemctl start serverkit-agent
+ sleep 2
+ if systemctl is-active --quiet serverkit-agent; then
+ log_success "Agent is running"
+ else
+ log_error "Agent failed to start"
+ journalctl -u serverkit-agent -n 20 --no-pager
+ exit 1
+ fi
+ else
+ log_warn "Please start the agent manually: $INSTALL_DIR/serverkit-agent start"
+ fi
+}
+
+# Main installation flow
+main() {
+ echo ""
+ echo -e "${GREEN}╔══════════════════════════════════════════╗${NC}"
+ echo -e "${GREEN}║ ServerKit Agent Installation ║${NC}"
+ echo -e "${GREEN}╚══════════════════════════════════════════╝${NC}"
+ echo ""
+
+ check_root
+ detect_platform
+ detect_init_system
+ create_user
+ download_agent
+ install_agent
+ register_agent
+
+ if [ "$INIT_SYSTEM" = "systemd" ]; then
+ install_systemd_service
+ fi
+
+ start_agent
+
+ echo ""
+ log_success "Installation complete!"
+ echo ""
+ echo "Agent Status: serverkit-agent status"
+ echo "View Logs: journalctl -u serverkit-agent -f"
+ echo "Config File: $CONFIG_DIR/config.yaml"
+ echo ""
+}
+
+main
diff --git a/agent/serverkit-agent.exe b/agent/serverkit-agent.exe
new file mode 100644
index 00000000..7d458ce2
Binary files /dev/null and b/agent/serverkit-agent.exe differ