Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: arcane self-updater (#744)
Kyle Mendell73f4e5b8f1bc
diff --git a/backend/internal/api/environment_handler.go b/backend/internal/api/environment_handler.goindex 40b75ea21..81d84849e 100644--- a/backend/internal/api/environment_handler.go+++ b/backend/internal/api/environment_handler.go@@ -3,6 +3,7 @@ package apiimport ("log/slog""net/http"+ "time""github.com/gin-gonic/gin""github.com/ofkm/arcane-backend/internal/config"@@ -20,6 +21,7 @@ type EnvironmentHandler struct {environmentService *services.EnvironmentServicesettingsService *services.SettingsServicecfg *config.Config+ httpClient *http.Client}func NewEnvironmentHandler(@@ -33,6 +35,9 @@ func NewEnvironmentHandler(environmentService: environmentService,settingsService: settingsService,cfg: cfg,+ httpClient: &http.Client{+ Timeout: 30 * time.Second,+ },}apiGroup := group.Group("/environments")diff --git a/backend/internal/api/system_handler.go b/backend/internal/api/system_handler.goindex 0736fbf6e..60ffdf031 100644--- a/backend/internal/api/system_handler.go+++ b/backend/internal/api/system_handler.go@@ -2,6 +2,7 @@ package apiimport ("context"+ "errors""log/slog""net/http""runtime"@@ -28,6 +29,7 @@ import (type SystemHandler struct {dockerService *services.DockerClientServicesystemService *services.SystemService+ upgradeService *services.SystemUpgradeServicesysWsUpgrader websocket.UpgraderactiveConnections sync.MapcpuCache struct {@@ -42,10 +44,11 @@ type SystemHandler struct {}}-func NewSystemHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, systemService *services.SystemService, authMiddleware *middleware.AuthMiddleware, cfg *config.Config) {+func NewSystemHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, systemService *services.SystemService, upgradeService *services.SystemUpgradeService, authMiddleware *middleware.AuthMiddleware, cfg *config.Config) {handler := &SystemHandler{- dockerService: dockerService,- systemService: systemService,+ dockerService: dockerService,+ systemService: systemService,+ upgradeService: upgradeService,sysWsUpgrader: websocket.Upgrader{CheckOrigin: httputil.ValidateWebSocketOrigin(cfg.AppUrl),},@@ -54,6 +57,7 @@ func NewSystemHandler(group *gin.RouterGroup, dockerService *services.DockerClieapiGroup := group.Group("/environments/:id/system")apiGroup.Use(authMiddleware.WithAdminNotRequired().Add()){+ apiGroup.HEAD("/health", handler.Health)apiGroup.GET("/stats/ws", handler.Stats)apiGroup.GET("/docker/info", handler.GetDockerInfo)apiGroup.POST("/prune", handler.PruneAll)@@ -62,6 +66,9 @@ func NewSystemHandler(group *gin.RouterGroup, dockerService *services.DockerClieapiGroup.POST("/containers/stop-all", handler.StopAllContainers)apiGroup.POST("/convert", handler.ConvertDockerRun)+ // Upgrade endpoints (admin required)+ apiGroup.GET("/upgrade/check", authMiddleware.WithAdminRequired().Add(), handler.CheckUpgradeAvailable)+ apiGroup.POST("/upgrade", authMiddleware.WithAdminRequired().Add(), handler.TriggerUpgrade)}}@@ -77,6 +84,26 @@ type SystemStats struct {Hostname string `json:"hostname,omitempty"`}+func (h *SystemHandler) Health(c *gin.Context) {+ ctx := c.Request.Context()++ dockerClient, err := h.dockerService.CreateConnection(ctx)+ if err != nil {+ c.Status(http.StatusServiceUnavailable)+ return+ }+ defer dockerClient.Close()++ // Try to ping Docker to ensure it's responsive+ _, err = dockerClient.Ping(ctx)+ if err != nil {+ c.Status(http.StatusServiceUnavailable)+ return+ }++ c.Status(http.StatusOK)+}+func (h *SystemHandler) GetDockerInfo(c *gin.Context) {ctx := c.Request.Context()@@ -449,3 +476,57 @@ func (h *SystemHandler) ConvertDockerRun(c *gin.Context) {ServiceName: serviceName,})}++// CheckUpgradeAvailable checks if the local system can be upgraded+// Remote environments are handled by the proxy middleware+func (h *SystemHandler) CheckUpgradeAvailable(c *gin.Context) {+ canUpgrade, err := h.upgradeService.CanUpgrade(c.Request.Context())++ if err != nil {+ c.JSON(http.StatusOK, gin.H{+ "canUpgrade": false,+ "error": true,+ "message": err.Error(),+ })+ slog.Debug("System upgrade check failed", "error", err)+ return+ }++ c.JSON(http.StatusOK, gin.H{+ "canUpgrade": canUpgrade,+ "error": false,+ "message": "System can be upgraded",+ })+}++// TriggerUpgrade triggers a system upgrade by spawning the upgrade CLI command+// This runs the upgrade from outside the current container to avoid self-termination issues+func (h *SystemHandler) TriggerUpgrade(c *gin.Context) {+ currentUser, ok := middleware.RequireAuthentication(c)+ if !ok {+ return+ }++ slog.Info("System upgrade triggered", "user", currentUser.Username, "userId", currentUser.ID)++ err := h.upgradeService.TriggerUpgradeViaCLI(c.Request.Context(), *currentUser)+ if err != nil {+ slog.Error("System upgrade failed", "error", err, "user", currentUser.Username)++ statusCode := http.StatusInternalServerError+ if errors.Is(err, services.ErrUpgradeInProgress) {+ statusCode = http.StatusConflict+ }++ c.JSON(statusCode, gin.H{+ "error": err.Error(),+ "message": "Failed to initiate upgrade",+ })+ return+ }++ c.JSON(http.StatusAccepted, gin.H{+ "message": "Upgrade initiated successfully. A new container is being created and will replace this one shortly.",+ "success": true,+ })+}diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex 829768539..b67aeaff3 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -102,7 +102,7 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {api.NewImageUpdateHandler(apiGroup, appServices.ImageUpdate, authMiddleware)api.NewNetworkHandler(apiGroup, appServices.Docker, appServices.Network, authMiddleware)api.NewProjectHandler(apiGroup, appServices.Project, authMiddleware, cfg)- api.NewSystemHandler(apiGroup, appServices.Docker, appServices.System, authMiddleware, cfg)+ api.NewSystemHandler(apiGroup, appServices.Docker, appServices.System, appServices.SystemUpgrade, authMiddleware, cfg)api.NewUpdaterHandler(apiGroup, appServices.Updater, authMiddleware)api.NewVolumeHandler(apiGroup, appServices.Docker, appServices.Volume, authMiddleware)api.NewNotificationHandler(apiGroup, appServices.Notification, authMiddleware)diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.goindex e1d5f20ab..61a0516ca 100644--- a/backend/internal/bootstrap/services_bootstrap.go+++ b/backend/internal/bootstrap/services_bootstrap.go@@ -30,6 +30,7 @@ type Services struct {Template *services.TemplateServiceContainerRegistry *services.ContainerRegistryServiceSystem *services.SystemService+ SystemUpgrade *services.SystemUpgradeServiceUpdater *services.UpdaterServiceEvent *services.EventServiceVersion *services.VersionService@@ -65,6 +66,7 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Configsvcs.Updater = services.NewUpdaterService(db, svcs.Settings, svcs.Docker, svcs.Project, svcs.ImageUpdate, svcs.ContainerRegistry, svcs.Event, svcs.Image, svcs.Notification)svcs.System = services.NewSystemService(db, svcs.Docker, svcs.Container, svcs.Image, svcs.Volume, svcs.Network, svcs.Settings)svcs.Version = services.NewVersionService(httpClient, cfg.UpdateCheckDisabled, config.Version, config.Revision)+ svcs.SystemUpgrade = services.NewSystemUpgradeService(svcs.Docker, svcs.Version, svcs.Event)return svcs, dockerClient, nil}diff --git a/backend/internal/cli/root.go b/backend/internal/cli/root.goindex 0fd49dd56..8cf96d3f4 100644--- a/backend/internal/cli/root.go+++ b/backend/internal/cli/root.go@@ -9,6 +9,7 @@ import ("github.com/ofkm/arcane-backend/internal/bootstrap""github.com/ofkm/arcane-backend/internal/cli/generate"+ "github.com/ofkm/arcane-backend/internal/cli/upgrade""github.com/ofkm/arcane-backend/internal/config""github.com/ofkm/arcane-backend/internal/utils/signals")@@ -38,6 +39,7 @@ func Execute() {func init() {rootCmd.AddCommand(generate.GenerateCmd)+ rootCmd.AddCommand(upgrade.UpgradeCmd)}func getVersion() string {diff --git a/backend/internal/cli/upgrade/upgrade.go b/backend/internal/cli/upgrade/upgrade.gonew file mode 100644index 000000000..ea8f9ea97--- /dev/null+++ b/backend/internal/cli/upgrade/upgrade.go@@ -0,0 +1,404 @@+package upgrade++import (+ "context"+ "fmt"+ "io"+ "log/slog"+ "os"+ "strings"+ "time"++ "github.com/docker/docker/api/types/container"+ "github.com/docker/docker/api/types/filters"+ "github.com/docker/docker/api/types/image"+ "github.com/docker/docker/api/types/network"+ "github.com/docker/docker/client"+ "github.com/spf13/cobra"+)++var (+ containerName string+ targetImage string+ autoDetect bool+)++var UpgradeCmd = &cobra.Command{+ Use: "upgrade",+ Short: "Upgrade an Arcane container to the latest version",+ Long: `Upgrade an Arcane container by pulling the latest image and recreating the container.+This command should be run from outside the container (e.g., from the host or another container).`,+ Example: ` # Auto-detect and upgrade the Arcane container+ arcane upgrade --auto++ # Upgrade a specific container+ arcane upgrade --container arcane++ # Upgrade to a specific image tag+ arcane upgrade --container arcane --image ghcr.io/ofkm/arcane:v1.2.3`,+ // Use background context to ignore signals during upgrade+ // This prevents the upgrade from being interrupted when the target container stops+ RunE: runUpgrade,+}++func init() {+ UpgradeCmd.Flags().StringVarP(&containerName, "container", "c", "", "Name of the container to upgrade")+ UpgradeCmd.Flags().StringVarP(&targetImage, "image", "i", "", "Target image to upgrade to (defaults to current tag)")+ UpgradeCmd.Flags().BoolVarP(&autoDetect, "auto", "a", false, "Auto-detect Arcane container")+}++func runUpgrade(cmd *cobra.Command, args []string) error {+ // Use background context instead of command context to ignore signals+ // This prevents interruption when stopping the target container+ ctx := context.Background()++ // Connect to Docker+ dockerClient, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }+ defer dockerClient.Close()++ // Find the container+ var targetContainer container.InspectResponse+ if autoDetect || containerName == "" {+ slog.Info("Auto-detecting Arcane container...")+ targetContainer, err = findArcaneContainer(ctx, dockerClient)+ if err != nil {+ return fmt.Errorf("failed to find Arcane container: %w", err)+ }+ containerName = strings.TrimPrefix(targetContainer.Name, "/")+ slog.Info("Found Arcane container", "name", containerName, "id", targetContainer.ID[:12])+ } else {+ targetContainer, err = dockerClient.ContainerInspect(ctx, containerName)+ if err != nil {+ return fmt.Errorf("failed to inspect container %s: %w", containerName, err)+ }+ }++ // Determine image to pull+ imageToPull := targetImage+ if imageToPull == "" {+ imageToPull = determineImageName(ctx, dockerClient, targetContainer)+ slog.Info("Determined image to pull", "image", imageToPull)+ }++ // Pull the new image+ slog.Info("Pulling new image", "image", imageToPull)+ if err := pullImage(ctx, dockerClient, imageToPull); err != nil {+ return fmt.Errorf("failed to pull image: %w", err)+ }++ // Perform the upgrade+ slog.Info("Starting container upgrade", "container", containerName)+ if err := upgradeContainer(ctx, dockerClient, targetContainer, imageToPull); err != nil {+ return fmt.Errorf("failed to upgrade container: %w", err)+ }++ slog.Info("Upgrade completed successfully", "container", containerName, "image", imageToPull)+ return nil+}++func findArcaneContainer(ctx context.Context, dockerClient *client.Client) (container.InspectResponse, error) {+ // Look for containers with "arcane" in the image name+ filter := filters.NewArgs()+ filter.Add("status", "running")++ containers, err := dockerClient.ContainerList(ctx, container.ListOptions{Filters: filter})+ if err != nil {+ return container.InspectResponse{}, err+ }++ selfID := getSelfContainerID()+ slog.Info("Searching for Arcane container", "selfID", selfID, "totalContainers", len(containers))++ now := time.Now()++ for _, c := range containers {+ if shouldSkipContainer(c, selfID, now) {+ continue+ }++ if strings.Contains(strings.ToLower(c.Image), "arcane") {+ slog.Info("Found matching container", "id", c.ID[:12], "image", c.Image, "names", c.Names)+ return dockerClient.ContainerInspect(ctx, c.ID)+ }+ }++ return container.InspectResponse{}, fmt.Errorf("no running Arcane container found")+}++// getSelfContainerID attempts to detect the container ID if running in Docker+func getSelfContainerID() string {+ data, err := os.ReadFile("/proc/self/cgroup")+ if err != nil {+ return ""+ }++ content := string(data)+ for _, line := range strings.Split(content, "\n") {+ // cgroup v1: 12:pids:/docker/abc123...+ if id := extractCgroupV1ID(line); id != "" {+ return id+ }+ // cgroup v2: 0::/system.slice/docker-abc123....scope+ if id := extractCgroupV2ID(line); id != "" {+ return id+ }+ }++ return ""+}++// extractCgroupV1ID extracts container ID from cgroup v1 format+func extractCgroupV1ID(line string) string {+ if !strings.Contains(line, "/docker/") {+ return ""+ }++ parts := strings.Split(line, "/docker/")+ if len(parts) <= 1 {+ return ""+ }++ id := strings.TrimSpace(parts[1])+ if idx := strings.Index(id, "/"); idx != -1 {+ id = id[:idx]+ }++ if len(id) >= 12 {+ return id[:12]+ }++ return ""+}++// extractCgroupV2ID extracts container ID from cgroup v2 format+func extractCgroupV2ID(line string) string {+ if !strings.Contains(line, "docker-") || !strings.Contains(line, ".scope") {+ return ""+ }++ start := strings.Index(line, "docker-")+ if start == -1 {+ return ""+ }++ start += 7 // len("docker-")+ end := strings.Index(line[start:], ".scope")+ if end == -1 {+ return ""+ }++ id := line[start : start+end]+ if len(id) >= 12 {+ return id[:12]+ }++ return ""+}++// shouldSkipContainer determines if a container should be skipped during search+func shouldSkipContainer(c container.Summary, selfID string, now time.Time) bool {+ // Skip ourselves (the upgrader container) by ID+ if selfID != "" && strings.HasPrefix(c.ID, selfID) {+ slog.Info("Skipping self by ID", "id", c.ID[:12], "names", c.Names)+ return true+ }++ // Skip very recently created containers (likely the upgrader)+ if c.Created > 0 {+ createdTime := time.Unix(c.Created, 0)+ age := now.Sub(createdTime)+ if age < 30*time.Second {+ slog.Info("Skipping recently created container", "id", c.ID[:12], "age", age, "names", c.Names)+ return true+ }+ }++ // Skip containers with "upgrader" in the name+ for _, name := range c.Names {+ if strings.Contains(strings.ToLower(name), "upgrader") {+ slog.Info("Skipping upgrader container by name", "name", name)+ return true+ }+ }++ return false+}++func determineImageName(ctx context.Context, dockerClient *client.Client, cont container.InspectResponse) string {+ imageName := extractImageNameFromConfig(cont)+ imageName = stripDigest(imageName)++ // If no explicit tag, try to infer from image RepoTags+ if !hasExplicitTag(imageName) {+ if inferredName := inferImageNameFromDocker(ctx, dockerClient, cont.Image); inferredName != "" {+ imageName = inferredName+ }+ }++ // Default to :latest if still no tag+ if !hasExplicitTag(imageName) {+ imageName = ensureDefaultTag(imageName)+ }++ return imageName+}++// extractImageNameFromConfig gets the image name from container config+func extractImageNameFromConfig(cont container.InspectResponse) string {+ if cont.Config == nil {+ return ""+ }+ return strings.TrimSpace(cont.Config.Image)+}++// stripDigest removes digest from image reference+func stripDigest(imageName string) string {+ if idx := strings.Index(imageName, "@"); idx != -1 {+ return imageName[:idx]+ }+ return imageName+}++// hasExplicitTag checks if image reference has a tag+func hasExplicitTag(ref string) bool {+ if ref == "" {+ return false+ }+ slash := strings.LastIndex(ref, "/")+ colon := strings.LastIndex(ref, ":")+ return colon > slash+}++// inferImageNameFromDocker attempts to find the best tag from Docker image inspect+func inferImageNameFromDocker(ctx context.Context, dockerClient *client.Client, imageID string) string {+ ii, err := dockerClient.ImageInspect(ctx, imageID)+ if err != nil {+ return ""+ }++ var arcaneNonLatest string+ var arcaneAny string++ for _, t := range ii.RepoTags {+ if t == "" || t == "<none>:<none>" {+ continue+ }++ t = stripDigest(t)++ if strings.Contains(t, "arcane") {+ if arcaneAny == "" {+ arcaneAny = t+ }+ if !strings.HasSuffix(t, ":latest") && arcaneNonLatest == "" {+ arcaneNonLatest = t+ }+ }+ }++ // Prefer non-latest tags+ if arcaneNonLatest != "" {+ return arcaneNonLatest+ }+ return arcaneAny+}++// ensureDefaultTag adds :latest tag if no tag is present+func ensureDefaultTag(imageName string) string {+ if imageName == "" {+ return "ghcr.io/ofkm/arcane:latest"+ }+ return imageName + ":latest"+}++func pullImage(ctx context.Context, dockerClient *client.Client, imageName string) error {+ reader, err := dockerClient.ImagePull(ctx, imageName, image.PullOptions{})+ if err != nil {+ return err+ }+ defer reader.Close()++ // Copy output to discard but wait for completion+ _, err = io.Copy(io.Discard, reader)+ return err+}++func upgradeContainer(ctx context.Context, dockerClient *client.Client, oldContainer container.InspectResponse, newImage string) error {+ originalName := strings.TrimPrefix(oldContainer.Name, "/")+ tempName := fmt.Sprintf("%s-upgrading", originalName)++ // Create new container config+ config := *oldContainer.Config+ config.Image = newImage++ hostConfig := oldContainer.HostConfig++ // Build network config - preserve all network settings including IP addresses+ networkConfig := &network.NetworkingConfig{+ EndpointsConfig: make(map[string]*network.EndpointSettings),+ }+ for networkName, networkSettings := range oldContainer.NetworkSettings.Networks {+ networkConfig.EndpointsConfig[networkName] = &network.EndpointSettings{+ IPAMConfig: networkSettings.IPAMConfig,+ Links: networkSettings.Links,+ Aliases: networkSettings.Aliases,+ NetworkID: networkSettings.NetworkID,+ EndpointID: networkSettings.EndpointID,+ Gateway: networkSettings.Gateway,+ IPAddress: networkSettings.IPAddress,+ IPPrefixLen: networkSettings.IPPrefixLen,+ IPv6Gateway: networkSettings.IPv6Gateway,+ GlobalIPv6Address: networkSettings.GlobalIPv6Address,+ GlobalIPv6PrefixLen: networkSettings.GlobalIPv6PrefixLen,+ MacAddress: networkSettings.MacAddress,+ DriverOpts: networkSettings.DriverOpts,+ }+ }++ fmt.Println("PROGRESS:70:Stopping old container")+ slog.Info("Stopping old container", "name", originalName)+ timeout := 10+ if err := dockerClient.ContainerStop(ctx, oldContainer.ID, container.StopOptions{Timeout: &timeout}); err != nil {+ return fmt.Errorf("stop old container: %w", err)+ }++ fmt.Println("PROGRESS:75:Creating new container")+ slog.Info("Creating new container", "tempName", tempName)+ resp, err := dockerClient.ContainerCreate(ctx, &config, hostConfig, networkConfig, nil, tempName)+ if err != nil {+ // Try to restart old container on failure+ _ = dockerClient.ContainerStart(ctx, oldContainer.ID, container.StartOptions{})+ return fmt.Errorf("create new container: %w", err)+ }++ fmt.Println("PROGRESS:80:Starting new container")+ slog.Info("Starting new container", "id", resp.ID[:12])+ if err := dockerClient.ContainerStart(ctx, resp.ID, container.StartOptions{}); err != nil {+ // Cleanup new container and restart old one+ _ = dockerClient.ContainerRemove(ctx, resp.ID, container.RemoveOptions{Force: true})+ _ = dockerClient.ContainerStart(ctx, oldContainer.ID, container.StartOptions{})+ return fmt.Errorf("start new container: %w", err)+ }++ // Wait a moment for the new container to initialize+ // Wait a moment for the new container to initialize+ fmt.Println("PROGRESS:85:Waiting for container to start")+ time.Sleep(2 * time.Second)++ fmt.Println("PROGRESS:90:Removing old container")+ slog.Info("Removing old container", "id", oldContainer.ID[:12])+ if err := dockerClient.ContainerRemove(ctx, oldContainer.ID, container.RemoveOptions{}); err != nil {+ slog.Warn("Failed to remove old container", "error", err)+ }++ fmt.Println("PROGRESS:95:Renaming new container")+ slog.Info("Renaming new container", "from", tempName, "to", originalName)+ if err := dockerClient.ContainerRename(ctx, resp.ID, originalName); err != nil {+ slog.Warn("Failed to rename container", "error", err)+ }++ return nil+}diff --git a/backend/internal/models/event.go b/backend/internal/models/event.goindex 2fb7bae3c..e5eb023b7 100644--- a/backend/internal/models/event.go+++ b/backend/internal/models/event.go@@ -38,6 +38,7 @@ const (EventTypeUserLogin EventType = "user.login"EventTypeUserLogout EventType = "user.logout"EventTypeSystemAutoUpdate EventType = "system.auto_update"+ EventTypeSystemUpgrade EventType = "system.upgrade"// Event severitiesEventSeverityInfo EventSeverity = "info"diff --git a/backend/internal/services/event_service.go b/backend/internal/services/event_service.goindex c1fa7022a..5bfd1742f 100644--- a/backend/internal/services/event_service.go+++ b/backend/internal/services/event_service.go@@ -395,6 +395,8 @@ func (s *EventService) generateEventTitle(eventType models.EventType, resourceNareturn "System prune completed"case models.EventTypeSystemAutoUpdate:return "System auto-update completed"+ case models.EventTypeSystemUpgrade:+ return "System upgrade completed"case models.EventTypeUserLogin:return fmt.Sprintf("User logged in: %s", resourceName)case models.EventTypeUserLogout:@@ -448,6 +450,8 @@ func (s *EventService) generateEventDescription(eventType models.EventType, resoreturn "System resources have been pruned"case models.EventTypeSystemAutoUpdate:return "System auto-update process has completed"+ case models.EventTypeSystemUpgrade:+ return "System upgrade process has completed"case models.EventTypeUserLogin:return fmt.Sprintf("User '%s' has logged in", resourceName)case models.EventTypeUserLogout:@@ -463,7 +467,7 @@ func (s *EventService) getEventSeverity(eventType models.EventType) models.Eventreturn models.EventSeverityWarningcase models.EventTypeContainerStart, models.EventTypeContainerCreate, models.EventTypeImagePull, models.EventTypeProjectDeploy, models.EventTypeProjectStart, models.EventTypeProjectCreate, models.EventTypeVolumeCreate, models.EventTypeNetworkCreate:return models.EventSeveritySuccess- case models.EventTypeContainerStop, models.EventTypeContainerRestart, models.EventTypeContainerScan, models.EventTypeContainerUpdate, models.EventTypeImageScan, models.EventTypeProjectStop, models.EventTypeProjectUpdate, models.EventTypeSystemPrune, models.EventTypeSystemAutoUpdate, models.EventTypeUserLogin, models.EventTypeUserLogout:+ case models.EventTypeContainerStop, models.EventTypeContainerRestart, models.EventTypeContainerScan, models.EventTypeContainerUpdate, models.EventTypeImageScan, models.EventTypeProjectStop, models.EventTypeProjectUpdate, models.EventTypeSystemPrune, models.EventTypeSystemAutoUpdate, models.EventTypeSystemUpgrade, models.EventTypeUserLogin, models.EventTypeUserLogout:return models.EventSeverityInfodefault:return models.EventSeverityInfodiff --git a/backend/internal/services/system_upgrade_service.go b/backend/internal/services/system_upgrade_service.gonew file mode 100644index 000000000..fa69044c4--- /dev/null+++ b/backend/internal/services/system_upgrade_service.go@@ -0,0 +1,275 @@+package services++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "os"+ "strings"+ "sync/atomic"+ "time"++ containertypes "github.com/docker/docker/api/types/container"+ "github.com/docker/docker/api/types/filters"+ "github.com/ofkm/arcane-backend/internal/models"+)++var (+ ErrNotRunningInDocker = errors.New("arcane is not running in a Docker container")+ ErrContainerNotFound = errors.New("could not find Arcane container")+ ErrUpgradeInProgress = errors.New("an upgrade is already in progress")+ ErrDockerSocketAccess = errors.New("docker socket is not accessible")+)++type SystemUpgradeService struct {+ upgrading atomic.Bool+ dockerService *DockerClientService+ versionService *VersionService+ eventService *EventService+}++func NewSystemUpgradeService(+ dockerService *DockerClientService,+ versionService *VersionService,+ eventService *EventService,+) *SystemUpgradeService {+ return &SystemUpgradeService{+ dockerService: dockerService,+ versionService: versionService,+ eventService: eventService,+ }+}++// CanUpgrade checks if self-upgrade is possible+func (s *SystemUpgradeService) CanUpgrade(ctx context.Context) (bool, error) {+ // Check if running in Docker+ containerId, err := s.getCurrentContainerID()+ if err != nil {+ return false, ErrNotRunningInDocker+ }++ // Verify we can access Docker+ _, err = s.dockerService.CreateConnection(ctx)+ if err != nil {+ return false, ErrDockerSocketAccess+ }++ // Verify we can find our container+ _, err = s.findArcaneContainer(ctx, containerId)+ if err != nil {+ return false, err+ }++ return true, nil+}++// TriggerUpgradeViaCLI spawns the upgrade CLI command in a separate container+// This avoids self-termination issues by running the upgrade from outside+func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user models.User) error {+ if !s.upgrading.CompareAndSwap(false, true) {+ return ErrUpgradeInProgress+ }+ defer s.upgrading.Store(false)++ // Get current container name+ containerId, err := s.getCurrentContainerID()+ if err != nil {+ return fmt.Errorf("get current container: %w", err)+ }++ currentContainer, err := s.findArcaneContainer(ctx, containerId)+ if err != nil {+ return fmt.Errorf("inspect container: %w", err)+ }++ containerName := strings.TrimPrefix(currentContainer.Name, "/")++ // Log upgrade event+ metadata := models.JSON{+ "action": "system_upgrade_cli",+ "containerId": containerId,+ "containerName": containerName,+ "method": "cli",+ }+ if err := s.eventService.LogUserEvent(ctx, models.EventTypeSystemUpgrade, user.ID, user.Username, metadata); err != nil {+ slog.Warn("Failed to log upgrade event", "error", err)+ }++ // Use the official Arcane image for the upgrader container+ // This ensures we always use the packaged CLI from the official image+ upgraderImage := "ghcr.io/ofkm/arcane:self-update"++ slog.Info("Spawning upgrade CLI command",+ "containerName", containerName,+ "upgraderImage", upgraderImage,+ )++ // Spawn the upgrade command in a detached container+ // This will run independently of the current container+ dockerClient, err := s.dockerService.CreateConnection(ctx)+ if err != nil {+ return fmt.Errorf("failed to connect to Docker: %w", err)+ }+ defer dockerClient.Close()++ // Create the upgrader container config+ config := &containertypes.Config{+ Image: upgraderImage,+ Cmd: []string{"/app/arcane", "upgrade", "--container", containerName},+ }++ hostConfig := &containertypes.HostConfig{+ AutoRemove: true, // Clean up after completion+ Binds: []string{+ "/var/run/docker.sock:/var/run/docker.sock",+ },+ }++ containerName = fmt.Sprintf("%s-upgrader-%d", containerName, time.Now().Unix())++ resp, err := dockerClient.ContainerCreate(ctx, config, hostConfig, nil, nil, containerName)+ if err != nil {+ return fmt.Errorf("create upgrader container: %w", err)+ }++ // Start the upgrader container - it will run the upgrade and auto-remove+ if err := dockerClient.ContainerStart(ctx, resp.ID, containertypes.StartOptions{}); err != nil {+ _ = dockerClient.ContainerRemove(ctx, resp.ID, containertypes.RemoveOptions{Force: true})+ return fmt.Errorf("start upgrader container: %w", err)+ }++ slog.Info("Upgrade container started",+ "upgraderId", resp.ID[:12],+ "upgraderName", containerName,+ )++ return nil+}++// getCurrentContainerID detects if we're running in Docker and returns container ID+func (s *SystemUpgradeService) getCurrentContainerID() (string, error) {+ // Try reading from /proc/self/cgroup (Linux)+ if id, err := s.getContainerIDFromCgroup(); err == nil {+ return id, nil+ }++ // Try reading from /proc/self/mountinfo (alternative method)+ if id, err := s.getContainerIDFromMountinfo(); err == nil {+ return id, nil+ }++ // Try hostname (works in many Docker setups)+ if id, err := s.getContainerIDFromHostname(); err == nil {+ return id, nil+ }++ return "", ErrNotRunningInDocker+}++// getContainerIDFromCgroup reads container ID from /proc/self/cgroup+func (s *SystemUpgradeService) getContainerIDFromCgroup() (string, error) {+ data, err := os.ReadFile("/proc/self/cgroup")+ if err != nil {+ return "", err+ }++ lines := strings.Split(string(data), "\n")+ for _, line := range lines {+ if strings.Contains(line, "docker") || strings.Contains(line, "containerd") {+ parts := strings.Split(line, "/")+ if len(parts) > 0 {+ id := strings.TrimSpace(parts[len(parts)-1])+ if len(id) >= 12 {+ return id, nil+ }+ }+ }+ }++ return "", errors.New("container ID not found in cgroup")+}++// getContainerIDFromMountinfo reads container ID from /proc/self/mountinfo+func (s *SystemUpgradeService) getContainerIDFromMountinfo() (string, error) {+ data, err := os.ReadFile("/proc/self/mountinfo")+ if err != nil {+ return "", err+ }++ lines := strings.Split(string(data), "\n")+ for _, line := range lines {+ if strings.Contains(line, "/docker/containers/") {+ parts := strings.Split(line, "/docker/containers/")+ if len(parts) > 1 {+ idParts := strings.Split(parts[1], "/")+ if len(idParts) > 0 && len(idParts[0]) >= 12 {+ return idParts[0], nil+ }+ }+ }+ }++ return "", errors.New("container ID not found in mountinfo")+}++// getContainerIDFromHostname tries to get container ID from hostname+func (s *SystemUpgradeService) getContainerIDFromHostname() (string, error) {+ hostname, err := os.Hostname()+ if err != nil {+ return "", err+ }++ if len(hostname) == 12 || len(hostname) == 64 {+ return hostname, nil+ }++ return "", errors.New("hostname is not a valid container ID")+}++// findArcaneContainer finds the container using the ID+func (s *SystemUpgradeService) findArcaneContainer(ctx context.Context, containerId string) (containertypes.InspectResponse, error) {+ dockerClient, err := s.dockerService.CreateConnection(ctx)+ if err != nil {+ return containertypes.InspectResponse{}, err+ }+ defer dockerClient.Close()++ // Try to inspect the container directly+ container, err := dockerClient.ContainerInspect(ctx, containerId)+ if err == nil {+ return container, nil+ }++ // Fallback: search for containers with arcane image+ filter := filters.NewArgs()+ filter.Add("ancestor", "ofkm/arcane")++ containers, err := dockerClient.ContainerList(ctx, containertypes.ListOptions{+ All: true,+ Filters: filter,+ })+ if err != nil {+ return containertypes.InspectResponse{}, err+ }++ for _, c := range containers {+ if strings.HasPrefix(c.ID, containerId) {+ return dockerClient.ContainerInspect(ctx, c.ID)+ }+ }++ // Try without filter - search all containers+ allContainers, err := dockerClient.ContainerList(ctx, containertypes.ListOptions{All: true})+ if err != nil {+ return containertypes.InspectResponse{}, err+ }++ for _, c := range allContainers {+ if strings.HasPrefix(c.ID, containerId) || c.ID == containerId {+ return dockerClient.ContainerInspect(ctx, c.ID)+ }+ }++ return containertypes.InspectResponse{}, ErrContainerNotFound+}diff --git a/backend/internal/services/system_upgrade_service_test.go b/backend/internal/services/system_upgrade_service_test.gonew file mode 100644index 000000000..661605e16--- /dev/null+++ b/backend/internal/services/system_upgrade_service_test.go@@ -0,0 +1,152 @@+package services++import (+ "testing"++ "github.com/stretchr/testify/require"+)++// TestSystemUpgradeService_UpgradeFlag tests the upgrading flag behavior+func TestSystemUpgradeService_UpgradeFlag(t *testing.T) {+ s := NewSystemUpgradeService(nil, nil, nil)++ // Initially should be false+ require.False(t, s.upgrading.Load())++ // Simulate manual flag setting+ s.upgrading.Store(true)+ require.True(t, s.upgrading.Load())++ // Should be able to reset+ s.upgrading.Store(false)+ require.False(t, s.upgrading.Load())+}++// TestSystemUpgradeService_Initialization tests proper initialization+func TestSystemUpgradeService_Initialization(t *testing.T) {+ s := NewSystemUpgradeService(nil, nil, nil)++ require.NotNil(t, s)+ require.False(t, s.upgrading.Load())+ // Services can be nil in this test since we're just testing initialization+}++// TestSystemUpgradeService_ErrorVariables tests that error variables are properly defined+func TestSystemUpgradeService_ErrorVariables(t *testing.T) {+ // Test that all expected errors exist and are not nil+ require.Error(t, ErrNotRunningInDocker)+ require.Error(t, ErrContainerNotFound)+ require.Error(t, ErrUpgradeInProgress)+ require.Error(t, ErrDockerSocketAccess)++ // Test error messages+ require.Equal(t, "arcane is not running in a Docker container", ErrNotRunningInDocker.Error())+ require.Equal(t, "could not find Arcane container", ErrContainerNotFound.Error())+ require.Equal(t, "an upgrade is already in progress", ErrUpgradeInProgress.Error())+ require.Equal(t, "docker socket is not accessible", ErrDockerSocketAccess.Error())+}++// TestSystemUpgradeService_UpgradingFlag_ConcurrentAccess tests upgrading flag+func TestSystemUpgradeService_UpgradingFlag_ConcurrentAccess(t *testing.T) {+ s := NewSystemUpgradeService(nil, nil, nil)++ // Test initial state+ require.False(t, s.upgrading.Load(), "upgrading flag should start as false")++ // Test setting to true+ s.upgrading.Store(true)+ require.True(t, s.upgrading.Load(), "upgrading flag should be true after setting")++ // Test setting back to false+ s.upgrading.Store(false)+ require.False(t, s.upgrading.Load(), "upgrading flag should be false after resetting")+}++// TestSystemUpgradeService_CompareAndSwap tests atomic CompareAndSwap operation+func TestSystemUpgradeService_CompareAndSwap(t *testing.T) {+ s := NewSystemUpgradeService(nil, nil, nil)++ // Test successful CompareAndSwap from false to true+ swapped := s.upgrading.CompareAndSwap(false, true)+ require.True(t, swapped, "CompareAndSwap should succeed when value is false")+ require.True(t, s.upgrading.Load(), "upgrading should be true after swap")++ // Test failed CompareAndSwap (already true)+ swapped = s.upgrading.CompareAndSwap(false, true)+ require.False(t, swapped, "CompareAndSwap should fail when value is already true")+ require.True(t, s.upgrading.Load(), "upgrading should still be true")++ // Reset and test again+ s.upgrading.Store(false)+ swapped = s.upgrading.CompareAndSwap(false, true)+ require.True(t, swapped, "CompareAndSwap should succeed after reset")+}++// TestSystemUpgradeService_Services tests that services are stored correctly+func TestSystemUpgradeService_Services(t *testing.T) {+ // Create upgrade service with nil services (valid for testing initialization)+ s := NewSystemUpgradeService(nil, nil, nil)++ // Verify service is created and initialized properly+ require.NotNil(t, s)+ require.False(t, s.upgrading.Load())+}++// TestSystemUpgradeService_ConcurrentUpgradeAttempts tests that concurrent upgrade attempts are prevented+func TestSystemUpgradeService_ConcurrentUpgradeAttempts(t *testing.T) {+ s := NewSystemUpgradeService(nil, nil, nil)++ // Simulate first upgrade starting+ success := s.upgrading.CompareAndSwap(false, true)+ require.True(t, success, "First upgrade attempt should succeed")++ // Simulate second concurrent upgrade attempt+ success = s.upgrading.CompareAndSwap(false, true)+ require.False(t, success, "Second concurrent upgrade attempt should fail")++ // Cleanup+ s.upgrading.Store(false)++ // Should be able to upgrade again after cleanup+ success = s.upgrading.CompareAndSwap(false, true)+ require.True(t, success, "Upgrade should be possible after reset")+}++// TestSystemUpgradeService_UpgradeInProgressError tests the upgrade in progress sentinel error+func TestSystemUpgradeService_UpgradeInProgressError(t *testing.T) {+ // This tests the specific error that the handler checks for+ // The handler uses: if errors.Is(err, services.ErrUpgradeInProgress)++ require.Equal(t, "an upgrade is already in progress", ErrUpgradeInProgress.Error())++ // Test that the error is not nil+ require.Error(t, ErrUpgradeInProgress)+}++// TestSystemUpgradeService_AtomicOperations tests atomic.Bool operations+func TestSystemUpgradeService_AtomicOperations(t *testing.T) {+ s := NewSystemUpgradeService(nil, nil, nil)++ // Test Load+ require.False(t, s.upgrading.Load())++ // Test Store+ s.upgrading.Store(true)+ require.True(t, s.upgrading.Load())++ // Test CompareAndSwap success+ s.upgrading.Store(false)+ swapped := s.upgrading.CompareAndSwap(false, true)+ require.True(t, swapped)++ // Test CompareAndSwap failure+ swapped = s.upgrading.CompareAndSwap(false, true)+ require.False(t, swapped)+ require.True(t, s.upgrading.Load())++ // Test Swap+ s.upgrading.Store(false)+ old := s.upgrading.Swap(true)+ require.False(t, old)+ require.True(t, s.upgrading.Load())+}diff --git a/examples/compose.upgrader.yaml b/examples/compose.upgrader.yamlnew file mode 100644index 000000000..7d86f6f4c--- /dev/null+++ b/examples/compose.upgrader.yaml@@ -0,0 +1,40 @@+services:+ arcane:+ image: ghcr.io/ofkm/arcane:latest+ container_name: arcane+ ports:+ - "3552:3552"+ volumes:+ - /var/run/docker.sock:/var/run/docker.sock+ - arcane-data:/app/data+ environment:+ - PUID=1000+ - PGID=1000+ - ENCRYPTION_KEY=xxxxxxxxxxxxxxxxxxxxxx+ - JWT_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxx+ healthcheck:+ test:+ [+ "CMD-SHELL",+ "curl -fsS http://localhost:3552/api/health >/dev/null || exit 1",+ ]+ interval: 10s+ timeout: 3s+ retries: 5+ start_period: 15s+ restart: unless-stopped++ # Upgrader container - runs the upgrade command and exits+ # Usage: docker compose run --rm upgrader+ upgrader:+ image: ghcr.io/ofkm/arcane:latest+ container_name: arcane-upgrader+ volumes:+ - /var/run/docker.sock:/var/run/docker.sock+ entrypoint: ["/app/arcane"]+ command: ["upgrade", "--auto"]+ profiles:+ - tools # Only runs when explicitly specified++volumes:+ arcane-data:diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex a6b507671..acb04901b 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -1434,5 +1434,37 @@"first_login_error_mismatch": "Passwords do not match","first_login_error_length": "Password must be at least 8 characters","first_login_error_failed": "Failed to change password",- "first_login_success": "Password changed successfully"+ "first_login_success": "Password changed successfully",+ "upgrade_available": "Update Available",+ "upgrade_to_version": "Update to {version}",+ "upgrade_confirm_title": "Confirm System Upgrade",+ "upgrade_confirm_description": "You are about to upgrade Arcane to version {version}.",+ "upgrade_confirm_what_happens": "This upgrade will:",+ "upgrade_step_pull": "Pull the latest Arcane Docker image",+ "upgrade_step_stop": "Stop the current Arcane container",+ "upgrade_step_start": "Start a new container with the updated image",+ "upgrade_step_preserve": "Preserve all your data and settings",+ "upgrade_warning_interruption": "This will cause a brief service interruption (~30 seconds)",+ "upgrade_now": "Upgrade Now",+ "upgrade_in_progress": "Upgrading...",+ "upgrade_success": "Upgrade initiated successfully. Arcane will restart shortly.",+ "upgrade_failed": "Failed to initiate upgrade: {error}",+ "upgrade_checking": "Checking...",+ "upgrade_not_available": "Running in latest version",+ "upgrade_progress_message": "Upgrade in progress...",+ "upgrade_wait_message": "The upgrade is in progress. This may take a few minutes depending on your connection speed.",+ "upgrade_reload_message": "Please refresh this page manually once the upgrade completes (typically 1-2 minutes).",+ "upgrade_reload_countdown": "Reloading in {countdown} seconds...",+ "upgrade_reload_auto": "Page will reload automatically in {countdown} seconds",+ "upgrade_reload_now": "Reload Now",+ "upgrade_remote_description": "You are about to upgrade {targetDescription} to v{version}.",+ "upgrade_this_system": "this system",+ "upgrade_phase_waiting": "Starting upgrade process...",+ "upgrade_phase_stopping": "Stopping old container and starting new one...",+ "upgrade_phase_restarting": "New container is ready, reloading...",+ "upgrade_status_pulling": "Downloading new version and preparing to restart...",+ "upgrade_status_complete": "Upgrade complete!",+ "upgrade_status_checking": "Checking for new version...",+ "upgrade_status_detected": "New version detected!",+ "upgrade_wait_info": "This may take 30-60 seconds. The page will reload automatically when ready."}diff --git a/frontend/src/lib/components/dialogs/upgrade-confirmation-dialog.svelte b/frontend/src/lib/components/dialogs/upgrade-confirmation-dialog.sveltenew file mode 100644index 000000000..9a221eaeb--- /dev/null+++ b/frontend/src/lib/components/dialogs/upgrade-confirmation-dialog.svelte@@ -0,0 +1,229 @@+<script lang="ts">+ import * as Dialog from '$lib/components/ui/dialog';+ import { Button } from '$lib/components/ui/button';+ import AlertTriangleIcon from '@lucide/svelte/icons/alert-triangle';+ import InfoIcon from '@lucide/svelte/icons/info';+ import CheckCircle2Icon from '@lucide/svelte/icons/check-circle-2';+ import Spinner from '$lib/components/ui/spinner/spinner.svelte';+ import * as m from '$lib/paraglide/messages';+ import { onDestroy } from 'svelte';+ import systemUpgradeService from '$lib/services/api/system-upgrade-service';+ import { cn } from '$lib/utils';++ let {+ open = $bindable(false),+ version,+ onConfirm,+ environmentName,+ environmentId,+ upgrading = $bindable(false)+ }: {+ open?: boolean;+ version: string;+ onConfirm: () => void;+ environmentName?: string;+ environmentId?: string;+ upgrading?: boolean;+ } = $props();++ const isRemoteEnvironment = $derived(!!environmentName);+ const targetDescription = $derived(isRemoteEnvironment ? `remote environment "${environmentName}"` : m.upgrade_this_system());++ let upgradeStatus = $state<'upgrading' | 'waiting' | 'ready' | 'countdown'>('upgrading');+ let countdown = $state(10);+ let pollInterval: ReturnType<typeof setInterval> | null = null;+ let countdownInterval: ReturnType<typeof setInterval> | null = null;+ let fallbackTimeout: ReturnType<typeof setTimeout> | null = null;+ let consecutiveSuccessfulChecks = $state(0);++ async function startHealthPolling() {+ console.log('[Upgrade] Starting upgrade monitoring...');++ // Wait 15 seconds for the upgrade to start, then begin polling+ setTimeout(() => {+ upgradeStatus = 'waiting';+ consecutiveSuccessfulChecks = 0;+ console.log('[Upgrade] Starting health polling...');++ pollInterval = setInterval(async () => {+ const { healthy } = await systemUpgradeService.checkHealth(environmentId);++ console.log('[Upgrade] Health check:', { healthy, consecutiveSuccessfulChecks, environmentId });++ if (healthy) {+ consecutiveSuccessfulChecks++;+ console.log('[Upgrade] Container is up! Consecutive checks:', consecutiveSuccessfulChecks);++ if (consecutiveSuccessfulChecks >= 3) {+ console.log('[Upgrade] 3 consecutive checks passed! Starting countdown...');+ if (pollInterval) clearInterval(pollInterval);+ if (fallbackTimeout) clearTimeout(fallbackTimeout);+ upgradeStatus = 'ready';+ setTimeout(() => {+ startCountdown();+ }, 2000);+ }+ } else {+ consecutiveSuccessfulChecks = 0;+ console.log('[Upgrade] Container not ready yet, waiting...');+ }+ }, 2000);++ // Stop polling after 3 minutes and show error+ setTimeout(() => {+ if (pollInterval && upgradeStatus !== 'ready') {+ console.log('[Upgrade] 3-minute timeout reached, stopping polling');+ clearInterval(pollInterval);+ pollInterval = null;+ upgradeStatus = 'upgrading';+ upgrading = false;+ }+ }, 180000);++ // Force reload after 2.5 minutes as fallback+ fallbackTimeout = setTimeout(() => {+ if (upgradeStatus !== 'countdown') {+ console.log('[Upgrade] Fallback timeout reached, forcing reload');+ if (pollInterval) clearInterval(pollInterval);+ reloadPage();+ }+ }, 150000);+ }, 15000);+ }++ function startCountdown() {+ upgradeStatus = 'countdown';+ countdown = 10;+ countdownInterval = setInterval(() => {+ countdown--;+ if (countdown <= 0) {+ if (countdownInterval) clearInterval(countdownInterval);+ reloadPage();+ }+ }, 1000);+ }++ function reloadPage() {+ window.location.reload();+ }++ function handleConfirm() {+ upgrading = true;+ upgradeStatus = 'upgrading';+ onConfirm();+ if (!isRemoteEnvironment) {+ startHealthPolling();+ }+ }++ onDestroy(() => {+ if (pollInterval) clearInterval(pollInterval);+ if (countdownInterval) clearInterval(countdownInterval);+ if (fallbackTimeout) clearTimeout(fallbackTimeout);+ });+</script>++<Dialog.Root bind:open>+ <Dialog.Content+ class={cn('sm:max-w-[500px]', upgrading && '[&>button]:hidden')}+ onInteractOutside={(e: Event) => {+ if (upgrading) e.preventDefault();+ }}+ >+ <Dialog.Header>+ <Dialog.Title>+ {#if upgrading}+ {m.upgrade_in_progress()}+ {:else}+ {m.upgrade_confirm_title()}+ {/if}+ </Dialog.Title>+ {#if !upgrading}+ <Dialog.Description>+ {#if isRemoteEnvironment}+ {m.upgrade_remote_description({ targetDescription, version })}+ {:else}+ {m.upgrade_confirm_description({ version })}+ {/if}+ </Dialog.Description>+ {/if}+ </Dialog.Header>++ {#if upgrading}+ <div class="space-y-4 py-4">+ <div class="flex items-center justify-center gap-2 text-sm">+ {#if upgradeStatus === 'countdown'}+ <CheckCircle2Icon class="size-5 text-green-500" />+ <span class="font-medium text-green-600 dark:text-green-400">{m.upgrade_status_complete()}</span>+ {:else if upgradeStatus === 'ready'}+ <CheckCircle2Icon class="size-5 animate-pulse text-green-500" />+ <span class="font-medium text-green-600 dark:text-green-400">{m.upgrade_status_detected()}</span>+ {:else}+ <Spinner class="text-primary size-5" />+ <span class="font-medium">+ {#if upgradeStatus === 'upgrading'}+ {m.upgrade_status_pulling()}+ {:else if upgradeStatus === 'waiting'}+ {m.upgrade_status_checking()}+ {/if}+ </span>+ {/if}+ </div>++ {#if upgradeStatus === 'countdown'}+ <div class="rounded-lg border border-green-200 bg-green-50 p-3 dark:border-green-800 dark:bg-green-950/20">+ <p class="flex items-center gap-2 text-sm font-medium text-green-800 dark:text-green-200">+ <InfoIcon class="size-4" />+ {m.upgrade_reload_auto({ countdown })}+ </p>+ </div>+ <div class="flex justify-center">+ <Button onclick={reloadPage} variant="default" size="sm" class="w-full sm:w-auto">+ {m.upgrade_reload_now()}+ </Button>+ </div>+ {:else if upgradeStatus === 'waiting'}+ <div class="rounded-lg border border-blue-200 bg-blue-50 p-3 dark:border-blue-800 dark:bg-blue-950/20">+ <p class="flex items-center gap-2 text-sm font-medium text-blue-800 dark:text-blue-200">+ <InfoIcon class="size-4" />+ {m.upgrade_wait_info()}+ </p>+ </div>+ {:else}+ <div class="rounded-lg border border-blue-200 bg-blue-50 p-3 dark:border-blue-800 dark:bg-blue-950/20">+ <p class="flex items-center gap-2 text-sm font-medium text-blue-800 dark:text-blue-200">+ <InfoIcon class="size-4" />+ {m.upgrade_wait_message()}+ </p>+ </div>+ {/if}+ </div>+ {:else}+ <div class="space-y-3 py-4">+ <p class="text-sm font-medium">{m.upgrade_confirm_what_happens()}</p>+ <ul class="text-muted-foreground list-inside list-disc space-y-1 text-sm">+ <li>{m.upgrade_step_pull()}</li>+ <li>{m.upgrade_step_stop()}</li>+ <li>{m.upgrade_step_start()}</li>+ <li>{m.upgrade_step_preserve()}</li>+ </ul>++ <div class="rounded-lg border border-orange-200 bg-orange-50 p-3 dark:border-orange-800 dark:bg-orange-950/20">+ <p class="flex items-center gap-2 text-sm font-medium text-orange-800 dark:text-orange-200">+ <AlertTriangleIcon class="size-4" />+ {m.upgrade_warning_interruption()}+ </p>+ </div>+ </div>++ <Dialog.Footer>+ <Button variant="outline" onclick={() => (open = false)}>+ {m.cancel()}+ </Button>+ <Button onclick={handleConfirm}>+ {m.upgrade_now()}+ </Button>+ </Dialog.Footer>+ {/if}+ </Dialog.Content>+</Dialog.Root>diff --git a/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte b/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelteindex 0f9d08104..f97dc959f 100644--- a/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte+++ b/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte@@ -3,26 +3,121 @@import * as Separator from '$lib/components/ui/separator/index.js';import * as Tooltip from '$lib/components/ui/tooltip/index.js';import ExternalLink from '@lucide/svelte/icons/external-link';+ import DownloadIcon from '@lucide/svelte/icons/download';import { useSidebar } from '$lib/components/ui/sidebar/index.js';import type { AppVersionInformation } from '$lib/types/application-configuration';+ import type { User } from '$lib/types/user.type';import { m } from '$lib/paraglide/messages';import { Button } from '$lib/components/ui/button/index.js';+ import systemUpgradeService from '$lib/services/api/system-upgrade-service';+ import UpgradeConfirmationDialog from '$lib/components/dialogs/upgrade-confirmation-dialog.svelte';+ import { toast } from 'svelte-sonner';+ import { onMount } from 'svelte';let {isCollapsed,versionInformation,- updateAvailable = false+ updateAvailable = false,+ debug = false,+ user}: {isCollapsed: boolean;versionInformation?: AppVersionInformation;updateAvailable?: boolean;+ debug?: boolean;+ user?: User | null;} = $props();const sidebar = useSidebar();- const shouldShowBanner = $derived(updateAvailable && versionInformation?.isSemverVersion);+ let canUpgrade = $state(false);+ let checkingUpgrade = $state(false);+ let upgrading = $state(false);+ let showConfirmDialog = $state(false);++ const isAdmin = $derived(!!user?.roles?.includes('admin'));+ const shouldShowUpgrade = $derived((canUpgrade && isAdmin) || debug);+ const upgradeButtonText = $derived.by(() => {+ if (upgrading) return m.upgrade_in_progress();+ if (checkingUpgrade) return m.upgrade_checking();+ return m.upgrade_to_version({ version: versionInformation?.newestVersion ?? '' });+ });++ // Debug mode: force show upgrade button+ $effect(() => {+ if (debug) {+ canUpgrade = true;+ }+ });++ // Check if self-upgrade is available+ onMount(() => {+ if (updateAvailable && isAdmin && !debug) {+ checkUpgradeAvailability();+ }+ });++ async function checkUpgradeAvailability() {+ if (checkingUpgrade) return;++ checkingUpgrade = true;+ try {+ const result = await systemUpgradeService.checkUpgradeAvailable();+ canUpgrade = result.canUpgrade && !result.error;+ } catch (error) {+ canUpgrade = false;+ } finally {+ checkingUpgrade = false;+ }+ }++ function handleUpgradeClick() {+ showConfirmDialog = true;+ }++ async function handleConfirmUpgrade() {+ try {+ await systemUpgradeService.triggerUpgrade();+ // Dialog will handle countdown and reload+ } catch (error: any) {+ const errorMessage = error?.response?.data?.error || error?.message || 'Unknown error';+ toast.error(m.upgrade_failed({ error: errorMessage }));+ upgrading = false;+ }+ }++ const shouldShowBanner = $derived((updateAvailable && versionInformation?.isSemverVersion) || debug);</script>+{#snippet updateInfo()}+ <div class="flex flex-col gap-1">+ <span class="text-sm font-semibold">{m.sidebar_update_available()}</span>+ <span class="text-xs text-blue-500/80">+ {m.sidebar_version({ version: versionInformation?.newestVersion ?? m.common_unknown() })}+ </span>+ </div>+{/snippet}++{#snippet upgradeButton()}+ <Button+ variant="default"+ size="sm"+ class="bg-primary text-primary-foreground hover:bg-primary/90 focus-visible:ring-primary/40 h-9 w-full gap-2 rounded-xl shadow-sm transition-colors focus-visible:ring-2 focus-visible:outline-none"+ onclick={handleUpgradeClick}+ disabled={upgrading || checkingUpgrade}+ >+ <DownloadIcon class="size-4" />+ {upgradeButtonText}+ </Button>+{/snippet}++<UpgradeConfirmationDialog+ bind:open={showConfirmDialog}+ bind:upgrading+ version={versionInformation?.newestVersion ?? ''}+ onConfirm={handleConfirmUpgrade}+/>+{#if shouldShowBanner}<div class={cn('pb-2', isCollapsed ? 'px-1' : 'px-4')}><Separator.Root class="mb-3 opacity-30" />@@ -31,24 +126,24 @@<divclass="rounded-xl border border-blue-500/20 bg-gradient-to-br from-blue-500/10 to-blue-600/5 p-3 transition-all hover:scale-[1.02] hover:from-blue-500/15 hover:to-blue-600/10 hover:shadow-md">- <Button- variant="link"- href={versionInformation?.releaseUrl}- target="_blank"- rel="noopener noreferrer"- class="group flex items-center justify-between text-blue-600 transition-colors duration-200 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"- >- <div class="flex flex-col gap-1">- <span class="text-sm font-semibold">{m.sidebar_update_available()}</span>- <span class="text-xs text-blue-500/80"- >{m.sidebar_version({ version: versionInformation?.newestVersion ?? m.common_unknown() })}</span- >- </div>- <ExternalLink size={16} class="transition-transform duration-200 group-hover:scale-110" />- </Button>+ <div class="flex flex-col gap-2">+ <a+ href={versionInformation?.releaseUrl}+ target="_blank"+ rel="noopener noreferrer"+ class="group flex items-center justify-between text-blue-600 transition-colors duration-200 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"+ >+ {@render updateInfo()}+ <ExternalLink size={16} class="transition-transform duration-200 group-hover:scale-110" />+ </a>++ {#if shouldShowUpgrade}+ {@render upgradeButton()}+ {/if}+ </div></div>{:else}- <div class="flex justify-center">+ <div class="flex flex-col items-center gap-2"><Tooltip.Root><Tooltip.Trigger>{#snippet child({ props })}@@ -68,9 +163,31 @@{/snippet}</Tooltip.Trigger><Tooltip.Content side="right" align="center" hidden={sidebar.state !== 'collapsed' || sidebar.isHovered}>- {m.sidebar_update_available_tooltip({ version: versionInformation?.newestVersion ?? m.common_unknown() })}+ {m.sidebar_update_available_tooltip({+ version: versionInformation?.newestVersion ?? m.common_unknown()+ })}</Tooltip.Content></Tooltip.Root>++ {#if shouldShowUpgrade}+ <Tooltip.Root>+ <Tooltip.Trigger>+ {#snippet child({ props })}+ <button+ onclick={handleUpgradeClick}+ disabled={upgrading || checkingUpgrade}+ class="border-primary/20 bg-primary/15 text-primary hover:bg-primary/25 focus-visible:ring-primary/40 dark:text-primary flex size-8 items-center justify-center rounded-lg border transition-all hover:scale-[1.02] hover:shadow-md focus-visible:ring-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"+ {...props}+ >+ <DownloadIcon size={14} />+ </button>+ {/snippet}+ </Tooltip.Trigger>+ <Tooltip.Content side="right" align="center" hidden={sidebar.state !== 'collapsed' || sidebar.isHovered}>+ {upgradeButtonText}+ </Tooltip.Content>+ </Tooltip.Root>+ {/if}</div>{/if}</div>diff --git a/frontend/src/lib/components/sidebar/sidebar.svelte b/frontend/src/lib/components/sidebar/sidebar.svelteindex 3f123651c..faca2202f 100644--- a/frontend/src/lib/components/sidebar/sidebar.svelte+++ b/frontend/src/lib/components/sidebar/sidebar.svelte@@ -76,7 +76,13 @@{/if}</Sidebar.Content><Sidebar.Footer>- <SidebarUpdatebanner {isCollapsed} {versionInformation} updateAvailable={versionInformation.updateAvailable} />+ <SidebarUpdatebanner+ {isCollapsed}+ {versionInformation}+ updateAvailable={versionInformation.updateAvailable}+ user={effectiveUser}+ debug={false}+ />{#if effectiveUser}{#if isCollapsed}<div class="px-0 pb-2">diff --git a/frontend/src/lib/services/api/environment-upgrade-service.ts b/frontend/src/lib/services/api/environment-upgrade-service.tsnew file mode 100644index 000000000..85dd94f24--- /dev/null+++ b/frontend/src/lib/services/api/environment-upgrade-service.ts@@ -0,0 +1,38 @@+import axios from 'axios';++export interface EnvironmentUpgradeCheckResponse {+ canUpgrade: boolean;+ error: boolean;+ message: string;+}++export interface EnvironmentUpgradeResponse {+ message: string;+ success: boolean;+ error?: string;+}++/**+ * Check if a remote environment can perform a self-upgrade+ * @param environmentId - The ID of the environment to check+ * @returns Promise with upgrade availability status+ */+async function checkEnvironmentUpgradeAvailable(environmentId: string): Promise<EnvironmentUpgradeCheckResponse> {+ const res = await axios.get<EnvironmentUpgradeCheckResponse>(`/api/environments/${environmentId}/system/upgrade/check`);+ return res.data;+}++/**+ * Trigger a self-upgrade on a remote environment+ * @param environmentId - The ID of the environment to upgrade+ * @returns Promise with upgrade initiation result+ */+async function triggerEnvironmentUpgrade(environmentId: string): Promise<EnvironmentUpgradeResponse> {+ const res = await axios.post<EnvironmentUpgradeResponse>(`/api/environments/${environmentId}/system/upgrade`);+ return res.data;+}++export default {+ checkEnvironmentUpgradeAvailable,+ triggerEnvironmentUpgrade+};diff --git a/frontend/src/lib/services/api/system-upgrade-service.ts b/frontend/src/lib/services/api/system-upgrade-service.tsnew file mode 100644index 000000000..bde9ffca6--- /dev/null+++ b/frontend/src/lib/services/api/system-upgrade-service.ts@@ -0,0 +1,58 @@+import axios from 'axios';++export interface UpgradeCheckResponse {+ canUpgrade: boolean;+ error: boolean;+ message: string;+}++export interface UpgradeResponse {+ message: string;+ success: boolean;+ error?: string;+}++export interface HealthCheckResult {+ healthy: boolean;+}++/**+ * Check if the system can perform a self-upgrade+ * @returns Promise with upgrade availability status+ */+async function checkUpgradeAvailable(): Promise<UpgradeCheckResponse> {+ const res = await axios.get<UpgradeCheckResponse>('/api/environments/0/system/upgrade/check');+ return res.data;+}++/**+ * Trigger a system self-upgrade+ * @returns Promise with upgrade initiation result+ */+async function triggerUpgrade(): Promise<UpgradeResponse> {+ const res = await axios.post<UpgradeResponse>('/api/environments/0/system/upgrade');+ return res.data;+}++/**+ * Check system health+ * @param environmentId - Optional environment ID for remote environments (defaults to local system)+ * @returns Promise with health check result+ */+async function checkHealth(environmentId: string = '0'): Promise<HealthCheckResult> {+ try {+ const endpoint = environmentId === '0' ? '/api/health' : `/api/environments/${environmentId}/system/health`;+ const res = await axios.head(endpoint, {+ timeout: 3000+ });+ return { healthy: res.status === 200 };+ } catch {+ return { healthy: false };+ }+}++export default {+ checkUpgradeAvailable,+ triggerUpgrade,+ checkHealth+};diff --git a/frontend/src/routes/environments/environment-table.svelte b/frontend/src/routes/environments/environment-table.svelteindex c8b43d35f..02f138c1f 100644--- a/frontend/src/routes/environments/environment-table.svelte+++ b/frontend/src/routes/environments/environment-table.svelte@@ -7,6 +7,7 @@import TerminalIcon from '@lucide/svelte/icons/terminal';import Trash2Icon from '@lucide/svelte/icons/trash-2';import MonitorIcon from '@lucide/svelte/icons/monitor';+ import DownloadIcon from '@lucide/svelte/icons/download';import StatusBadge from '$lib/components/badges/status-badge.svelte';import { goto } from '$app/navigation';import { openConfirmDialog } from '$lib/components/confirm-dialog';@@ -20,6 +21,8 @@import { m } from '$lib/paraglide/messages';import { environmentManagementService } from '$lib/services/env-mgmt-service';import CloudIcon from '@lucide/svelte/icons/cloud';+ import environmentUpgradeService from '$lib/services/api/environment-upgrade-service';+ import UpgradeConfirmationDialog from '$lib/components/dialogs/upgrade-confirmation-dialog.svelte';let {environments = $bindable(),@@ -31,7 +34,10 @@requestOptions: SearchPaginationSortRequest;} = $props();- let isLoading = $state({ removing: false, testing: false });+ let isLoading = $state({ removing: false, testing: false, upgrading: false });+ let upgradingEnvironmentId = $state<string | null>(null);+ let showUpgradeDialog = $state(false);+ let selectedEnvironmentForUpgrade = $state<Environment | null>(null);async function handleDeleteSelected(ids: string[]) {if (!ids?.length) return;@@ -119,6 +125,40 @@isLoading.testing = false;}+ async function handleUpgradeClick(environment: Environment) {+ selectedEnvironmentForUpgrade = environment;+ showUpgradeDialog = true;+ }++ async function handleConfirmUpgrade() {+ if (!selectedEnvironmentForUpgrade) return;++ const envId = selectedEnvironmentForUpgrade.id;+ const envName = selectedEnvironmentForUpgrade.name;++ isLoading.upgrading = true;+ upgradingEnvironmentId = envId;+ showUpgradeDialog = false;++ try {+ const result = await environmentUpgradeService.triggerEnvironmentUpgrade(envId);++ if (result.success) {+ toast.success(m.upgrade_success());+ toast.info(`Environment "${envName}" is upgrading and will restart shortly.`);+ } else {+ toast.error(result.error || m.upgrade_failed({ error: 'Unknown error' }));+ }+ } catch (error: any) {+ const errorMessage = error?.response?.data?.error || error?.message || 'Unknown error';+ toast.error(m.upgrade_failed({ error: errorMessage }));+ } finally {+ isLoading.upgrading = false;+ upgradingEnvironmentId = null;+ selectedEnvironmentForUpgrade = null;+ }+ }+const columns = [{ accessorKey: 'id', title: m.common_id(), hidden: true },{@@ -234,6 +274,16 @@<EyeIcon class="size-4" />{m.common_view_details()}</DropdownMenu.Item>+ {#if item.status === 'online'}+ <DropdownMenu.Separator />+ <DropdownMenu.Item+ onclick={() => handleUpgradeClick(item)}+ disabled={isLoading.upgrading || upgradingEnvironmentId === item.id}+ >+ <DownloadIcon class="size-4" />+ {upgradingEnvironmentId === item.id ? m.upgrade_in_progress() : m.upgrade_to_version({ version: 'Latest' })}+ </DropdownMenu.Item>+ {/if}<DropdownMenu.Separator /><DropdownMenu.Itemvariant="destructive"@@ -261,3 +311,12 @@rowActions={RowActions}mobileCard={EnvironmentMobileCardSnippet}/>++<UpgradeConfirmationDialog+ bind:open={showUpgradeDialog}+ version="Latest"+ onConfirm={handleConfirmUpgrade}+ environmentName={selectedEnvironmentForUpgrade?.name}+ environmentId={selectedEnvironmentForUpgrade?.id}+ bind:upgrading={isLoading.upgrading}+/>