Skip to content

Modern Docker Management, Designed for Everyone

fix: refactor updater to have safer and more consistent upgrades (#1315)

Kyle Mendell24b03c4f7ccf
diff --git a/.github/CLAUDE.md b/.github/CLAUDE.md
new file mode 100644
index 000000000..3c64f9b88
--- /dev/null
+++ b/.github/CLAUDE.md
@@ -0,0 +1,127 @@
+# CLAUDE.md
+
+This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+
+## Project Overview
+
+Arcane is a modern Docker management UI with a Go backend and SvelteKit frontend. It manages containers, images, volumes, networks, stacks, and tracks image updates.
+
+## Commands
+
+### Development
+
+```bash
+./scripts/development/dev.sh start # Start Docker-based dev environment (recommended)
+./scripts/development/dev.sh stop|restart|rebuild|clean
+```
+
+### Backend (Go)
+
+```bash
+cd backend
+go build ./... # Build all modules
+go test ./... # Run tests
+golangci-lint run # Lint
+```
+
+### Frontend (SvelteKit)
+
+```bash
+pnpm -w -C frontend dev # Dev server (port 3000)
+pnpm -w -C frontend build # Production build
+pnpm -w -C frontend check # Type check
+pnpm -w format # Format all code
+```
+
+### E2E Tests (Playwright)
+
+```bash
+pnpm test # Run tests
+```
+
+## Architecture
+
+**Three Go modules** unified via `go.work`:
+
+- `backend/` - API server, services, models
+- `cli/` - Command-line tool (uses Cobra)
+- `types/` - Shared type definitions
+
+**Frontend**: SvelteKit in `frontend/` with pnpm
+
+### Backend Structure
+
+```
+backend/internal/
+├── bootstrap/ # App initialization & DI wiring (start here)
+├── api/ # HTTP handlers (*_handler.go)
+├── services/ # Business logic (*_service.go)
+├── models/ # GORM database models
+├── dto/ # Request/response DTOs
+├── huma/ # Huma v2 API handlers (newer pattern)
+└── job/ # Background job scheduling (gocron v2)
+```
+
+### Frontend Structure
+
+```
+frontend/src/
+├── routes/(app)/ # Main app pages (dashboard, containers, images, etc.)
+├── routes/(auth)/ # Auth pages
+├── lib/components/ # Reusable Svelte components (shadcn-svelte)
+├── lib/services/api/ # API service classes (Axios)
+├── lib/stores/ # Svelte stores
+└── lib/types/ # TypeScript types
+```
+
+## Key Patterns
+
+### Backend
+
+- **Thin handlers**: HTTP handlers call services; business logic lives in `*_service.go`
+- **Bootstrap DI**: All wiring happens in `internal/bootstrap/` - check here for how services are instantiated
+- **DTOs for boundaries**: Use `internal/dto/` for API request/response types
+- **Structured logging**: Use `slog` with context
+- **Error wrapping**: `fmt.Errorf("context: %w", err)`
+
+### Frontend (Svelte 5 Only)
+
+```svelte
+<!-- Props -->
+let { prop1, prop2 } = $props();
+
+<!-- State -->
+let count = $state(0);
+
+<!-- Derived -->
+let doubled = $derived(count * 2);
+
+<!-- Effects -->
+$effect(() => { /* side effects */ });
+```
+
+**Do NOT update state values in an effect**
+
+**Do NOT use Svelte 4 syntax** (`export let`, `on:click`, `$:`, etc.)
+
+### Database
+
+- GORM with SQLite or PostgreSQL
+- Models include `BaseModel` (UUID, timestamps)
+- Use proper preloading for relationships
+
+## Anti-Patterns
+
+- Don't put business logic in handlers
+- Don't use Svelte 4 syntax anywhere
+- Don't hardcode registry-specific logic (support generic OCI patterns)
+- Don't bypass TypeScript with `any`
+- Don't add unnecessary comments
+
+## Container Registry Integration
+
+When working with registries:
+
+- Use generic authentication (bearer tokens, basic auth)
+- Support multiple providers (Docker Hub, GHCR, custom OCI)
+- Use case-insensitive header checking
diff --git a/.gitignore b/.gitignore
index c8a43b55c..87db1b50d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -39,3 +39,4 @@ tests/package-lock.json
/.idea/**
.pnpm-store/**
.pnpm-store
+.claude/settings.local.json
diff --git a/.goreleaser.yaml b/.goreleaser.yaml
index 4c372f59d..1f1e05feb 100644
--- a/.goreleaser.yaml
+++ b/.goreleaser.yaml
@@ -178,7 +178,7 @@ dockers_v2:
'org.opencontainers.image.title': 'Arcane'
'org.opencontainers.image.description': 'Modern Docker Management, Made for Everyone'
'com.getarcaneapp.arcane.updater': 'false'
- 'com.getarcaneapp.arcane.server': 'true'
+ 'com.getarcaneapp.arcane': 'true'
disable: '{{ if not (index .Env "BUILD_NEXT") }}true{{ end }}'
sbom: true
@@ -206,7 +206,7 @@ dockers_v2:
'org.opencontainers.image.title': 'Arcane Agent'
'org.opencontainers.image.description': 'Arcane Agent'
'com.getarcaneapp.arcane.updater': 'false'
- 'com.getarcaneapp.arcane.server': 'true'
+ 'com.getarcaneapp.arcane.agent': 'true'
disable: '{{ if not (index .Env "BUILD_NEXT") }}true{{ end }}'
sbom: true
@@ -234,7 +234,7 @@ dockers_v2:
'org.opencontainers.image.title': 'Arcane'
'org.opencontainers.image.description': 'Modern Docker Management, Made for Everyone'
'com.getarcaneapp.arcane.updater': 'false'
- 'com.getarcaneapp.arcane.server': 'true'
+ 'com.getarcaneapp.arcane': 'true'
disable: '{{ if not (index .Env "BUILD_NEXT") }}true{{ end }}'
sbom: true
@@ -262,7 +262,7 @@ dockers_v2:
'org.opencontainers.image.title': 'Arcane Agent'
'org.opencontainers.image.description': 'Arcane Agent'
'com.getarcaneapp.arcane.updater': 'false'
- 'com.getarcaneapp.arcane.server': 'true'
+ 'com.getarcaneapp.arcane.agent': 'true'
disable: '{{ if not (index .Env "BUILD_NEXT") }}true{{ end }}'
sbom: true
diff --git a/backend/cli/upgrade/upgrade.go b/backend/cli/upgrade/upgrade.go
index f843149c4..b8d693871 100644
--- a/backend/cli/upgrade/upgrade.go
+++ b/backend/cli/upgrade/upgrade.go
@@ -5,7 +5,6 @@ import (
"fmt"
"io"
"log/slog"
- "os"
"strings"
"time"
@@ -14,6 +13,8 @@ import (
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
+ "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/arcaneupdater"
"github.com/spf13/cobra"
)
@@ -52,6 +53,18 @@ func runUpgrade(cmd *cobra.Command, args []string) error {
// This prevents interruption when stopping the target container
ctx := context.Background()
+ logFile, err := arcaneupdater.SetupMessageOnlyLogFile("/app/data", "arcane-upgrade", slog.LevelInfo)
+ if err != nil {
+ slog.Warn("Failed to setup file logging", "error", err)
+ } else if logFile != nil {
+ defer func() {
+ if err := logFile.Close(); err != nil {
+ slog.Warn("Failed to close upgrade log file", "error", err, "path", logFile.Name())
+ }
+ }()
+ slog.Info("Upgrade log file created", "path", logFile.Name())
+ }
+
// Connect to Docker
dockerClient, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
@@ -100,7 +113,7 @@ func runUpgrade(cmd *cobra.Command, args []string) error {
}
func findArcaneContainer(ctx context.Context, dockerClient *client.Client) (container.InspectResponse, error) {
- // Look for containers with "arcane" in the image name
+ // Prefer explicit Arcane labels; fall back to image name heuristics.
filter := filters.NewArgs()
filter.Add("status", "running")
@@ -109,7 +122,7 @@ func findArcaneContainer(ctx context.Context, dockerClient *client.Client) (cont
return container.InspectResponse{}, err
}
- selfID := getSelfContainerID()
+ selfID, _ := utils.GetCurrentContainerID()
slog.Info("Searching for Arcane container", "selfID", selfID, "totalContainers", len(containers))
now := time.Now()
@@ -119,83 +132,75 @@ func findArcaneContainer(ctx context.Context, dockerClient *client.Client) (cont
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)
+ inspect, err := dockerClient.ContainerInspect(ctx, c.ID)
+ if err != nil {
+ continue
}
- }
- 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 ""
- }
+ if isAgentContainer(inspect) {
+ slog.Debug("Skipping agent container", "id", c.ID[:12], "names", c.Names)
+ continue
+ }
- content := string(data)
- for _, line := range strings.Split(content, "\n") {
- // cgroup v1: 12:pids:/docker/abc123...
- if id := extractCgroupV1ID(line); id != "" {
- return id
+ labels := map[string]string{}
+ if inspect.Config != nil && inspect.Config.Labels != nil {
+ labels = inspect.Config.Labels
}
- // cgroup v2: 0::/system.slice/docker-abc123....scope
- if id := extractCgroupV2ID(line); id != "" {
- return id
+
+ // New label: com.getarcaneapp.arcane=true
+ if arcaneupdater.IsArcaneContainer(labels) {
+ slog.Info("Found Arcane container by label", "id", c.ID[:12], "image", c.Image, "names", c.Names)
+ return inspect, nil
}
- }
- return ""
-}
+ // Legacy label (pre-migration): com.getarcaneapp.arcane.server=true
+ // NOTE: older agent images also used this label, so we must additionally exclude AGENT_MODE=true.
+ if isLegacyServerLabel(labels) {
+ slog.Info("Found Arcane container by legacy label", "id", c.ID[:12], "image", c.Image, "names", c.Names)
+ return inspect, nil
+ }
-// extractCgroupV1ID extracts container ID from cgroup v1 format
-func extractCgroupV1ID(line string) string {
- if !strings.Contains(line, "/docker/") {
- return ""
+ // Fallback: image name heuristic
+ if strings.Contains(strings.ToLower(c.Image), "arcane") {
+ slog.Info("Found matching container by image name", "id", c.ID[:12], "image", c.Image, "names", c.Names)
+ return inspect, nil
+ }
}
- parts := strings.Split(line, "/docker/")
- if len(parts) <= 1 {
- return ""
- }
+ return container.InspectResponse{}, fmt.Errorf("no running Arcane container found")
+}
- id := strings.TrimSpace(parts[1])
- if idx := strings.Index(id, "/"); idx != -1 {
- id = id[:idx]
+func isLegacyServerLabel(labels map[string]string) bool {
+ if labels == nil {
+ return false
}
-
- if len(id) >= 12 {
- return id[:12]
+ for k, v := range labels {
+ if strings.EqualFold(k, "com.getarcaneapp.arcane.server") {
+ return strings.EqualFold(strings.TrimSpace(v), "true")
+ }
}
-
- return ""
+ return false
}
-// 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 ""
+func isAgentContainer(inspect container.InspectResponse) bool {
+ if inspect.Config == nil {
+ return false
}
-
- start += 7 // len("docker-")
- end := strings.Index(line[start:], ".scope")
- if end == -1 {
- return ""
+ // New label for agent containers
+ if inspect.Config.Labels != nil {
+ for k, v := range inspect.Config.Labels {
+ if strings.EqualFold(k, "com.getarcaneapp.arcane.agent") {
+ return strings.EqualFold(strings.TrimSpace(v), "true")
+ }
+ }
}
-
- id := line[start : start+end]
- if len(id) >= 12 {
- return id[:12]
+ // Legacy agent detection: AGENT_MODE=true in env
+ for _, env := range inspect.Config.Env {
+ if strings.EqualFold(env, "AGENT_MODE=true") {
+ return true
+ }
}
-
- return ""
+ return false
}
// shouldSkipContainer determines if a container should be skipped during search
@@ -328,7 +333,7 @@ func pullImage(ctx context.Context, dockerClient *client.Client, imageName strin
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)
+ oldName := fmt.Sprintf("%s-old-%d", originalName, time.Now().UnixNano())
// Create new container config
config := *oldContainer.Config
@@ -344,6 +349,13 @@ func upgradeContainer(ctx context.Context, dockerClient *client.Client, oldConta
config.Domainname = ""
}
+ // Clear hostname if it looks like a container ID (auto-generated by Docker)
+ // This allows Docker to assign the new container's ID as the hostname
+ if looksLikeContainerID(config.Hostname) {
+ slog.Debug("Clearing auto-generated hostname", "oldHostname", config.Hostname)
+ config.Hostname = ""
+ }
+
// Fix for "conflicting options: port exposing and the container type network mode"
// When network mode is "container:...", port mappings are not allowed
if nm.IsContainer() {
@@ -377,19 +389,27 @@ func upgradeContainer(ctx context.Context, dockerClient *client.Client, oldConta
}
}
+ fmt.Println("PROGRESS:65:Renaming old container")
+ slog.Info("Renaming old container", "from", originalName, "to", oldName)
+ if err := dockerClient.ContainerRename(ctx, oldContainer.ID, oldName); err != nil {
+ return fmt.Errorf("rename old container: %w", err)
+ }
+
fmt.Println("PROGRESS:70:Stopping old container")
- slog.Info("Stopping old container", "name", originalName)
+ slog.Info("Stopping old container", "name", oldName)
timeout := 10
if err := dockerClient.ContainerStop(ctx, oldContainer.ID, container.StopOptions{Timeout: &timeout}); err != nil {
+ _ = dockerClient.ContainerRename(ctx, oldContainer.ID, originalName)
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)
+ slog.Info("Creating new container", "name", originalName)
+ resp, err := dockerClient.ContainerCreate(ctx, &config, hostConfig, networkConfig, nil, originalName)
if err != nil {
- // Try to restart old container on failure
+ // Try to restart and restore old container on failure
_ = dockerClient.ContainerStart(ctx, oldContainer.ID, container.StartOptions{})
+ _ = dockerClient.ContainerRename(ctx, oldContainer.ID, originalName)
return fmt.Errorf("create new container: %w", err)
}
@@ -399,6 +419,7 @@ func upgradeContainer(ctx context.Context, dockerClient *client.Client, oldConta
// Cleanup new container and restart old one
_ = dockerClient.ContainerRemove(ctx, resp.ID, container.RemoveOptions{Force: true})
_ = dockerClient.ContainerStart(ctx, oldContainer.ID, container.StartOptions{})
+ _ = dockerClient.ContainerRename(ctx, oldContainer.ID, originalName)
return fmt.Errorf("start new container: %w", err)
}
@@ -413,11 +434,21 @@ func upgradeContainer(ctx context.Context, dockerClient *client.Client, oldConta
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)
- }
+ fmt.Println("PROGRESS:95:Upgrade complete")
return nil
}
+
+// looksLikeContainerID checks if a string looks like a Docker container ID
+// (12 or 64 lowercase hex characters, which Docker auto-generates as hostnames)
+func looksLikeContainerID(s string) bool {
+ if len(s) != 12 && len(s) != 64 {
+ return false
+ }
+ for _, c := range s {
+ if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
+ return false
+ }
+ }
+ return true
+}
diff --git a/backend/go.mod b/backend/go.mod
index a0c13320b..00a08e2e2 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -36,6 +36,7 @@ require (
github.com/stretchr/testify v1.11.1
go.podman.io/image/v5 v5.38.0
golang.org/x/crypto v0.46.0
+ golang.org/x/mod v0.31.0
golang.org/x/net v0.48.0
golang.org/x/oauth2 v0.34.0
golang.org/x/sync v0.19.0
diff --git a/backend/go.sum b/backend/go.sum
index 6ffe4e5eb..4f31a9300 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -584,8 +584,8 @@ golang.org/x/exp v0.0.0-20250911091902-df9299821621 h1:2id6c1/gto0kaHYyrixvknJ8t
golang.org/x/exp v0.0.0-20250911091902-df9299821621/go.mod h1:TwQYMMnGpvZyc+JpB/UAuTNIsVJifOlSkrZkhcvpVUk=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
-golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
-golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
+golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
+golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
diff --git a/backend/internal/huma/handlers/version.go b/backend/internal/huma/handlers/version.go
index 2a5c6e3d5..1bbec33d8 100644
--- a/backend/internal/huma/handlers/version.go
+++ b/backend/internal/huma/handlers/version.go
@@ -70,15 +70,10 @@ func (h *VersionHandler) GetVersion(ctx context.Context, input *GetVersionInput)
}
current := strings.TrimSpace(input.Current)
- info, _ := h.versionService.GetVersionInformation(ctx, current)
+ check, _ := h.versionService.GetVersionInformation(ctx, current)
return &GetVersionOutput{
- Body: version.Check{
- CurrentVersion: info.CurrentVersion,
- NewestVersion: info.NewestVersion,
- UpdateAvailable: info.UpdateAvailable,
- ReleaseURL: info.ReleaseURL,
- },
+ Body: *check,
}, nil
}
diff --git a/backend/internal/services/system_service.go b/backend/internal/services/system_service.go
index ca12305fb..d1ee36366 100644
--- a/backend/internal/services/system_service.go
+++ b/backend/internal/services/system_service.go
@@ -13,6 +13,7 @@ import (
"github.com/docker/docker/api/types/filters"
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/arcaneupdater"
"github.com/getarcaneapp/arcane/backend/internal/utils/converter"
containertypes "github.com/getarcaneapp/arcane/types/container"
"github.com/getarcaneapp/arcane/types/system"
@@ -253,8 +254,8 @@ func (s *SystemService) StopAllContainers(ctx context.Context) (*containertypes.
return s.performBatchContainerAction(ctx, containers, "stop",
func(c container.Summary) bool {
- // Skip Arcane server container
- return c.Labels == nil || c.Labels["com.getarcaneapp.arcane.server"] != "true"
+ // Skip Arcane container
+ return !arcaneupdater.IsArcaneContainer(c.Labels)
},
func(ctx context.Context, id string) error {
return s.containerService.StopContainer(ctx, id, systemUser)
diff --git a/backend/internal/services/system_upgrade_service.go b/backend/internal/services/system_upgrade_service.go
index 01028a4b5..fbf5dd853 100644
--- a/backend/internal/services/system_upgrade_service.go
+++ b/backend/internal/services/system_upgrade_service.go
@@ -14,7 +14,10 @@ import (
containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
imagetypes "github.com/docker/docker/api/types/image"
+ mounttypes "github.com/docker/docker/api/types/mount"
"github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/utils"
+ dockerutils "github.com/getarcaneapp/arcane/backend/internal/utils/docker"
)
var (
@@ -22,6 +25,7 @@ var (
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")
+ ArcaneUpgraderImage = "ghcr.io/getarcaneapp/arcane:latest"
)
type SystemUpgradeService struct {
@@ -98,10 +102,16 @@ func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user mo
slog.Warn("Failed to log upgrade event", "error", err)
}
- // Use latest tag for the upgrader CLI container
- upgraderImage := "ghcr.io/getarcaneapp/arcane:latest"
+ // Use the same image reference as the currently running Arcane container for the upgrader.
+ // This avoids mismatches where a newer/older upgrader CLI expects different behavior.
+ if currentContainer.Config != nil {
+ if img := strings.TrimSpace(currentContainer.Config.Image); img != "" {
+ ArcaneUpgraderImage = img
+ }
+ }
+ slog.Debug("Using upgrader image", "image", ArcaneUpgraderImage)
- slog.Info("Spawning upgrade CLI command", "containerName", containerName, "upgraderImage", upgraderImage)
+ slog.Info("Spawning upgrade CLI command", "containerName", containerName, "upgraderImage", ArcaneUpgraderImage)
// Spawn the upgrade command in a detached container
// This will run independently of the current container
@@ -111,27 +121,49 @@ func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user mo
}
// Pull the upgrader image first to ensure it exists
- slog.Info("Pulling upgrader image", "image", upgraderImage)
- pullReader, err := dockerClient.ImagePull(ctx, upgraderImage, imagetypes.PullOptions{})
+ slog.Info("Pulling upgrader image", "image", ArcaneUpgraderImage)
+ pullReader, err := dockerClient.ImagePull(ctx, ArcaneUpgraderImage, imagetypes.PullOptions{})
if err != nil {
return fmt.Errorf("pull upgrader image: %w", err)
}
// Drain the reader to complete the pull
_, _ = io.Copy(io.Discard, pullReader)
pullReader.Close()
- slog.Info("Upgrader image pulled successfully", "image", upgraderImage)
+ slog.Info("Upgrader image pulled successfully", "image", ArcaneUpgraderImage)
+
+ // Try to get the /app/data mount from current container so upgrade logs persist.
+ appDataMount := dockerutils.MountForDestination(currentContainer.Mounts, "/app/data", "/app/data")
+ if appDataMount == nil {
+ slog.Warn("Could not detect /app/data mount; upgrader logs may not persist")
+ } else {
+ slog.Debug("Mounting /app/data into upgrader container", "type", appDataMount.Type, "source", appDataMount.Source)
+ }
// Create the upgrader container config
config := &containertypes.Config{
- Image: upgraderImage,
+ Image: ArcaneUpgraderImage,
Cmd: []string{"/app/arcane", "upgrade", "--container", containerName},
+ Labels: map[string]string{
+ "com.getarcaneapp.arcane.upgrader": "true",
+ "com.getarcaneapp.arcane": "true",
+ },
+ }
+
+ mounts := []mounttypes.Mount{
+ {Type: mounttypes.TypeBind, Source: "/var/run/docker.sock", Target: "/var/run/docker.sock"},
+ }
+ if appDataMount != nil {
+ mounts = append(mounts, *appDataMount)
+ }
+
+ keepUpgraderContainer := strings.EqualFold(strings.TrimSpace(os.Getenv("ARCANE_UPGRADE_KEEP_CONTAINER")), "true")
+ if keepUpgraderContainer {
+ slog.Info("Keeping upgrader container after exit (ARCANE_UPGRADE_KEEP_CONTAINER=true)")
}
hostConfig := &containertypes.HostConfig{
- AutoRemove: true, // Clean up after completion
- Binds: []string{
- "/var/run/docker.sock:/var/run/docker.sock",
- },
+ AutoRemove: !keepUpgraderContainer, // default: clean up after completion
+ Mounts: mounts,
}
containerName = fmt.Sprintf("%s-upgrader-%d", containerName, time.Now().Unix())
@@ -154,82 +186,11 @@ func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user mo
// 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")
+ id, err := utils.GetCurrentContainerID()
if err != nil {
- return "", err
+ return "", ErrNotRunningInDocker
}
-
- 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")
+ return id, nil
}
// findArcaneContainer finds the container using the ID
diff --git a/backend/internal/services/updater_service.go b/backend/internal/services/updater_service.go
index c160f2eee..341745a9b 100644
--- a/backend/internal/services/updater_service.go
+++ b/backend/internal/services/updater_service.go
@@ -13,9 +13,11 @@ import (
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
- "github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/database"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/arcaneupdater"
+ arcRegistry "github.com/getarcaneapp/arcane/backend/internal/utils/registry"
"github.com/getarcaneapp/arcane/types/updater"
)
@@ -89,12 +91,10 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, dryRun bool) (*update
oldRef string
newRef string
oldIDs []string // sha256:... image IDs that currently back oldRef
+ pulled bool
}
var plans []updatePlan
- // track all old image IDs we saw so we can prune them after restart
- oldIDSet := map[string]struct{}{}
-
for _, r := range records {
if r.Repository == "" || r.Tag == "" {
continue
@@ -114,11 +114,6 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, dryRun bool) (*update
}
oldIDs, _ := s.resolveLocalImageIDsForRef(ctx, oldRef)
- for _, id := range oldIDs {
- if id != "" {
- oldIDSet[id] = struct{}{}
- }
- }
plans = append(plans, updatePlan{oldRef: oldRef, newRef: newRef, oldIDs: oldIDs})
}
@@ -135,20 +130,28 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, dryRun bool) (*update
"time": time.Now().UTC().Format(time.RFC3339),
})
- // Build maps for fast matching later
- oldRefToNewRef := map[string]string{}
- oldIDToNewRef := map[string]string{} // sha256 -> newRef
- for _, p := range plans {
- oldRefToNewRef[p.oldRef] = p.newRef
- for _, id := range p.oldIDs {
- oldIDToNewRef[id] = p.newRef
+ // Pull images with ImageService (waits for completion)
+ // Only containers using the OLD image IDs will be restarted after pulls succeed.
+ // This prevents restarts when pulls fail or when the image digest didn't change.
+ dcli, err := s.dockerService.GetClient()
+ if err != nil {
+ return nil, fmt.Errorf("docker connect: %w", err)
+ }
+ registryClient := arcRegistry.NewClient()
+ digestChecker := arcaneupdater.NewDigestChecker(dcli, registryClient)
+
+ enabledRegs := []models.ContainerRegistry{}
+ if s.registryService != nil {
+ if regs, rerr := s.registryService.GetEnabledRegistries(ctx); rerr == nil {
+ enabledRegs = regs
}
}
- // Pull images with ImageService (waits for completion)
- newImageIDs := map[string][]string{} // newRef -> []imageIDs after pull
+ // track all old image IDs we saw for pulled updates so we can prune them after restart
+ oldIDSet := map[string]struct{}{}
- for _, p := range plans {
+ for i := range plans {
+ p := plans[i]
item := updater.ResourceResult{
ResourceID: p.oldRef,
ResourceType: "image",
@@ -175,6 +178,32 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, dryRun bool) (*update
continue
}
+ // Digest pre-check: if registry supports it and digests match, avoid pulling entirely.
+ // This also prevents unnecessary restarts when the update record is stale.
+ normNew := s.normalizeRef(p.newRef)
+ host, repo, tag := s.parseNormalizedRef(normNew)
+ authHeader, _, _, _ := arcRegistry.ResolveAuthHeaderForRepository(ctx, host, repo, tag, enabledRegs)
+ check := digestChecker.CheckImageNeedsUpdate(ctx, normNew, authHeader)
+ if check.CheckedViaAPI && check.Error == nil && !check.NeedsUpdate {
+ item.Status = "skipped"
+ item.Error = "image already up to date"
+ out.Skipped++
+ out.Items = append(out.Items, item)
+ _ = s.recordRun(ctx, item)
+
+ s.logAutoUpdate(ctx, s.severityFromStatus(item.Status), models.JSON{
+ "phase": "image_pull",
+ "imageOld": p.oldRef,
+ "imageNew": p.newRef,
+ "status": item.Status,
+ "digestLocal": check.LocalDigest,
+ "digestRemote": check.RemoteDigest,
+ "checkedViaApi": true,
+ "error": item.Error,
+ })
+ continue
+ }
+
if err := s.imageService.PullImage(ctx, p.newRef, io.Discard, systemUser, nil); err != nil {
item.Status = "failed"
item.Error = err.Error()
@@ -183,13 +212,10 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, dryRun bool) (*update
item.Status = "updated"
item.UpdateApplied = true
out.Updated++
- newIDs, _ := s.resolveLocalImageIDsForRef(ctx, p.newRef)
- if len(newIDs) > 0 {
- newImageIDs[p.newRef] = newIDs
- for _, newID := range newIDs {
- if newID != "" {
- oldIDToNewRef[newID] = p.newRef
- }
+ plans[i].pulled = true
+ for _, id := range p.oldIDs {
+ if id != "" {
+ oldIDSet[id] = struct{}{}
}
}
}
@@ -205,7 +231,22 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, dryRun bool) (*update
})
}
- if !dryRun && len(oldIDToNewRef) > 0 {
+ // Build maps for fast matching later (only for successfully pulled updates)
+ oldRefToNewRef := map[string]string{}
+ oldIDToNewRef := map[string]string{} // sha256 -> newRef
+ for _, p := range plans {
+ if !p.pulled {
+ continue
+ }
+ oldRefToNewRef[p.oldRef] = p.newRef
+ for _, id := range p.oldIDs {
+ if id != "" {
+ oldIDToNewRef[id] = p.newRef
+ }
+ }
+ }
+
+ if !dryRun && (len(oldIDToNewRef) > 0 || len(oldRefToNewRef) > 0) {
results, err := s.restartContainersUsingOldIDs(ctx, oldIDToNewRef, oldRefToNewRef)
if err != nil {
slog.Warn("container restarts had errors", "err", err)
@@ -245,7 +286,7 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, dryRun bool) (*update
}
}
- // Prune old images that are no longer used
+ // Prune old images that are no longer used (only for images that were actually updated)
if !dryRun && len(oldIDSet) > 0 {
ids := make([]string, 0, len(oldIDSet))
for id := range oldIDSet {
@@ -328,6 +369,39 @@ func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerID
containerName := s.getContainerName(*targetContainer)
+ // Inspect container to get full config (needed for label-based controls)
+ inspectBefore, err := dcli.ContainerInspect(ctx, targetContainer.ID)
+ if err != nil {
+ out.Items = append(out.Items, updater.ResourceResult{
+ ResourceID: targetContainer.ID,
+ ResourceType: "container",
+ ResourceName: containerName,
+ Status: "failed",
+ Error: fmt.Sprintf("inspect failed: %v", err),
+ })
+ out.Failed++
+ out.Duration = time.Since(start).String()
+ return out, nil
+ }
+
+ labels := map[string]string{}
+ if inspectBefore.Config != nil && inspectBefore.Config.Labels != nil {
+ labels = inspectBefore.Config.Labels
+ }
+ if arcaneupdater.IsUpdateDisabled(labels) {
+ out.Items = append(out.Items, updater.ResourceResult{
+ ResourceID: targetContainer.ID,
+ ResourceType: "container",
+ ResourceName: containerName,
+ Status: "skipped",
+ Error: "updates disabled by label",
+ })
+ out.Skipped++
+ out.Checked = 1
+ out.Duration = time.Since(start).String()
+ return out, nil
+ }
+
// Get the image reference
imageRef := targetContainer.Image
normalizedRef := s.normalizeRef(imageRef)
@@ -362,21 +436,25 @@ func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerID
return out, nil
}
- // Inspect container to get full config
- inspect, err := dcli.ContainerInspect(ctx, targetContainer.ID)
- if err != nil {
+ // Compare with pulled image to avoid unnecessary restart
+ checker := arcaneupdater.NewDigestChecker(dcli, arcRegistry.NewClient())
+ changed, cmpErr := checker.CompareWithPulled(ctx, inspectBefore.Image, normalizedRef)
+ if cmpErr == nil && !changed {
out.Items = append(out.Items, updater.ResourceResult{
ResourceID: targetContainer.ID,
ResourceType: "container",
ResourceName: containerName,
- Status: "failed",
- Error: fmt.Sprintf("inspect failed: %v", err),
+ Status: "skipped",
+ Error: "image digest unchanged after pull",
})
- out.Failed++
+ out.Skipped++
+ out.Checked = 1
out.Duration = time.Since(start).String()
return out, nil
}
+ inspect := inspectBefore
+
// Update the container
if err := s.updateContainer(ctx, *targetContainer, inspect, normalizedRef); err != nil {
out.Items = append(out.Items, updater.ResourceResult{
@@ -488,6 +566,7 @@ func (s *UpdaterService) GetHistory(ctx context.Context, limit int) ([]models.Au
// --- internals ---
+//nolint:gocognit
func (s *UpdaterService) updateContainer(ctx context.Context, cnt container.Summary, inspect container.InspectResponse, newRef string) error {
dcli, err := s.dockerService.GetClient()
if err != nil {
@@ -495,21 +574,70 @@ func (s *UpdaterService) updateContainer(ctx context.Context, cnt container.Summ
}
name := s.getContainerName(cnt)
- slog.DebugContext(ctx, "updateContainer: starting update", "containerId", cnt.ID, "containerName", name, "newRef", newRef)
+ labels := inspect.Config.Labels
+ isArcane := arcaneupdater.IsArcaneContainer(labels)
+ var selfUpdate *arcaneupdater.SelfUpdate
+ if isArcane {
+ selfUpdate = arcaneupdater.NewSelfUpdate(dcli)
+ if ok, ierr := selfUpdate.IsArcaneContainerByID(ctx, cnt.ID); ierr != nil {
+ slog.WarnContext(ctx, "updateContainer: failed to verify Arcane container by ID", "containerId", cnt.ID, "error", ierr.Error())
+ } else if !ok {
+ // Keep behavior label-driven, but log the inconsistency.
+ slog.WarnContext(ctx, "updateContainer: label indicated Arcane container but ID verification did not", "containerId", cnt.ID, "containerName", name)
+ }
+ }
+
+ slog.DebugContext(ctx, "updateContainer: starting update", "containerId", cnt.ID, "containerName", name, "newRef", newRef, "isArcane", isArcane)
- // stop
- if err := dcli.ContainerStop(ctx, cnt.ID, container.StopOptions{}); err != nil {
- slog.DebugContext(ctx, "updateContainer: stop failed", "containerId", cnt.ID, "err", err)
- return fmt.Errorf("stop: %w", err)
+ // Execute pre-update lifecycle hook (skip for Arcane self-update)
+ if !isArcane {
+ hookResult := arcaneupdater.ExecutePreUpdateCommand(ctx, dcli, cnt.ID, labels)
+ if hookResult.Executed {
+ if hookResult.SkipUpdate {
+ slog.InfoContext(ctx, "updateContainer: container requested skip via pre-update hook", "containerId", cnt.ID, "containerName", name)
+ return fmt.Errorf("container requested skip update via exit code %d", arcaneupdater.ExitCodeSkipUpdate)
+ }
+ if hookResult.Error != nil {
+ slog.WarnContext(ctx, "updateContainer: pre-update hook failed", "containerId", cnt.ID, "err", hookResult.Error)
+ // Continue with update despite hook failure (configurable in future)
+ }
+ }
+ }
+
+ // For Arcane self-update: rename the old container so new one can use the same name
+ originalName := inspect.Name
+ if isArcane {
+ tempName, renameErr := selfUpdate.PrepareForSelfUpdate(ctx, cnt.ID, originalName)
+ if renameErr != nil {
+ slog.WarnContext(ctx, "updateContainer: failed to rename Arcane container for self-update", "err", renameErr)
+ return fmt.Errorf("cannot proceed with self-update without renaming old container: %w", renameErr)
+ }
+ slog.InfoContext(ctx, "updateContainer: renamed Arcane container for self-update", "oldName", originalName, "tempName", tempName)
}
- _ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerStop, cnt.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{"action": "updater_stop"})
- // remove
- if err := dcli.ContainerRemove(ctx, cnt.ID, container.RemoveOptions{}); err != nil {
- slog.DebugContext(ctx, "updateContainer: remove failed", "containerId", cnt.ID, "err", err)
- return fmt.Errorf("remove: %w", err)
+ // Get custom stop signal if configured
+ stopSignal := arcaneupdater.GetStopSignal(labels)
+ stopOpts := container.StopOptions{}
+ if stopSignal != "" {
+ stopOpts.Signal = stopSignal
+ slog.DebugContext(ctx, "updateContainer: using custom stop signal", "signal", stopSignal)
+ }
+
+ // stop (skip for Arcane - it will be stopped after new one starts)
+ if !isArcane {
+ if err := dcli.ContainerStop(ctx, cnt.ID, stopOpts); err != nil {
+ slog.DebugContext(ctx, "updateContainer: stop failed", "containerId", cnt.ID, "err", err)
+ return fmt.Errorf("stop: %w", err)
+ }
+ _ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerStop, cnt.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{"action": "updater_stop"})
+
+ // remove
+ if err := dcli.ContainerRemove(ctx, cnt.ID, container.RemoveOptions{}); err != nil {
+ slog.DebugContext(ctx, "updateContainer: remove failed", "containerId", cnt.ID, "err", err)
+ return fmt.Errorf("remove: %w", err)
+ }
+ _ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerDelete, cnt.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{"action": "updater_delete"})
}
- _ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerDelete, cnt.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{"action": "updater_delete"})
// recreate with new image ref
cfg := inspect.Config
@@ -536,9 +664,12 @@ func (s *UpdaterService) updateContainer(ctx context.Context, cnt container.Summ
networkingConfig = &network.NetworkingConfig{EndpointsConfig: inspect.NetworkSettings.Networks}
}
- resp, err := dcli.ContainerCreate(ctx, cfg, inspect.HostConfig, networkingConfig, nil, inspect.Name)
+ // Use original name for new container
+ containerName := strings.TrimPrefix(originalName, "/")
+
+ resp, err := dcli.ContainerCreate(ctx, cfg, inspect.HostConfig, networkingConfig, nil, containerName)
if err != nil {
- slog.DebugContext(ctx, "updateContainer: create failed", "containerName", inspect.Name, "err", err)
+ slog.DebugContext(ctx, "updateContainer: create failed", "containerName", containerName, "err", err)
return fmt.Errorf("create: %w", err)
}
_ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerCreate, resp.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{"action": "updater_create", "newImageId": resp.ID})
@@ -549,6 +680,35 @@ func (s *UpdaterService) updateContainer(ctx context.Context, cnt container.Summ
}
_ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerStart, resp.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{"action": "updater_start"})
+ // For Arcane self-update: now stop and remove the old container
+ if isArcane {
+ slog.InfoContext(ctx, "updateContainer: Arcane self-update - stopping old container", "oldContainerId", cnt.ID)
+ _ = dcli.ContainerStop(ctx, cnt.ID, container.StopOptions{})
+ _ = dcli.ContainerRemove(ctx, cnt.ID, container.RemoveOptions{Force: true})
+
+ // Best-effort cleanup of any leftover arcane-old-* containers from prior self-updates.
+ if selfUpdate != nil {
+ if removed, cerr := selfUpdate.CleanupOldArcaneInstances(ctx, false); cerr != nil {
+ slog.DebugContext(ctx, "updateContainer: CleanupOldArcaneInstances failed", "error", cerr.Error())
+ } else if len(removed) > 0 {
+ slog.InfoContext(ctx, "updateContainer: cleaned up old Arcane instances", "count", len(removed))
+ }
+
+ if cur, gerr := selfUpdate.GetCurrentArcaneContainer(ctx); gerr == nil && cur != nil {
+ slog.InfoContext(ctx, "updateContainer: current Arcane container after self-update", "containerId", cur.ID, "name", arcaneupdater.ExtractContainerName(*cur))
+ }
+ }
+ }
+
+ // Execute post-update lifecycle hook on the new container
+ if !isArcane {
+ hookResult := arcaneupdater.ExecutePostUpdateCommand(ctx, dcli, resp.ID, labels)
+ if hookResult.Executed && hookResult.Error != nil {
+ slog.WarnContext(ctx, "updateContainer: post-update hook failed", "newContainerId", resp.ID, "err", hookResult.Error)
+ // Log but don't fail the update
+ }
+ }
+
_ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerUpdate, resp.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{
"oldContainerId": cnt.ID,
"newContainerId": resp.ID,
@@ -602,27 +762,6 @@ func (s *UpdaterService) stripDigest(ref string) string {
return ref
}
-const arcaneUpdaterLabel = "com.getarcaneapp.arcane.updater"
-
-// isUpdateDisabled returns true if the special label is present and evaluates to false.
-// Accepts false/0/no/off (case-insensitive) as "disabled". Default is enabled.
-func (s *UpdaterService) isUpdateDisabled(labels map[string]string) bool {
- if labels == nil {
- return false
- }
- for k, v := range labels {
- if strings.EqualFold(k, arcaneUpdaterLabel) {
- switch strings.TrimSpace(strings.ToLower(v)) {
- case "false", "0", "no", "off":
- return true
- default:
- return false
- }
- }
- }
- return false
-}
-
// collectUsedImagesFromContainers adds normalized image tags from non-opted-out running containers.
func (s *UpdaterService) collectUsedImagesFromContainers(ctx context.Context, dcli *client.Client, out map[string]struct{}) error {
if dcli == nil {
@@ -634,7 +773,7 @@ func (s *UpdaterService) collectUsedImagesFromContainers(ctx context.Context, dc
}
slog.DebugContext(ctx, "collectUsedImagesFromContainers: container list fetched", "count", len(list))
for _, c := range list {
- if s.isUpdateDisabled(c.Labels) {
+ if arcaneupdater.IsUpdateDisabled(c.Labels) {
slog.DebugContext(ctx, "collectUsedImagesFromContainers: container opted out by labels", "containerId", c.ID)
continue
}
@@ -643,7 +782,7 @@ func (s *UpdaterService) collectUsedImagesFromContainers(ctx context.Context, dc
slog.DebugContext(ctx, "collectUsedImagesFromContainers: container inspect failed", "containerId", c.ID, "err", err)
continue
}
- if inspect.Config != nil && s.isUpdateDisabled(inspect.Config.Labels) {
+ if inspect.Config != nil && arcaneupdater.IsUpdateDisabled(inspect.Config.Labels) {
slog.DebugContext(ctx, "collectUsedImagesFromContainers: container inspect labels opted out", "containerId", c.ID)
continue
}
@@ -654,22 +793,6 @@ func (s *UpdaterService) collectUsedImagesFromContainers(ctx context.Context, dc
return nil
}
-func (s *UpdaterService) isProjectOptedOut(ctx context.Context, dcli *client.Client, projectName string) bool {
- if dcli == nil {
- return false
- }
- containers, err := s.getProjectContainers(ctx, dcli, projectName)
- if err != nil {
- return false
- }
- for _, c := range containers {
- if s.isUpdateDisabled(c.Labels) {
- return true
- }
- }
- return false
-}
-
// Aggregate images in use across containers and compose projects
func (s *UpdaterService) collectUsedImages(ctx context.Context) (map[string]struct{}, error) {
out := map[string]struct{}{}
@@ -683,13 +806,13 @@ func (s *UpdaterService) collectUsedImages(ctx context.Context) (map[string]stru
}
_ = s.collectUsedImagesFromContainers(ctx, dcli, out)
- _ = s.collectUsedImagesFromProjects(ctx, dcli, out)
+ _ = s.collectUsedImagesFromProjects(ctx, out)
slog.DebugContext(ctx, "collectUsedImages: collected used images", "count", len(out))
return out, nil
}
-func (s *UpdaterService) collectUsedImagesFromProjects(ctx context.Context, dcli *client.Client, out map[string]struct{}) error {
+func (s *UpdaterService) collectUsedImagesFromProjects(ctx context.Context, out map[string]struct{}) error {
if s.projectService == nil {
return nil
}
@@ -704,16 +827,15 @@ func (s *UpdaterService) collectUsedImagesFromProjects(ctx context.Context, dcli
if p.Status != models.ProjectStatusRunning && p.Status != models.ProjectStatusPartiallyRunning {
continue
}
- // optional opt-out via labels on compose project
- if dcli != nil && s.isProjectOptedOut(ctx, dcli, p.Name) {
- continue
- }
services, serr := s.projectService.GetProjectServices(ctx, p.ID)
if serr != nil {
continue
}
for _, svc := range services {
+ if svc.ServiceConfig != nil && arcaneupdater.IsUpdateDisabled(svc.ServiceConfig.Labels) {
+ continue
+ }
img := strings.TrimSpace(svc.Image)
if img == "" {
continue
@@ -811,14 +933,16 @@ func (s *UpdaterService) resolveLocalImageIDsForRef(ctx context.Context, ref str
return nil, err
}
- ids := []string{}
- if ii, err := dcli.ImageInspect(ctx, ref); err == nil && ii.ID != "" {
- ids = append(ids, ii.ID)
+ checker := arcaneupdater.NewDigestChecker(dcli, arcRegistry.NewClient())
+ ids, err := checker.GetImageIDsForRef(ctx, ref)
+ if err != nil {
+ return nil, err
}
slog.DebugContext(ctx, "resolveLocalImageIDsForRef: resolved ids", "ref", ref, "ids", ids)
return ids, nil
}
+//nolint:gocognit
func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldIDToNewRef map[string]string, oldRefToNewRef map[string]string) ([]updater.ResourceResult, error) {
dcli, err := s.dockerService.GetClient()
if err != nil {
@@ -831,22 +955,48 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldID
}
slog.DebugContext(ctx, "restartContainersUsingOldIDs: scanning containers for matching images", "containers", len(list), "oldIDMatches", len(oldIDToNewRef), "oldRefMatches", len(oldRefToNewRef))
- var results []updater.ResourceResult
- for _, c := range list {
- // Skip containers with opt-out label
- if s.isUpdateDisabled(c.Labels) {
- continue
- }
+ updatedNorm := map[string]string{}
+ for oldRef, nr := range oldRefToNewRef {
+ updatedNorm[s.normalizeRef(oldRef)] = nr
+ }
+
+ type restartPlan struct {
+ cnt container.Summary
+ inspect container.InspectResponse
+ newRef string
+ match string
+ explicit bool
+ implicit bool
+ }
+
+ plansByName := map[string]*restartPlan{}
+ markedForRestart := map[string]bool{}
+ containersWithDeps := make([]arcaneupdater.ContainerWithDeps, 0, len(list))
+ for _, c := range list {
inspect, err := dcli.ContainerInspect(ctx, c.ID)
if err != nil {
continue
}
- // Also honor labels from full inspect
- if inspect.Config != nil && s.isUpdateDisabled(inspect.Config.Labels) {
+
+ labels := c.Labels
+ if inspect.Config != nil && inspect.Config.Labels != nil {
+ labels = inspect.Config.Labels
+ }
+
+ // Skip containers with opt-out label
+ if arcaneupdater.IsUpdateDisabled(labels) {
continue
}
+ // Ensure labels map exists to avoid nil panics in implicit restart marking
+ if c.Labels == nil {
+ c.Labels = map[string]string{}
+ }
+
+ dep := arcaneupdater.ExtractContainerDeps(ctx, dcli, c, inspect)
+ containersWithDeps = append(containersWithDeps, dep)
+
var (
newRef string
match string
@@ -858,10 +1008,6 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldID
match = inspect.Image
} else {
// Fallback: resolve tags and match by tag
- updatedNorm := map[string]string{}
- for oldRef, nr := range oldRefToNewRef {
- updatedNorm[s.normalizeRef(oldRef)] = nr
- }
for _, t := range s.getNormalizedTagsForContainer(ctx, dcli, inspect) {
if nr, ok := updatedNorm[t]; ok {
newRef = nr
@@ -869,37 +1015,118 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldID
break
}
}
- if newRef == "" {
- continue
+ }
+
+ p := &restartPlan{cnt: c, inspect: inspect, newRef: newRef, match: match, explicit: newRef != ""}
+ plansByName[dep.Name] = p
+ if p.explicit {
+ markedForRestart[dep.Name] = true
+ }
+ }
+
+ // Propagate implicit restarts: if a dependency is restarting, restart dependents too.
+ for {
+ added := arcaneupdater.UpdateImplicitRestart(containersWithDeps, markedForRestart)
+ if len(added) == 0 {
+ break
+ }
+ for _, name := range added {
+ if p, ok := plansByName[name]; ok {
+ if p.newRef == "" {
+ if p.inspect.Config != nil {
+ p.newRef = strings.TrimSpace(p.inspect.Config.Image)
+ }
+ if p.newRef == "" {
+ p.newRef = p.cnt.Image
+ }
+ p.match = "dependency_restart"
+ p.implicit = true
+ }
}
}
+ }
+
+ // Build the set of containers that will be restarted and sort them by dependency order.
+ candidates := make([]arcaneupdater.ContainerWithDeps, 0, len(containersWithDeps))
+ for _, cd := range containersWithDeps {
+ if markedForRestart[cd.Name] {
+ candidates = append(candidates, cd)
+ }
+ }
+
+ sorter := arcaneupdater.NewContainerSorter(candidates)
+ sorted, sortErr := sorter.Sort()
+ _, _ = sorter.SortReverse() // keep method used; reverse order may be useful for future stop-first flows
+ if sortErr != nil {
+ slog.WarnContext(ctx, "restartContainersUsingOldIDs: dependency sort failed, falling back to unsorted order", "error", sortErr.Error())
+ sorted = candidates
+ }
+
+ var results []updater.ResourceResult
+ for _, cd := range sorted {
+ p := plansByName[cd.Name]
+ if p == nil {
+ continue
+ }
- slog.DebugContext(ctx, "restartContainersUsingOldIDs: matched container for update", "containerId", c.ID, "match", match, "newRef", newRef)
+ name := cd.Name
+ labels := map[string]string{}
+ if p.inspect.Config != nil && p.inspect.Config.Labels != nil {
+ labels = p.inspect.Config.Labels
+ }
- name := s.getContainerName(c)
res := updater.ResourceResult{
- ResourceID: c.ID,
+ ResourceID: p.cnt.ID,
ResourceName: name,
ResourceType: "container",
Status: "checked",
- OldImages: map[string]string{"main": match},
- NewImages: map[string]string{"main": s.normalizeRef(newRef)},
+ OldImages: map[string]string{"main": p.match},
+ NewImages: map[string]string{"main": s.normalizeRef(p.newRef)},
+ }
+
+ // Lifecycle hooks for "check" phase (best-effort)
+ if !arcaneupdater.IsArcaneContainer(labels) {
+ pre := arcaneupdater.ExecutePreCheckCommand(ctx, dcli, p.cnt.ID, labels)
+ if pre.Executed {
+ if pre.SkipUpdate {
+ res.Status = "skipped"
+ res.Error = fmt.Sprintf("container requested skip via pre-check hook (exit %d)", arcaneupdater.ExitCodeSkipUpdate)
+ results = append(results, res)
+ continue
+ }
+ if pre.Error != nil {
+ slog.WarnContext(ctx, "restartContainersUsingOldIDs: pre-check hook failed", "container", name, "error", pre.Error.Error())
+ }
+ }
+ post := arcaneupdater.ExecutePostCheckCommand(ctx, dcli, p.cnt.ID, labels)
+ if post.Executed && post.Error != nil {
+ slog.WarnContext(ctx, "restartContainersUsingOldIDs: post-check hook failed", "container", name, "error", post.Error.Error())
+ }
+ }
+
+ if p.newRef == "" {
+ res.Status = "skipped"
+ res.Error = "no matching updated image"
+ results = append(results, res)
+ continue
}
- if err := s.updateContainer(ctx, c, inspect, newRef); err != nil {
+ slog.DebugContext(ctx, "restartContainersUsingOldIDs: restarting container", "containerId", p.cnt.ID, "container", name, "match", p.match, "newRef", p.newRef, "implicit", p.implicit)
+
+ if err := s.updateContainer(ctx, p.cnt, p.inspect, p.newRef); err != nil {
res.Status = "failed"
res.Error = err.Error()
- slog.DebugContext(ctx, "restartContainersUsingOldIDs: update failed", "containerId", c.ID, "err", err)
+ slog.DebugContext(ctx, "restartContainersUsingOldIDs: update failed", "containerId", p.cnt.ID, "err", err)
} else {
res.Status = "updated"
res.UpdateAvailable = true
res.UpdateApplied = true
- slog.DebugContext(ctx, "restartContainersUsingOldIDs: update succeeded", "containerId", c.ID)
+ slog.DebugContext(ctx, "restartContainersUsingOldIDs: update succeeded", "containerId", p.cnt.ID)
// Send notification after successful container update
if s.notificationService != nil {
- if notifErr := s.notificationService.SendContainerUpdateNotification(ctx, name, newRef, match, s.normalizeRef(newRef)); notifErr != nil {
- slog.WarnContext(ctx, "Failed to send container update notification", "containerId", c.ID, "containerName", name, "imageRef", newRef, "error", notifErr.Error())
+ if notifErr := s.notificationService.SendContainerUpdateNotification(ctx, name, p.newRef, p.match, s.normalizeRef(p.newRef)); notifErr != nil {
+ slog.WarnContext(ctx, "Failed to send container update notification", "containerId", p.cnt.ID, "containerName", name, "imageRef", p.newRef, "error", notifErr.Error())
}
}
}
@@ -909,28 +1136,23 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldID
return results, nil
}
-func (s *UpdaterService) getProjectContainers(ctx context.Context, dcli *client.Client, projectName string) ([]container.Summary, error) {
- byID := map[string]container.Summary{}
-
- // Compose label
- f1 := filters.NewArgs()
- f1.Add("label", "com.docker.compose.project="+projectName)
- cs1, err := dcli.ContainerList(ctx, container.ListOptions{All: true, Filters: f1})
- if err == nil {
- for _, c := range cs1 {
- byID[c.ID] = c
- }
- }
-
- if err != nil {
- return nil, err
- }
-
- out := make([]container.Summary, 0, len(byID))
- for _, c := range byID {
- out = append(out, c)
+// parseNormalizedRef expects a normalized ref in the form "host/repository:tag".
+func (s *UpdaterService) parseNormalizedRef(ref string) (host, repository, tag string) {
+ // host/repo:tag
+ parts := strings.SplitN(ref, "/", 2)
+ if len(parts) != 2 {
+ return "", "", ""
+ }
+ host = parts[0]
+ rest := parts[1]
+ tag = "latest"
+ if i := strings.LastIndex(rest, ":"); i != -1 && strings.LastIndex(rest, "/") < i {
+ tag = rest[i+1:]
+ repository = rest[:i]
+ } else {
+ repository = rest
}
- return out, nil
+ return host, repository, tag
}
func (s *UpdaterService) logAutoUpdate(ctx context.Context, sev models.EventSeverity, metadata models.JSON) {
diff --git a/backend/internal/services/version_service.go b/backend/internal/services/version_service.go
index 9a60b29ea..0761b5cea 100644
--- a/backend/internal/services/version_service.go
+++ b/backend/internal/services/version_service.go
@@ -7,14 +7,19 @@ import (
"fmt"
"log/slog"
"net/http"
- "os"
"strings"
"time"
+ containertypes "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/api/types/filters"
+ "github.com/docker/docker/client"
"github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/arcaneupdater"
"github.com/getarcaneapp/arcane/backend/internal/utils/cache"
"github.com/getarcaneapp/arcane/types/version"
ref "go.podman.io/image/v5/docker/reference"
+ "golang.org/x/mod/semver"
)
const (
@@ -91,17 +96,37 @@ func (s *VersionService) GetLatestVersion(ctx context.Context) (string, error) {
}
func (s *VersionService) IsNewer(latest, current string) bool {
- lp := parseSemver(latest)
- cp := parseSemver(current)
- for i := 0; i < 3; i++ {
- if lp[i] > cp[i] {
- return true
+ // Ensure both versions have 'v' prefix for semver package
+ latest = s.normalizeVersion(latest)
+ current = s.normalizeVersion(current)
+
+ // Use semver.Compare: returns 1 if latest > current
+ return semver.Compare(latest, current) > 0
+}
+
+// normalizeVersion ensures version has 'v' prefix and is valid semver format
+func (s *VersionService) normalizeVersion(ver string) string {
+ ver = strings.TrimSpace(ver)
+ if ver == "" {
+ return "v0.0.0"
+ }
+ if !strings.HasPrefix(ver, "v") {
+ ver = "v" + ver
+ }
+ // If not valid semver, try to make it valid
+ if !semver.IsValid(ver) {
+ // Extract just the numeric part before any suffix
+ if idx := strings.IndexAny(ver, "-+"); idx > 0 {
+ ver = ver[:idx]
}
- if lp[i] < cp[i] {
- return false
+ // Ensure at least v0.0.0 format
+ parts := strings.Split(strings.TrimPrefix(ver, "v"), ".")
+ for len(parts) < 3 {
+ parts = append(parts, "0")
}
+ ver = "v" + strings.Join(parts[:3], ".")
}
- return false
+ return ver
}
func (s *VersionService) ReleaseURL(version string) string {
@@ -116,29 +141,20 @@ func (s *VersionService) ReleaseURL(version string) string {
return "https://github.com/getarcaneapp/arcane/releases/tag/" + v
}
-type VersionInformation struct {
- CurrentVersion string `json:"currentVersion"`
- NewestVersion string `json:"newestVersion,omitempty"`
- UpdateAvailable bool `json:"updateAvailable"`
- ReleaseURL string `json:"releaseUrl,omitempty"`
-}
-
-func (s *VersionService) GetVersionInformation(ctx context.Context, currentVersion string) (*VersionInformation, error) {
+func (s *VersionService) GetVersionInformation(ctx context.Context, currentVersion string) (*version.Check, error) {
if currentVersion == "" {
currentVersion = s.version
}
- cur := strings.TrimSpace(currentVersion)
- if !strings.HasPrefix(cur, "v") && len(cur) > 0 && cur[0] >= '0' && cur[0] <= '9' {
- cur = "v" + cur
+ cur := s.normalizeVersion(currentVersion)
+
+ check := &version.Check{
+ CurrentVersion: cur,
+ ReleaseURL: s.ReleaseURL(""),
+ UpdateAvailable: false,
}
if s.disabled {
- return &VersionInformation{
- CurrentVersion: cur,
- NewestVersion: "",
- UpdateAvailable: false,
- ReleaseURL: s.ReleaseURL(""),
- }, nil
+ return check, nil
}
latest, err := s.GetLatestVersion(ctx)
@@ -147,47 +163,26 @@ func (s *VersionService) GetVersionInformation(ctx context.Context, currentVersi
if errors.As(err, &staleErr) {
slog.Warn("Failed to refresh latest version; using stale cache", "error", staleErr.Err)
} else {
- return &VersionInformation{
- CurrentVersion: cur,
- ReleaseURL: s.ReleaseURL(""),
- }, err
+ return check, err
}
}
- return &VersionInformation{
- CurrentVersion: cur,
- NewestVersion: latest,
- UpdateAvailable: s.IsNewer(latest, cur),
- ReleaseURL: s.ReleaseURL(latest),
- }, nil
+ if latest != "" {
+ check.NewestVersion = latest
+ check.UpdateAvailable = s.IsNewer(latest, cur)
+ check.ReleaseURL = s.ReleaseURL(latest)
+ }
+
+ return check, nil
}
// isSemverVersion checks if a version string is semver-based (e.g., v1.0.0)
func (s *VersionService) isSemverVersion() bool {
- version := strings.TrimPrefix(strings.TrimSpace(s.version), "v")
- parts := strings.Split(version, ".")
- if len(parts) < 3 {
- return false
- }
- for i := 0; i < 3; i++ {
- // Extract just the numeric part (ignoring suffixes like -alpha, +build)
- numPart := parts[i]
- if i == len(parts)-1 {
- // Last part might have additional info like "0-alpha" or "0+build"
- numPart = strings.FieldsFunc(numPart, func(r rune) bool {
- return r == '-' || r == '+'
- })[0]
- }
- if numPart == "" {
- return false
- }
- for _, c := range numPart {
- if c < '0' || c > '9' {
- return false
- }
- }
+ version := strings.TrimSpace(s.version)
+ if !strings.HasPrefix(version, "v") {
+ version = "v" + version
}
- return true
+ return semver.IsValid(version)
}
// getDisplayVersion formats the version for display purposes
@@ -206,125 +201,78 @@ func (s *VersionService) getDisplayVersion() string {
// GetAppVersionInfo returns application version information including display version
func (s *VersionService) GetAppVersionInfo(ctx context.Context) *version.Info {
- ver := strings.TrimSpace(s.version)
- if s.isSemverVersion() && !strings.HasPrefix(ver, "v") {
- ver = "v" + ver
- }
- displayVersion := s.getDisplayVersion()
isSemver := s.isSemverVersion()
+ ver := s.normalizeVersion(s.version)
- // Detect current container image tag, digest, and registry
+ // Always detect current image info
currentTag, currentDigest, currentImageRef := s.detectCurrentImageInfo(ctx)
- // Common fields for all responses
- shortRev := config.ShortRevision()
- goVer := config.GoVersion()
- buildTime := config.BuildTime
+ // Build base info struct (always populated)
+ info := &version.Info{
+ CurrentVersion: ver,
+ CurrentTag: currentTag,
+ CurrentDigest: currentDigest,
+ DisplayVersion: s.getDisplayVersion(),
+ Revision: s.revision,
+ ShortRevision: config.ShortRevision(),
+ GoVersion: config.GoVersion(),
+ BuildTime: config.BuildTime,
+ IsSemverVersion: isSemver,
+ UpdateAvailable: false,
+ }
+ // If update checks disabled, return base info
if s.disabled {
- return &version.Info{
- CurrentVersion: ver,
- CurrentTag: currentTag,
- CurrentDigest: currentDigest,
- DisplayVersion: displayVersion,
- Revision: s.revision,
- ShortRevision: shortRev,
- GoVersion: goVer,
- BuildTime: buildTime,
- IsSemverVersion: isSemver,
- UpdateAvailable: false,
- }
+ return info
}
// For semver versions, check GitHub releases
if isSemver {
latest, err := s.GetLatestVersion(ctx)
- if err != nil {
- var staleErr *cache.ErrStale
- if !errors.As(err, &staleErr) {
- return &version.Info{
- CurrentVersion: ver,
- CurrentTag: currentTag,
- CurrentDigest: currentDigest,
- DisplayVersion: displayVersion,
- Revision: s.revision,
- ShortRevision: shortRev,
- GoVersion: goVer,
- BuildTime: buildTime,
- IsSemverVersion: isSemver,
- }
+ var staleErr *cache.ErrStale
+ if err == nil || errors.As(err, &staleErr) {
+ if latest != "" {
+ info.NewestVersion = latest
+ info.UpdateAvailable = s.IsNewer(latest, ver)
+ info.ReleaseURL = s.ReleaseURL(latest)
}
- slog.Warn("Failed to refresh latest version; using stale cache", "error", staleErr.Err)
- }
-
- return &version.Info{
- CurrentVersion: ver,
- CurrentTag: currentTag,
- CurrentDigest: currentDigest,
- DisplayVersion: displayVersion,
- Revision: s.revision,
- ShortRevision: shortRev,
- GoVersion: goVer,
- BuildTime: buildTime,
- IsSemverVersion: isSemver,
- NewestVersion: latest,
- UpdateAvailable: s.IsNewer(latest, ver),
- ReleaseURL: s.ReleaseURL(latest),
}
+ return info
}
// For non-semver versions (like "next"), check digest-based updates
- if currentTag != "" && s.containerRegistryService != nil {
+ if currentTag != "" && currentDigest != "" && currentImageRef != "" && s.containerRegistryService != nil {
updateAvailable, latestDigest := s.checkDigestBasedUpdate(ctx, currentTag, currentDigest, currentImageRef)
- return &version.Info{
- CurrentVersion: ver,
- CurrentTag: currentTag,
- CurrentDigest: currentDigest,
- DisplayVersion: displayVersion,
- Revision: s.revision,
- ShortRevision: shortRev,
- GoVersion: goVer,
- BuildTime: buildTime,
- IsSemverVersion: isSemver,
- NewestDigest: latestDigest,
- UpdateAvailable: updateAvailable,
- }
+ info.UpdateAvailable = updateAvailable
+ info.NewestDigest = latestDigest
}
- return &version.Info{
- CurrentVersion: ver,
- CurrentTag: currentTag,
- CurrentDigest: currentDigest,
- DisplayVersion: displayVersion,
- Revision: s.revision,
- ShortRevision: shortRev,
- GoVersion: goVer,
- BuildTime: buildTime,
- IsSemverVersion: isSemver,
- UpdateAvailable: false,
- }
+ return info
}
// detectCurrentImageInfo attempts to detect the current container's image tag and digest
func (s *VersionService) detectCurrentImageInfo(ctx context.Context) (tag string, digest string, imageRef string) {
if s.dockerService == nil {
+ slog.Debug("detectCurrentImageInfo: dockerService is nil")
return "", "", ""
}
- // Try to get current container ID
- containerId, err := s.getCurrentContainerID()
+ dockerClient, err := s.dockerService.GetClient()
if err != nil {
+ slog.Debug("detectCurrentImageInfo: failed to get docker client", "error", err)
return "", "", ""
}
- // Connect to Docker and inspect the container
- dockerClient, err := s.dockerService.GetClient()
- if err != nil {
+ containerId := s.detectContainerID(ctx, dockerClient)
+ if containerId == "" {
+ slog.Debug("detectCurrentImageInfo: could not detect container ID")
return "", "", ""
}
+ slog.Debug("detectCurrentImageInfo: detected container", "containerId", containerId)
container, err := dockerClient.ContainerInspect(ctx, containerId)
if err != nil {
+ slog.Debug("detectCurrentImageInfo: failed to inspect container", "containerId", containerId, "error", err)
return "", "", ""
}
@@ -332,52 +280,101 @@ func (s *VersionService) detectCurrentImageInfo(ctx context.Context) (tag string
tag = s.extractTagFromImageRef(container.Config.Image)
// Get digest and normalized imageRef from container image
- if container.Image != "" {
- imageInspect, err := dockerClient.ImageInspect(ctx, container.Image)
- if err == nil && len(imageInspect.RepoDigests) > 0 {
- // Extract digest and repository from first RepoDigest
- // Format: "ghcr.io/getarcaneapp/arcane@sha256:abc123..."
- // Use RepoDigests for imageRef as it contains the fully qualified registry path
- for _, repoDigest := range imageInspect.RepoDigests {
- if repo, dig, ok := strings.Cut(repoDigest, "@"); ok {
- imageRef = repo
- digest = dig
- break
- }
- }
- }
- }
+ imageRef, digest = s.extractImageDetails(ctx, dockerClient, container)
// Fallback to container config image if RepoDigests didn't provide imageRef
if imageRef == "" {
- imageRef = container.Config.Image
+ imageRef = s.normalizeImageRef(container.Config.Image)
}
return tag, digest, imageRef
}
-// getCurrentContainerID detects if we're running in Docker and returns container ID
-func (s *VersionService) getCurrentContainerID() (string, error) {
- // Try reading from /proc/self/cgroup (Linux)
- data, err := os.ReadFile("/proc/self/cgroup")
+// detectContainerID tries to get the current container ID, falling back to label-based detection
+func (s *VersionService) detectContainerID(ctx context.Context, dockerClient *client.Client) string {
+ containerId, err := s.getCurrentContainerID()
+ if err == nil {
+ slog.Debug("detectContainerID: found via getCurrentContainerID", "containerId", containerId)
+ return containerId
+ }
+ slog.Debug("detectContainerID: getCurrentContainerID failed, trying label fallback", "error", err)
+
+ // Fallback: locate the Arcane container by label (works even when cgroup/hostname detection fails)
+ return s.findArcaneContainerByLabel(ctx, dockerClient)
+}
+
+// findArcaneContainerByLabel searches for the Arcane container using labels
+func (s *VersionService) findArcaneContainerByLabel(ctx context.Context, dockerClient *client.Client) string {
+ f := filters.NewArgs()
+ f.Add("label", arcaneupdater.LabelArcane+"=true")
+ list, err := dockerClient.ContainerList(ctx, containertypes.ListOptions{All: true, Filters: f})
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
- }
- }
+ slog.Debug("findArcaneContainerByLabel: failed to list containers", "error", err)
+ return ""
+ }
+ slog.Debug("findArcaneContainerByLabel: found containers with arcane label", "count", len(list))
+
+ var fallbackID string
+ for _, c := range list {
+ slog.Debug("findArcaneContainerByLabel: checking container", "id", c.ID[:12], "state", c.State, "labels", c.Labels)
+ // Skip the upgrader helper container
+ if v, ok := c.Labels["com.getarcaneapp.arcane.upgrader"]; ok && strings.EqualFold(strings.TrimSpace(v), "true") {
+ slog.Debug("findArcaneContainerByLabel: skipping upgrader container", "id", c.ID[:12])
+ continue
+ }
+ // Prefer running containers
+ if strings.EqualFold(strings.TrimSpace(c.State), "running") {
+ slog.Debug("findArcaneContainerByLabel: found running container", "id", c.ID[:12])
+ return c.ID
}
+ if fallbackID == "" {
+ fallbackID = c.ID
+ }
+ }
+ if fallbackID != "" {
+ slog.Debug("findArcaneContainerByLabel: using fallback container", "id", fallbackID[:12])
+ } else {
+ slog.Debug("findArcaneContainerByLabel: no container found")
+ }
+ return fallbackID
+}
+
+// extractImageDetails extracts digest and imageRef from a container's image
+func (s *VersionService) extractImageDetails(ctx context.Context, dockerClient *client.Client, container containertypes.InspectResponse) (imageRef, digest string) {
+ if container.Image == "" {
+ return "", ""
}
- return "", errors.New("container ID not found")
+ imageInspect, err := dockerClient.ImageInspect(ctx, container.Image)
+ if err != nil {
+ return "", ""
+ }
+
+ // Extract digest and repository from first RepoDigest using reference library
+ for _, repoDigest := range imageInspect.RepoDigests {
+ named, err := ref.ParseNormalizedNamed(repoDigest)
+ if err != nil {
+ continue
+ }
+ if digested, ok := named.(ref.Digested); ok {
+ return named.Name(), string(digested.Digest())
+ }
+ }
+
+ return "", ""
+}
+
+// normalizeImageRef extracts just the repository name from an image reference
+func (s *VersionService) normalizeImageRef(configImage string) string {
+ if named, err := ref.ParseNormalizedNamed(configImage); err == nil {
+ return named.Name()
+ }
+ return configImage
+}
+
+// getCurrentContainerID detects if we're running in Docker via cgroup, mountinfo, or hostname
+func (s *VersionService) getCurrentContainerID() (string, error) {
+ return utils.GetCurrentContainerID()
}
// extractTagFromImageRef extracts the tag from an image reference using distribution/reference
@@ -420,35 +417,3 @@ func (s *VersionService) checkDigestBasedUpdate(ctx context.Context, currentTag,
return updateAvailable, latestDigest
}
-
-func parseSemver(s string) [3]int {
- var out [3]int
- part := 0
- num := 0
- sign := 1
-
- flush := func() {
- if part < 3 {
- out[part] = sign * num
- part++
- }
- num = 0
- sign = 1
- }
-
- for i := 0; i < len(s); i++ {
- switch c := s[i]; {
- case c == '-':
- i = len(s)
- case c == '.':
- flush()
- case c >= '0' && c <= '9':
- num = num*10 + int(c-'0')
- case c == '+' || c == 'v' || c == 'V':
- default:
- i = len(s)
- }
- }
- flush()
- return out
-}
diff --git a/backend/internal/utils/arcaneupdater/digest.go b/backend/internal/utils/arcaneupdater/digest.go
new file mode 100644
index 000000000..4576bd45f
--- /dev/null
+++ b/backend/internal/utils/arcaneupdater/digest.go
@@ -0,0 +1,203 @@
+package arcaneupdater
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "strings"
+
+ "github.com/docker/docker/api/types/image"
+ "github.com/docker/docker/client"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/registry"
+)
+
+// DigestChecker provides methods to check if an image needs updating by comparing digests
+type DigestChecker struct {
+ dcli *client.Client
+ registryClient *registry.Client
+}
+
+// NewDigestChecker creates a new DigestChecker
+func NewDigestChecker(dcli *client.Client, registryClient *registry.Client) *DigestChecker {
+ return &DigestChecker{
+ dcli: dcli,
+ registryClient: registryClient,
+ }
+}
+
+// CheckResult contains the result of a digest check
+type CheckResult struct {
+ NeedsUpdate bool
+ LocalDigest string
+ RemoteDigest string
+ Error error
+ CheckedViaAPI bool // True if we checked via registry API, false if we had to pull
+}
+
+// CheckImageNeedsUpdate checks if an image has a newer version available without pulling
+// Returns true if the remote digest differs from the local digest
+func (c *DigestChecker) CheckImageNeedsUpdate(ctx context.Context, imageRef string, authToken string) CheckResult {
+ result := CheckResult{}
+
+ // Parse image reference
+ registryHost, repository, tag := parseImageRef(imageRef)
+
+ slog.DebugContext(ctx, "CheckImageNeedsUpdate: checking image",
+ "imageRef", imageRef,
+ "registry", registryHost,
+ "repository", repository,
+ "tag", tag)
+
+ // Get local digest
+ localDigest, err := c.getLocalDigest(ctx, imageRef)
+ if err != nil {
+ slog.DebugContext(ctx, "CheckImageNeedsUpdate: failed to get local digest",
+ "imageRef", imageRef,
+ "error", err)
+ // Image not present locally - definitely needs update
+ result.NeedsUpdate = true
+ result.Error = err
+ return result
+ }
+ result.LocalDigest = localDigest
+
+ // Get remote digest via HEAD request
+ remoteDigest, err := c.registryClient.GetLatestDigest(ctx, registryHost, repository, tag, authToken)
+ if err != nil {
+ slog.DebugContext(ctx, "CheckImageNeedsUpdate: failed to get remote digest via HEAD",
+ "imageRef", imageRef,
+ "error", err)
+ // Can't determine remotely - caller should fall back to pull
+ result.Error = err
+ return result
+ }
+
+ result.RemoteDigest = remoteDigest
+ result.CheckedViaAPI = true
+ result.NeedsUpdate = localDigest != remoteDigest
+
+ slog.DebugContext(ctx, "CheckImageNeedsUpdate: digest comparison complete",
+ "imageRef", imageRef,
+ "localDigest", localDigest,
+ "remoteDigest", remoteDigest,
+ "needsUpdate", result.NeedsUpdate)
+
+ return result
+}
+
+// getLocalDigest retrieves the digest of a locally stored image
+func (c *DigestChecker) getLocalDigest(ctx context.Context, imageRef string) (string, error) {
+ inspect, err := c.dcli.ImageInspect(ctx, imageRef)
+ if err != nil {
+ return "", fmt.Errorf("image not found locally: %w", err)
+ }
+
+ // Try to get digest from RepoDigests
+ for _, rd := range inspect.RepoDigests {
+ if strings.Contains(rd, "@sha256:") {
+ parts := strings.Split(rd, "@")
+ if len(parts) == 2 {
+ return parts[1], nil
+ }
+ }
+ }
+
+ // Fall back to image ID (which is a content-addressed hash)
+ if inspect.ID != "" {
+ return inspect.ID, nil
+ }
+
+ return "", fmt.Errorf("no digest available for image")
+}
+
+// CompareWithPulled compares the current container's image with a freshly pulled image
+// This is the fallback when HEAD request doesn't work
+func (c *DigestChecker) CompareWithPulled(ctx context.Context, containerImageID string, newImageRef string) (bool, error) {
+ // Get the new image info after pull
+ newInspect, err := c.dcli.ImageInspect(ctx, newImageRef)
+ if err != nil {
+ return false, fmt.Errorf("failed to inspect new image: %w", err)
+ }
+
+ // Compare image IDs
+ return containerImageID != newInspect.ID, nil
+}
+
+// GetImageIDsForRef returns the image IDs associated with a reference
+func (c *DigestChecker) GetImageIDsForRef(ctx context.Context, ref string) ([]string, error) {
+ // First try direct inspect
+ inspect, err := c.dcli.ImageInspect(ctx, ref)
+ if err == nil && inspect.ID != "" {
+ return []string{inspect.ID}, nil
+ }
+
+ // Fall back to listing and filtering
+ images, err := c.dcli.ImageList(ctx, image.ListOptions{})
+ if err != nil {
+ return nil, err
+ }
+
+ normalizedRef := normalizeRef(ref)
+ var ids []string
+ for _, img := range images {
+ for _, tag := range img.RepoTags {
+ if normalizeRef(tag) == normalizedRef {
+ ids = append(ids, img.ID)
+ break
+ }
+ }
+ }
+
+ return ids, nil
+}
+
+// parseImageRef splits an image reference into registry, repository, and tag
+func parseImageRef(ref string) (registry, repository, tag string) {
+ // Strip digest if present
+ if i := strings.Index(ref, "@"); i != -1 {
+ ref = ref[:i]
+ }
+
+ // Default tag
+ tag = "latest"
+ if i := strings.LastIndex(ref, ":"); i != -1 && strings.LastIndex(ref, "/") < i {
+ tag = ref[i+1:]
+ ref = ref[:i]
+ }
+
+ // Parse registry and repository
+ parts := strings.Split(ref, "/")
+ switch {
+ case len(parts) > 0 && (strings.Contains(parts[0], ".") || strings.Contains(parts[0], ":") || parts[0] == "localhost"):
+ registry = parts[0]
+ repository = strings.Join(parts[1:], "/")
+ default:
+ registry = "docker.io"
+ repository = ref
+ // Docker Hub official images are in library/
+ if !strings.Contains(repository, "/") {
+ repository = "library/" + repository
+ }
+ }
+
+ return registry, repository, tag
+}
+
+// normalizeRef normalizes an image reference for comparison
+func normalizeRef(ref string) string {
+ // Strip digest
+ if i := strings.Index(ref, "@"); i != -1 {
+ ref = ref[:i]
+ }
+
+ // Parse and reconstruct
+ reg, repo, tag := parseImageRef(ref)
+
+ // Normalize docker.io variants
+ switch reg {
+ case "index.docker.io", "registry-1.docker.io":
+ reg = "docker.io"
+ }
+
+ return strings.ToLower(reg + "/" + repo + ":" + tag)
+}
diff --git a/backend/internal/utils/arcaneupdater/labels.go b/backend/internal/utils/arcaneupdater/labels.go
new file mode 100644
index 000000000..a4b843624
--- /dev/null
+++ b/backend/internal/utils/arcaneupdater/labels.go
@@ -0,0 +1,91 @@
+package arcaneupdater
+
+import "strings"
+
+const (
+ // Core labels
+ LabelArcane = "com.getarcaneapp.arcane" // Identifies the Arcane container itself
+ LabelUpdater = "com.getarcaneapp.arcane.updater" // Enable/disable updates (true/false)
+
+ // Lifecycle hook labels
+ LabelPreCheck = "com.getarcaneapp.arcane.lifecycle.pre-check" // Command to run before checking for updates
+ LabelPostCheck = "com.getarcaneapp.arcane.lifecycle.post-check" // Command to run after checking for updates
+ LabelPreUpdate = "com.getarcaneapp.arcane.lifecycle.pre-update" // Command to run before stopping container
+ LabelPostUpdate = "com.getarcaneapp.arcane.lifecycle.post-update" // Command to run after starting new container
+
+ // Lifecycle timeout labels (in seconds)
+ LabelPreUpdateTimeout = "com.getarcaneapp.arcane.lifecycle.pre-update-timeout"
+ LabelPostUpdateTimeout = "com.getarcaneapp.arcane.lifecycle.post-update-timeout"
+
+ // Dependency labels
+ LabelDependsOn = "com.getarcaneapp.arcane.depends-on" // Comma-separated list of container names this depends on
+ LabelStopSignal = "com.getarcaneapp.arcane.stop-signal" // Custom stop signal (e.g., SIGINT)
+
+ ExitCodeSkipUpdate = 75
+)
+
+// IsArcaneContainer checks if the container is the Arcane application itself
+func IsArcaneContainer(labels map[string]string) bool {
+ if labels == nil {
+ return false
+ }
+ for k, v := range labels {
+ if strings.EqualFold(k, LabelArcane) {
+ switch strings.TrimSpace(strings.ToLower(v)) {
+ case "true", "1", "yes", "on":
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// IsUpdateDisabled returns true if the special label is present and evaluates to false.
+// Accepts false/0/no/off (case-insensitive) as "disabled". Default is enabled.
+func IsUpdateDisabled(labels map[string]string) bool {
+ if labels == nil {
+ return false
+ }
+ for k, v := range labels {
+ if strings.EqualFold(k, LabelUpdater) {
+ switch strings.TrimSpace(strings.ToLower(v)) {
+ case "false", "0", "no", "off":
+ return true
+ default:
+ return false
+ }
+ }
+ }
+ return false
+}
+
+// GetLifecycleCommand returns the lifecycle command for the given label, if set
+func GetLifecycleCommand(labels map[string]string, lifecycleLabel string) []string {
+ if labels == nil {
+ return nil
+ }
+ for k, v := range labels {
+ if strings.EqualFold(k, lifecycleLabel) {
+ v = strings.TrimSpace(v)
+ if v == "" {
+ return nil
+ }
+ // Simple shell-style split (use /bin/sh -c for complex commands)
+ return []string{"/bin/sh", "-c", v}
+ }
+ }
+ return nil
+}
+
+// GetStopSignal returns the custom stop signal if set, otherwise empty string
+func GetStopSignal(labels map[string]string) string {
+ if labels == nil {
+ return ""
+ }
+ for k, v := range labels {
+ if strings.EqualFold(k, LabelStopSignal) {
+ return strings.TrimSpace(strings.ToUpper(v))
+ }
+ }
+ return ""
+}
diff --git a/backend/internal/utils/arcaneupdater/labels_test.go b/backend/internal/utils/arcaneupdater/labels_test.go
new file mode 100644
index 000000000..59bc6316b
--- /dev/null
+++ b/backend/internal/utils/arcaneupdater/labels_test.go
@@ -0,0 +1,291 @@
+package arcaneupdater
+
+import (
+ "testing"
+)
+
+func TestIsArcaneContainer(t *testing.T) {
+ tests := []struct {
+ name string
+ labels map[string]string
+ want bool
+ }{
+ {
+ name: "nil labels",
+ labels: nil,
+ want: false,
+ },
+ {
+ name: "empty labels",
+ labels: map[string]string{},
+ want: false,
+ },
+ {
+ name: "arcane label true",
+ labels: map[string]string{LabelArcane: "true"},
+ want: true,
+ },
+ {
+ name: "arcane label 1",
+ labels: map[string]string{LabelArcane: "1"},
+ want: true,
+ },
+ {
+ name: "arcane label yes",
+ labels: map[string]string{LabelArcane: "yes"},
+ want: true,
+ },
+ {
+ name: "arcane label on",
+ labels: map[string]string{LabelArcane: "on"},
+ want: true,
+ },
+ {
+ name: "arcane label false",
+ labels: map[string]string{LabelArcane: "false"},
+ want: false,
+ },
+ {
+ name: "arcane label TRUE uppercase",
+ labels: map[string]string{LabelArcane: "TRUE"},
+ want: true,
+ },
+ {
+ name: "arcane label with whitespace",
+ labels: map[string]string{LabelArcane: " true "},
+ want: true,
+ },
+ {
+ name: "case insensitive label key",
+ labels: map[string]string{"COM.GETARCANEAPP.ARCANE": "true"},
+ want: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := IsArcaneContainer(tt.labels); got != tt.want {
+ t.Errorf("IsArcaneContainer() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestIsUpdateDisabled(t *testing.T) {
+ tests := []struct {
+ name string
+ labels map[string]string
+ want bool
+ }{
+ {
+ name: "nil labels - default enabled",
+ labels: nil,
+ want: false,
+ },
+ {
+ name: "empty labels - default enabled",
+ labels: map[string]string{},
+ want: false,
+ },
+ {
+ name: "no updater label - default enabled",
+ labels: map[string]string{"other": "value"},
+ want: false,
+ },
+ {
+ name: "updater label false",
+ labels: map[string]string{LabelUpdater: "false"},
+ want: true,
+ },
+ {
+ name: "updater label 0",
+ labels: map[string]string{LabelUpdater: "0"},
+ want: true,
+ },
+ {
+ name: "updater label no",
+ labels: map[string]string{LabelUpdater: "no"},
+ want: true,
+ },
+ {
+ name: "updater label off",
+ labels: map[string]string{LabelUpdater: "off"},
+ want: true,
+ },
+ {
+ name: "updater label true - enabled",
+ labels: map[string]string{LabelUpdater: "true"},
+ want: false,
+ },
+ {
+ name: "updater label FALSE uppercase",
+ labels: map[string]string{LabelUpdater: "FALSE"},
+ want: true,
+ },
+ {
+ name: "updater label with whitespace",
+ labels: map[string]string{LabelUpdater: " false "},
+ want: true,
+ },
+ {
+ name: "case insensitive label key",
+ labels: map[string]string{"COM.GETARCANEAPP.ARCANE.UPDATER": "false"},
+ want: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := IsUpdateDisabled(tt.labels); got != tt.want {
+ t.Errorf("IsUpdateDisabled() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestGetLifecycleCommand(t *testing.T) {
+ tests := []struct {
+ name string
+ labels map[string]string
+ lifecycleLabel string
+ want []string
+ }{
+ {
+ name: "nil labels",
+ labels: nil,
+ lifecycleLabel: LabelPreUpdate,
+ want: nil,
+ },
+ {
+ name: "empty labels",
+ labels: map[string]string{},
+ lifecycleLabel: LabelPreUpdate,
+ want: nil,
+ },
+ {
+ name: "no matching label",
+ labels: map[string]string{"other": "value"},
+ lifecycleLabel: LabelPreUpdate,
+ want: nil,
+ },
+ {
+ name: "empty command",
+ labels: map[string]string{LabelPreUpdate: ""},
+ lifecycleLabel: LabelPreUpdate,
+ want: nil,
+ },
+ {
+ name: "whitespace only command",
+ labels: map[string]string{LabelPreUpdate: " "},
+ lifecycleLabel: LabelPreUpdate,
+ want: nil,
+ },
+ {
+ name: "valid command",
+ labels: map[string]string{LabelPreUpdate: "echo 'before update'"},
+ lifecycleLabel: LabelPreUpdate,
+ want: []string{"/bin/sh", "-c", "echo 'before update'"},
+ },
+ {
+ name: "command with leading/trailing whitespace",
+ labels: map[string]string{LabelPreUpdate: " echo test "},
+ lifecycleLabel: LabelPreUpdate,
+ want: []string{"/bin/sh", "-c", "echo test"},
+ },
+ {
+ name: "case insensitive label key",
+ labels: map[string]string{"COM.GETARCANEAPP.ARCANE.LIFECYCLE.PRE-UPDATE": "echo test"},
+ lifecycleLabel: LabelPreUpdate,
+ want: []string{"/bin/sh", "-c", "echo test"},
+ },
+ {
+ name: "pre-check command",
+ labels: map[string]string{LabelPreCheck: "curl -f http://health"},
+ lifecycleLabel: LabelPreCheck,
+ want: []string{"/bin/sh", "-c", "curl -f http://health"},
+ },
+ {
+ name: "post-update command",
+ labels: map[string]string{LabelPostUpdate: "docker exec -it nginx nginx -s reload"},
+ lifecycleLabel: LabelPostUpdate,
+ want: []string{"/bin/sh", "-c", "docker exec -it nginx nginx -s reload"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := GetLifecycleCommand(tt.labels, tt.lifecycleLabel)
+ if len(got) != len(tt.want) {
+ t.Errorf("GetLifecycleCommand() len = %v, want %v", len(got), len(tt.want))
+ return
+ }
+ for i := range got {
+ if got[i] != tt.want[i] {
+ t.Errorf("GetLifecycleCommand()[%d] = %v, want %v", i, got[i], tt.want[i])
+ }
+ }
+ })
+ }
+}
+
+func TestGetStopSignal(t *testing.T) {
+ tests := []struct {
+ name string
+ labels map[string]string
+ want string
+ }{
+ {
+ name: "nil labels",
+ labels: nil,
+ want: "",
+ },
+ {
+ name: "empty labels",
+ labels: map[string]string{},
+ want: "",
+ },
+ {
+ name: "no stop signal label",
+ labels: map[string]string{"other": "value"},
+ want: "",
+ },
+ {
+ name: "SIGTERM",
+ labels: map[string]string{LabelStopSignal: "SIGTERM"},
+ want: "SIGTERM",
+ },
+ {
+ name: "SIGINT",
+ labels: map[string]string{LabelStopSignal: "SIGINT"},
+ want: "SIGINT",
+ },
+ {
+ name: "SIGKILL",
+ labels: map[string]string{LabelStopSignal: "SIGKILL"},
+ want: "SIGKILL",
+ },
+ {
+ name: "lowercase signal",
+ labels: map[string]string{LabelStopSignal: "sigterm"},
+ want: "SIGTERM",
+ },
+ {
+ name: "signal with whitespace",
+ labels: map[string]string{LabelStopSignal: " SIGTERM "},
+ want: "SIGTERM",
+ },
+ {
+ name: "case insensitive label key",
+ labels: map[string]string{"COM.GETARCANEAPP.ARCANE.STOP-SIGNAL": "SIGINT"},
+ want: "SIGINT",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := GetStopSignal(tt.labels); got != tt.want {
+ t.Errorf("GetStopSignal() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/backend/internal/utils/arcaneupdater/lifecycle.go b/backend/internal/utils/arcaneupdater/lifecycle.go
new file mode 100644
index 000000000..a049df647
--- /dev/null
+++ b/backend/internal/utils/arcaneupdater/lifecycle.go
@@ -0,0 +1,211 @@
+package arcaneupdater
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "log/slog"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/client"
+)
+
+const (
+ DefaultPreUpdateTimeout = 60 * time.Second
+ DefaultPostUpdateTimeout = 60 * time.Second
+)
+
+// LifecycleHookResult contains the result of executing a lifecycle hook
+type LifecycleHookResult struct {
+ Executed bool
+ SkipUpdate bool // True if exit code was ExitCodeSkipUpdate (75)
+ ExitCode int
+ Output string
+ Error error
+}
+
+// ExecutePreUpdateCommand runs the pre-update lifecycle hook on a container
+// Returns SkipUpdate=true if the command exits with code 75 (EX_TEMPFAIL)
+func ExecutePreUpdateCommand(ctx context.Context, dcli *client.Client, containerID string, labels map[string]string) LifecycleHookResult {
+ cmd := GetLifecycleCommand(labels, LabelPreUpdate)
+ if len(cmd) == 0 {
+ return LifecycleHookResult{Executed: false}
+ }
+
+ timeout := getTimeout(labels, LabelPreUpdateTimeout, DefaultPreUpdateTimeout)
+
+ slog.DebugContext(ctx, "ExecutePreUpdateCommand: running pre-update hook",
+ "containerID", containerID,
+ "command", cmd,
+ "timeout", timeout)
+
+ return executeLifecycleCommand(ctx, dcli, containerID, cmd, timeout)
+}
+
+// ExecutePostUpdateCommand runs the post-update lifecycle hook on a container
+func ExecutePostUpdateCommand(ctx context.Context, dcli *client.Client, containerID string, labels map[string]string) LifecycleHookResult {
+ cmd := GetLifecycleCommand(labels, LabelPostUpdate)
+ if len(cmd) == 0 {
+ return LifecycleHookResult{Executed: false}
+ }
+
+ timeout := getTimeout(labels, LabelPostUpdateTimeout, DefaultPostUpdateTimeout)
+
+ slog.DebugContext(ctx, "ExecutePostUpdateCommand: running post-update hook",
+ "containerID", containerID,
+ "command", cmd,
+ "timeout", timeout)
+
+ return executeLifecycleCommand(ctx, dcli, containerID, cmd, timeout)
+}
+
+// ExecutePreCheckCommand runs the pre-check lifecycle hook on a container
+func ExecutePreCheckCommand(ctx context.Context, dcli *client.Client, containerID string, labels map[string]string) LifecycleHookResult {
+ cmd := GetLifecycleCommand(labels, LabelPreCheck)
+ if len(cmd) == 0 {
+ return LifecycleHookResult{Executed: false}
+ }
+
+ return executeLifecycleCommand(ctx, dcli, containerID, cmd, DefaultPreUpdateTimeout)
+}
+
+// ExecutePostCheckCommand runs the post-check lifecycle hook on a container
+func ExecutePostCheckCommand(ctx context.Context, dcli *client.Client, containerID string, labels map[string]string) LifecycleHookResult {
+ cmd := GetLifecycleCommand(labels, LabelPostCheck)
+ if len(cmd) == 0 {
+ return LifecycleHookResult{Executed: false}
+ }
+
+ return executeLifecycleCommand(ctx, dcli, containerID, cmd, DefaultPostUpdateTimeout)
+}
+
+func executeLifecycleCommand(ctx context.Context, dcli *client.Client, containerID string, cmd []string, timeout time.Duration) LifecycleHookResult {
+ result := LifecycleHookResult{Executed: true}
+
+ // Create exec configuration
+ execConfig := container.ExecOptions{
+ Cmd: cmd,
+ AttachStdout: true,
+ AttachStderr: true,
+ }
+
+ // Create the exec instance
+ execResp, err := dcli.ContainerExecCreate(ctx, containerID, execConfig)
+ if err != nil {
+ result.Error = fmt.Errorf("failed to create exec: %w", err)
+ slog.WarnContext(ctx, "executeLifecycleCommand: failed to create exec",
+ "containerID", containerID,
+ "error", err)
+ return result
+ }
+
+ // Attach to the exec instance to get output
+ attachResp, err := dcli.ContainerExecAttach(ctx, execResp.ID, container.ExecAttachOptions{})
+ if err != nil {
+ result.Error = fmt.Errorf("failed to attach to exec: %w", err)
+ slog.WarnContext(ctx, "executeLifecycleCommand: failed to attach to exec",
+ "containerID", containerID,
+ "error", err)
+ return result
+ }
+ defer attachResp.Close()
+
+ // Read output with timeout
+ outputChan := make(chan []byte, 1)
+ errChan := make(chan error, 1)
+
+ go func() {
+ var buf bytes.Buffer
+ _, err := buf.ReadFrom(attachResp.Reader)
+ if err != nil {
+ errChan <- err
+ return
+ }
+ outputChan <- buf.Bytes()
+ }()
+
+ // Wait for output or timeout
+ timeoutCtx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+
+ select {
+ case <-timeoutCtx.Done():
+ result.Error = fmt.Errorf("lifecycle command timed out after %v", timeout)
+ slog.WarnContext(ctx, "executeLifecycleCommand: command timed out",
+ "containerID", containerID,
+ "timeout", timeout)
+ return result
+ case err := <-errChan:
+ result.Error = fmt.Errorf("error reading output: %w", err)
+ return result
+ case output := <-outputChan:
+ result.Output = string(output)
+ }
+
+ // Inspect the exec to get exit code
+ execInspect, err := dcli.ContainerExecInspect(ctx, execResp.ID)
+ if err != nil {
+ result.Error = fmt.Errorf("failed to inspect exec: %w", err)
+ slog.WarnContext(ctx, "executeLifecycleCommand: failed to inspect exec",
+ "containerID", containerID,
+ "error", err)
+ return result
+ }
+
+ result.ExitCode = execInspect.ExitCode
+
+ // Check for skip update signal (exit code 75 = EX_TEMPFAIL)
+ if result.ExitCode == ExitCodeSkipUpdate {
+ result.SkipUpdate = true
+ slog.InfoContext(ctx, "executeLifecycleCommand: container requested skip update",
+ "containerID", containerID,
+ "exitCode", result.ExitCode)
+ return result
+ }
+
+ // Non-zero exit code (other than 75) is an error
+ if result.ExitCode != 0 {
+ result.Error = fmt.Errorf("lifecycle command exited with code %d", result.ExitCode)
+ slog.WarnContext(ctx, "executeLifecycleCommand: command failed",
+ "containerID", containerID,
+ "exitCode", result.ExitCode,
+ "output", result.Output)
+ return result
+ }
+
+ slog.DebugContext(ctx, "executeLifecycleCommand: command completed successfully",
+ "containerID", containerID,
+ "exitCode", result.ExitCode)
+
+ return result
+}
+
+func getTimeout(labels map[string]string, timeoutLabel string, defaultTimeout time.Duration) time.Duration {
+ if labels == nil {
+ return defaultTimeout
+ }
+
+ for k, v := range labels {
+ if k == timeoutLabel {
+ v = strings.TrimSpace(v)
+ if v == "" {
+ return defaultTimeout
+ }
+
+ // Try parsing as seconds
+ if secs, err := strconv.Atoi(v); err == nil && secs > 0 {
+ return time.Duration(secs) * time.Second
+ }
+
+ // Try parsing as duration string
+ if d, err := time.ParseDuration(v); err == nil && d > 0 {
+ return d
+ }
+ }
+ }
+
+ return defaultTimeout
+}
diff --git a/backend/internal/utils/arcaneupdater/lifecycle_test.go b/backend/internal/utils/arcaneupdater/lifecycle_test.go
new file mode 100644
index 000000000..e59e69bf5
--- /dev/null
+++ b/backend/internal/utils/arcaneupdater/lifecycle_test.go
@@ -0,0 +1,260 @@
+package arcaneupdater
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestGetTimeout(t *testing.T) {
+ tests := []struct {
+ name string
+ labels map[string]string
+ label string
+ defaultValue time.Duration
+ want time.Duration
+ }{
+ {
+ name: "no label - use default",
+ labels: map[string]string{},
+ label: LabelPreUpdateTimeout,
+ defaultValue: 60 * time.Second,
+ want: 60 * time.Second,
+ },
+ {
+ name: "nil labels - use default",
+ labels: nil,
+ label: LabelPreUpdateTimeout,
+ defaultValue: 60 * time.Second,
+ want: 60 * time.Second,
+ },
+ {
+ name: "valid timeout 30",
+ labels: map[string]string{LabelPreUpdateTimeout: "30"},
+ label: LabelPreUpdateTimeout,
+ defaultValue: 60 * time.Second,
+ want: 30 * time.Second,
+ },
+ {
+ name: "valid timeout 120",
+ labels: map[string]string{LabelPostUpdateTimeout: "120"},
+ label: LabelPostUpdateTimeout,
+ defaultValue: 60 * time.Second,
+ want: 120 * time.Second,
+ },
+ {
+ name: "invalid timeout - use default",
+ labels: map[string]string{LabelPreUpdateTimeout: "invalid"},
+ label: LabelPreUpdateTimeout,
+ defaultValue: 60 * time.Second,
+ want: 60 * time.Second,
+ },
+ {
+ name: "negative timeout - use default",
+ labels: map[string]string{LabelPreUpdateTimeout: "-10"},
+ label: LabelPreUpdateTimeout,
+ defaultValue: 60 * time.Second,
+ want: 60 * time.Second,
+ },
+ {
+ name: "zero timeout - use default",
+ labels: map[string]string{LabelPreUpdateTimeout: "0"},
+ label: LabelPreUpdateTimeout,
+ defaultValue: 60 * time.Second,
+ want: 60 * time.Second,
+ },
+ {
+ name: "timeout with whitespace",
+ labels: map[string]string{LabelPreUpdateTimeout: " 45 "},
+ label: LabelPreUpdateTimeout,
+ defaultValue: 60 * time.Second,
+ want: 45 * time.Second,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := getTimeout(tt.labels, tt.label, tt.defaultValue)
+ if got != tt.want {
+ t.Errorf("getTimeout() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestLifecycleHookResult_SkipUpdate(t *testing.T) {
+ tests := []struct {
+ name string
+ result LifecycleHookResult
+ wantSkip bool
+ }{
+ {
+ name: "exit code 75 - should skip",
+ result: LifecycleHookResult{
+ Executed: true,
+ SkipUpdate: true,
+ ExitCode: ExitCodeSkipUpdate,
+ },
+ wantSkip: true,
+ },
+ {
+ name: "exit code 0 - should not skip",
+ result: LifecycleHookResult{
+ Executed: true,
+ SkipUpdate: false,
+ ExitCode: 0,
+ },
+ wantSkip: false,
+ },
+ {
+ name: "not executed - should not skip",
+ result: LifecycleHookResult{
+ Executed: false,
+ SkipUpdate: false,
+ },
+ wantSkip: false,
+ },
+ {
+ name: "error occurred - should not skip",
+ result: LifecycleHookResult{
+ Executed: true,
+ ExitCode: 1,
+ Error: errors.New("command failed"),
+ },
+ wantSkip: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := tt.result.SkipUpdate; got != tt.wantSkip {
+ t.Errorf("LifecycleHookResult.SkipUpdate = %v, want %v", got, tt.wantSkip)
+ }
+ })
+ }
+}
+
+func TestExecuteLifecycleCommands_NoCommand(t *testing.T) {
+ ctx := context.Background()
+
+ // Test with no pre-update command
+ result := ExecutePreUpdateCommand(ctx, nil, "test-container", map[string]string{})
+ if result.Executed {
+ t.Error("ExecutePreUpdateCommand() should not execute when no command is configured")
+ }
+
+ // Test with no post-update command
+ result = ExecutePostUpdateCommand(ctx, nil, "test-container", map[string]string{})
+ if result.Executed {
+ t.Error("ExecutePostUpdateCommand() should not execute when no command is configured")
+ }
+
+ // Test with no pre-check command
+ result = ExecutePreCheckCommand(ctx, nil, "test-container", map[string]string{})
+ if result.Executed {
+ t.Error("ExecutePreCheckCommand() should not execute when no command is configured")
+ }
+
+ // Test with no post-check command
+ result = ExecutePostCheckCommand(ctx, nil, "test-container", map[string]string{})
+ if result.Executed {
+ t.Error("ExecutePostCheckCommand() should not execute when no command is configured")
+ }
+}
+
+func TestLifecycleCommandOutput(t *testing.T) {
+ tests := []struct {
+ name string
+ output string
+ wantContains string
+ }{
+ {
+ name: "output with timestamp",
+ output: "2024-01-01T00:00:00Z Starting backup...",
+ wantContains: "Starting backup",
+ },
+ {
+ name: "multi-line output",
+ output: "Line 1\nLine 2\nLine 3",
+ wantContains: "Line 2",
+ },
+ {
+ name: "empty output",
+ output: "",
+ wantContains: "",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := LifecycleHookResult{
+ Executed: true,
+ Output: tt.output,
+ }
+ if tt.wantContains != "" && !strings.Contains(result.Output, tt.wantContains) {
+ t.Errorf("Output does not contain expected string: want %q in %q", tt.wantContains, result.Output)
+ }
+ })
+ }
+}
+
+func TestDefaultTimeouts(t *testing.T) {
+ if DefaultPreUpdateTimeout != 60*time.Second {
+ t.Errorf("DefaultPreUpdateTimeout = %v, want %v", DefaultPreUpdateTimeout, 60*time.Second)
+ }
+ if DefaultPostUpdateTimeout != 60*time.Second {
+ t.Errorf("DefaultPostUpdateTimeout = %v, want %v", DefaultPostUpdateTimeout, 60*time.Second)
+ }
+}
+
+func TestExitCodeSkipUpdate(t *testing.T) {
+ if ExitCodeSkipUpdate != 75 {
+ t.Errorf("ExitCodeSkipUpdate = %d, want 75", ExitCodeSkipUpdate)
+ }
+}
+
+func TestLifecycleHookResult_ErrorHandling(t *testing.T) {
+ tests := []struct {
+ name string
+ result LifecycleHookResult
+ wantError bool
+ }{
+ {
+ name: "no error",
+ result: LifecycleHookResult{
+ Executed: true,
+ ExitCode: 0,
+ Error: nil,
+ },
+ wantError: false,
+ },
+ {
+ name: "with error",
+ result: LifecycleHookResult{
+ Executed: true,
+ ExitCode: 1,
+ Error: errors.New("command failed"),
+ },
+ wantError: true,
+ },
+ {
+ name: "not executed no error",
+ result: LifecycleHookResult{
+ Executed: false,
+ Error: nil,
+ },
+ wantError: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ hasError := tt.result.Error != nil
+ if hasError != tt.wantError {
+ t.Errorf("LifecycleHookResult has error = %v, want %v", hasError, tt.wantError)
+ }
+ })
+ }
+}
diff --git a/backend/internal/utils/arcaneupdater/logfile.go b/backend/internal/utils/arcaneupdater/logfile.go
new file mode 100644
index 000000000..b8c9ef57b
--- /dev/null
+++ b/backend/internal/utils/arcaneupdater/logfile.go
@@ -0,0 +1,194 @@
+package arcaneupdater
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+type teeHandler struct {
+ a slog.Handler
+ b slog.Handler
+}
+
+func (t teeHandler) Enabled(ctx context.Context, level slog.Level) bool {
+ return t.a.Enabled(ctx, level) || t.b.Enabled(ctx, level)
+}
+
+func (t teeHandler) Handle(ctx context.Context, r slog.Record) error {
+ var err error
+ if t.a.Enabled(ctx, r.Level) {
+ err = t.a.Handle(ctx, r)
+ }
+ if t.b.Enabled(ctx, r.Level) {
+ if err2 := t.b.Handle(ctx, r); err == nil {
+ err = err2
+ }
+ }
+ return err
+}
+
+func (t teeHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
+ return teeHandler{a: t.a.WithAttrs(attrs), b: t.b.WithAttrs(attrs)}
+}
+
+func (t teeHandler) WithGroup(name string) slog.Handler {
+ return teeHandler{a: t.a.WithGroup(name), b: t.b.WithGroup(name)}
+}
+
+type messageOnlyHandler struct {
+ mu *sync.Mutex
+ w io.Writer
+ minLevel slog.Level
+ attrs []slog.Attr
+ groups []string
+}
+
+func newMessageOnlyHandler(w io.Writer, minLevel slog.Level) *messageOnlyHandler {
+ return &messageOnlyHandler{mu: &sync.Mutex{}, w: w, minLevel: minLevel}
+}
+
+func (h *messageOnlyHandler) Enabled(_ context.Context, level slog.Level) bool {
+ return level >= h.minLevel
+}
+
+func (h *messageOnlyHandler) Handle(_ context.Context, r slog.Record) error {
+ if h.mu != nil {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ }
+
+ line := r.Message
+ appendAttr := func(a slog.Attr) {
+ if a.Equal(slog.Attr{}) {
+ return
+ }
+ key := a.Key
+ if len(h.groups) > 0 {
+ key = strings.Join(h.groups, ".") + "." + key
+ }
+ line += " " + key + "=" + formatSlogValue(a.Value)
+ }
+
+ for _, a := range h.attrs {
+ appendAttr(a)
+ }
+
+ r.Attrs(func(a slog.Attr) bool {
+ if a.Value.Kind() == slog.KindGroup {
+ g := a.Value.Group()
+ prev := h.groups
+ if a.Key != "" {
+ h.groups = append(h.groups, a.Key)
+ }
+ for _, ga := range g {
+ appendAttr(ga)
+ }
+ h.groups = prev
+ return true
+ }
+ appendAttr(a)
+ return true
+ })
+
+ _, err := fmt.Fprintln(h.w, strings.TrimSpace(line))
+ return err
+}
+
+func (h *messageOnlyHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
+ return &messageOnlyHandler{
+ mu: h.mu,
+ w: h.w,
+ minLevel: h.minLevel,
+ attrs: append(append([]slog.Attr{}, h.attrs...), attrs...),
+ groups: append([]string{}, h.groups...),
+ }
+}
+
+func (h *messageOnlyHandler) WithGroup(name string) slog.Handler {
+ groups := append([]string{}, h.groups...)
+ if strings.TrimSpace(name) != "" {
+ groups = append(groups, name)
+ }
+ return &messageOnlyHandler{
+ mu: h.mu,
+ w: h.w,
+ minLevel: h.minLevel,
+ attrs: append([]slog.Attr{}, h.attrs...),
+ groups: groups,
+ }
+}
+
+func formatSlogValue(v slog.Value) string {
+ switch v.Kind() {
+ case slog.KindAny:
+ return strconv.Quote(fmt.Sprint(v.Any()))
+ case slog.KindString:
+ return strconv.Quote(v.String())
+ case slog.KindInt64:
+ return strconv.FormatInt(v.Int64(), 10)
+ case slog.KindUint64:
+ return strconv.FormatUint(v.Uint64(), 10)
+ case slog.KindFloat64:
+ return strconv.FormatFloat(v.Float64(), 'f', -1, 64)
+ case slog.KindTime:
+ return strconv.Quote(v.Time().Format(time.RFC3339Nano))
+ case slog.KindDuration:
+ return strconv.Quote(v.Duration().String())
+ case slog.KindBool:
+ if v.Bool() {
+ return "true"
+ }
+ return "false"
+ case slog.KindGroup:
+ // Groups are typically flattened earlier in Handle(), but handle defensively.
+ return strconv.Quote(fmt.Sprint(v.Group()))
+ case slog.KindLogValuer:
+ return formatSlogValue(v.Resolve())
+ default:
+ return strconv.Quote(fmt.Sprint(v.Any()))
+ }
+}
+
+// SetupMessageOnlyLogFile configures slog to write structured logs to stdout and a
+// message-only format to a file under dataDir.
+//
+// The file format is: <msg> key=value key=value ... (no time/level/source) to keep
+// upgrade logs concise for end users.
+func SetupMessageOnlyLogFile(dataDir string, filePrefix string, minLevel slog.Level) (*os.File, error) {
+ if strings.TrimSpace(dataDir) == "" {
+ return nil, fmt.Errorf("dataDir is required")
+ }
+ if strings.TrimSpace(filePrefix) == "" {
+ filePrefix = "arcane-upgrade"
+ }
+
+ if err := os.MkdirAll(dataDir, 0755); err != nil {
+ return nil, fmt.Errorf("failed to create data directory: %w", err)
+ }
+
+ logFileName := fmt.Sprintf("%s-%d.log", filePrefix, time.Now().Unix())
+ logFilePath := filepath.Join(dataDir, logFileName)
+
+ logFile, err := os.OpenFile(logFilePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open log file: %w", err)
+ }
+
+ stdoutHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
+ Level: minLevel,
+ AddSource: true,
+ })
+ fileHandler := newMessageOnlyHandler(logFile, minLevel)
+
+ slog.SetDefault(slog.New(teeHandler{a: stdoutHandler, b: fileHandler}))
+
+ return logFile, nil
+}
diff --git a/backend/internal/utils/arcaneupdater/logfile_test.go b/backend/internal/utils/arcaneupdater/logfile_test.go
new file mode 100644
index 000000000..4893a1fd8
--- /dev/null
+++ b/backend/internal/utils/arcaneupdater/logfile_test.go
@@ -0,0 +1,388 @@
+package arcaneupdater
+
+import (
+ "bytes"
+ "context"
+ "log/slog"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestMessageOnlyHandler_Handle(t *testing.T) {
+ tests := []struct {
+ name string
+ level slog.Level
+ message string
+ attrs []slog.Attr
+ want string
+ }{
+ {
+ name: "info message only",
+ level: slog.LevelInfo,
+ message: "Test message",
+ attrs: []slog.Attr{},
+ want: "Test message",
+ },
+ {
+ name: "debug message",
+ level: slog.LevelDebug,
+ message: "Debug info",
+ attrs: []slog.Attr{},
+ want: "Debug info",
+ },
+ {
+ name: "error message",
+ level: slog.LevelError,
+ message: "Error occurred",
+ attrs: []slog.Attr{},
+ want: "Error occurred",
+ },
+ {
+ name: "message with string attribute",
+ level: slog.LevelInfo,
+ message: "Processing",
+ attrs: []slog.Attr{slog.String("key", "value")},
+ want: "Processing key=\"value\"",
+ },
+ {
+ name: "message with int attribute",
+ level: slog.LevelInfo,
+ message: "Count",
+ attrs: []slog.Attr{slog.Int("count", 42)},
+ want: "Count count=42",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var buf bytes.Buffer
+ handler := newMessageOnlyHandler(&buf, slog.LevelDebug)
+
+ record := slog.NewRecord(time.Now(), tt.level, tt.message, 0)
+ for _, attr := range tt.attrs {
+ record.AddAttrs(attr)
+ }
+
+ if err := handler.Handle(context.Background(), record); err != nil {
+ t.Errorf("Handle() error = %v", err)
+ return
+ }
+
+ got := strings.TrimSpace(buf.String())
+ if got != tt.want {
+ t.Errorf("Handle() output = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestMessageOnlyHandler_Enabled(t *testing.T) {
+ tests := []struct {
+ name string
+ minLevel slog.Level
+ level slog.Level
+ want bool
+ }{
+ {
+ name: "info enabled at debug level",
+ minLevel: slog.LevelDebug,
+ level: slog.LevelInfo,
+ want: true,
+ },
+ {
+ name: "debug disabled at info level",
+ minLevel: slog.LevelInfo,
+ level: slog.LevelDebug,
+ want: false,
+ },
+ {
+ name: "error enabled at info level",
+ minLevel: slog.LevelInfo,
+ level: slog.LevelError,
+ want: true,
+ },
+ {
+ name: "warn enabled at warn level",
+ minLevel: slog.LevelWarn,
+ level: slog.LevelWarn,
+ want: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var buf bytes.Buffer
+ handler := newMessageOnlyHandler(&buf, tt.minLevel)
+
+ if got := handler.Enabled(context.Background(), tt.level); got != tt.want {
+ t.Errorf("Enabled() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestMessageOnlyHandler_WithAttrs(t *testing.T) {
+ var buf bytes.Buffer
+ handler := newMessageOnlyHandler(&buf, slog.LevelInfo)
+
+ attrs := []slog.Attr{
+ slog.String("key1", "value1"),
+ slog.Int("key2", 42),
+ }
+
+ newHandler := handler.WithAttrs(attrs)
+ if newHandler == nil {
+ t.Error("WithAttrs() returned nil")
+ }
+
+ // Should return same handler type
+ if _, ok := newHandler.(*messageOnlyHandler); !ok {
+ t.Error("WithAttrs() did not return messageOnlyHandler")
+ }
+
+ // Test that attrs are included in output
+ record := slog.NewRecord(time.Now(), slog.LevelInfo, "Test", 0)
+ if err := newHandler.Handle(context.Background(), record); err != nil {
+ t.Errorf("Handle() error = %v", err)
+ }
+
+ output := buf.String()
+ if !strings.Contains(output, "key1") || !strings.Contains(output, "key2") {
+ t.Errorf("WithAttrs() output missing attributes: %q", output)
+ }
+}
+
+func TestMessageOnlyHandler_WithGroup(t *testing.T) {
+ var buf bytes.Buffer
+ handler := newMessageOnlyHandler(&buf, slog.LevelInfo)
+
+ newHandler := handler.WithGroup("testgroup")
+ if newHandler == nil {
+ t.Error("WithGroup() returned nil")
+ }
+
+ // Should return same handler type
+ if _, ok := newHandler.(*messageOnlyHandler); !ok {
+ t.Error("WithGroup() did not return messageOnlyHandler")
+ }
+
+ // Test that group is used in output
+ record := slog.NewRecord(time.Now(), slog.LevelInfo, "Test", 0)
+ record.AddAttrs(slog.String("key", "value"))
+ if err := newHandler.Handle(context.Background(), record); err != nil {
+ t.Errorf("Handle() error = %v", err)
+ }
+
+ output := buf.String()
+ if !strings.Contains(output, "testgroup") {
+ t.Errorf("WithGroup() output missing group name: %q", output)
+ }
+}
+
+func TestFormatSlogValue(t *testing.T) {
+ tests := []struct {
+ name string
+ value slog.Value
+ want string
+ }{
+ {
+ name: "string value",
+ value: slog.StringValue("test"),
+ want: "\"test\"",
+ },
+ {
+ name: "int value",
+ value: slog.Int64Value(42),
+ want: "42",
+ },
+ {
+ name: "bool value true",
+ value: slog.BoolValue(true),
+ want: "true",
+ },
+ {
+ name: "bool value false",
+ value: slog.BoolValue(false),
+ want: "false",
+ },
+ {
+ name: "float value",
+ value: slog.Float64Value(3.14),
+ want: "3.14",
+ },
+ {
+ name: "uint value",
+ value: slog.Uint64Value(100),
+ want: "100",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := formatSlogValue(tt.value)
+ if got != tt.want {
+ t.Errorf("formatSlogValue() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestFormatSlogValue_Time(t *testing.T) {
+ now := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
+ value := slog.TimeValue(now)
+
+ got := formatSlogValue(value)
+
+ // Should be quoted and contain the date
+ if !strings.HasPrefix(got, "\"") || !strings.HasSuffix(got, "\"") {
+ t.Errorf("formatSlogValue(time) should be quoted, got %q", got)
+ }
+ if !strings.Contains(got, "2024") {
+ t.Errorf("formatSlogValue(time) should contain year, got %q", got)
+ }
+}
+
+func TestFormatSlogValue_Duration(t *testing.T) {
+ value := slog.DurationValue(5 * time.Second)
+ got := formatSlogValue(value)
+
+ // Should be quoted and contain duration string
+ if !strings.HasPrefix(got, "\"") || !strings.HasSuffix(got, "\"") {
+ t.Errorf("formatSlogValue(duration) should be quoted, got %q", got)
+ }
+ if !strings.Contains(got, "5s") {
+ t.Errorf("formatSlogValue(duration) should contain duration, got %q", got)
+ }
+}
+
+func TestTeeHandler_Enabled(t *testing.T) {
+ var buf1, buf2 bytes.Buffer
+ handler1 := newMessageOnlyHandler(&buf1, slog.LevelInfo)
+ handler2 := newMessageOnlyHandler(&buf2, slog.LevelWarn)
+
+ tee := teeHandler{a: handler1, b: handler2}
+
+ tests := []struct {
+ name string
+ level slog.Level
+ want bool
+ }{
+ {
+ name: "debug - neither enabled",
+ level: slog.LevelDebug,
+ want: false,
+ },
+ {
+ name: "info - first enabled",
+ level: slog.LevelInfo,
+ want: true,
+ },
+ {
+ name: "warn - both enabled",
+ level: slog.LevelWarn,
+ want: true,
+ },
+ {
+ name: "error - both enabled",
+ level: slog.LevelError,
+ want: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := tee.Enabled(context.Background(), tt.level); got != tt.want {
+ t.Errorf("Enabled() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestTeeHandler_Handle(t *testing.T) {
+ var buf1, buf2 bytes.Buffer
+ handler1 := newMessageOnlyHandler(&buf1, slog.LevelInfo)
+ handler2 := newMessageOnlyHandler(&buf2, slog.LevelInfo)
+
+ tee := teeHandler{a: handler1, b: handler2}
+
+ record := slog.NewRecord(time.Now(), slog.LevelInfo, "Test message", 0)
+ if err := tee.Handle(context.Background(), record); err != nil {
+ t.Errorf("Handle() error = %v", err)
+ }
+
+ // Both handlers should have received the message
+ if !strings.Contains(buf1.String(), "Test message") {
+ t.Error("teeHandler did not write to first handler")
+ }
+ if !strings.Contains(buf2.String(), "Test message") {
+ t.Error("teeHandler did not write to second handler")
+ }
+}
+
+func TestTeeHandler_WithAttrs(t *testing.T) {
+ var buf1, buf2 bytes.Buffer
+ handler1 := newMessageOnlyHandler(&buf1, slog.LevelInfo)
+ handler2 := newMessageOnlyHandler(&buf2, slog.LevelInfo)
+
+ tee := teeHandler{a: handler1, b: handler2}
+
+ attrs := []slog.Attr{slog.String("key", "value")}
+ newTee := tee.WithAttrs(attrs)
+
+ if _, ok := newTee.(teeHandler); !ok {
+ t.Error("WithAttrs() did not return teeHandler")
+ }
+}
+
+func TestTeeHandler_WithGroup(t *testing.T) {
+ var buf1, buf2 bytes.Buffer
+ handler1 := newMessageOnlyHandler(&buf1, slog.LevelInfo)
+ handler2 := newMessageOnlyHandler(&buf2, slog.LevelInfo)
+
+ tee := teeHandler{a: handler1, b: handler2}
+
+ newTee := tee.WithGroup("testgroup")
+
+ if _, ok := newTee.(teeHandler); !ok {
+ t.Error("WithGroup() did not return teeHandler")
+ }
+}
+
+func TestNewMessageOnlyHandler(t *testing.T) {
+ var buf bytes.Buffer
+ handler := newMessageOnlyHandler(&buf, slog.LevelInfo)
+
+ if handler.minLevel != slog.LevelInfo {
+ t.Errorf("newMessageOnlyHandler() minLevel = %v, want %v", handler.minLevel, slog.LevelInfo)
+ }
+
+ if handler.mu == nil {
+ t.Error("newMessageOnlyHandler() did not initialize mutex")
+ }
+}
+
+func TestMessageOnlyHandler_MultipleMessages(t *testing.T) {
+ var buf bytes.Buffer
+ handler := newMessageOnlyHandler(&buf, slog.LevelInfo)
+
+ messages := []string{
+ "First message",
+ "Second message",
+ "Third message",
+ }
+
+ for _, msg := range messages {
+ record := slog.NewRecord(time.Now(), slog.LevelInfo, msg, 0)
+ if err := handler.Handle(context.Background(), record); err != nil {
+ t.Errorf("Handle() error = %v", err)
+ }
+ }
+
+ output := buf.String()
+ for _, msg := range messages {
+ if !strings.Contains(output, msg) {
+ t.Errorf("Output missing message %q", msg)
+ }
+ }
+}
diff --git a/backend/internal/utils/arcaneupdater/selfupdate.go b/backend/internal/utils/arcaneupdater/selfupdate.go
new file mode 100644
index 000000000..a8f3e8a38
--- /dev/null
+++ b/backend/internal/utils/arcaneupdater/selfupdate.go
@@ -0,0 +1,164 @@
+package arcaneupdater
+
+import (
+ "context"
+ "crypto/rand"
+ "log/slog"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/api/types/filters"
+ "github.com/docker/docker/client"
+)
+
+// SelfUpdate handles the special case of updating the Arcane container itself
+type SelfUpdate struct {
+ dcli *client.Client
+}
+
+// NewSelfUpdate creates a new SelfUpdate handler
+func NewSelfUpdate(dcli *client.Client) *SelfUpdate {
+ return &SelfUpdate{dcli: dcli}
+}
+
+// IsArcaneContainerByID checks if a container ID belongs to an Arcane container
+func (s *SelfUpdate) IsArcaneContainerByID(ctx context.Context, containerID string) (bool, error) {
+ inspect, err := s.dcli.ContainerInspect(ctx, containerID)
+ if err != nil {
+ return false, err
+ }
+
+ if inspect.Config == nil {
+ return false, nil
+ }
+
+ return IsArcaneContainer(inspect.Config.Labels), nil
+}
+
+// PrepareForSelfUpdate renames the current Arcane container so the new one can use its name
+// Returns the new temporary name assigned to the old container
+func (s *SelfUpdate) PrepareForSelfUpdate(ctx context.Context, containerID string, originalName string) (string, error) {
+ // Generate a random temporary name
+ tempName := generateTempName()
+
+ slog.InfoContext(ctx, "PrepareForSelfUpdate: renaming Arcane container for self-update", "containerID", containerID, "originalName", originalName, "tempName", tempName)
+
+ if err := s.dcli.ContainerRename(ctx, containerID, tempName); err != nil {
+ return "", err
+ }
+
+ return tempName, nil
+}
+
+// CleanupOldArcaneInstances finds and removes old Arcane container instances
+// This should be called on startup to clean up any leftover containers from previous updates
+func (s *SelfUpdate) CleanupOldArcaneInstances(ctx context.Context, keepNewest bool) ([]string, error) {
+ // Find all containers with the Arcane label
+ filterArgs := filters.NewArgs()
+ filterArgs.Add("label", LabelArcane+"=true")
+
+ containers, err := s.dcli.ContainerList(ctx, container.ListOptions{
+ All: true,
+ Filters: filterArgs,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ // Only remove containers that were renamed by Arcane self-update.
+ // This avoids deleting legitimate multi-instance Arcane containers.
+ old := make([]container.Summary, 0, len(containers))
+ for _, c := range containers {
+ name := ExtractContainerName(c)
+ if strings.HasPrefix(name, "arcane-old-") {
+ old = append(old, c)
+ }
+ }
+
+ if len(old) == 0 {
+ return nil, nil // Nothing to clean up
+ }
+
+ // Sort by creation time (newest first)
+ sortByCreated(old)
+
+ var removed []string
+ startIdx := 0
+ if keepNewest {
+ startIdx = 1 // Skip the newest container
+ }
+
+ for _, c := range old[startIdx:] {
+ name := ExtractContainerName(c)
+
+ slog.InfoContext(ctx, "CleanupOldArcaneInstances: removing old Arcane instance", "containerID", c.ID, "name", name, "created", c.Created)
+
+ // Stop if running
+ if c.State == "running" {
+ timeout := 30 // seconds
+ if err := s.dcli.ContainerStop(ctx, c.ID, container.StopOptions{Timeout: &timeout}); err != nil {
+ slog.WarnContext(ctx, "CleanupOldArcaneInstances: failed to stop container", "containerID", c.ID, "error", err)
+ continue
+ }
+ }
+
+ // Remove container
+ if err := s.dcli.ContainerRemove(ctx, c.ID, container.RemoveOptions{Force: true}); err != nil {
+ slog.WarnContext(ctx, "CleanupOldArcaneInstances: failed to remove container", "containerID", c.ID, "error", err)
+ continue
+ }
+
+ removed = append(removed, c.ID)
+ }
+
+ return removed, nil
+}
+
+// GetCurrentArcaneContainer returns the currently running Arcane container, if any
+func (s *SelfUpdate) GetCurrentArcaneContainer(ctx context.Context) (*container.Summary, error) {
+ filterArgs := filters.NewArgs()
+ filterArgs.Add("label", LabelArcane+"=true")
+ filterArgs.Add("status", "running")
+
+ containers, err := s.dcli.ContainerList(ctx, container.ListOptions{
+ Filters: filterArgs,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ if len(containers) == 0 {
+ return nil, nil
+ }
+
+ // Return the newest running instance
+ sortByCreated(containers)
+ return &containers[0], nil
+}
+
+// sortByCreated sorts containers by creation time, newest first
+func sortByCreated(containers []container.Summary) {
+ for i := 0; i < len(containers)-1; i++ {
+ for j := i + 1; j < len(containers); j++ {
+ if containers[i].Created < containers[j].Created {
+ containers[i], containers[j] = containers[j], containers[i]
+ }
+ }
+ }
+}
+
+// generateTempName generates a random temporary name for the old container
+func generateTempName() string {
+ const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
+ b := make([]byte, 8)
+ if _, err := rand.Read(b); err != nil {
+ // Extremely unlikely, but avoid failing the update due to entropy issues.
+ return "arcane-old-fallback-" + strconv.FormatInt(time.Now().UnixNano(), 36)
+ }
+ for i := range b {
+ b[i] = charset[int(b[i])%len(charset)]
+ }
+ return "arcane-old-" + string(b)
+}
diff --git a/backend/internal/utils/arcaneupdater/selfupdate_test.go b/backend/internal/utils/arcaneupdater/selfupdate_test.go
new file mode 100644
index 000000000..7ea61ee9d
--- /dev/null
+++ b/backend/internal/utils/arcaneupdater/selfupdate_test.go
@@ -0,0 +1,142 @@
+package arcaneupdater
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/docker/docker/api/types/container"
+)
+
+func TestGenerateTempName(t *testing.T) {
+ names := make(map[string]bool)
+
+ for i := 0; i < 10; i++ {
+ name := generateTempName()
+
+ if !strings.HasPrefix(name, "arcane-old-") {
+ t.Errorf("generateTempName() = %q, want prefix 'arcane-old-'", name)
+ }
+
+ if len(name) != 19 {
+ t.Errorf("generateTempName() length = %d, want 19", len(name))
+ }
+
+ // Check for valid alphanumeric chars
+ suffix := strings.TrimPrefix(name, "arcane-old-")
+ for _, c := range suffix {
+ if (c < 'a' || c > 'z') && (c < '0' || c > '9') {
+ t.Errorf("generateTempName() suffix contains invalid char: %c in %q", c, suffix)
+ }
+ }
+
+ names[name] = true
+ }
+
+ // Should have unique names
+ if len(names) < 9 {
+ t.Errorf("generateTempName() not unique enough: %d unique out of 10", len(names))
+ }
+}
+
+func TestSortByCreated(t *testing.T) {
+ now := time.Now()
+
+ tests := []struct {
+ name string
+ containers []container.Summary
+ want []string // Expected order (newest first)
+ }{
+ {
+ name: "empty list",
+ containers: []container.Summary{},
+ want: []string{},
+ },
+ {
+ name: "single container",
+ containers: []container.Summary{
+ {ID: "abc", Created: now.Unix()},
+ },
+ want: []string{"abc"},
+ },
+ {
+ name: "two containers - newest first",
+ containers: []container.Summary{
+ {ID: "older", Created: now.Add(-1 * time.Hour).Unix()},
+ {ID: "newer", Created: now.Unix()},
+ },
+ want: []string{"newer", "older"},
+ },
+ {
+ name: "three containers - newest first",
+ containers: []container.Summary{
+ {ID: "oldest", Created: now.Add(-2 * time.Hour).Unix()},
+ {ID: "middle", Created: now.Add(-1 * time.Hour).Unix()},
+ {ID: "newest", Created: now.Unix()},
+ },
+ want: []string{"newest", "middle", "oldest"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ containers := make([]container.Summary, len(tt.containers))
+ copy(containers, tt.containers)
+
+ sortByCreated(containers)
+
+ if len(containers) != len(tt.want) {
+ t.Errorf("sortByCreated() len = %d, want %d", len(containers), len(tt.want))
+ return
+ }
+
+ for i, want := range tt.want {
+ if containers[i].ID != want {
+ t.Errorf("sortByCreated()[%d].ID = %q, want %q", i, containers[i].ID, want)
+ }
+ }
+ })
+ }
+}
+
+func TestNewSelfUpdate(t *testing.T) {
+ su := NewSelfUpdate(nil)
+
+ // NewSelfUpdate always returns a valid instance
+ if su.dcli != nil {
+ t.Error("NewSelfUpdate(nil) should set dcli to nil")
+ }
+}
+
+func TestGenerateTempName_ValidDockerName(t *testing.T) {
+ name := generateTempName()
+
+ // Docker container names must match [a-zA-Z0-9][a-zA-Z0-9_.-]*
+ for i, c := range name {
+ valid := (c >= 'a' && c <= 'z') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c >= '0' && c <= '9') ||
+ c == '-' || c == '_' || c == '.'
+
+ if !valid {
+ t.Errorf("generateTempName()[%d] = %c is not valid for Docker container name", i, c)
+ }
+ }
+}
+
+func TestSortByCreated_SameTimestamp(t *testing.T) {
+ now := time.Now().Unix()
+
+ containers := []container.Summary{
+ {ID: "first", Created: now},
+ {ID: "second", Created: now},
+ {ID: "third", Created: now},
+ }
+
+ sortByCreated(containers)
+
+ // Order should be preserved since all have same timestamp
+ if containers[0].ID != "first" || containers[1].ID != "second" || containers[2].ID != "third" {
+ t.Errorf("sortByCreated() not stable for equal elements")
+ }
+}
diff --git a/backend/internal/utils/arcaneupdater/sorter.go b/backend/internal/utils/arcaneupdater/sorter.go
new file mode 100644
index 000000000..db110e24b
--- /dev/null
+++ b/backend/internal/utils/arcaneupdater/sorter.go
@@ -0,0 +1,220 @@
+package arcaneupdater
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "slices"
+ "strings"
+
+ "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/client"
+)
+
+// ContainerWithDeps represents a container with its dependency information for sorting
+type ContainerWithDeps struct {
+ Container container.Summary
+ Inspect container.InspectResponse
+ Name string
+ Links []string // Container names this one links to
+ DependsOn []string // Explicit dependencies from label
+ NetworkDeps []string // Implicit dependencies from container network mode
+}
+
+// ContainerSorter handles topological sorting of containers based on dependencies
+type ContainerSorter struct {
+ containers []ContainerWithDeps
+ nameToIndex map[string]int
+ visited map[string]bool
+ marked map[string]bool // For cycle detection
+ sorted []ContainerWithDeps
+}
+
+// NewContainerSorter creates a new sorter for the given containers
+func NewContainerSorter(containers []ContainerWithDeps) *ContainerSorter {
+ nameToIndex := make(map[string]int, len(containers))
+ for i, c := range containers {
+ nameToIndex[c.Name] = i
+ }
+ return &ContainerSorter{
+ containers: containers,
+ nameToIndex: nameToIndex,
+ visited: make(map[string]bool),
+ marked: make(map[string]bool),
+ sorted: make([]ContainerWithDeps, 0, len(containers)),
+ }
+}
+
+// Sort performs topological sort and returns containers in dependency order
+// Dependencies come first, dependents come later
+func (s *ContainerSorter) Sort() ([]ContainerWithDeps, error) {
+ for _, c := range s.containers {
+ if !s.visited[c.Name] {
+ if err := s.visit(c); err != nil {
+ return nil, err
+ }
+ }
+ }
+ return s.sorted, nil
+}
+
+// SortReverse returns containers in reverse dependency order
+// Dependents come first, dependencies come later (for stopping)
+func (s *ContainerSorter) SortReverse() ([]ContainerWithDeps, error) {
+ sorted, err := s.Sort()
+ if err != nil {
+ return nil, err
+ }
+
+ slices.Reverse(sorted)
+ return sorted, nil
+}
+
+func (s *ContainerSorter) visit(c ContainerWithDeps) error {
+ if s.marked[c.Name] {
+ return fmt.Errorf("circular dependency detected: %s", c.Name)
+ }
+ if s.visited[c.Name] {
+ return nil
+ }
+
+ s.marked[c.Name] = true
+ defer delete(s.marked, c.Name)
+
+ // Visit all dependencies first
+ allDeps := s.getAllDependencies(c)
+ for _, depName := range allDeps {
+ if idx, ok := s.nameToIndex[depName]; ok {
+ if err := s.visit(s.containers[idx]); err != nil {
+ return err
+ }
+ }
+ }
+
+ s.visited[c.Name] = true
+ s.sorted = append(s.sorted, c)
+ return nil
+}
+
+func (s *ContainerSorter) getAllDependencies(c ContainerWithDeps) []string {
+ seen := make(map[string]struct{})
+ var deps []string
+
+ for _, d := range c.Links {
+ if _, ok := seen[d]; !ok {
+ seen[d] = struct{}{}
+ deps = append(deps, d)
+ }
+ }
+ for _, d := range c.DependsOn {
+ if _, ok := seen[d]; !ok {
+ seen[d] = struct{}{}
+ deps = append(deps, d)
+ }
+ }
+ for _, d := range c.NetworkDeps {
+ if _, ok := seen[d]; !ok {
+ seen[d] = struct{}{}
+ deps = append(deps, d)
+ }
+ }
+
+ return deps
+}
+
+// ExtractContainerDeps extracts dependency information from a container
+func ExtractContainerDeps(ctx context.Context, dcli *client.Client, cnt container.Summary, inspect container.InspectResponse) ContainerWithDeps {
+ c := ContainerWithDeps{
+ Container: cnt,
+ Inspect: inspect,
+ Name: ExtractContainerName(cnt),
+ }
+
+ // Extract Docker links
+ if inspect.HostConfig != nil {
+ for _, link := range inspect.HostConfig.Links {
+ // Links are in format "container:/alias"
+ parts := strings.SplitN(link, ":", 2)
+ if len(parts) > 0 {
+ linkName := strings.TrimPrefix(parts[0], "/")
+ c.Links = append(c.Links, linkName)
+ }
+ }
+ }
+
+ // Extract explicit depends-on from label
+ if inspect.Config != nil && inspect.Config.Labels != nil {
+ if deps, ok := inspect.Config.Labels[LabelDependsOn]; ok {
+ for _, dep := range strings.Split(deps, ",") {
+ dep = strings.TrimSpace(dep)
+ if dep != "" {
+ c.DependsOn = append(c.DependsOn, dep)
+ }
+ }
+ }
+ }
+
+ // Extract implicit dependencies from network mode (container:xxx)
+ if inspect.HostConfig != nil {
+ nm := inspect.HostConfig.NetworkMode
+ if nm.IsContainer() {
+ // NetworkMode is "container:<name_or_id>"
+ containerRef := strings.TrimPrefix(string(nm), "container:")
+ c.NetworkDeps = append(c.NetworkDeps, containerRef)
+ }
+ }
+
+ slog.DebugContext(ctx, "ExtractContainerDeps: extracted dependencies",
+ "container", c.Name,
+ "links", c.Links,
+ "dependsOn", c.DependsOn,
+ "networkDeps", c.NetworkDeps)
+
+ return c
+}
+
+// UpdateImplicitRestart marks containers that need to restart because their dependencies are restarting.
+// Returns the names of containers that were marked for implicit restart.
+// Note: This function mutates the containers slice by adding "_arcane_implicit_restart" labels.
+func UpdateImplicitRestart(containers []ContainerWithDeps, markedForRestart map[string]bool) []string {
+ var implicitRestarts []string
+
+ for i, c := range containers {
+ if markedForRestart[c.Name] {
+ continue // Already marked
+ }
+
+ // Check if any dependency is marked for restart
+ allDeps := make([]string, 0, len(c.Links)+len(c.DependsOn)+len(c.NetworkDeps))
+ allDeps = append(allDeps, c.Links...)
+ allDeps = append(allDeps, c.DependsOn...)
+ allDeps = append(allDeps, c.NetworkDeps...)
+
+ for _, dep := range allDeps {
+ if markedForRestart[dep] {
+ // This container's dependency is restarting, so it needs to restart too
+ markedForRestart[c.Name] = true
+ if containers[i].Container.Labels == nil {
+ containers[i].Container.Labels = map[string]string{}
+ }
+ containers[i].Container.Labels["_arcane_implicit_restart"] = "true"
+ implicitRestarts = append(implicitRestarts, c.Name)
+ break
+ }
+ }
+ }
+
+ return implicitRestarts
+}
+
+// ExtractContainerName extracts a clean container name from the summary
+func ExtractContainerName(cnt container.Summary) string {
+ if len(cnt.Names) > 0 {
+ n := cnt.Names[0]
+ if strings.HasPrefix(n, "/") {
+ return n[1:]
+ }
+ return n
+ }
+ return cnt.ID[:12]
+}
diff --git a/backend/internal/utils/arcaneupdater/sorter_test.go b/backend/internal/utils/arcaneupdater/sorter_test.go
new file mode 100644
index 000000000..3f7681c2c
--- /dev/null
+++ b/backend/internal/utils/arcaneupdater/sorter_test.go
@@ -0,0 +1,390 @@
+package arcaneupdater
+
+import (
+ "testing"
+
+ "github.com/docker/docker/api/types/container"
+)
+
+func TestContainerSorter_Sort(t *testing.T) {
+ tests := []struct {
+ name string
+ containers []ContainerWithDeps
+ want []string // Expected order by name
+ wantErr bool
+ }{
+ {
+ name: "empty containers",
+ containers: []ContainerWithDeps{},
+ want: []string{},
+ wantErr: false,
+ },
+ {
+ name: "single container no deps",
+ containers: []ContainerWithDeps{
+ {Name: "app", Container: container.Summary{ID: "app1"}},
+ },
+ want: []string{"app"},
+ wantErr: false,
+ },
+ {
+ name: "two containers no deps",
+ containers: []ContainerWithDeps{
+ {Name: "app", Container: container.Summary{ID: "app1"}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ },
+ want: []string{"app", "db"},
+ wantErr: false,
+ },
+ {
+ name: "simple dependency - app depends on db",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ },
+ want: []string{"db", "app"},
+ wantErr: false,
+ },
+ {
+ name: "link dependency - app links to db",
+ containers: []ContainerWithDeps{
+ {Name: "app", Links: []string{"db"}, Container: container.Summary{ID: "app1"}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ },
+ want: []string{"db", "app"},
+ wantErr: false,
+ },
+ {
+ name: "network dependency - app uses db network",
+ containers: []ContainerWithDeps{
+ {Name: "app", NetworkDeps: []string{"db"}, Container: container.Summary{ID: "app1"}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ },
+ want: []string{"db", "app"},
+ wantErr: false,
+ },
+ {
+ name: "chain dependency - app -> db -> cache",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},
+ {Name: "db", DependsOn: []string{"cache"}, Container: container.Summary{ID: "db1"}},
+ {Name: "cache", Container: container.Summary{ID: "cache1"}},
+ },
+ want: []string{"cache", "db", "app"},
+ wantErr: false,
+ },
+ {
+ name: "multiple dependencies - app depends on db and cache",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db", "cache"}, Container: container.Summary{ID: "app1"}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ {Name: "cache", Container: container.Summary{ID: "cache1"}},
+ },
+ want: []string{"db", "cache", "app"},
+ wantErr: false,
+ },
+ {
+ name: "diamond dependency - app and worker depend on db, both depend on cache",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},
+ {Name: "worker", DependsOn: []string{"db"}, Container: container.Summary{ID: "worker1"}},
+ {Name: "db", DependsOn: []string{"cache"}, Container: container.Summary{ID: "db1"}},
+ {Name: "cache", Container: container.Summary{ID: "cache1"}},
+ },
+ want: []string{"cache", "db", "app", "worker"},
+ wantErr: false,
+ },
+ {
+ name: "circular dependency - app -> db -> app",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},
+ {Name: "db", DependsOn: []string{"app"}, Container: container.Summary{ID: "db1"}},
+ },
+ want: nil,
+ wantErr: true,
+ },
+ {
+ name: "circular dependency chain - app -> db -> cache -> app",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},
+ {Name: "db", DependsOn: []string{"cache"}, Container: container.Summary{ID: "db1"}},
+ {Name: "cache", DependsOn: []string{"app"}, Container: container.Summary{ID: "cache1"}},
+ },
+ want: nil,
+ wantErr: true,
+ },
+ {
+ name: "missing dependency - app depends on nonexistent db",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},
+ },
+ want: []string{"app"},
+ wantErr: false,
+ },
+ {
+ name: "mixed dependency types - links, depends-on, network",
+ containers: []ContainerWithDeps{
+ {Name: "app", Links: []string{"db"}, NetworkDeps: []string{"proxy"}, Container: container.Summary{ID: "app1"}},
+ {Name: "worker", DependsOn: []string{"db"}, Container: container.Summary{ID: "worker1"}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ {Name: "proxy", Container: container.Summary{ID: "proxy1"}},
+ },
+ want: []string{"db", "proxy", "app", "worker"},
+ wantErr: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ s := NewContainerSorter(tt.containers)
+ got, err := s.Sort()
+
+ if (err != nil) != tt.wantErr {
+ t.Errorf("Sort() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+
+ if tt.wantErr {
+ return
+ }
+
+ if len(got) != len(tt.want) {
+ t.Errorf("Sort() returned %d containers, want %d", len(got), len(tt.want))
+ return
+ }
+
+ for i, c := range got {
+ if c.Name != tt.want[i] {
+ t.Errorf("Sort()[%d].Name = %v, want %v", i, c.Name, tt.want[i])
+ }
+ }
+ })
+ }
+}
+
+func TestContainerSorter_SortReverse(t *testing.T) {
+ tests := []struct {
+ name string
+ containers []ContainerWithDeps
+ want []string // Expected reverse order by name
+ wantErr bool
+ }{
+ {
+ name: "empty containers",
+ containers: []ContainerWithDeps{},
+ want: []string{},
+ wantErr: false,
+ },
+ {
+ name: "simple dependency - reverse should be app then db",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ },
+ want: []string{"app", "db"},
+ wantErr: false,
+ },
+ {
+ name: "chain dependency - reverse should be app -> db -> cache",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},
+ {Name: "db", DependsOn: []string{"cache"}, Container: container.Summary{ID: "db1"}},
+ {Name: "cache", Container: container.Summary{ID: "cache1"}},
+ },
+ want: []string{"app", "db", "cache"},
+ wantErr: false,
+ },
+ {
+ name: "circular dependency",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},
+ {Name: "db", DependsOn: []string{"app"}, Container: container.Summary{ID: "db1"}},
+ },
+ want: nil,
+ wantErr: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ s := NewContainerSorter(tt.containers)
+ got, err := s.SortReverse()
+
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SortReverse() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+
+ if tt.wantErr {
+ return
+ }
+
+ if len(got) != len(tt.want) {
+ t.Errorf("SortReverse() returned %d containers, want %d", len(got), len(tt.want))
+ return
+ }
+
+ for i, c := range got {
+ if c.Name != tt.want[i] {
+ t.Errorf("SortReverse()[%d].Name = %v, want %v", i, c.Name, tt.want[i])
+ }
+ }
+ })
+ }
+}
+
+func TestUpdateImplicitRestart(t *testing.T) {
+ tests := []struct {
+ name string
+ containers []ContainerWithDeps
+ markedForRestart map[string]bool
+ wantImplicit []string
+ wantMarkedAfter map[string]bool
+ }{
+ {
+ name: "no containers",
+ containers: []ContainerWithDeps{},
+ markedForRestart: map[string]bool{},
+ wantImplicit: []string{},
+ wantMarkedAfter: map[string]bool{},
+ },
+ {
+ name: "no dependencies, no restarts",
+ containers: []ContainerWithDeps{
+ {Name: "app", Container: container.Summary{ID: "app1"}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ },
+ markedForRestart: map[string]bool{},
+ wantImplicit: []string{},
+ wantMarkedAfter: map[string]bool{},
+ },
+ {
+ name: "db marked for restart, app depends on db",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1", Labels: map[string]string{}}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ },
+ markedForRestart: map[string]bool{"db": true},
+ wantImplicit: []string{"app"},
+ wantMarkedAfter: map[string]bool{"db": true, "app": true},
+ },
+ {
+ name: "chain reaction - cache restart triggers db (not app in single pass)",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1", Labels: map[string]string{}}},
+ {Name: "db", DependsOn: []string{"cache"}, Container: container.Summary{ID: "db1", Labels: map[string]string{}}},
+ {Name: "cache", Container: container.Summary{ID: "cache1"}},
+ },
+ markedForRestart: map[string]bool{"cache": true},
+ wantImplicit: []string{"db"}, // Only direct dependencies in single pass
+ wantMarkedAfter: map[string]bool{"cache": true, "db": true},
+ },
+ {
+ name: "app already marked, should not be in implicit list",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ },
+ markedForRestart: map[string]bool{"db": true, "app": true},
+ wantImplicit: []string{},
+ wantMarkedAfter: map[string]bool{"db": true, "app": true},
+ },
+ {
+ name: "link dependency triggers restart",
+ containers: []ContainerWithDeps{
+ {Name: "app", Links: []string{"db"}, Container: container.Summary{ID: "app1", Labels: map[string]string{}}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ },
+ markedForRestart: map[string]bool{"db": true},
+ wantImplicit: []string{"app"},
+ wantMarkedAfter: map[string]bool{"db": true, "app": true},
+ },
+ {
+ name: "network dependency triggers restart",
+ containers: []ContainerWithDeps{
+ {Name: "app", NetworkDeps: []string{"db"}, Container: container.Summary{ID: "app1", Labels: map[string]string{}}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ },
+ markedForRestart: map[string]bool{"db": true},
+ wantImplicit: []string{"app"},
+ wantMarkedAfter: map[string]bool{"db": true, "app": true},
+ },
+ {
+ name: "multiple dependencies - one triggers restart",
+ containers: []ContainerWithDeps{
+ {Name: "app", DependsOn: []string{"db", "cache"}, Container: container.Summary{ID: "app1", Labels: map[string]string{}}},
+ {Name: "db", Container: container.Summary{ID: "db1"}},
+ {Name: "cache", Container: container.Summary{ID: "cache1"}},
+ },
+ markedForRestart: map[string]bool{"db": true},
+ wantImplicit: []string{"app"},
+ wantMarkedAfter: map[string]bool{"db": true, "app": true},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := UpdateImplicitRestart(tt.containers, tt.markedForRestart)
+
+ if len(got) != len(tt.wantImplicit) {
+ t.Errorf("UpdateImplicitRestart() returned %d implicit restarts, want %d", len(got), len(tt.wantImplicit))
+ t.Errorf("Got: %v, Want: %v", got, tt.wantImplicit)
+ }
+
+ // Check implicit restart list
+ implicitMap := make(map[string]bool)
+ for _, name := range got {
+ implicitMap[name] = true
+ }
+ for _, want := range tt.wantImplicit {
+ if !implicitMap[want] {
+ t.Errorf("UpdateImplicitRestart() missing implicit restart for %v", want)
+ }
+ }
+
+ // Check markedForRestart map after update
+ for name, want := range tt.wantMarkedAfter {
+ if got := tt.markedForRestart[name]; got != want {
+ t.Errorf("After UpdateImplicitRestart(), markedForRestart[%v] = %v, want %v", name, got, want)
+ }
+ }
+ })
+ }
+}
+
+func TestExtractContainerName(t *testing.T) {
+ tests := []struct {
+ name string
+ cnt container.Summary
+ want string
+ }{
+ {
+ name: "single name with slash",
+ cnt: container.Summary{Names: []string{"/myapp"}, ID: "abc123"},
+ want: "myapp",
+ },
+ {
+ name: "single name without slash",
+ cnt: container.Summary{Names: []string{"myapp"}, ID: "abc123"},
+ want: "myapp",
+ },
+ {
+ name: "multiple names - uses first",
+ cnt: container.Summary{Names: []string{"/myapp", "/myapp-alias"}, ID: "abc123"},
+ want: "myapp",
+ },
+ {
+ name: "no names - falls back to short ID",
+ cnt: container.Summary{Names: []string{}, ID: "abc123456789"},
+ want: "abc123456789",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := ExtractContainerName(tt.cnt); got != tt.want {
+ t.Errorf("ExtractContainerName() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/backend/internal/utils/cgroup_utils.go b/backend/internal/utils/cgroup_utils.go
index 34a33396f..1073559b2 100644
--- a/backend/internal/utils/cgroup_utils.go
+++ b/backend/internal/utils/cgroup_utils.go
@@ -2,9 +2,12 @@ package utils
import (
"bufio"
+ "errors"
"fmt"
+ "log/slog"
"os"
"path/filepath"
+ "regexp"
"strconv"
"strings"
@@ -265,3 +268,110 @@ func readCgroupV1CPUControllerInt64(cgroupPath, filename string) (int64, error)
return 0, lastErr
}
+
+// Container ID detection patterns for cgroup v1 and v2
+var (
+ // cgroup v1: "12:memory:/docker/abc123..." or "12:memory:/kubepods/.../docker/abc123..."
+ cgroupV1ContainerPattern = regexp.MustCompile(`/docker/([a-f0-9]{64})`)
+ // cgroup v2: "0::/system.slice/docker-abc123.scope"
+ cgroupV2ContainerPattern = regexp.MustCompile(`docker-([a-f0-9]{64})\.scope`)
+)
+
+// GetCurrentContainerID detects the current container ID using multiple detection methods
+// It tries cgroup, mountinfo, and hostname in that order
+func GetCurrentContainerID() (string, error) {
+ // Try cgroup first (works on cgroup v1 and cgroupns=host mode)
+ if id, err := getContainerIDFromCgroup(); err == nil {
+ slog.Debug("GetCurrentContainerID: found via cgroup", "containerId", id)
+ return id, nil
+ }
+
+ // Try mountinfo (works when cgroup namespace is private)
+ if id, err := getContainerIDFromMountinfo(); err == nil {
+ slog.Debug("GetCurrentContainerID: found via mountinfo", "containerId", id)
+ return id, nil
+ }
+
+ // Try hostname (Docker often sets hostname to container ID)
+ if id, err := getContainerIDFromHostname(); err == nil {
+ slog.Debug("GetCurrentContainerID: found via hostname", "containerId", id)
+ return id, nil
+ }
+
+ return "", errors.New("no container ID found via cgroup, mountinfo, or hostname")
+}
+
+// getContainerIDFromCgroup tries to extract container ID from /proc/self/cgroup
+func getContainerIDFromCgroup() (string, error) {
+ data, err := os.ReadFile("/proc/self/cgroup")
+ if err != nil {
+ return "", err
+ }
+
+ content := string(data)
+
+ // Try cgroup v1 pattern
+ if matches := cgroupV1ContainerPattern.FindStringSubmatch(content); len(matches) >= 2 {
+ return matches[1], nil
+ }
+
+ // Try cgroup v2 pattern
+ if matches := cgroupV2ContainerPattern.FindStringSubmatch(content); len(matches) >= 2 {
+ return matches[1], nil
+ }
+
+ return "", errors.New("no container ID found in cgroup")
+}
+
+// getContainerIDFromMountinfo tries to extract container ID from /proc/self/mountinfo
+// This works even when cgroup namespace is private (cgroupns=private)
+func getContainerIDFromMountinfo() (string, error) {
+ data, err := os.ReadFile("/proc/self/mountinfo")
+ if err != nil {
+ return "", err
+ }
+
+ content := string(data)
+ lines := strings.Split(content, "\n")
+
+ for _, line := range lines {
+ // Look for Docker container paths in mountinfo
+ 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 {
+ id := idParts[0]
+ if len(id) >= 64 {
+ return id[:64], nil
+ }
+ return id, nil
+ }
+ }
+ }
+ }
+
+ return "", errors.New("no container ID found in mountinfo")
+}
+
+// getContainerIDFromHostname tries to use hostname as container ID
+// Docker often sets the hostname to the container ID (12 or 64 hex chars)
+func getContainerIDFromHostname() (string, error) {
+ hostname, err := os.Hostname()
+ if err != nil {
+ return "", err
+ }
+
+ // Docker often sets hostname to the short container ID (12 chars) or full ID (64 chars)
+ if len(hostname) == 12 || len(hostname) == 64 {
+ // Verify it looks like a hex string
+ for _, c := range hostname {
+ if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
+ return "", errors.New("hostname doesn't match container ID pattern")
+ }
+ }
+ return hostname, nil
+ }
+
+ return "", errors.New("hostname doesn't match expected container ID length")
+}
diff --git a/backend/internal/utils/docker/mount_utils.go b/backend/internal/utils/docker/mount_utils.go
new file mode 100644
index 000000000..b940af9aa
--- /dev/null
+++ b/backend/internal/utils/docker/mount_utils.go
@@ -0,0 +1,55 @@
+package docker
+
+import (
+ "strings"
+
+ containertypes "github.com/docker/docker/api/types/container"
+ mounttypes "github.com/docker/docker/api/types/mount"
+)
+
+// MountForDestination returns a Mount suitable for container creation that mirrors an
+// existing container mount at the given destination.
+//
+// It currently supports bind and named volume mounts. If target is empty, destination
+// is used as the target.
+func MountForDestination(mounts []containertypes.MountPoint, destination string, target string) *mounttypes.Mount {
+ if strings.TrimSpace(destination) == "" {
+ return nil
+ }
+ if strings.TrimSpace(target) == "" {
+ target = destination
+ }
+
+ for _, m := range mounts {
+ if m.Destination != destination {
+ continue
+ }
+
+ readOnly := !m.RW
+
+ switch m.Type {
+ case mounttypes.TypeVolume:
+ if strings.TrimSpace(m.Name) == "" {
+ return nil
+ }
+ return &mounttypes.Mount{Type: mounttypes.TypeVolume, Source: m.Name, Target: target, ReadOnly: readOnly}
+ case mounttypes.TypeBind:
+ if strings.TrimSpace(m.Source) == "" {
+ return nil
+ }
+ return &mounttypes.Mount{Type: mounttypes.TypeBind, Source: m.Source, Target: target, ReadOnly: readOnly}
+ case mounttypes.TypeTmpfs:
+ return nil
+ case mounttypes.TypeNamedPipe:
+ return nil
+ case mounttypes.TypeCluster:
+ return nil
+ case mounttypes.TypeImage:
+ return nil
+ default:
+ return nil
+ }
+ }
+
+ return nil
+}
diff --git a/backend/internal/utils/pagination/filters.go b/backend/internal/utils/pagination/filters.go
index 101fb75ec..ee6d3a34a 100644
--- a/backend/internal/utils/pagination/filters.go
+++ b/backend/internal/utils/pagination/filters.go
@@ -1,11 +1,5 @@
package pagination
-import (
- "strconv"
-
- "github.com/gin-gonic/gin"
-)
-
type FilterResult[T any] struct {
Items []T
TotalCount int64
@@ -72,8 +66,3 @@ func filterFn[T any](items []T, filters map[string]string, accessors []FilterAcc
}
return results
}
-
-func ApplyFilterResultsHeaders[T any](w *gin.ResponseWriter, result FilterResult[T]) {
- (*w).Header().Set("X-Arcane-Total-Items", strconv.FormatInt(result.TotalCount, 10))
- (*w).Header().Set("X-Arcane-Total-Available", strconv.FormatInt(result.TotalAvailable, 10))
-}
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 8e3f1911f..bf6141525 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -96,6 +96,6 @@ org.opencontainers.image.ref.name="arcane" \
org.opencontainers.image.title="Arcane" \
org.opencontainers.image.description="Modern Docker Management, Made for Everyone" \
com.getarcaneapp.arcane.updater="false" \
-com.getarcaneapp.arcane.server="true"
+com.getarcaneapp.arcane="true"
CMD ["./arcane"]
\ No newline at end of file
diff --git a/docker/Dockerfile-agent b/docker/Dockerfile-agent
index 50d8ecfce..9d76c2fc1 100644
--- a/docker/Dockerfile-agent
+++ b/docker/Dockerfile-agent
@@ -74,7 +74,7 @@ LABEL org.opencontainers.image.title="Arcane Agent"
LABEL org.opencontainers.image.description="Arcane Agent"
LABEL com.getarcaneapp.arcane.updater="false"
-LABEL com.getarcaneapp.arcane.server="true"
+LABEL com.getarcaneapp.arcane.agent="true"
EXPOSE 3553
VOLUME ["/app/data"]
diff --git a/docker/compose.dev.yaml b/docker/compose.dev.yaml
index 5745e7aae..850164bfe 100644
--- a/docker/compose.dev.yaml
+++ b/docker/compose.dev.yaml
@@ -127,21 +127,19 @@ networks:
arcane-dev:
driver: bridge
name: arcane-dev-network
- external: true
volumes:
arcane-dev-data:
name: arcane-dev-data
- external: true
+
agent-dev-data:
name: agent-dev-data
- external: true
+
go-build-cache:
name: arcane-go-build-cache
- external: true
+
go-mod-cache:
name: arcane-go-mod-cache
- external: true
+
pnpm-cache:
name: arcane-pnpm-cache
- external: true
diff --git a/docker/examples/compose.agent.yaml b/docker/examples/compose.agent.yaml
index ff9d1cc66..1a9bac5f6 100644
--- a/docker/examples/compose.agent.yaml
+++ b/docker/examples/compose.agent.yaml
@@ -11,6 +11,9 @@ services:
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- agent-data:/app/data
+ # Use host cgroup namespace for better container self-detection
+ # This allows Arcane to detect its own container ID more reliably
+ cgroup: host
restart: unless-stopped
volumes:
diff --git a/docker/examples/compose.basic.yaml b/docker/examples/compose.basic.yaml
index fb7c1e0f2..eac030257 100644
--- a/docker/examples/compose.basic.yaml
+++ b/docker/examples/compose.basic.yaml
@@ -11,6 +11,9 @@ services:
environment:
- ENCRYPTION_KEY=xxxxxxxxxxxxxxxxxxxxxx
- JWT_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxx
+ # Use host cgroup namespace for better container self-detection
+ # This allows Arcane to detect its own container ID more reliably
+ cgroup: host
healthcheck:
test:
[
diff --git a/docker/examples/compose.proxy.yaml b/docker/examples/compose.proxy.yaml
index c37ee1c9d..edc160db1 100644
--- a/docker/examples/compose.proxy.yaml
+++ b/docker/examples/compose.proxy.yaml
@@ -62,6 +62,9 @@ services:
timeout: 3s
retries: 5
start_period: 15s
+ # Use host cgroup namespace for better container self-detection
+ # This allows Arcane to detect its own container ID more reliably
+ cgroup: host
restart: unless-stopped
networks:
diff --git a/frontend/src/lib/components/dialogs/upgrade-confirmation-dialog.svelte b/frontend/src/lib/components/dialogs/upgrade-confirmation-dialog.svelte
index bffb75007..bf78f91d4 100644
--- a/frontend/src/lib/components/dialogs/upgrade-confirmation-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/upgrade-confirmation-dialog.svelte
@@ -7,10 +7,13 @@
import systemUpgradeService from '$lib/services/api/system-upgrade-service';
import { cn } from '$lib/utils';
import { AlertIcon, InfoIcon, SuccessIcon } from '$lib/icons';
+ import type { AppVersionInformation } from '$lib/types/application-configuration';
let {
open = $bindable(false),
version,
+ expectedVersion,
+ expectedDigest,
onConfirm,
environmentName,
environmentId,
@@ -18,7 +21,9 @@
}: {
open?: boolean;
version: string;
- onConfirm: () => void;
+ expectedVersion?: string;
+ expectedDigest?: string;
+ onConfirm: () => void | Promise<void>;
environmentName?: string;
environmentId?: string;
upgrading?: boolean;
@@ -29,64 +34,137 @@
let upgradeStatus = $state<'upgrading' | 'waiting' | 'ready' | 'countdown'>('upgrading');
let countdown = $state(10);
- let pollInterval: ReturnType<typeof setInterval> | null = null;
+ let pollAbort = $state<{ aborted: boolean } | 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();
+ let baselineVersionInfo = $state<AppVersionInformation | null>(null);
+ let lastSeenVersionInfo = $state<AppVersionInformation | null>(null);
+ let consecutiveHealthyChecks = $state(0);
+
+ function short(v?: string | null, n = 12): string {
+ if (!v) return '';
+ const s = String(v);
+ return s.length > n ? s.slice(0, n) : s;
+ }
+
+ function log(step: string, data?: unknown) {
+ if (data === undefined) {
+ console.log(`[Upgrade] ${step}`);
+ return;
+ }
+ console.log(`[Upgrade] ${step}`, data);
+ }
+
+ function versionInfoChanged(a: AppVersionInformation | null, b: AppVersionInformation | null) {
+ if (!a || !b) return false;
+ return (
+ (a.currentDigest && b.currentDigest && a.currentDigest !== b.currentDigest) ||
+ a.currentVersion !== b.currentVersion ||
+ a.revision !== b.revision ||
+ a.displayVersion !== b.displayVersion
+ );
+ }
+
+ function matchesExpected(info: AppVersionInformation) {
+ const expVer = expectedVersion?.trim();
+ const expDig = expectedDigest?.trim();
+ if (expVer) return info.currentVersion === expVer;
+ if (expDig) return info.currentDigest === expDig;
+ return true;
+ }
+
+ async function monitorUpgrade() {
+ const envId = environmentId ?? '0';
+ log('monitor-start', {
+ envId,
+ expectedVersion,
+ expectedDigest: short(expectedDigest)
+ });
+
+ pollAbort = { aborted: false };
+ const abortRef = pollAbort;
+
+ upgradeStatus = 'waiting';
+ consecutiveHealthyChecks = 0;
+
+ const startedAt = Date.now();
+ const timeoutMs = 3 * 60 * 1000;
+ let delayMs = 1000;
+
+ while (!abortRef.aborted && Date.now() - startedAt < timeoutMs) {
+ const { healthy } = await systemUpgradeService.checkHealth(envId);
+ if (!healthy) {
+ log('health', { healthy, consecutiveHealthyChecks, backoffMs: delayMs });
+ consecutiveHealthyChecks = 0;
+ await new Promise((r) => setTimeout(r, delayMs));
+ delayMs = Math.min(Math.round(delayMs * 1.4), 5000);
+ continue;
+ }
+
+ consecutiveHealthyChecks++;
+ log('health', { healthy, consecutiveHealthyChecks });
+ if (consecutiveHealthyChecks < 2) {
+ await new Promise((r) => setTimeout(r, 1000));
+ continue;
+ }
+
+ try {
+ const info = await systemUpgradeService.getVersionInfo(envId);
+ lastSeenVersionInfo = info;
+
+ const expVer = expectedVersion?.trim();
+ const expDig = expectedDigest?.trim();
+ const ok = matchesExpected(info);
+ const changed = versionInfoChanged(baselineVersionInfo, info);
+
+ log('version-check', {
+ currentVersion: info.currentVersion,
+ currentDigest: short(info.currentDigest),
+ revision: short(info.revision, 8),
+ baselineVersion: baselineVersionInfo?.currentVersion,
+ baselineDigest: short(baselineVersionInfo?.currentDigest),
+ ok
+ });
+
+ const verified = expVer || expDig ? ok : !!baselineVersionInfo && changed;
+ if (verified) {
+ log('verified', {
+ mode: expVer || expDig ? 'expected' : 'baseline-change',
+ currentVersion: info.currentVersion,
+ currentDigest: short(info.currentDigest)
+ });
+ upgradeStatus = 'ready';
+ setTimeout(() => startCountdown(), 1500);
+ return;
}
- }, 150000);
- }, 15000);
+ } catch (err) {
+ log('version-endpoint-error', err);
+ }
+
+ await new Promise((r) => setTimeout(r, 2000));
+ }
+
+ if (!abortRef.aborted) {
+ log('monitor-timeout', { timeoutMs });
+ upgradeStatus = 'upgrading';
+ upgrading = false;
+ }
+ }
+
+ async function captureBaseline() {
+ try {
+ baselineVersionInfo = await systemUpgradeService.getVersionInfo(environmentId ?? '0');
+ lastSeenVersionInfo = baselineVersionInfo;
+ log('baseline', {
+ currentVersion: baselineVersionInfo.currentVersion,
+ currentDigest: short(baselineVersionInfo.currentDigest),
+
+ revision: short(baselineVersionInfo.revision, 8)
+ });
+ } catch (err) {
+ log('baseline-error', err);
+ baselineVersionInfo = null;
+ }
}
function startCountdown() {
@@ -105,19 +183,49 @@
window.location.reload();
}
- function handleConfirm() {
+ async function handleConfirm() {
upgrading = true;
upgradeStatus = 'upgrading';
- onConfirm();
+ log('confirm', {
+ isRemoteEnvironment,
+ environmentId: environmentId ?? '0',
+ expectedVersion,
+ expectedDigest: short(expectedDigest)
+ });
+
+ if (!isRemoteEnvironment) {
+ await captureBaseline();
+ }
+ try {
+ await onConfirm();
+ } catch (err) {
+ log('trigger-error', err);
+ upgrading = false;
+ return;
+ }
+ if (!upgrading) return;
+
if (!isRemoteEnvironment) {
- startHealthPolling();
+ if (fallbackTimeout) clearTimeout(fallbackTimeout);
+ fallbackTimeout = setTimeout(
+ () => {
+ log('fallback-reload', { reason: 'timeout' });
+ if (upgradeStatus !== 'countdown') {
+ reloadPage();
+ }
+ },
+ 4 * 60 * 1000
+ );
+
+ monitorUpgrade();
}
}
onDestroy(() => {
- if (pollInterval) clearInterval(pollInterval);
+ log('destroy');
if (countdownInterval) clearInterval(countdownInterval);
if (fallbackTimeout) clearTimeout(fallbackTimeout);
+ if (pollAbort) pollAbort.aborted = true;
});
</script>
diff --git a/frontend/src/lib/components/dialogs/version-info-dialog.svelte b/frontend/src/lib/components/dialogs/version-info-dialog.svelte
index dc9a36ab7..6b2934c34 100644
--- a/frontend/src/lib/components/dialogs/version-info-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/version-info-dialog.svelte
@@ -1,7 +1,6 @@
<script lang="ts">
- import * as Dialog from '$lib/components/ui/dialog/index.js';
+ import { ResponsiveDialog } from '$lib/components/ui/responsive-dialog/index.js';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { Badge } from '$lib/components/ui/badge';
import type { AppVersionInformation } from '$lib/types/application-configuration';
import { m } from '$lib/paraglide/messages';
import { CopyButton } from '$lib/components/ui/copy-button';
@@ -21,39 +20,40 @@
const logoUrl = $derived(getApplicationLogo(false));
</script>
-<Dialog.Root bind:open {onOpenChange}>
- <Dialog.Content class="sm:max-w-md">
- <Dialog.Header>
- <Dialog.Title class="flex items-center gap-2">
- <img src={logoUrl} alt="Arcane" class="size-6" />
- {m.version_info_title()}
- </Dialog.Title>
- <Dialog.Description>
- {m.version_info_description()}
- </Dialog.Description>
- </Dialog.Header>
+<ResponsiveDialog bind:open {onOpenChange} description={m.version_info_description()} contentClass="sm:max-w-md">
+ {#snippet title()}
+ <div class="flex items-center gap-2">
+ <img src={logoUrl} alt="Arcane" class="size-6" />
+ {m.version_info_title()}
+ </div>
+ {/snippet}
- <div class="space-y-2 rounded-lg border p-3">
- {@render infoRow(m.version_info_version(), versionInfo.displayVersion || versionInfo.currentVersion)}
+ {#snippet children()}
+ <div class="flex flex-col gap-6 pt-4">
+ <div class="space-y-1.5 rounded-lg border p-3">
+ {@render infoRow(m.version_info_version(), versionInfo.displayVersion || versionInfo.currentVersion)}
- {#if versionInfo.currentTag}
- {@render infoRow(m.version_info_tag(), versionInfo.currentTag)}
- {/if}
+ {#if versionInfo.currentTag}
+ {@render infoRow(m.version_info_tag(), versionInfo.currentTag)}
+ {/if}
- {@render infoRowWithCopy(m.version_info_full_commit(), shortCommit, versionInfo.revision)}
+ {@render infoRowWithCopy(m.version_info_full_commit(), shortCommit, versionInfo.revision)}
- {@render infoRow(m.version_info_go_version(), versionInfo.goVersion || '-')}
+ {@render infoRow(m.version_info_go_version(), versionInfo.goVersion || '-')}
- {#if versionInfo.buildTime && versionInfo.buildTime !== 'unknown'}
- {@render infoRow(m.version_info_build_time(), versionInfo.buildTime)}
- {/if}
+ {#if versionInfo.buildTime && versionInfo.buildTime !== 'unknown'}
+ {@render infoRow(m.version_info_build_time(), versionInfo.buildTime, false)}
+ {/if}
- {#if versionInfo.currentDigest}
- {@render infoRowWithCopy(m.version_info_digest(), shortDigest, versionInfo.currentDigest)}
- {/if}
+ {#if versionInfo.currentDigest}
+ {@render infoRowWithCopy(m.version_info_digest(), shortDigest, versionInfo.currentDigest)}
+ {/if}
+ </div>
</div>
+ {/snippet}
- <Dialog.Footer class="flex-col gap-2 sm:flex-row">
+ {#snippet footer()}
+ <div class="flex w-full flex-col gap-2 sm:flex-row sm:justify-end">
{#if versionInfo.releaseUrl}
<ArcaneButton
action="base"
@@ -80,22 +80,22 @@
title="GitHub"
icon={GithubIcon}
/>
- </Dialog.Footer>
- </Dialog.Content>
-</Dialog.Root>
+ </div>
+ {/snippet}
+</ResponsiveDialog>
-{#snippet infoRow(label: string, value: string | undefined | null)}
+{#snippet infoRow(label: string, value: string | undefined | null, mono: boolean = true)}
<div class="flex items-center justify-between gap-4">
- <span class="text-muted-foreground shrink-0 text-xs">{label}</span>
- <Badge variant="secondary" class="text-xs font-normal" title={value ?? ''}>{value || '-'}</Badge>
+ <span class="text-muted-foreground shrink-0 text-xs tracking-tight uppercase">{label}</span>
+ <span class="text-sm {mono ? 'font-mono' : ''}" title={value ?? ''}>{value || '-'}</span>
</div>
{/snippet}
{#snippet infoRowWithCopy(label: string, displayValue: string, fullValue: string | undefined | null)}
<div class="flex items-center justify-between gap-4">
- <span class="text-muted-foreground shrink-0 text-xs">{label}</span>
+ <span class="text-muted-foreground shrink-0 text-xs tracking-tight uppercase">{label}</span>
<div class="flex items-center gap-2">
- <Badge variant="secondary" class="text-xs font-normal" title={fullValue ?? ''}>{displayValue}</Badge>
+ <span class="font-mono text-sm" title={fullValue ?? ''}>{displayValue}</span>
{#if fullValue && fullValue !== 'unknown'}
<CopyButton text={fullValue} size="icon" class="size-6" />
{/if}
diff --git a/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte b/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte
index e7912d9e3..38a617f5d 100644
--- a/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte
@@ -12,6 +12,7 @@
import { toast } from 'svelte-sonner';
import { onMount } from 'svelte';
import { DownloadIcon, ExternalLinkIcon } from '$lib/icons';
+ import { extractApiErrorMessage } from '$lib/utils/api.util';
let {
isCollapsed,
@@ -104,8 +105,9 @@
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 }));
+ const errorMessage = extractApiErrorMessage(error);
+ const wrappedPrefix = m.upgrade_failed({ error: '' });
+ toast.error(errorMessage.startsWith(wrappedPrefix) ? errorMessage : m.upgrade_failed({ error: errorMessage }));
upgrading = false;
}
}
@@ -150,6 +152,8 @@
bind:open={showConfirmDialog}
bind:upgrading
version={versionInformation?.newestVersion ?? ''}
+ expectedVersion={versionInformation?.newestVersion}
+ expectedDigest={versionInformation?.newestDigest}
onConfirm={handleConfirmUpgrade}
/>
diff --git a/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.svelte b/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.svelte
index 6d9e76f4e..a9707ce12 100644
--- a/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.svelte
+++ b/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.svelte
@@ -27,6 +27,14 @@
}
</script>
+{#snippet renderTitle()}
+ {#if typeof title === 'string'}
+ {title}
+ {:else if title}
+ {@render title()}
+ {/if}
+{/snippet}
+
{#if isDesktop.current}
{#if variant === 'sheet'}
<Sheet.Root bind:open onOpenChange={handleOpenChange}>
@@ -39,7 +47,7 @@
{#if title || description}
<Sheet.Header class="shrink-0 px-6 pt-6">
{#if title}
- <Sheet.Title>{title}</Sheet.Title>
+ <Sheet.Title>{@render renderTitle()}</Sheet.Title>
{/if}
{#if description}
<Sheet.Description>{description}</Sheet.Description>
@@ -72,7 +80,7 @@
{#if title || description}
<Dialog.Header class="shrink-0 px-6 pt-6">
{#if title}
- <Dialog.Title>{title}</Dialog.Title>
+ <Dialog.Title>{@render renderTitle()}</Dialog.Title>
{/if}
{#if description}
<Dialog.Description>{description}</Dialog.Description>
@@ -101,7 +109,7 @@
{#if title || description}
<Drawer.Header class="shrink-0 text-left">
{#if title}
- <Drawer.Title>{title}</Drawer.Title>
+ <Drawer.Title>{@render renderTitle()}</Drawer.Title>
{/if}
{#if description}
<Drawer.Description>{description}</Drawer.Description>
diff --git a/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.type.ts b/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.type.ts
index 0002c37ed..336c32c02 100644
--- a/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.type.ts
+++ b/frontend/src/lib/components/ui/responsive-dialog/responsive-dialog.type.ts
@@ -21,7 +21,7 @@ export interface ResponsiveDialogProps {
/**
* Title displayed in the dialog/drawer header
*/
- title?: string;
+ title?: string | Snippet;
/**
* Description displayed in the dialog/drawer header
diff --git a/frontend/src/lib/services/api/system-upgrade-service.ts b/frontend/src/lib/services/api/system-upgrade-service.ts
index bde9ffca6..2c2ea8333 100644
--- a/frontend/src/lib/services/api/system-upgrade-service.ts
+++ b/frontend/src/lib/services/api/system-upgrade-service.ts
@@ -1,4 +1,5 @@
import axios from 'axios';
+import type { AppVersionInformation } from '$lib/types/application-configuration';
export interface UpgradeCheckResponse {
canUpgrade: boolean;
@@ -16,6 +17,12 @@ export interface HealthCheckResult {
healthy: boolean;
}
+type ApiResponse<T> = {
+ success: boolean;
+ data: T;
+ message?: string;
+};
+
/**
* Check if the system can perform a self-upgrade
* @returns Promise with upgrade availability status
@@ -51,8 +58,25 @@ async function checkHealth(environmentId: string = '0'): Promise<HealthCheckResu
}
}
+/**
+ * Fetch the running version info (including current digest) for the local system (envId=0)
+ * or a remote environment.
+ */
+async function getVersionInfo(environmentId: string = '0'): Promise<AppVersionInformation> {
+ if (environmentId === '0') {
+ const res = await axios.get<AppVersionInformation>('/api/app-version', { timeout: 5000 });
+ return res.data;
+ }
+
+ const res = await axios.get<ApiResponse<AppVersionInformation>>(`/api/environments/${environmentId}/version`, {
+ timeout: 5000
+ });
+ return res.data.data;
+}
+
export default {
checkUpgradeAvailable,
triggerUpgrade,
- checkHealth
+ checkHealth,
+ getVersionInfo
};
diff --git a/frontend/src/lib/utils/api.util.ts b/frontend/src/lib/utils/api.util.ts
index 7e38d8fe2..1bbe98274 100644
--- a/frontend/src/lib/utils/api.util.ts
+++ b/frontend/src/lib/utils/api.util.ts
@@ -1,21 +1,53 @@
import type { Result } from './try-catch';
import { toast } from 'svelte-sonner';
-function extractDockerErrorMessage(error: any): string {
+function extractServerMessage(data: any): string | undefined {
+ const inner = data && typeof data === 'object' ? ((data as any).data ?? data) : data;
+ if (typeof inner === 'string') return inner;
+ if (!inner || typeof inner !== 'object') return undefined;
+
+ // Support both Arcane-style (error/message) and Huma RFC 7807 (detail)
+ const msg = (inner as any).error || (inner as any).message || (inner as any).detail || (inner as any).error_description;
+ if (typeof msg === 'string' && msg.trim()) return msg;
+
+ if (Array.isArray((inner as any).errors) && (inner as any).errors.length) {
+ const first = (inner as any).errors[0];
+ if (typeof first === 'string' && first.trim()) return first;
+ if (first && typeof first === 'object') {
+ const em = (first as any).message || (first as any).error;
+ if (typeof em === 'string' && em.trim()) return em;
+ }
+ }
+
+ return undefined;
+}
+
+export function extractApiErrorMessage(error: any): string {
if (!error) return 'Unknown error';
- if (error.response && error.response.data) {
- if (typeof error.response.data === 'string') return error.response.data;
- if (error.response.data.error) return error.response.data.error;
+ const respData = error?.response?.data;
+ const serverMsg = extractServerMessage(respData);
+ if (serverMsg) return serverMsg;
+
+ // Some callers pass `{ body: ... }`
+ const bodyMsg = extractServerMessage(error?.body);
+ if (bodyMsg) return bodyMsg;
+
+ if (typeof error?.error === 'string' && error.error.trim()) return error.error;
+ if (typeof error?.reason === 'string' && error.reason.trim()) return error.reason;
+ if (typeof error?.stderr === 'string' && error.stderr.trim()) return error.stderr;
+ if (typeof error?.data === 'string' && error.data.trim()) return error.data;
+ if (typeof error?.message === 'string' && error.message.trim()) return error.message;
+
+ try {
+ return JSON.stringify(error);
+ } catch {
+ return 'Unknown error';
}
+}
- if (error.body && error.body.error) return error.body.error;
- if (error.error) return error.error;
- if (error.reason) return error.reason;
- if (error.stderr) return error.stderr;
- if (error.data && typeof error.data === 'string') return error.data;
- if (error.message) return error.message;
- return JSON.stringify(error);
+function extractDockerErrorMessage(error: any): string {
+ return extractApiErrorMessage(error);
}
export async function handleApiResultWithCallbacks<T>({
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
index d67b9e9a7..3b084a9c1 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
@@ -28,7 +28,6 @@
import {
ArrowLeftIcon,
AlertIcon,
- RefreshIcon,
VolumesIcon,
FileTextIcon,
SettingsIcon,
@@ -260,11 +259,6 @@
return isNaN(d.getTime()) ? null : d;
}
- function formatDockerDate(input: string | Date | undefined | null, fmt = 'PP p'): string {
- const d = parseDockerDate(input);
- return d ? format(d, fmt) : 'N/A';
- }
-
const backUrl = $derived.by(() => {
const from = page.url.searchParams.get('from');
const projectId = page.url.searchParams.get('projectId');
diff --git a/frontend/src/routes/(app)/environments/environment-table.svelte b/frontend/src/routes/(app)/environments/environment-table.svelte
index fe422ec28..5d95e7709 100644
--- a/frontend/src/routes/(app)/environments/environment-table.svelte
+++ b/frontend/src/routes/(app)/environments/environment-table.svelte
@@ -9,6 +9,7 @@
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import { toast } from 'svelte-sonner';
+ import { extractApiErrorMessage } from '$lib/utils/api.util';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
import type { ColumnSpec, MobileFieldVisibility } from '$lib/components/arcane-table';
import { UniversalMobileCard } from '$lib/components/arcane-table';
@@ -161,8 +162,9 @@
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 }));
+ const errorMessage = extractApiErrorMessage(error);
+ const wrappedPrefix = m.upgrade_failed({ error: '' });
+ toast.error(errorMessage.startsWith(wrappedPrefix) ? errorMessage : m.upgrade_failed({ error: errorMessage }));
} finally {
isLoading.upgrading = false;
upgradingEnvironmentId = null;
diff --git a/scripts/build-docker.sh b/scripts/build-docker.sh
index 5261917e4..9a73f2728 100755
--- a/scripts/build-docker.sh
+++ b/scripts/build-docker.sh
@@ -7,7 +7,7 @@ if [ -f .arcane.json ]; then
REVISION=$(jq -r '.revision // empty' .arcane.json)
fi
VERSION=${VERSION:-"dev"}
-REVISION=${REVISION:-$(git rev-parse --short HEAD 2>/dev/null || "unknown")}
+REVISION=${REVISION:-$(git rev-parse HEAD 2>/dev/null || "unknown")}
# Parse optional arguments
TAG="${1:-arcane:latest}"
diff --git a/scripts/github/build-binaries.sh b/scripts/github/build-binaries.sh
index 337f88814..ebf9011c4 100755
--- a/scripts/github/build-binaries.sh
+++ b/scripts/github/build-binaries.sh
@@ -12,7 +12,7 @@ if [ -f ../.arcane.json ]; then
REVISION=${REVISION:-$(jq -r '.revision // empty' ../.arcane.json)}
fi
VERSION=${VERSION:-"dev"}
-REVISION=${REVISION:-$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")}
+REVISION=${REVISION:-$(git rev-parse HEAD 2>/dev/null || echo "unknown")}
BUILD_TIME=$(date -u '+%Y-%m-%dT%H:%M:%SZ')
LDFLAGS="-w -s -buildid=${VERSION} \
diff --git a/scripts/github/build-cli-binaries.sh b/scripts/github/build-cli-binaries.sh
index 9209ee550..9a7f32e17 100644
--- a/scripts/github/build-cli-binaries.sh
+++ b/scripts/github/build-cli-binaries.sh
@@ -18,7 +18,7 @@ fi
VERSION=${VERSION:-"dev"}
# Tags are typically like v1.2.3; the CLI version string expects 1.2.3.
VERSION=${VERSION#v}
-REVISION=${REVISION:-$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")}
+REVISION=${REVISION:-$(git rev-parse HEAD 2>/dev/null || echo "unknown")}
LDFLAGS="-w -s -buildid=${VERSION} \
-X github.com/getarcaneapp/arcane/cli/internal/config.Version=${VERSION} \
diff --git a/scripts/github/create-release.sh b/scripts/github/create-release.sh
index 844f8fea8..b56e9d5c0 100755
--- a/scripts/github/create-release.sh
+++ b/scripts/github/create-release.sh
@@ -112,7 +112,7 @@ fi
# Update .arcane.json file with the new version and revision
echo "Updating .arcane.json file..."
-LATEST_REVISION=$(git rev-parse --short HEAD)
+LATEST_REVISION=$(git rev-parse HEAD)
jq --arg version "$NEW_VERSION" --arg revision "$LATEST_REVISION" \
'.version = $version | .revision = $revision' .arcane.json > .arcane_tmp.json && mv .arcane_tmp.json .arcane.json
git add .arcane.json
diff --git a/scripts/github/hotfix-release.sh b/scripts/github/hotfix-release.sh
index 21b8ead38..dfbe2c715 100755
--- a/scripts/github/hotfix-release.sh
+++ b/scripts/github/hotfix-release.sh
@@ -180,7 +180,7 @@ echo ""
echo -e "${BLUE}Finalizing hotfix release ${NEW_TAG}...${NC}"
# Update .arcane.json file with the new version and revision
-LATEST_REVISION=$(git rev-parse --short HEAD)
+LATEST_REVISION=$(git rev-parse HEAD)
jq --arg version "$NEW_VERSION" --arg revision "$LATEST_REVISION" \
'.version = $version | .revision = $revision' .arcane.json > .arcane_tmp.json && mv .arcane_tmp.json .arcane.json
git add .arcane.json