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 agent auto-update mechanism and backend endpoints

Juan Denis4e9767a6caad
diff --git a/ROADMAP.md b/ROADMAP.md
index 18ea0222..4310e754 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -131,7 +131,7 @@ This document outlines the development roadmap for ServerKit. Features are organ
- [x] HMAC-SHA256 authentication
- [x] GitHub Actions for agent releases (Linux/Windows)
- [x] Installation scripts endpoint
-- [ ] Agent auto-update mechanism
+- [x] Agent auto-update mechanism
---
diff --git a/SERVERS_INTEGRATION_PLAN.md b/SERVERS_INTEGRATION_PLAN.md
index e1d4d466..fadb6d45 100644
--- a/SERVERS_INTEGRATION_PLAN.md
+++ b/SERVERS_INTEGRATION_PLAN.md
@@ -1310,7 +1310,7 @@ system:exec: # Requires explicit permission
[x] Health grid view
```
-### Phase 10.7: Installation & Distribution 🔄 IN PROGRESS
+### Phase 10.7: Installation & Distribution ✅ MOSTLY COMPLETE
**Duration: ~1-2 weeks**
```
@@ -1332,10 +1332,13 @@ system:exec: # Requires explicit permission
[ ] .msi installer
[ ] Homebrew formula
+[x] Auto-update system
+ [x] Version checking endpoint
+ [x] Auto-update mechanism in agent
+ [x] Manual update command (`serverkit-agent update`)
+
[ ] Distribution
[ ] Download page in UI
- [ ] Version checking
- [ ] Auto-update mechanism
```
### Phase 10.8: Advanced Features
diff --git a/agent/cmd/agent/main.go b/agent/cmd/agent/main.go
index e54ba421..bca0d016 100644
--- a/agent/cmd/agent/main.go
+++ b/agent/cmd/agent/main.go
@@ -10,6 +10,7 @@ import (
"github.com/serverkit/agent/internal/agent"
"github.com/serverkit/agent/internal/config"
"github.com/serverkit/agent/internal/logger"
+ "github.com/serverkit/agent/internal/updater"
"github.com/spf13/cobra"
)
@@ -42,6 +43,7 @@ enabling remote Docker management, monitoring, and more.`,
rootCmd.AddCommand(statusCmd())
rootCmd.AddCommand(versionCmd())
rootCmd.AddCommand(configCmd())
+ rootCmd.AddCommand(updateCmd())
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
@@ -134,6 +136,93 @@ func configCmd() *cobra.Command {
return cmd
}
+func updateCmd() *cobra.Command {
+ var forceUpdate bool
+ var checkOnly bool
+
+ cmd := &cobra.Command{
+ Use: "update",
+ Short: "Check for and install updates",
+ Long: `Check for available updates and optionally install them.
+
+By default, this command checks for updates and prompts before installing.
+Use --force to install without prompting.
+Use --check to only check for updates without installing.`,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runUpdate(forceUpdate, checkOnly)
+ },
+ }
+
+ cmd.Flags().BoolVarP(&forceUpdate, "force", "f", false, "install update without prompting")
+ cmd.Flags().BoolVarP(&checkOnly, "check", "c", false, "only check for updates, don't install")
+
+ return cmd
+}
+
+func runUpdate(force, checkOnly bool) error {
+ // Load configuration
+ cfg, err := config.Load(cfgFile)
+ if err != nil {
+ return fmt.Errorf("failed to load config: %w", err)
+ }
+
+ log := logger.New(config.LoggingConfig{Level: "info"})
+ u := updater.New(cfg, log, Version)
+
+ ctx := context.Background()
+
+ fmt.Printf("Current version: %s\n", Version)
+ fmt.Println("Checking for updates...")
+
+ info, err := u.CheckForUpdate(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to check for updates: %w", err)
+ }
+
+ if !info.UpdateAvailable {
+ fmt.Println("You are running the latest version.")
+ return nil
+ }
+
+ fmt.Printf("\nUpdate available: v%s -> v%s\n", info.CurrentVersion, info.LatestVersion)
+ fmt.Printf("Published: %s\n", info.PublishedAt)
+ if info.ReleaseNotesURL != "" {
+ fmt.Printf("Release notes: %s\n", info.ReleaseNotesURL)
+ }
+
+ if checkOnly {
+ return nil
+ }
+
+ // Prompt for confirmation unless forced
+ if !force {
+ fmt.Print("\nDo you want to install this update? [y/N]: ")
+ var response string
+ fmt.Scanln(&response)
+ if response != "y" && response != "Y" {
+ fmt.Println("Update cancelled.")
+ return nil
+ }
+ }
+
+ fmt.Println("\nDownloading update...")
+ binaryPath, err := u.DownloadUpdate(ctx, info)
+ if err != nil {
+ return fmt.Errorf("failed to download update: %w", err)
+ }
+
+ fmt.Println("Installing update...")
+ if err := u.InstallUpdate(binaryPath); err != nil {
+ u.Cleanup(binaryPath)
+ return fmt.Errorf("failed to install update: %w", err)
+ }
+
+ fmt.Println("\nUpdate installed successfully!")
+ fmt.Println("The agent will restart with the new version.")
+
+ return nil
+}
+
func runAgent() error {
// Load configuration
cfg, err := config.Load(cfgFile)
@@ -167,6 +256,10 @@ func runAgent() error {
return fmt.Errorf("failed to create agent: %w", err)
}
+ // Start update checker in background
+ updateChecker := updater.NewChecker(cfg, log, Version)
+ go updateChecker.Start(ctx)
+
// Handle graceful shutdown
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
diff --git a/agent/internal/config/config.go b/agent/internal/config/config.go
index 8b1c80c9..b1455718 100644
--- a/agent/internal/config/config.go
+++ b/agent/internal/config/config.go
@@ -26,6 +26,7 @@ type Config struct {
Docker DockerConfig `yaml:"docker"`
Security SecurityConfig `yaml:"security"`
Logging LoggingConfig `yaml:"logging"`
+ Update UpdateConfig `yaml:"update"`
}
// ServerConfig holds connection settings
@@ -90,6 +91,13 @@ type LoggingConfig struct {
Compress bool `yaml:"compress"`
}
+// UpdateConfig holds auto-update settings
+type UpdateConfig struct {
+ Enabled bool `yaml:"enabled"`
+ CheckInterval time.Duration `yaml:"check_interval"`
+ AutoInstall bool `yaml:"auto_install"`
+}
+
// Default returns default configuration
func Default() *Config {
return &Config{
@@ -132,6 +140,11 @@ func Default() *Config {
MaxAge: 30,
Compress: true,
},
+ Update: UpdateConfig{
+ Enabled: true,
+ CheckInterval: 1 * time.Hour,
+ AutoInstall: false, // Require manual confirmation by default
+ },
}
}
diff --git a/agent/internal/updater/checker.go b/agent/internal/updater/checker.go
new file mode 100644
index 00000000..f16dd985
--- /dev/null
+++ b/agent/internal/updater/checker.go
@@ -0,0 +1,152 @@
+package updater
+
+import (
+ "context"
+ "sync"
+ "time"
+
+ "github.com/serverkit/agent/internal/config"
+ "github.com/serverkit/agent/internal/logger"
+)
+
+// UpdateChecker runs periodic update checks
+type UpdateChecker struct {
+ updater *Updater
+ cfg *config.Config
+ log *logger.Logger
+
+ mu sync.Mutex
+ lastCheck time.Time
+ latestVersion string
+ updatePending bool
+}
+
+// NewChecker creates a new update checker
+func NewChecker(cfg *config.Config, log *logger.Logger, currentVersion string) *UpdateChecker {
+ return &UpdateChecker{
+ updater: New(cfg, log, currentVersion),
+ cfg: cfg,
+ log: log,
+ }
+}
+
+// Start begins the periodic update check routine
+func (c *UpdateChecker) Start(ctx context.Context) {
+ if !c.cfg.Update.Enabled {
+ c.log.Info("Auto-update checks disabled")
+ return
+ }
+
+ c.log.Info("Starting update checker",
+ "interval", c.cfg.Update.CheckInterval,
+ "auto_install", c.cfg.Update.AutoInstall,
+ )
+
+ // Do initial check after a short delay
+ go func() {
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(1 * time.Minute):
+ c.checkAndNotify(ctx)
+ }
+ }()
+
+ // Start periodic checks
+ ticker := time.NewTicker(c.cfg.Update.CheckInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ c.log.Debug("Update checker stopped")
+ return
+ case <-ticker.C:
+ c.checkAndNotify(ctx)
+ }
+ }
+}
+
+func (c *UpdateChecker) checkAndNotify(ctx context.Context) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ c.lastCheck = time.Now()
+
+ info, err := c.updater.CheckForUpdate(ctx)
+ if err != nil {
+ c.log.Warn("Update check failed", "error", err)
+ return
+ }
+
+ if !info.UpdateAvailable {
+ c.log.Debug("No update available")
+ c.updatePending = false
+ return
+ }
+
+ c.latestVersion = info.LatestVersion
+ c.updatePending = true
+
+ c.log.Info("Update available",
+ "current", info.CurrentVersion,
+ "latest", info.LatestVersion,
+ )
+
+ // Auto-install if enabled
+ if c.cfg.Update.AutoInstall {
+ c.log.Info("Auto-install enabled, downloading update...")
+ if err := c.installUpdate(ctx, info); err != nil {
+ c.log.Error("Auto-update failed", "error", err)
+ }
+ }
+}
+
+func (c *UpdateChecker) installUpdate(ctx context.Context, info *VersionInfo) error {
+ binaryPath, err := c.updater.DownloadUpdate(ctx, info)
+ if err != nil {
+ return err
+ }
+
+ if err := c.updater.InstallUpdate(binaryPath); err != nil {
+ c.updater.Cleanup(binaryPath)
+ return err
+ }
+
+ return nil
+}
+
+// CheckNow performs an immediate update check
+func (c *UpdateChecker) CheckNow(ctx context.Context) (*VersionInfo, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ c.lastCheck = time.Now()
+ return c.updater.CheckForUpdate(ctx)
+}
+
+// GetUpdater returns the underlying updater for manual operations
+func (c *UpdateChecker) GetUpdater() *Updater {
+ return c.updater
+}
+
+// HasPendingUpdate returns true if an update is available
+func (c *UpdateChecker) HasPendingUpdate() bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.updatePending
+}
+
+// GetLatestVersion returns the latest available version
+func (c *UpdateChecker) GetLatestVersion() string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.latestVersion
+}
+
+// GetLastCheck returns when the last check was performed
+func (c *UpdateChecker) GetLastCheck() time.Time {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.lastCheck
+}
diff --git a/agent/internal/updater/updater.go b/agent/internal/updater/updater.go
new file mode 100644
index 00000000..076e2c82
--- /dev/null
+++ b/agent/internal/updater/updater.go
@@ -0,0 +1,495 @@
+package updater
+
+import (
+ "archive/tar"
+ "archive/zip"
+ "compress/gzip"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "time"
+
+ "github.com/serverkit/agent/internal/config"
+ "github.com/serverkit/agent/internal/logger"
+)
+
+// VersionInfo holds version check response
+type VersionInfo struct {
+ UpdateAvailable bool `json:"update_available"`
+ CurrentVersion string `json:"current_version"`
+ LatestVersion string `json:"latest_version"`
+ DownloadURL string `json:"download_url"`
+ ChecksumsURL string `json:"checksums_url"`
+ ReleaseNotesURL string `json:"release_notes_url"`
+ PublishedAt string `json:"published_at"`
+}
+
+// Updater handles agent self-updates
+type Updater struct {
+ cfg *config.Config
+ log *logger.Logger
+ currentVersion string
+ serverURL string
+ httpClient *http.Client
+}
+
+// New creates a new Updater instance
+func New(cfg *config.Config, log *logger.Logger, currentVersion string) *Updater {
+ // Derive HTTP URL from WebSocket URL
+ serverURL := cfg.Server.URL
+ serverURL = strings.Replace(serverURL, "wss://", "https://", 1)
+ serverURL = strings.Replace(serverURL, "ws://", "http://", 1)
+ // Remove /agent/ws path if present
+ serverURL = strings.TrimSuffix(serverURL, "/agent/ws")
+ serverURL = strings.TrimSuffix(serverURL, "/agent")
+
+ return &Updater{
+ cfg: cfg,
+ log: log,
+ currentVersion: currentVersion,
+ serverURL: serverURL,
+ httpClient: &http.Client{
+ Timeout: 30 * time.Second,
+ },
+ }
+}
+
+// CheckForUpdate checks if a new version is available
+func (u *Updater) CheckForUpdate(ctx context.Context) (*VersionInfo, error) {
+ u.log.Debug("Checking for updates", "current_version", u.currentVersion)
+
+ url := fmt.Sprintf("%s/api/servers/agent/version/check", u.serverURL)
+
+ payload := map[string]string{
+ "current_version": u.currentVersion,
+ "os": runtime.GOOS,
+ "arch": runtime.GOARCH,
+ }
+
+ body, err := json.Marshal(payload)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal request: %w", err)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, "POST", url, strings.NewReader(string(body)))
+ 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", u.currentVersion))
+
+ resp, err := u.httpClient.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("failed to check for updates: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("update check failed with status: %d", resp.StatusCode)
+ }
+
+ var info VersionInfo
+ if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {
+ return nil, fmt.Errorf("failed to decode response: %w", err)
+ }
+
+ u.log.Debug("Update check complete",
+ "update_available", info.UpdateAvailable,
+ "latest_version", info.LatestVersion,
+ )
+
+ return &info, nil
+}
+
+// DownloadUpdate downloads the new version
+func (u *Updater) DownloadUpdate(ctx context.Context, info *VersionInfo) (string, error) {
+ if info.DownloadURL == "" {
+ return "", fmt.Errorf("no download URL available")
+ }
+
+ u.log.Info("Downloading update", "version", info.LatestVersion, "url", info.DownloadURL)
+
+ // Create temp directory
+ tmpDir, err := os.MkdirTemp("", "serverkit-update-*")
+ if err != nil {
+ return "", fmt.Errorf("failed to create temp directory: %w", err)
+ }
+
+ // Determine archive type
+ var archivePath string
+ if runtime.GOOS == "windows" {
+ archivePath = filepath.Join(tmpDir, "agent.zip")
+ } else {
+ archivePath = filepath.Join(tmpDir, "agent.tar.gz")
+ }
+
+ // Download archive
+ if err := u.downloadFile(ctx, info.DownloadURL, archivePath); err != nil {
+ os.RemoveAll(tmpDir)
+ return "", fmt.Errorf("failed to download update: %w", err)
+ }
+
+ // Verify checksum if available
+ if info.ChecksumsURL != "" {
+ if err := u.verifyChecksum(ctx, archivePath, info.ChecksumsURL); err != nil {
+ os.RemoveAll(tmpDir)
+ return "", fmt.Errorf("checksum verification failed: %w", err)
+ }
+ u.log.Info("Checksum verified successfully")
+ }
+
+ // Extract binary
+ binaryPath, err := u.extractBinary(archivePath, tmpDir)
+ if err != nil {
+ os.RemoveAll(tmpDir)
+ return "", fmt.Errorf("failed to extract update: %w", err)
+ }
+
+ u.log.Info("Update downloaded and verified", "path", binaryPath)
+ return binaryPath, nil
+}
+
+// InstallUpdate installs the new binary and restarts the agent
+func (u *Updater) InstallUpdate(newBinaryPath string) error {
+ u.log.Info("Installing update", "new_binary", newBinaryPath)
+
+ // Get current binary path
+ currentBinary, err := os.Executable()
+ if err != nil {
+ return fmt.Errorf("failed to get current executable: %w", err)
+ }
+ currentBinary, err = filepath.EvalSymlinks(currentBinary)
+ if err != nil {
+ return fmt.Errorf("failed to resolve symlinks: %w", err)
+ }
+
+ // Create backup path
+ backupPath := currentBinary + ".backup"
+
+ // On Windows, we need to rename the current binary first
+ if runtime.GOOS == "windows" {
+ return u.installWindows(currentBinary, newBinaryPath, backupPath)
+ }
+
+ return u.installUnix(currentBinary, newBinaryPath, backupPath)
+}
+
+func (u *Updater) installUnix(currentBinary, newBinaryPath, backupPath string) error {
+ // Remove old backup if exists
+ os.Remove(backupPath)
+
+ // Backup current binary
+ if err := os.Rename(currentBinary, backupPath); err != nil {
+ return fmt.Errorf("failed to backup current binary: %w", err)
+ }
+
+ // Copy new binary to target location
+ if err := copyFile(newBinaryPath, currentBinary); err != nil {
+ // Restore backup on failure
+ os.Rename(backupPath, currentBinary)
+ return fmt.Errorf("failed to copy new binary: %w", err)
+ }
+
+ // Make executable
+ if err := os.Chmod(currentBinary, 0755); err != nil {
+ os.Rename(backupPath, currentBinary)
+ return fmt.Errorf("failed to set permissions: %w", err)
+ }
+
+ u.log.Info("Update installed successfully, restarting agent...")
+
+ // Restart via systemd if available
+ if u.isSystemd() {
+ cmd := exec.Command("systemctl", "restart", "serverkit-agent")
+ if err := cmd.Start(); err != nil {
+ u.log.Warn("Failed to restart via systemd", "error", err)
+ }
+ return nil
+ }
+
+ // Self-restart
+ return u.selfRestart(currentBinary)
+}
+
+func (u *Updater) installWindows(currentBinary, newBinaryPath, backupPath string) error {
+ // On Windows, create a batch script to:
+ // 1. Wait for current process to exit
+ // 2. Replace the binary
+ // 3. Start the new binary/service
+
+ batchScript := fmt.Sprintf(`@echo off
+timeout /t 2 /nobreak > nul
+del "%s.backup" 2>nul
+move "%s" "%s.backup"
+copy "%s" "%s"
+net start ServerKitAgent
+del "%%~f0"
+`, currentBinary, currentBinary, currentBinary, newBinaryPath, currentBinary)
+
+ scriptPath := filepath.Join(os.TempDir(), "serverkit-update.bat")
+ if err := os.WriteFile(scriptPath, []byte(batchScript), 0755); err != nil {
+ return fmt.Errorf("failed to create update script: %w", err)
+ }
+
+ // Stop the service
+ exec.Command("net", "stop", "ServerKitAgent").Run()
+
+ // Run the batch script detached
+ cmd := exec.Command("cmd", "/c", "start", "/b", scriptPath)
+ if err := cmd.Start(); err != nil {
+ return fmt.Errorf("failed to start update script: %w", err)
+ }
+
+ u.log.Info("Update scheduled, agent will restart shortly")
+ return nil
+}
+
+func (u *Updater) downloadFile(ctx context.Context, url, destPath string) error {
+ req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
+ if err != nil {
+ return err
+ }
+
+ req.Header.Set("User-Agent", fmt.Sprintf("ServerKit-Agent/%s", u.currentVersion))
+
+ resp, err := u.httpClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("download failed with status: %d", resp.StatusCode)
+ }
+
+ out, err := os.Create(destPath)
+ if err != nil {
+ return err
+ }
+ defer out.Close()
+
+ _, err = io.Copy(out, resp.Body)
+ return err
+}
+
+func (u *Updater) verifyChecksum(ctx context.Context, filePath, checksumsURL string) error {
+ // Download checksums file
+ req, err := http.NewRequestWithContext(ctx, "GET", checksumsURL, nil)
+ if err != nil {
+ return err
+ }
+
+ resp, err := u.httpClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ checksumsData, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return err
+ }
+
+ // Parse checksums
+ checksums := make(map[string]string)
+ for _, line := range strings.Split(string(checksumsData), "\n") {
+ parts := strings.Fields(line)
+ if len(parts) >= 2 {
+ checksums[parts[1]] = parts[0]
+ }
+ }
+
+ // Calculate file hash
+ f, err := os.Open(filePath)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+
+ hasher := sha256.New()
+ if _, err := io.Copy(hasher, f); err != nil {
+ return err
+ }
+ actualHash := hex.EncodeToString(hasher.Sum(nil))
+
+ // Find expected hash
+ fileName := filepath.Base(filePath)
+ // Try to match by looking for platform-specific name
+ expectedHash := ""
+ for name, hash := range checksums {
+ if strings.Contains(name, runtime.GOOS) && strings.Contains(name, runtime.GOARCH) {
+ expectedHash = hash
+ break
+ }
+ }
+
+ if expectedHash == "" {
+ // Try exact match
+ if hash, ok := checksums[fileName]; ok {
+ expectedHash = hash
+ }
+ }
+
+ if expectedHash == "" {
+ u.log.Warn("Could not find checksum for downloaded file, skipping verification")
+ return nil
+ }
+
+ if actualHash != expectedHash {
+ return fmt.Errorf("checksum mismatch: expected %s, got %s", expectedHash, actualHash)
+ }
+
+ return nil
+}
+
+func (u *Updater) extractBinary(archivePath, destDir string) (string, error) {
+ if runtime.GOOS == "windows" {
+ return u.extractZip(archivePath, destDir)
+ }
+ return u.extractTarGz(archivePath, destDir)
+}
+
+func (u *Updater) extractTarGz(archivePath, destDir string) (string, error) {
+ f, err := os.Open(archivePath)
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+
+ gzr, err := gzip.NewReader(f)
+ if err != nil {
+ return "", err
+ }
+ defer gzr.Close()
+
+ tr := tar.NewReader(gzr)
+
+ var binaryPath string
+ for {
+ header, err := tr.Next()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return "", err
+ }
+
+ // Look for the agent binary
+ if header.Typeflag == tar.TypeReg && strings.Contains(header.Name, "serverkit-agent") {
+ binaryPath = filepath.Join(destDir, "serverkit-agent")
+ outFile, err := os.Create(binaryPath)
+ if err != nil {
+ return "", err
+ }
+ if _, err := io.Copy(outFile, tr); err != nil {
+ outFile.Close()
+ return "", err
+ }
+ outFile.Close()
+ os.Chmod(binaryPath, 0755)
+ }
+ }
+
+ if binaryPath == "" {
+ return "", fmt.Errorf("agent binary not found in archive")
+ }
+
+ return binaryPath, nil
+}
+
+func (u *Updater) extractZip(archivePath, destDir string) (string, error) {
+ r, err := zip.OpenReader(archivePath)
+ if err != nil {
+ return "", err
+ }
+ defer r.Close()
+
+ var binaryPath string
+ for _, f := range r.File {
+ if strings.Contains(f.Name, "serverkit-agent") && strings.HasSuffix(f.Name, ".exe") {
+ binaryPath = filepath.Join(destDir, "serverkit-agent.exe")
+
+ rc, err := f.Open()
+ if err != nil {
+ return "", err
+ }
+
+ outFile, err := os.Create(binaryPath)
+ if err != nil {
+ rc.Close()
+ return "", err
+ }
+
+ _, err = io.Copy(outFile, rc)
+ outFile.Close()
+ rc.Close()
+
+ if err != nil {
+ return "", err
+ }
+ }
+ }
+
+ if binaryPath == "" {
+ return "", fmt.Errorf("agent binary not found in archive")
+ }
+
+ return binaryPath, nil
+}
+
+func (u *Updater) isSystemd() bool {
+ if runtime.GOOS != "linux" {
+ return false
+ }
+ _, err := os.Stat("/run/systemd/system")
+ return err == nil
+}
+
+func (u *Updater) selfRestart(binaryPath string) error {
+ // Fork a new process and exit current one
+ cmd := exec.Command(binaryPath, "start")
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+
+ if err := cmd.Start(); err != nil {
+ return fmt.Errorf("failed to start new process: %w", err)
+ }
+
+ u.log.Info("Restarting with new version...")
+ os.Exit(0)
+ return nil
+}
+
+func copyFile(src, dst string) error {
+ sourceFile, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer sourceFile.Close()
+
+ destFile, err := os.Create(dst)
+ if err != nil {
+ return err
+ }
+ defer destFile.Close()
+
+ _, err = io.Copy(destFile, sourceFile)
+ return err
+}
+
+// Cleanup removes temporary update files
+func (u *Updater) Cleanup(tmpDir string) {
+ if tmpDir != "" {
+ os.RemoveAll(tmpDir)
+ }
+}
diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py
index 4354d2d5..1f343dcb 100644
--- a/backend/app/api/servers.py
+++ b/backend/app/api/servers.py
@@ -5,8 +5,10 @@ Endpoints for managing remote servers and their agents.
"""
import os
+import hashlib
+import requests
from datetime import datetime, timedelta
-from flask import Blueprint, request, jsonify, Response, current_app
+from flask import Blueprint, request, jsonify, Response, current_app, redirect
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
@@ -967,3 +969,295 @@ def get_install_instructions(server_id):
},
'note': 'Replace YOUR_TOKEN with the registration token shown in the UI'
})
+
+
+# ==================== Agent Updates ====================
+
+# Cache for GitHub releases to avoid rate limiting
+_releases_cache = {
+ 'data': None,
+ 'expires': None
+}
+
+GITHUB_REPO = os.environ.get('SERVERKIT_GITHUB_REPO', 'serverkit/serverkit')
+
+
+def _get_latest_agent_release():
+ """Fetch latest agent release from GitHub with caching"""
+ now = datetime.utcnow()
+
+ # Check cache
+ if _releases_cache['data'] and _releases_cache['expires'] and _releases_cache['expires'] > now:
+ return _releases_cache['data']
+
+ try:
+ # Fetch releases from GitHub
+ response = requests.get(
+ f'https://api.github.com/repos/{GITHUB_REPO}/releases',
+ headers={'Accept': 'application/vnd.github.v3+json'},
+ timeout=10
+ )
+ response.raise_for_status()
+ releases = response.json()
+
+ # Find latest agent release
+ for release in releases:
+ if release.get('tag_name', '').startswith('agent-v'):
+ version = release['tag_name'].replace('agent-v', '')
+
+ # Build assets map
+ assets = {}
+ for asset in release.get('assets', []):
+ name = asset['name']
+ if 'linux-amd64' in name:
+ assets['linux-amd64'] = asset['browser_download_url']
+ elif 'linux-arm64' in name:
+ assets['linux-arm64'] = asset['browser_download_url']
+ elif 'windows-amd64' in name:
+ assets['windows-amd64'] = asset['browser_download_url']
+ elif name == 'checksums.txt':
+ assets['checksums'] = asset['browser_download_url']
+
+ result = {
+ 'version': version,
+ 'tag': release['tag_name'],
+ 'published_at': release['published_at'],
+ 'release_url': release['html_url'],
+ 'assets': assets,
+ 'body': release.get('body', '')
+ }
+
+ # Cache for 5 minutes
+ _releases_cache['data'] = result
+ _releases_cache['expires'] = now + timedelta(minutes=5)
+
+ return result
+
+ return None
+
+ except Exception as e:
+ current_app.logger.error(f"Failed to fetch GitHub releases: {e}")
+ # Return cached data if available, even if expired
+ if _releases_cache['data']:
+ return _releases_cache['data']
+ return None
+
+
+@servers_bp.route('/agent/version', methods=['GET'])
+def get_agent_version():
+ """
+ Get the latest agent version information.
+
+ This endpoint is called by agents to check for updates.
+ Returns version info and download URLs for all platforms.
+ """
+ release = _get_latest_agent_release()
+
+ if not release:
+ return jsonify({
+ 'error': 'Unable to fetch version information',
+ 'message': 'GitHub API may be unavailable'
+ }), 503
+
+ # Get base URL for local downloads (fallback)
+ base_url = request.url_root.rstrip('/')
+
+ return jsonify({
+ 'version': release['version'],
+ 'published_at': release['published_at'],
+ 'release_notes_url': release['release_url'],
+ 'downloads': {
+ 'linux-amd64': release['assets'].get('linux-amd64'),
+ 'linux-arm64': release['assets'].get('linux-arm64'),
+ 'windows-amd64': release['assets'].get('windows-amd64'),
+ },
+ 'checksums_url': release['assets'].get('checksums'),
+ 'update_available_message': f"A new version of ServerKit Agent is available: v{release['version']}"
+ })
+
+
+@servers_bp.route('/agent/version/check', methods=['POST'])
+def check_agent_version():
+ """
+ Check if an agent needs to be updated.
+
+ Called by agents with their current version to check if an update is needed.
+
+ Request body:
+ {
+ "current_version": "1.0.0",
+ "os": "linux",
+ "arch": "amd64"
+ }
+ """
+ data = request.get_json() or {}
+ current_version = data.get('current_version', '0.0.0')
+ agent_os = data.get('os', 'linux')
+ agent_arch = data.get('arch', 'amd64')
+
+ release = _get_latest_agent_release()
+
+ if not release:
+ return jsonify({
+ 'update_available': False,
+ 'error': 'Unable to check for updates'
+ })
+
+ latest_version = release['version']
+
+ # Compare versions (simple string comparison works for semver)
+ update_available = _compare_versions(current_version, latest_version) < 0
+
+ platform_key = f"{agent_os}-{agent_arch}"
+ download_url = release['assets'].get(platform_key)
+
+ return jsonify({
+ 'update_available': update_available,
+ 'current_version': current_version,
+ 'latest_version': latest_version,
+ 'download_url': download_url,
+ 'checksums_url': release['assets'].get('checksums'),
+ 'release_notes_url': release['release_url'],
+ 'published_at': release['published_at']
+ })
+
+
+def _compare_versions(v1, v2):
+ """
+ Compare two semantic versions.
+ Returns: -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2
+ """
+ def parse_version(v):
+ # Remove leading 'v' if present
+ v = v.lstrip('v')
+ # Split by dots and convert to integers
+ parts = []
+ for part in v.split('.'):
+ # Handle pre-release versions like 1.0.0-beta.1
+ if '-' in part:
+ num, _ = part.split('-', 1)
+ parts.append(int(num) if num.isdigit() else 0)
+ else:
+ parts.append(int(part) if part.isdigit() else 0)
+ # Pad to at least 3 parts
+ while len(parts) < 3:
+ parts.append(0)
+ return parts
+
+ try:
+ p1 = parse_version(v1)
+ p2 = parse_version(v2)
+
+ for a, b in zip(p1, p2):
+ if a < b:
+ return -1
+ elif a > b:
+ return 1
+ return 0
+ except:
+ return 0
+
+
+@servers_bp.route('/agent/download/<os_name>/<arch>', methods=['GET'])
+def download_agent(os_name, arch):
+ """
+ Redirect to the appropriate agent download.
+
+ This endpoint redirects to the GitHub release asset for the
+ requested OS and architecture.
+ """
+ # Validate inputs
+ valid_os = ['linux', 'windows', 'darwin']
+ valid_arch = ['amd64', 'arm64']
+
+ if os_name not in valid_os:
+ return jsonify({'error': f'Invalid OS. Valid options: {valid_os}'}), 400
+
+ if arch not in valid_arch:
+ return jsonify({'error': f'Invalid architecture. Valid options: {valid_arch}'}), 400
+
+ release = _get_latest_agent_release()
+
+ if not release:
+ return jsonify({'error': 'Unable to fetch release information'}), 503
+
+ platform_key = f"{os_name}-{arch}"
+ download_url = release['assets'].get(platform_key)
+
+ if not download_url:
+ return jsonify({
+ 'error': f'No release available for {os_name}-{arch}',
+ 'available': list(release['assets'].keys())
+ }), 404
+
+ # Redirect to GitHub release
+ return redirect(download_url, code=302)
+
+
+@servers_bp.route('/agent/checksums', methods=['GET'])
+def get_agent_checksums():
+ """
+ Get SHA256 checksums for agent binaries.
+
+ Returns the checksums.txt content from the latest release.
+ """
+ release = _get_latest_agent_release()
+
+ if not release or not release['assets'].get('checksums'):
+ return jsonify({'error': 'Checksums not available'}), 404
+
+ try:
+ response = requests.get(release['assets']['checksums'], timeout=10)
+ response.raise_for_status()
+
+ return Response(
+ response.text,
+ mimetype='text/plain',
+ headers={
+ 'Content-Disposition': 'inline; filename="checksums.txt"',
+ 'X-Agent-Version': release['version']
+ }
+ )
+ except Exception as e:
+ current_app.logger.error(f"Failed to fetch checksums: {e}")
+ return jsonify({'error': 'Failed to fetch checksums'}), 503
+
+
+@servers_bp.route('/<server_id>/agent/update', methods=['POST'])
+@jwt_required()
+def trigger_agent_update(server_id):
+ """
+ Trigger an agent update on a specific server.
+
+ Sends a command to the agent to check for and install updates.
+ """
+ server = Server.query.get(server_id)
+ if not server:
+ return jsonify({'error': 'Server not found'}), 404
+
+ if not agent_registry.is_agent_connected(server_id):
+ return jsonify({
+ 'success': False,
+ 'error': 'Agent not connected'
+ }), 503
+
+ # Get latest version info
+ release = _get_latest_agent_release()
+ if not release:
+ return jsonify({
+ 'success': False,
+ 'error': 'Unable to fetch latest version'
+ }), 503
+
+ # Send update command to agent
+ result = agent_registry.send_command(
+ server_id=server_id,
+ action='agent:update',
+ params={
+ 'version': release['version'],
+ 'force': request.get_json().get('force', False) if request.get_json() else False
+ },
+ timeout=60.0 # Updates may take a while
+ )
+
+ return jsonify(result)