Skip to content

Modern Docker Management, Designed for Everyone

feat(backups): add system-managed volume backup scheduling (#3737)

Neureka53a959f93e26
diff --git a/backend/internal/backup/policies.go b/backend/internal/backup/policies.go
index 7fb668538..408976e02 100644
--- a/backend/internal/backup/policies.go
+++ b/backend/internal/backup/policies.go
@@ -8,44 +8,60 @@ import (
"emperror.dev/errors"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
+ s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/schedule"
backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"
"gorm.io/gorm"
)
// PolicyReconciliation reconciles a full set of policy updates against the
-// existing rows of one backup domain: shared validation, create/update/delete
-// in a single transaction, and the scheduled-job swap. Volume and system
-// backups both run through it so the flow cannot drift between them.
-type PolicyReconciliation[P any] struct {
+// existing policies of one backup domain, then swaps the scheduled jobs.
+type PolicyReconciliation[P, U any] struct {
// Domain names the backup flavor in validation errors ("volume", "system").
Domain string
DB *database.DB
// Existing is every policy currently persisted for the reconciled scope.
Existing []P
ID func(*P) string
+ UpdateID func(U) string
// New returns the blank policy for created entries, pre-scoped by the
// caller (e.g. with the volume name set).
- New func() P
- Apply func(*P, backuptypes.UpdateBackupPolicy)
- // ValidateUpdate adds per-domain checks on top of the shared ones; nil skips.
- ValidateUpdate func(backuptypes.UpdateBackupPolicy) error
- // S3Configured verifies the destination exists and is usable; its error is
- // returned to the caller verbatim.
- S3Configured func(ctx context.Context, destinationID string) error
- Unregister func(ctx context.Context, policyID string)
- Reschedule func(ctx context.Context, policy *P)
+ New func() P
+ // Build validates an update and applies it to an existing or new policy.
+ Build func(ctx context.Context, policy *P, update U) error
+ // Persist overrides the default GORM transaction for settings-backed policies.
+ Persist func(ctx context.Context, policies []P) error
+ Unregister func(ctx context.Context, policyID string)
+ Reschedule func(ctx context.Context, policy *P)
}
-func (r PolicyReconciliation[P]) Run(ctx context.Context, updates []backuptypes.UpdateBackupPolicy) error {
- if err := r.validateInternal(ctx, updates); err != nil {
- return err
- }
- policies, kept, err := r.buildInternal(updates)
+func (r PolicyReconciliation[P, U]) Run(ctx context.Context, updates []U) error {
+ policies, kept, err := r.buildInternal(ctx, updates)
if err != nil {
return err
}
- err = r.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := r.persistInternal(ctx, policies, kept); err != nil {
+ return fmt.Errorf("failed to save %s backup policies: %w", r.Domain, err)
+ }
+ for i := range r.Existing {
+ if _, ok := kept[r.ID(&r.Existing[i])]; !ok {
+ r.Unregister(ctx, r.ID(&r.Existing[i]))
+ }
+ }
+ for i := range policies {
+ r.Reschedule(ctx, &policies[i])
+ }
+ return nil
+}
+
+func (r PolicyReconciliation[P, U]) persistInternal(ctx context.Context, policies []P, kept map[string]struct{}) error {
+ if r.Persist != nil {
+ return r.Persist(ctx, policies)
+ }
+ if r.DB == nil {
+ return errors.New("backup policy database is unavailable")
+ }
+ return r.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
for i := range policies {
if saveErr := tx.Save(&policies[i]).Error; saveErr != nil {
return saveErr
@@ -60,57 +76,40 @@ func (r PolicyReconciliation[P]) Run(ctx context.Context, updates []backuptypes.
}
return nil
})
+}
+
+// ValidatePolicyUpdate applies the shared cron, retention, and destination rules used by backup policies.
+func ValidatePolicyUpdate(ctx context.Context, domain string, update backuptypes.UpdateBackupPolicy, s3 *s3domain.S3DestinationService) (backuptypes.UpdateBackupPolicy, error) {
+ normalized, err := schedule.NormalizeSixField(update.Schedule, domain+" backup")
if err != nil {
- return fmt.Errorf("failed to save %s backup policies: %w", r.Domain, err)
+ return update, err
}
- for i := range r.Existing {
- if _, ok := kept[r.ID(&r.Existing[i])]; !ok {
- r.Unregister(ctx, r.ID(&r.Existing[i]))
- }
+ update.Schedule = normalized
+ if update.RetentionCount < 0 || update.RetentionCount > 3650 {
+ return update, errors.New("retentionCount must be between 0 and 3650")
}
- for i := range policies {
- r.Reschedule(ctx, &policies[i])
+ if !update.LocalEnabled && !update.S3Enabled {
+ return update, fmt.Errorf("select at least one %s backup destination", domain)
}
- return nil
-}
-
-// validateInternal checks the shared policy rules and normalizes the updates
-// in place (canonical schedule, cleared destination when S3 is off).
-func (r PolicyReconciliation[P]) validateInternal(ctx context.Context, updates []backuptypes.UpdateBackupPolicy) error {
- for i := range updates {
- normalized, err := schedule.NormalizeSixField(updates[i].Schedule, r.Domain+" backup")
- if err != nil {
- return err
+ if update.S3Enabled {
+ if strings.TrimSpace(update.S3DestinationID) == "" {
+ return update, fmt.Errorf("select an S3 destination for %s backups", domain)
}
- updates[i].Schedule = normalized
- if updates[i].RetentionCount < 0 || updates[i].RetentionCount > 3650 {
- return errors.New("retentionCount must be between 0 and 3650")
+ if s3 == nil {
+ return update, errors.New("S3 backup destinations are unavailable")
}
- if !updates[i].LocalEnabled && !updates[i].S3Enabled {
- return fmt.Errorf("select at least one %s backup destination", r.Domain)
- }
- if updates[i].S3Enabled {
- if strings.TrimSpace(updates[i].S3DestinationID) == "" {
- return fmt.Errorf("select an S3 destination for %s backups", r.Domain)
- }
- if err := r.S3Configured(ctx, updates[i].S3DestinationID); err != nil {
- return err
- }
- } else {
- updates[i].S3DestinationID = ""
- }
- if r.ValidateUpdate != nil {
- if err := r.ValidateUpdate(updates[i]); err != nil {
- return err
- }
+ if _, err := s3.Configuration(ctx, update.S3DestinationID); err != nil {
+ return update, fmt.Errorf("select a valid S3 destination for %s backups", domain)
}
+ } else {
+ update.S3DestinationID = ""
}
- return nil
+ return update, nil
}
// buildInternal maps the updates onto existing or new policy rows and reports
// which existing IDs survive the reconciliation.
-func (r PolicyReconciliation[P]) buildInternal(updates []backuptypes.UpdateBackupPolicy) ([]P, map[string]struct{}, error) {
+func (r PolicyReconciliation[P, U]) buildInternal(ctx context.Context, updates []U) ([]P, map[string]struct{}, error) {
byID := make(map[string]P, len(r.Existing))
for i := range r.Existing {
byID[r.ID(&r.Existing[i])] = r.Existing[i]
@@ -119,18 +118,23 @@ func (r PolicyReconciliation[P]) buildInternal(updates []backuptypes.UpdateBacku
kept := make(map[string]struct{}, len(updates))
for _, update := range updates {
policy := r.New()
- if update.ID != "" {
+ updateID := r.UpdateID(update)
+ if updateID != "" {
var ok bool
- policy, ok = byID[update.ID]
+ policy, ok = byID[updateID]
if !ok {
return nil, nil, fmt.Errorf("%s backup policy not found", r.Domain)
}
- if _, duplicate := kept[update.ID]; duplicate {
+ if _, duplicate := kept[updateID]; duplicate {
return nil, nil, fmt.Errorf("duplicate %s backup policy", r.Domain)
}
- kept[update.ID] = struct{}{}
}
- r.Apply(&policy, update)
+ if err := r.Build(ctx, &policy, update); err != nil {
+ return nil, nil, err
+ }
+ if policyID := r.ID(&policy); policyID != "" {
+ kept[policyID] = struct{}{}
+ }
policies = append(policies, policy)
}
return policies, kept, nil
diff --git a/backend/internal/settings/model.go b/backend/internal/settings/model.go
index 042938280..69843c048 100644
--- a/backend/internal/settings/model.go
+++ b/backend/internal/settings/model.go
@@ -187,6 +187,7 @@ type Settings struct {
S3DestinationsCategoryPlaceholder SettingVariable `key:"s3DestinationsCategory,internal" meta:"label=S3 Destinations;type=internal;keywords=s3,storage,backup,aws,minio,backblaze,hetzner;category=s3destinations;description=Manage reusable S3-compatible storage destinations" catmeta:"id=s3destinations;title=S3 Destinations;icon=remoteenvironment;url=/settings/backups/s3;description=Create and manage reusable S3-compatible backup destinations"`
SystemBackupsCategoryPlaceholder SettingVariable `key:"systemBackupsCategory,internal" meta:"label=Backups;type=internal;keywords=backup,recovery,restore,configuration,secrets;category=systembackups;description=Back up and restore this Arcane instance" catmeta:"id=systembackups;title=Backups;icon=backup;url=/settings/backups;description=Create encrypted recovery backups of Arcane data and configuration"`
+ SystemVolumeBackupConfig SettingVariable `key:"systemVolumeBackupConfig,internal"`
FederatedCredentialsCategoryPlaceholder SettingVariable `key:"federatedCredentialsCategory,internal" meta:"label=Federated Credentials;type=internal;keywords=federated,credentials,workload,identity,oidc,token exchange,ci,github,gitlab;category=authentication;description=Manage workload identity federation credentials"`
diff --git a/backend/internal/settings/service.go b/backend/internal/settings/service.go
index c7cce3fb2..abeb66025 100644
--- a/backend/internal/settings/service.go
+++ b/backend/internal/settings/service.go
@@ -304,7 +304,8 @@ func DefaultSettingsConfig() *Settings {
ApnsChannelID: SettingVariable{Value: ""},
ApnsSigningKey: SettingVariable{Value: ""},
- InstanceID: SettingVariable{Value: ""},
+ InstanceID: SettingVariable{Value: ""},
+ SystemVolumeBackupConfig: SettingVariable{Value: `{"policies":[]}`},
}
}
diff --git a/backend/internal/systembackup/handler.go b/backend/internal/systembackup/handler.go
index 729afca59..146335239 100644
--- a/backend/internal/systembackup/handler.go
+++ b/backend/internal/systembackup/handler.go
@@ -36,6 +36,42 @@ type ListSystemBackupsInput struct {
Limit int `query:"limit" default:"20"`
}
+type ListBackupHistoryInput struct {
+ Search string `query:"search"`
+ Sort string `query:"sort" default:"createdAt"`
+ Order string `query:"order" default:"desc"`
+ Start int `query:"start" default:"0"`
+ Limit int `query:"limit" default:"20"`
+ Type string `query:"type"`
+}
+
+type ListBackupHistoryOutput struct {
+ Body struct {
+ Data []backuptypes.HistoryEntry `json:"data"`
+ Pagination base.PaginationResponse `json:"pagination"`
+ }
+}
+
+type SystemVolumeBackupConfigOutput struct {
+ Body backuptypes.SystemVolumeBackupPolicyCollection
+}
+
+type UpdateSystemVolumeBackupConfigInput struct {
+ Body backuptypes.UpdateSystemVolumeBackupPolicies
+}
+
+type SystemVolumeBackupOptionsOutput struct {
+ Body []backuptypes.SystemVolumeBackupOption
+}
+
+type SystemVolumeBackupRunOutput struct {
+ Body backuptypes.SystemVolumeBackupRunResult
+}
+
+type RunSystemVolumeBackupsInput struct {
+ Body *backuptypes.RunSystemVolumeBackupsRequest `json:"body,omitempty"`
+}
+
type ListSystemBackupsOutput struct {
Body struct {
Data []backuptypes.SystemBackupRun `json:"data"`
@@ -107,6 +143,11 @@ func RegisterSystemBackups(api huma.API, service *SystemBackupService, activityS
h := &SystemBackupHandler{service: service, activity: activityService, appCtx: appCtx.Context()}
adminOnly := middleware.RequireGlobalAdmin(api)
middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-system-backups", Method: http.MethodGet, Path: "/backups", Summary: "List Arcane system backups", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRead, h.List)
+ middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-backup-history", Method: http.MethodGet, Path: "/backups/history", Summary: "List unified backup history", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRead, h.ListHistory)
+ middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-system-volume-backup-config", Method: http.MethodGet, Path: "/backups/volumes/config", Summary: "Get system-managed volume backup policies", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRead, h.GetSystemVolumeConfig)
+ middleware.RegisterWithPermission(api, huma.Operation{OperationID: "update-system-volume-backup-config", Method: http.MethodPut, Path: "/backups/volumes/config", Summary: "Update system-managed volume backup policies", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsManage, h.UpdateSystemVolumeConfig)
+ middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-system-volume-backup-options", Method: http.MethodGet, Path: "/backups/volumes/options", Summary: "List volumes available to system-managed backups", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRead, h.ListSystemVolumeOptions)
+ middleware.RegisterWithPermission(api, huma.Operation{OperationID: "run-system-volume-backups", Method: http.MethodPost, Path: "/backups/volumes/run", Summary: "Run system-managed volume backups", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsManage, h.RunSystemVolumeBackups)
middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-system-backup-policies", Method: http.MethodGet, Path: "/backups/policies", Summary: "Get Arcane system backup policies", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRead, h.GetPolicies)
middleware.RegisterWithPermission(api, huma.Operation{OperationID: "update-system-backup-policies", Method: http.MethodPut, Path: "/backups/policies", Summary: "Update Arcane system backup policies", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsManage, h.UpdatePolicies)
middleware.RegisterWithPermission(api, huma.Operation{OperationID: "generate-system-backup-recovery-key", Method: http.MethodPost, Path: "/backups/recovery-key/generate", Summary: "Generate an Arcane system backup recovery key", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRecoveryKey, h.GenerateRecoveryKey)
@@ -120,6 +161,57 @@ func RegisterSystemBackups(api huma.API, service *SystemBackupService, activityS
middleware.RegisterWithPermission(api, huma.Operation{OperationID: "delete-system-backup", Method: http.MethodDelete, Path: "/backups/{id}", Summary: "Delete Arcane system backup", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsManage, h.Delete)
}
+func (h *SystemBackupHandler) ListHistory(ctx context.Context, input *ListBackupHistoryInput) (*ListBackupHistoryOutput, error) {
+ params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ params.Filters = map[string]string{"type": input.Type}
+ history, page, err := h.service.ListBackupHistory(ctx, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+ out := &ListBackupHistoryOutput{}
+ out.Body.Data, out.Body.Pagination = history, handlerutil.PaginationResponse(page)
+ return out, nil
+}
+
+func (h *SystemBackupHandler) GetSystemVolumeConfig(ctx context.Context, _ *struct{}) (*SystemVolumeBackupConfigOutput, error) {
+ config, err := h.service.GetSystemVolumeBackupConfig(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+ return &SystemVolumeBackupConfigOutput{Body: *config}, nil
+}
+
+func (h *SystemBackupHandler) UpdateSystemVolumeConfig(ctx context.Context, input *UpdateSystemVolumeBackupConfigInput) (*SystemVolumeBackupConfigOutput, error) {
+ config, err := h.service.UpdateSystemVolumeBackupConfig(ctx, input.Body.Policies)
+ if err != nil {
+ return nil, huma.Error400BadRequest(err.Error())
+ }
+ return &SystemVolumeBackupConfigOutput{Body: *config}, nil
+}
+
+func (h *SystemBackupHandler) ListSystemVolumeOptions(ctx context.Context, _ *struct{}) (*SystemVolumeBackupOptionsOutput, error) {
+ options, err := h.service.ListSystemVolumeBackupOptions(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+ return &SystemVolumeBackupOptionsOutput{Body: options}, nil
+}
+
+func (h *SystemBackupHandler) RunSystemVolumeBackups(ctx context.Context, input *RunSystemVolumeBackupsInput) (*SystemVolumeBackupRunOutput, error) {
+ request := backuptypes.RunSystemVolumeBackupsRequest{}
+ if input.Body != nil {
+ request = *input.Body
+ }
+ result, err := h.service.RunSystemVolumeBackups(ctx, request)
+ if errors.Is(err, ErrSystemBackupAlreadyRunning) {
+ return nil, huma.Error409Conflict(err.Error())
+ }
+ if err != nil {
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+ return &SystemVolumeBackupRunOutput{Body: *result}, nil
+}
+
func (h *SystemBackupHandler) List(ctx context.Context, input *ListSystemBackupsInput) (*ListSystemBackupsOutput, error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
runs, page, err := h.service.ListBackups(ctx, params)
diff --git a/backend/internal/systembackup/service.go b/backend/internal/systembackup/service.go
index f80c343cf..fc4643b60 100644
--- a/backend/internal/systembackup/service.go
+++ b/backend/internal/systembackup/service.go
@@ -1504,29 +1504,27 @@ func (s *SystemBackupService) UpdatePolicies(ctx context.Context, updates []back
if err != nil {
return nil, err
}
- reconcile := backup.PolicyReconciliation[SystemBackupPolicy]{
+ reconcile := backup.PolicyReconciliation[SystemBackupPolicy, backuptypes.UpdateSystemBackupPolicy]{
Domain: "system",
DB: s.db,
Existing: existing,
ID: func(policy *SystemBackupPolicy) string { return policy.ID },
+ UpdateID: func(update backuptypes.UpdateSystemBackupPolicy) string { return update.ID },
New: func() SystemBackupPolicy { return SystemBackupPolicy{} },
- Apply: func(policy *SystemBackupPolicy, update backuptypes.UpdateBackupPolicy) {
- policy.Enabled, policy.Schedule, policy.RetentionCount = update.Enabled, update.Schedule, update.RetentionCount
- policy.LocalEnabled, policy.S3Enabled, policy.S3DestinationID = update.LocalEnabled, update.S3Enabled, update.S3DestinationID
- },
- ValidateUpdate: func(update backuptypes.UpdateBackupPolicy) error {
+ Build: func(ctx context.Context, policy *SystemBackupPolicy, update backuptypes.UpdateSystemBackupPolicy) error {
+ normalized, normalizeErr := backup.ValidatePolicyUpdate(ctx, "system", update, s.s3Destinations)
+ if normalizeErr != nil {
+ return normalizeErr
+ }
+ update = normalized
if update.Enabled && !configured {
return errors.New("configure a recovery key before enabling scheduled system backups")
}
if update.Enabled && !s.SupportedDatabaseProvider() {
return errors.New("scheduled system backups require the SQLite database provider")
}
- return nil
- },
- S3Configured: func(ctx context.Context, destinationID string) error {
- if _, err := s.s3Destinations.Configuration(ctx, destinationID); err != nil {
- return errors.New("select a valid S3 destination for system backups")
- }
+ policy.Enabled, policy.Schedule, policy.RetentionCount = update.Enabled, update.Schedule, update.RetentionCount
+ policy.LocalEnabled, policy.S3Enabled, policy.S3DestinationID = update.LocalEnabled, update.S3Enabled, update.S3DestinationID
return nil
},
Unregister: s.jobs.Unregister,
@@ -1612,7 +1610,17 @@ func (s *SystemBackupService) RegisterBackupJobOnStartup(ctx context.Context) {
for i := range policies {
s.rescheduleSystemBackupPolicyInternal(ctx, &policies[i])
}
- slog.InfoContext(ctx, "Registered scheduled Arcane system backup jobs", "count", len(policies))
+ volumePolicyCount := 0
+ volumePolicies, configErr := s.loadSystemVolumeBackupPoliciesInternal()
+ if configErr != nil {
+ slog.ErrorContext(ctx, "Failed to load system-managed volume backup policies", "error", configErr)
+ } else {
+ volumePolicyCount = len(volumePolicies.Policies)
+ for i := range volumePolicies.Policies {
+ s.rescheduleSystemVolumeBackupInternal(ctx, &volumePolicies.Policies[i])
+ }
+ }
+ slog.InfoContext(ctx, "Registered backup schedules", "systemPolicies", len(policies), "volumePolicies", volumePolicyCount)
}
func (s *SystemBackupService) applyRetentionInternal(ctx context.Context, policyID string, keep int) error {
diff --git a/backend/internal/systembackup/system_volume.go b/backend/internal/systembackup/system_volume.go
new file mode 100644
index 000000000..8e616f52f
--- /dev/null
+++ b/backend/internal/systembackup/system_volume.go
@@ -0,0 +1,413 @@
+package systembackup
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "slices"
+ "strings"
+
+ "emperror.dev/errors"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/backup"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/volume"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
+ backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+const (
+ systemVolumeBackupConfigKey = "systemVolumeBackupConfig"
+ systemVolumeBackupJobPrefix = "volumes:"
+ defaultSystemVolumeSchedule = "0 0 2 * * *"
+)
+
+func (s *SystemBackupService) loadSystemVolumeBackupPoliciesInternal() (*backuptypes.SystemVolumeBackupPolicyCollection, error) {
+ collection := &backuptypes.SystemVolumeBackupPolicyCollection{Policies: []backuptypes.SystemVolumeBackupPolicy{}}
+ if s.settingsService == nil {
+ return collection, nil
+ }
+ raw := strings.TrimSpace(s.settingsService.GetSettingsConfig().SystemVolumeBackupConfig.Value)
+ if raw == "" {
+ return collection, nil
+ }
+ if err := json.Unmarshal([]byte(raw), collection); err != nil {
+ return nil, fmt.Errorf("decode system-managed volume backup policies: %w", err)
+ }
+ if collection.Policies == nil {
+ collection.Policies = []backuptypes.SystemVolumeBackupPolicy{}
+ }
+ return collection, nil
+}
+
+func (s *SystemBackupService) systemVolumeBackupPolicyInternal(policyID string) (*backuptypes.SystemVolumeBackupPolicy, error) {
+ collection, err := s.loadSystemVolumeBackupPoliciesInternal()
+ if err != nil {
+ return nil, err
+ }
+ for i := range collection.Policies {
+ if collection.Policies[i].ID == policyID {
+ policy := collection.Policies[i]
+ return &policy, nil
+ }
+ }
+ return nil, nil
+}
+
+func (s *SystemBackupService) GetSystemVolumeBackupConfig(ctx context.Context) (*backuptypes.SystemVolumeBackupPolicyCollection, error) {
+ collection, err := s.loadSystemVolumeBackupPoliciesInternal()
+ if err != nil {
+ return nil, err
+ }
+ destinations := make(map[string]string)
+ if s.s3Destinations != nil {
+ if available, listErr := s.s3Destinations.ListAllS3Destinations(ctx); listErr == nil {
+ for _, destination := range available {
+ destinations[destination.ID] = destination.Name
+ }
+ }
+ }
+ for i := range collection.Policies {
+ policy := &collection.Policies[i]
+ policy.S3DestinationName = destinations[policy.S3DestinationID]
+ if s.db == nil {
+ continue
+ }
+ var lastRun volume.VolumeBackup
+ runErr := s.db.WithContext(ctx).
+ Where("policy_id LIKE ?", backuptypes.SystemVolumePolicyPrefix+policy.ID+":%").
+ Order("created_at DESC").First(&lastRun).Error
+ if runErr == nil {
+ policy.LastRun = &backuptypes.SystemBackupRun{
+ ID: lastRun.ID, Size: lastRun.Size, CreatedAt: lastRun.CreatedAt, Status: string(lastRun.Status),
+ Trigger: string(lastRun.Trigger), Destination: backuptypes.SystemBackupDestination(lastRun.Destination),
+ LocalSnapshotID: lastRun.LocalSnapshotID, RemoteSnapshotID: lastRun.RemoteSnapshotID,
+ S3DestinationID: lastRun.S3DestinationID, S3DestinationName: destinations[lastRun.S3DestinationID],
+ PolicyID: lastRun.PolicyID, Error: lastRun.Error,
+ }
+ } else if !errors.Is(runErr, gorm.ErrRecordNotFound) {
+ return nil, fmt.Errorf("load latest system-managed volume backup: %w", runErr)
+ }
+ }
+ return collection, nil
+}
+
+func validateSystemVolumeSelectionInternal(mode backuptypes.SystemVolumeSelectionMode) error {
+ if mode != backuptypes.SystemVolumeSelectionAll && mode != backuptypes.SystemVolumeSelectionAllowlist && mode != backuptypes.SystemVolumeSelectionBlocklist {
+ return errors.New("selectionMode must be all, allowlist, or blocklist")
+ }
+ return nil
+}
+
+func (s *SystemBackupService) normalizeSystemVolumePolicyUpdateInternal(ctx context.Context, input backuptypes.UpdateSystemVolumeBackupPolicy) (backuptypes.SystemVolumeBackupPolicy, error) {
+ if err := validateSystemVolumeSelectionInternal(input.SelectionMode); err != nil {
+ return backuptypes.SystemVolumeBackupPolicy{}, err
+ }
+ update, err := backup.ValidatePolicyUpdate(ctx, "system-managed volume", input.UpdateBackupPolicy, s.s3Destinations)
+ if err != nil {
+ return backuptypes.SystemVolumeBackupPolicy{}, err
+ }
+ names := utils.UniqueNonEmptyStrings(input.VolumeNames)
+ slices.Sort(names)
+ if input.SelectionMode == backuptypes.SystemVolumeSelectionAll || names == nil {
+ names = []string{}
+ }
+ return backuptypes.SystemVolumeBackupPolicy{
+ ID: input.ID, Enabled: update.Enabled, Schedule: update.Schedule, RetentionCount: update.RetentionCount,
+ StopContainers: update.StopContainers, LocalEnabled: update.LocalEnabled, S3Enabled: update.S3Enabled,
+ S3DestinationID: update.S3DestinationID, SelectionMode: input.SelectionMode,
+ VolumeNames: names, IgnoreAnonymous: input.IgnoreAnonymous,
+ }, nil
+}
+
+func (s *SystemBackupService) UpdateSystemVolumeBackupConfig(ctx context.Context, updates []backuptypes.UpdateSystemVolumeBackupPolicy) (*backuptypes.SystemVolumeBackupPolicyCollection, error) {
+ if s.settingsService == nil {
+ return nil, errors.New("settings service is unavailable")
+ }
+ existing, err := s.loadSystemVolumeBackupPoliciesInternal()
+ if err != nil {
+ return nil, err
+ }
+ reconcile := backup.PolicyReconciliation[backuptypes.SystemVolumeBackupPolicy, backuptypes.UpdateSystemVolumeBackupPolicy]{
+ Domain: "system-managed volume",
+ Existing: existing.Policies,
+ ID: func(policy *backuptypes.SystemVolumeBackupPolicy) string { return policy.ID },
+ UpdateID: func(update backuptypes.UpdateSystemVolumeBackupPolicy) string { return update.ID },
+ New: func() backuptypes.SystemVolumeBackupPolicy {
+ return backuptypes.SystemVolumeBackupPolicy{ID: uuid.NewString()}
+ },
+ Build: func(ctx context.Context, policy *backuptypes.SystemVolumeBackupPolicy, update backuptypes.UpdateSystemVolumeBackupPolicy) error {
+ normalized, normalizeErr := s.normalizeSystemVolumePolicyUpdateInternal(ctx, update)
+ if normalizeErr != nil {
+ return normalizeErr
+ }
+ normalized.ID = policy.ID
+ *policy = normalized
+ return nil
+ },
+ Persist: func(ctx context.Context, policies []backuptypes.SystemVolumeBackupPolicy) error {
+ encoded, encodeErr := json.Marshal(backuptypes.SystemVolumeBackupPolicyCollection{Policies: policies})
+ if encodeErr != nil {
+ return fmt.Errorf("encode policies: %w", encodeErr)
+ }
+ return s.settingsService.UpdateSetting(ctx, systemVolumeBackupConfigKey, string(encoded))
+ },
+ Unregister: func(ctx context.Context, policyID string) {
+ s.jobs.Unregister(ctx, systemVolumeBackupJobPrefix+policyID)
+ },
+ Reschedule: s.rescheduleSystemVolumeBackupInternal,
+ }
+ if err := reconcile.Run(ctx, updates); err != nil {
+ return nil, err
+ }
+ return s.GetSystemVolumeBackupConfig(ctx)
+}
+
+// ListSystemVolumeBackupOptions returns live choices plus configured names that are currently unavailable.
+func (s *SystemBackupService) ListSystemVolumeBackupOptions(ctx context.Context) ([]backuptypes.SystemVolumeBackupOption, error) {
+ if s.volumeService == nil {
+ return nil, errors.New("volume service is unavailable")
+ }
+ options, err := s.volumeService.ListBackupVolumeOptions(ctx)
+ if err != nil {
+ return nil, err
+ }
+ collection, err := s.loadSystemVolumeBackupPoliciesInternal()
+ if err != nil {
+ return nil, err
+ }
+ known := make(map[string]struct{}, len(options))
+ for _, option := range options {
+ known[option.Name] = struct{}{}
+ }
+ for _, policy := range collection.Policies {
+ for _, name := range policy.VolumeNames {
+ if _, ok := known[name]; !ok {
+ options = append(options, backuptypes.SystemVolumeBackupOption{Name: name})
+ known[name] = struct{}{}
+ }
+ }
+ }
+ slices.SortFunc(options, func(a, b backuptypes.SystemVolumeBackupOption) int {
+ return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
+ })
+ return options, nil
+}
+
+func selectSystemVolumeBackupCandidatesInternal(policy backuptypes.SystemVolumeBackupPolicy, options []backuptypes.SystemVolumeBackupOption) []backuptypes.SystemVolumeBackupOption {
+ configured := make(map[string]struct{}, len(policy.VolumeNames))
+ for _, name := range policy.VolumeNames {
+ configured[name] = struct{}{}
+ }
+ result := make([]backuptypes.SystemVolumeBackupOption, 0, len(options))
+ for _, option := range options {
+ if !option.Available {
+ continue
+ }
+ _, selected := configured[option.Name]
+ matches := policy.SelectionMode == backuptypes.SystemVolumeSelectionAll ||
+ (policy.SelectionMode == backuptypes.SystemVolumeSelectionAllowlist && selected) ||
+ (policy.SelectionMode == backuptypes.SystemVolumeSelectionBlocklist && !selected)
+ if matches && (!policy.IgnoreAnonymous || !option.Anonymous) {
+ result = append(result, option)
+ }
+ }
+ return result
+}
+
+func systemVolumePolicyIDInternal(policyID, volumeName string) string {
+ sum := sha256.Sum256([]byte(volumeName))
+ return backuptypes.SystemVolumePolicyPrefix + policyID + ":" + hex.EncodeToString(sum[:8])
+}
+
+func systemVolumeManualPolicyIDInternal(volumeName string) string {
+ sum := sha256.Sum256([]byte(volumeName))
+ return backuptypes.SystemVolumePolicyPrefix + "manual:" + hex.EncodeToString(sum[:8])
+}
+
+func customSystemVolumePolicyInternal(custom *backuptypes.SystemVolumeBackupCustomRun) backuptypes.UpdateSystemVolumeBackupPolicy {
+ if custom == nil {
+ return backuptypes.UpdateSystemVolumeBackupPolicy{
+ Enabled: true, Schedule: defaultSystemVolumeSchedule, LocalEnabled: true,
+ SelectionMode: backuptypes.SystemVolumeSelectionAll, VolumeNames: []string{}, IgnoreAnonymous: true,
+ }
+ }
+ localEnabled := custom.Destination == backuptypes.SystemBackupDestinationLocal || custom.Destination == backuptypes.SystemBackupDestinationLocalS3
+ s3Enabled := custom.Destination == backuptypes.SystemBackupDestinationS3 || custom.Destination == backuptypes.SystemBackupDestinationLocalS3
+ return backuptypes.UpdateSystemVolumeBackupPolicy{
+ Enabled: true, Schedule: defaultSystemVolumeSchedule, RetentionCount: 0, StopContainers: custom.StopContainers,
+ LocalEnabled: localEnabled, S3Enabled: s3Enabled, S3DestinationID: custom.S3DestinationID,
+ SelectionMode: custom.SelectionMode, VolumeNames: custom.VolumeNames, IgnoreAnonymous: custom.IgnoreAnonymous,
+ }
+}
+
+func (s *SystemBackupService) resolveSystemVolumeRunPolicyInternal(ctx context.Context, request backuptypes.RunSystemVolumeBackupsRequest) (backuptypes.SystemVolumeBackupPolicy, bool, error) {
+ if request.PolicyID != "" {
+ if request.Custom != nil {
+ return backuptypes.SystemVolumeBackupPolicy{}, false, errors.New("select a saved policy or custom configuration, not both")
+ }
+ policy, err := s.systemVolumeBackupPolicyInternal(request.PolicyID)
+ if err != nil {
+ return backuptypes.SystemVolumeBackupPolicy{}, false, err
+ }
+ if policy == nil {
+ return backuptypes.SystemVolumeBackupPolicy{}, false, errors.New("system-managed volume backup policy not found")
+ }
+ return *policy, false, nil
+ }
+ custom := request.Custom
+ if custom != nil && custom.Destination != backuptypes.SystemBackupDestinationLocal && custom.Destination != backuptypes.SystemBackupDestinationS3 && custom.Destination != backuptypes.SystemBackupDestinationLocalS3 {
+ return backuptypes.SystemVolumeBackupPolicy{}, false, errors.New("destination must be local, s3, or local_s3")
+ }
+ policy, err := s.normalizeSystemVolumePolicyUpdateInternal(ctx, customSystemVolumePolicyInternal(custom))
+ return policy, true, err
+}
+
+func (s *SystemBackupService) RunSystemVolumeBackups(ctx context.Context, request backuptypes.RunSystemVolumeBackupsRequest) (*backuptypes.SystemVolumeBackupRunResult, error) {
+ return s.runSystemVolumeBackupsInternal(ctx, request, volume.VolumeBackupTriggerManual)
+}
+
+func (s *SystemBackupService) runSystemVolumeBackupsInternal(ctx context.Context, request backuptypes.RunSystemVolumeBackupsRequest, trigger volume.VolumeBackupTrigger) (*backuptypes.SystemVolumeBackupRunResult, error) {
+ if s.volumeService == nil {
+ return nil, errors.New("volume service is unavailable")
+ }
+ policyConfig, manualPolicy, err := s.resolveSystemVolumeRunPolicyInternal(ctx, request)
+ if err != nil {
+ return nil, err
+ }
+ lease, admitted, err := s.engine.TryAcquireRun(ctx, backup.SystemAdmissionScope, systemAdmissionID)
+ if err != nil {
+ return nil, err
+ }
+ if !admitted {
+ return nil, ErrSystemBackupAlreadyRunning
+ }
+ defer lease.Release()
+ options, err := s.volumeService.ListBackupVolumeOptions(ctx)
+ if err != nil {
+ return nil, err
+ }
+ candidates := selectSystemVolumeBackupCandidatesInternal(policyConfig, options)
+ result := &backuptypes.SystemVolumeBackupRunResult{
+ Matched: len(candidates), Failures: make([]backuptypes.SystemVolumeBackupFailure, 0),
+ }
+ policy := backuptypes.UpdateBackupPolicy{
+ Enabled: true, Schedule: policyConfig.Schedule, RetentionCount: policyConfig.RetentionCount,
+ StopContainers: policyConfig.StopContainers, LocalEnabled: policyConfig.LocalEnabled, S3Enabled: policyConfig.S3Enabled,
+ S3DestinationID: policyConfig.S3DestinationID,
+ }
+ for _, candidate := range candidates {
+ overridden, policyErr := s.volumeService.HasEnabledBackupPolicy(ctx, candidate.Name)
+ if policyErr != nil {
+ result.Failed++
+ result.Failures = append(result.Failures, backuptypes.SystemVolumeBackupFailure{VolumeName: candidate.Name, Error: policyErr.Error()})
+ continue
+ }
+ if overridden {
+ result.Skipped++
+ continue
+ }
+ seriesID := systemVolumePolicyIDInternal(policyConfig.ID, candidate.Name)
+ if manualPolicy {
+ seriesID = systemVolumeManualPolicyIDInternal(candidate.Name)
+ }
+ _, backupErr := s.volumeService.CreateSystemManagedBackup(ctx, candidate.Name, common.SystemUser, trigger, seriesID, policy)
+ if errors.Is(backupErr, volume.ErrVolumeBackupAlreadyRunning) {
+ result.Skipped++
+ continue
+ }
+ if backupErr != nil {
+ result.Failed++
+ result.Failures = append(result.Failures, backuptypes.SystemVolumeBackupFailure{VolumeName: candidate.Name, Error: backupErr.Error()})
+ continue
+ }
+ result.Succeeded++
+ }
+ return result, nil
+}
+
+func (s *SystemBackupService) runScheduledSystemVolumeBackupInternal(ctx context.Context, policyID string) {
+ policy, err := s.systemVolumeBackupPolicyInternal(policyID)
+ if err != nil || policy == nil || !policy.Enabled {
+ return
+ }
+ result, err := s.runSystemVolumeBackupsInternal(ctx, backuptypes.RunSystemVolumeBackupsRequest{PolicyID: policyID}, volume.VolumeBackupTriggerScheduled)
+ if errors.Is(err, ErrSystemBackupAlreadyRunning) {
+ slog.InfoContext(ctx, "Scheduled system-managed volume backups skipped; a system backup is running", "policyId", policyID)
+ return
+ }
+ if err != nil {
+ slog.ErrorContext(ctx, "Scheduled system-managed volume backups failed", "policyId", policyID, "error", err)
+ return
+ }
+ slog.InfoContext(ctx, "Scheduled system-managed volume backups completed", "policyId", policyID, "matched", result.Matched, "succeeded", result.Succeeded, "failed", result.Failed, "skipped", result.Skipped)
+}
+
+func (s *SystemBackupService) rescheduleSystemVolumeBackupInternal(ctx context.Context, policy *backuptypes.SystemVolumeBackupPolicy) {
+ if policy == nil {
+ return
+ }
+ jobID := systemVolumeBackupJobPrefix + policy.ID
+ if !policy.Enabled {
+ s.jobs.Unregister(ctx, jobID)
+ return
+ }
+ policyID := policy.ID
+ s.jobs.Register(ctx, jobID, func(context.Context) string {
+ current, err := s.systemVolumeBackupPolicyInternal(policyID)
+ if err != nil || current == nil {
+ return defaultSystemVolumeSchedule
+ }
+ return current.Schedule
+ }, func(ctx context.Context) {
+ s.runScheduledSystemVolumeBackupInternal(ctx, policyID)
+ })
+}
+
+const backupHistoryUnionInternal = `SELECT id, size, created_at, status, trigger, destination, '' AS format, local_snapshot_id, remote_snapshot_id, s3_destination_id, policy_id, error, 'system' AS type, 'system' AS resource_type, 'Arcane' AS resource_name FROM system_backup_runs UNION ALL SELECT id, size, created_at, status, trigger, destination, format, local_snapshot_id, remote_snapshot_id, s3_destination_id, policy_id, error, CASE WHEN policy_id LIKE 'system-volume:%' THEN 'system' ELSE 'volume' END AS type, 'volume' AS resource_type, volume_name AS resource_name FROM volume_backups`
+
+// ListBackupHistory returns a unified, server-paginated view of local backup records.
+func (s *SystemBackupService) ListBackupHistory(ctx context.Context, params pagination.QueryParams) ([]backuptypes.HistoryEntry, pagination.Response, error) {
+ query := s.db.WithContext(ctx).Table("(?) AS backup_history", s.db.Raw(backupHistoryUnionInternal))
+ if term := strings.TrimSpace(params.Search); term != "" {
+ pattern := "%" + term + "%"
+ query = query.Where("id LIKE ? OR status LIKE ? OR trigger LIKE ? OR destination LIKE ? OR COALESCE(error, '') LIKE ? OR resource_name LIKE ? OR resource_type LIKE ? OR type LIKE ?", pattern, pattern, pattern, pattern, pattern, pattern, pattern, pattern)
+ }
+ query = pagination.ApplyFilter(query, "type", params.Filters["type"])
+ if params.Sort == "" {
+ params.Sort = "createdAt"
+ params.Order = pagination.SortDesc
+ }
+ var history []backuptypes.HistoryEntry
+ page, err := pagination.PaginateAndSortDB(params, query, &history)
+ if err != nil {
+ return nil, pagination.Response{}, fmt.Errorf("list backup history: %w", err)
+ }
+ decorateHistoryDestinationsInternal(ctx, s.s3Destinations, history)
+ page.GrandTotalItems = page.TotalItems
+ return history, page, nil
+}
+
+func decorateHistoryDestinationsInternal(ctx context.Context, service *s3domain.S3DestinationService, history []backuptypes.HistoryEntry) {
+ if service == nil {
+ return
+ }
+ destinations, err := service.ListAllS3Destinations(ctx)
+ if err != nil {
+ return
+ }
+ names := make(map[string]string, len(destinations))
+ for _, destination := range destinations {
+ names[destination.ID] = destination.Name
+ }
+ for i := range history {
+ history[i].S3DestinationName = names[history[i].S3DestinationID]
+ }
+}
diff --git a/backend/internal/systembackup/system_volume_test.go b/backend/internal/systembackup/system_volume_test.go
new file mode 100644
index 000000000..508940027
--- /dev/null
+++ b/backend/internal/systembackup/system_volume_test.go
@@ -0,0 +1,99 @@
+package systembackup
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/volume"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"
+ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"
+ "github.com/libtnb/sqlite"
+ "github.com/stretchr/testify/require"
+ "gorm.io/gorm"
+)
+
+func TestSystemVolumeBackupSelectionInternal(t *testing.T) {
+ options := []backuptypes.SystemVolumeBackupOption{
+ {Name: "app", Available: true},
+ {Name: "cache", Available: true},
+ {Name: "anonymous", Anonymous: true, Available: true},
+ {Name: "deleted", Available: false},
+ }
+ tests := []struct {
+ name string
+ config backuptypes.SystemVolumeBackupPolicy
+ expected []string
+ }{
+ {
+ name: "all includes future named volumes",
+ config: backuptypes.SystemVolumeBackupPolicy{SelectionMode: backuptypes.SystemVolumeSelectionAll, IgnoreAnonymous: true},
+ expected: []string{"app", "cache"},
+ },
+ {
+ name: "allowlist includes exact live names only",
+ config: backuptypes.SystemVolumeBackupPolicy{SelectionMode: backuptypes.SystemVolumeSelectionAllowlist, VolumeNames: []string{"app", "deleted"}},
+ expected: []string{"app"},
+ },
+ {
+ name: "blocklist includes unselected future and anonymous volumes",
+ config: backuptypes.SystemVolumeBackupPolicy{SelectionMode: backuptypes.SystemVolumeSelectionBlocklist, VolumeNames: []string{"cache"}},
+ expected: []string{"app", "anonymous"},
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ selected := selectSystemVolumeBackupCandidatesInternal(tt.config, options)
+ names := make([]string, len(selected))
+ for i := range selected {
+ names[i] = selected[i].Name
+ }
+ require.Equal(t, tt.expected, names)
+ })
+ }
+}
+
+func TestListBackupHistoryClassifiesAndFiltersOrigins(t *testing.T) {
+ gormDB, err := gorm.Open(sqlite.Open("file:system-volume-history?mode=memory&cache=shared"), &gorm.Config{})
+ require.NoError(t, err)
+ require.NoError(t, gormDB.AutoMigrate(&SystemBackupRun{}, &volume.VolumeBackup{}))
+ now := time.Now().UTC()
+ require.NoError(t, gormDB.Create(&SystemBackupRun{
+ CreatedAt: now.Add(-2 * time.Minute), Status: SystemBackupStatusSucceeded, Trigger: SystemBackupTriggerManual,
+ Destination: backuptypes.SystemBackupDestinationLocal,
+ }).Error)
+ require.NoError(t, gormDB.Create(&volume.VolumeBackup{
+ VolumeName: "app-data", CreatedAt: now.Add(-time.Minute), Status: volume.VolumeBackupStatusSucceeded,
+ Trigger: volume.VolumeBackupTriggerScheduled, Destination: volumetypes.BackupDestinationLocal,
+ Format: volume.VolumeBackupFormatRustic, PolicyID: systemVolumePolicyIDInternal("nightly", "app-data"),
+ }).Error)
+ require.NoError(t, gormDB.Create(&volume.VolumeBackup{
+ VolumeName: "cache", CreatedAt: now, Status: volume.VolumeBackupStatusSucceeded,
+ Trigger: volume.VolumeBackupTriggerManual, Destination: volumetypes.BackupDestinationLocal,
+ Format: volume.VolumeBackupFormatRustic,
+ }).Error)
+ service := &SystemBackupService{db: &database.DB{DB: gormDB}}
+
+ systemRows, page, err := service.ListBackupHistory(context.Background(), pagination.QueryParams{
+ Sort: "createdAt", Order: pagination.SortDesc, Limit: 20,
+ Filters: map[string]string{"type": "system"},
+ })
+ require.NoError(t, err)
+ require.EqualValues(t, 2, page.TotalItems)
+ require.Len(t, systemRows, 2)
+ require.Equal(t, backuptypes.ManagementTypeSystem, systemRows[0].Type)
+ require.Equal(t, "app-data", systemRows[0].ResourceName)
+ require.Equal(t, "volume", systemRows[0].ResourceType)
+
+ volumeRows, page, err := service.ListBackupHistory(context.Background(), pagination.QueryParams{
+ Search: "cache", Sort: "createdAt", Order: pagination.SortDesc, Limit: 1,
+ Filters: map[string]string{"type": "volume"},
+ })
+ require.NoError(t, err)
+ require.EqualValues(t, 1, page.TotalItems)
+ require.Len(t, volumeRows, 1)
+ require.Equal(t, backuptypes.ManagementTypeVolume, volumeRows[0].Type)
+ require.Equal(t, "cache", volumeRows[0].ResourceName)
+}
diff --git a/backend/internal/volume/backup.go b/backend/internal/volume/backup.go
index a1f8b306d..af9e5bf4c 100644
--- a/backend/internal/volume/backup.go
+++ b/backend/internal/volume/backup.go
@@ -325,6 +325,7 @@ func (s *VolumeService) ListBackupsPaginated(ctx context.Context, volumeName str
slog.DebugContext(ctx, "volume service: list backups paginated", "volume", volumeName, "search", params.Search, "sort", params.Sort, "order", params.Order, "start", params.Start, "limit", params.Limit)
var backups []VolumeBackup
query := s.db.WithContext(ctx).Model(&VolumeBackup{}).Where("volume_name = ?", volumeName)
+ query = applyBackupManagementFilterInternal(query, params.Filters["type"])
if params.Search != "" {
pattern := "%" + params.Search + "%"
@@ -395,10 +396,40 @@ func (s *VolumeService) ListBackupsPaginated(ctx context.Context, volumeName str
}
}
}
+ for i := range backups {
+ backups[i].Type = volumeBackupManagementTypeInternal(backups[i].PolicyID)
+ }
return backups, pagination.BuildResponse(totalItems, totalItems, params), nil
}
+// applyBackupManagementFilterInternal derives the facet from the policy_id prefix; both or neither value selected means no filter.
+func applyBackupManagementFilterInternal(query *gorm.DB, typeFilter string) *gorm.DB {
+ var system, volume bool
+ for value := range strings.SplitSeq(typeFilter, ",") {
+ switch backuptypes.ManagementType(strings.TrimSpace(value)) {
+ case backuptypes.ManagementTypeSystem:
+ system = true
+ case backuptypes.ManagementTypeVolume:
+ volume = true
+ }
+ }
+ if system == volume {
+ return query
+ }
+ if system {
+ return query.Where("policy_id LIKE ?", backuptypes.SystemVolumePolicyPrefix+"%")
+ }
+ return query.Where("policy_id NOT LIKE ? OR policy_id IS NULL", backuptypes.SystemVolumePolicyPrefix+"%")
+}
+
+func volumeBackupManagementTypeInternal(policyID string) backuptypes.ManagementType {
+ if strings.HasPrefix(policyID, backuptypes.SystemVolumePolicyPrefix) {
+ return backuptypes.ManagementTypeSystem
+ }
+ return backuptypes.ManagementTypeVolume
+}
+
func (s *VolumeService) ListBackups(ctx context.Context, volumeName string) ([]VolumeBackup, error) {
slog.DebugContext(ctx, "volume service: list backups", "volume", volumeName)
var backups []VolumeBackup
@@ -510,13 +541,13 @@ type backupPlanInternal struct {
destination volumetypes.BackupDestination
}
-func (s *VolumeService) resolveBackupPlanInternal(ctx context.Context, volumeName string, trigger VolumeBackupTrigger, request volumetypes.CreateBackupRequest) (backupPlanInternal, error) {
+func (s *VolumeService) resolveBackupPlanInternal(ctx context.Context, volumeName string, trigger VolumeBackupTrigger, request volumetypes.CreateBackupRequest, suppliedPolicy *VolumeBackupPolicy) (backupPlanInternal, error) {
destination := request.Destination
if destination != "" && destination != volumetypes.BackupDestinationLocal && destination != volumetypes.BackupDestinationS3 && destination != volumetypes.BackupDestinationLocalS3 {
return backupPlanInternal{}, errors.New("invalid volume backup destination")
}
- var policy *VolumeBackupPolicy
- if trigger != VolumeBackupTriggerSafety {
+ policy := suppliedPolicy
+ if trigger != VolumeBackupTriggerSafety && policy == nil {
var err error
policy, err = s.loadVolumeBackupPolicyInternal(ctx, volumeName, request.PolicyID)
if err != nil {
@@ -563,19 +594,44 @@ func (s *VolumeService) resolveBackupPlanInternal(ctx context.Context, volumeNam
return backupPlanInternal{policy: policy, localEnabled: localEnabled, s3Enabled: s3Enabled, s3DestinationID: s3DestinationID, destination: destination}, nil
}
-//nolint:gocognit,gocyclo // backup orchestration keeps cleanup and persistence transitions in one transaction-like flow
func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, user common.User, trigger VolumeBackupTrigger, request volumetypes.CreateBackupRequest) (_ *VolumeBackup, err error) {
- workspaceLock, _ := ctx.Value(volumeWorkspaceLockContextKeyInternal{}).(volumeWorkspaceLockContextInternal)
- if workspaceLock.service != s || workspaceLock.volumeName != volumeName {
- defer s.workspaceLocks.Lock(volumeName)()
+ if trigger == "" {
+ trigger = VolumeBackupTriggerManual
+ }
+ plan, err := s.resolveBackupPlanInternal(ctx, volumeName, trigger, request, nil)
+ if err != nil {
+ return nil, err
+ }
+ return s.createBackupInternal(ctx, volumeName, user, trigger, request.PolicyID, plan)
+}
+
+// CreateSystemManagedBackup runs the existing volume backup workflow with a transient centralized policy.
+func (s *VolumeService) CreateSystemManagedBackup(ctx context.Context, volumeName string, user common.User, trigger VolumeBackupTrigger, policyID string, policy backuptypes.UpdateBackupPolicy) (*VolumeBackup, error) {
+ if !strings.HasPrefix(policyID, backuptypes.SystemVolumePolicyPrefix) {
+ return nil, errors.New("invalid system-managed volume backup policy id")
}
if trigger == "" {
trigger = VolumeBackupTriggerManual
}
- plan, err := s.resolveBackupPlanInternal(ctx, volumeName, trigger, request)
+ transient := &VolumeBackupPolicy{
+ VolumeName: volumeName, Enabled: true, Schedule: policy.Schedule, RetentionCount: policy.RetentionCount,
+ StopContainers: policy.StopContainers, LocalEnabled: policy.LocalEnabled, S3Enabled: policy.S3Enabled,
+ S3DestinationID: policy.S3DestinationID,
+ }
+ transient.ID = policyID
+ plan, err := s.resolveBackupPlanInternal(ctx, volumeName, trigger, volumetypes.CreateBackupRequest{}, transient)
if err != nil {
return nil, err
}
+ return s.createBackupInternal(ctx, volumeName, user, trigger, policyID, plan)
+}
+
+//nolint:gocognit // backup orchestration keeps cleanup and persistence transitions in one transaction-like flow
+func (s *VolumeService) createBackupInternal(ctx context.Context, volumeName string, user common.User, trigger VolumeBackupTrigger, policyID string, plan backupPlanInternal) (_ *VolumeBackup, err error) {
+ workspaceLock, _ := ctx.Value(volumeWorkspaceLockContextKeyInternal{}).(volumeWorkspaceLockContextInternal)
+ if workspaceLock.service != s || workspaceLock.volumeName != volumeName {
+ defer s.workspaceLocks.Lock(volumeName)()
+ }
lease, admitted, leaseErr := s.engine.TryAcquireRun(ctx, backup.VolumeAdmissionScope, volumeName)
if leaseErr != nil {
return nil, leaseErr
@@ -587,7 +643,7 @@ func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, use
entry := &VolumeBackup{
VolumeName: volumeName, CreatedAt: time.Now(), Status: VolumeBackupStatusRunning,
Trigger: trigger, Destination: plan.destination, Format: VolumeBackupFormatRustic,
- S3DestinationID: plan.s3DestinationID, PolicyID: request.PolicyID,
+ S3DestinationID: plan.s3DestinationID, PolicyID: policyID, Type: volumeBackupManagementTypeInternal(policyID),
}
entry.ID = fmt.Sprintf("%s-%d-%s", volumeName, time.Now().UnixNano(), uuid.New().String()[:8])
if err := s.db.WithContext(ctx).Create(entry).Error; err != nil {
@@ -682,6 +738,16 @@ func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, use
return entry, nil
}
+// HasEnabledBackupPolicy reports whether a volume-level schedule takes precedence over centralized backups.
+func (s *VolumeService) HasEnabledBackupPolicy(ctx context.Context, volumeName string) (bool, error) {
+ var count int64
+ if err := s.db.WithContext(ctx).Model(&VolumeBackupPolicy{}).
+ Where("volume_name = ? AND enabled = ?", volumeName, true).Count(&count).Error; err != nil {
+ return false, fmt.Errorf("failed to load volume backup policy override: %w", err)
+ }
+ return count > 0, nil
+}
+
func (s *VolumeService) UploadBackup(ctx context.Context, backupID, s3DestinationID string) (*VolumeBackup, error) {
var entry VolumeBackup
if err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&entry).Error; err != nil {
@@ -1664,24 +1730,22 @@ func (s *VolumeService) UpdateBackupPolicies(ctx context.Context, volumeName str
if err != nil {
return nil, err
}
- reconcile := backup.PolicyReconciliation[VolumeBackupPolicy]{
+ reconcile := backup.PolicyReconciliation[VolumeBackupPolicy, volumetypes.UpdateBackupPolicy]{
Domain: "volume",
DB: s.db,
Existing: existing,
ID: func(policy *VolumeBackupPolicy) string { return policy.ID },
+ UpdateID: func(update volumetypes.UpdateBackupPolicy) string { return update.ID },
New: func() VolumeBackupPolicy { return VolumeBackupPolicy{VolumeName: volumeName} },
- Apply: func(policy *VolumeBackupPolicy, update volumetypes.UpdateBackupPolicy) {
+ Build: func(ctx context.Context, policy *VolumeBackupPolicy, update volumetypes.UpdateBackupPolicy) error {
+ normalized, err := backup.ValidatePolicyUpdate(ctx, "volume", update, s.s3Destinations)
+ if err != nil {
+ return err
+ }
+ update = normalized
policy.Enabled, policy.Schedule, policy.RetentionCount = update.Enabled, update.Schedule, update.RetentionCount
policy.StopContainers, policy.LocalEnabled, policy.S3Enabled = update.StopContainers, update.LocalEnabled, update.S3Enabled
policy.S3DestinationID = update.S3DestinationID
- },
- S3Configured: func(ctx context.Context, destinationID string) error {
- if s.s3Destinations == nil {
- return errors.New("S3 backup destinations are unavailable")
- }
- if _, err := s.s3Destinations.Configuration(ctx, destinationID); err != nil {
- return errors.New("select a valid S3 destination for volume backups")
- }
return nil
},
Unregister: s.jobs.Unregister,
diff --git a/backend/internal/volume/backup_management_test.go b/backend/internal/volume/backup_management_test.go
new file mode 100644
index 000000000..3754955f1
--- /dev/null
+++ b/backend/internal/volume/backup_management_test.go
@@ -0,0 +1,46 @@
+package volume
+
+import (
+ "context"
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"
+ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"
+ "github.com/libtnb/sqlite"
+ "github.com/stretchr/testify/require"
+ "gorm.io/gorm"
+)
+
+func TestListBackupsPaginatedByManagementTypeInternal(t *testing.T) {
+ gormDB, err := gorm.Open(sqlite.Open("file:volume-backup-management?mode=memory&cache=shared"), &gorm.Config{})
+ require.NoError(t, err)
+ require.NoError(t, gormDB.AutoMigrate(&VolumeBackup{}))
+ for _, entry := range []*VolumeBackup{
+ {VolumeName: "app", Status: VolumeBackupStatusSucceeded, Destination: volumetypes.BackupDestinationLocal, PolicyID: backuptypes.SystemVolumePolicyPrefix + "abc"},
+ {VolumeName: "app", Status: VolumeBackupStatusSucceeded, Destination: volumetypes.BackupDestinationLocal, PolicyID: "per-volume"},
+ {VolumeName: "app", Status: VolumeBackupStatusSucceeded, Destination: volumetypes.BackupDestinationLocal},
+ } {
+ require.NoError(t, gormDB.Create(entry).Error)
+ }
+ service := &VolumeService{db: &database.DB{DB: gormDB}}
+
+ systemRows, page, err := service.ListBackupsPaginated(context.Background(), "app", pagination.QueryParams{
+ Filters: map[string]string{"type": "system"},
+ })
+ require.NoError(t, err)
+ require.EqualValues(t, 1, page.TotalItems)
+ require.Len(t, systemRows, 1)
+ require.Equal(t, backuptypes.ManagementTypeSystem, systemRows[0].Type)
+
+ volumeRows, page, err := service.ListBackupsPaginated(context.Background(), "app", pagination.QueryParams{
+ Filters: map[string]string{"type": "volume"},
+ })
+ require.NoError(t, err)
+ require.EqualValues(t, 2, page.TotalItems)
+ require.Len(t, volumeRows, 2)
+ for _, entry := range volumeRows {
+ require.Equal(t, backuptypes.ManagementTypeVolume, entry.Type)
+ }
+}
diff --git a/backend/internal/volume/handler.go b/backend/internal/volume/handler.go
index e426a31f6..30ce7a6af 100644
--- a/backend/internal/volume/handler.go
+++ b/backend/internal/volume/handler.go
@@ -173,6 +173,7 @@ type ListBackupsInput struct {
Order string `query:"order" default:"asc" doc:"Sort direction"`
Start int `query:"start" default:"0" doc:"Start index"`
Limit int `query:"limit" default:"20" doc:"Limit"`
+ Type string `query:"type" doc:"Management origin filter"`
}
type VolumeBackupPaginatedResponse struct {
@@ -949,6 +950,9 @@ func (h *VolumeHandler) ListBackups(ctx context.Context, input *ListBackupsInput
Order: pagination.SortOrder(input.Order),
Start: input.Start,
Limit: input.Limit,
+ Filters: map[string]string{
+ "type": input.Type,
+ },
}
if params.Limit == 0 {
diff --git a/backend/internal/volume/listing.go b/backend/internal/volume/listing.go
index 5c6be0a35..f8002f29f 100644
--- a/backend/internal/volume/listing.go
+++ b/backend/internal/volume/listing.go
@@ -3,6 +3,7 @@ package volume
import (
"context"
"log/slog"
+ "regexp"
"strings"
"time"
@@ -12,6 +13,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"
volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/mount"
@@ -296,6 +298,63 @@ func (s *VolumeService) isInternalVolumeInternal(v volumetypes.Volume) bool {
return libarcane.IsInternalContainer(v.Labels)
}
+var generatedAnonymousVolumeNameInternal = regexp.MustCompile(`^[a-f0-9]{64}$`)
+
+func isAnonymousVolumeInternal(v volume.Volume) bool {
+ if _, ok := v.Labels["com.docker.volume.anonymous"]; ok {
+ return true
+ }
+ return generatedAnonymousVolumeNameInternal.MatchString(v.Name)
+}
+
+func mountedVolumeNamesInternal(mounts []container.MountPoint) map[string]struct{} {
+ names := make(map[string]struct{})
+ for _, item := range mounts {
+ if item.Type != mount.TypeVolume {
+ continue
+ }
+ name := strings.TrimSpace(item.Name)
+ if name == "" {
+ name = strings.TrimSpace(item.Source)
+ }
+ if name != "" {
+ names[name] = struct{}{}
+ }
+ }
+ return names
+}
+
+// ListBackupVolumeOptions returns the current non-internal volumes used by centralized backup selection.
+func (s *VolumeService) ListBackupVolumeOptions(ctx context.Context) ([]backuptypes.SystemVolumeBackupOption, error) {
+ dockerClient, err := s.dockerService.GetClient(ctx)
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to connect to Docker")
+ }
+ result, err := dockerClient.VolumeList(ctx, client.VolumeListOptions{})
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to list Docker volumes")
+ }
+ arcaneVolumes := make(map[string]struct{})
+ if inspect, inspectErr := libarcane.InspectCurrentArcaneContainer(ctx, dockerClient); inspectErr == nil && inspect != nil {
+ arcaneVolumes = mountedVolumeNamesInternal(inspect.Mounts)
+ } else if inspectErr != nil {
+ slog.DebugContext(ctx, "volume service: could not identify Arcane-mounted volumes for centralized backups", "error", inspectErr)
+ }
+ options := make([]backuptypes.SystemVolumeBackupOption, 0, len(result.Items))
+ for _, item := range result.Items {
+ if s.isInternalVolumeInternal(volumetypes.NewSummary(item)) {
+ continue
+ }
+ if _, isArcaneVolume := arcaneVolumes[item.Name]; isArcaneVolume {
+ continue
+ }
+ options = append(options, backuptypes.SystemVolumeBackupOption{
+ Name: item.Name, Anonymous: isAnonymousVolumeInternal(item), Available: true,
+ })
+ }
+ return options, nil
+}
+
func (s *VolumeService) ListVolumesPaginated(ctx context.Context, params pagination.QueryParams, includeInternal bool) ([]volumetypes.Volume, pagination.Response, volumetypes.UsageCounts, error) {
startedAt := time.Now()
slog.DebugContext(ctx, "volume service: list volumes paginated", "search", params.Search, "sort", params.Sort, "order", params.Order, "start", params.Start, "limit", params.Limit, "include_internal", includeInternal)
diff --git a/backend/internal/volume/model.go b/backend/internal/volume/model.go
index e8ab26ed8..6a1638cb6 100644
--- a/backend/internal/volume/model.go
+++ b/backend/internal/volume/model.go
@@ -1,10 +1,10 @@
package volume
import (
- "github.com/getarcaneapp/arcane/backend/v2/internal/database"
-
"time"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"
+ backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"
"github.com/getarcaneapp/arcane/types/v2/volume"
)
@@ -34,20 +34,21 @@ const (
type VolumeBackup struct {
database.BaseModel
- VolumeName string `json:"volumeName" gorm:"column:volume_name;index"`
- Size int64 `json:"size" gorm:"column:size"`
- CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`
- Status VolumeBackupStatus `json:"status" gorm:"column:status;type:text;not null;default:succeeded"`
- Trigger VolumeBackupTrigger `json:"trigger" gorm:"column:trigger;type:text;not null;default:manual"`
- Destination volume.BackupDestination `json:"destination" gorm:"column:destination;type:text;not null;default:local"`
- Format VolumeBackupFormat `json:"format" gorm:"column:format;type:text;not null;default:archive"`
- LocalSnapshotID string `json:"localSnapshotId,omitempty" gorm:"column:local_snapshot_id;type:text"`
- RemoteSnapshotID string `json:"remoteSnapshotId,omitempty" gorm:"column:remote_snapshot_id;type:text"`
- S3DestinationID string `json:"s3DestinationId,omitempty" gorm:"column:s3_destination_id;type:text;index"`
- S3DestinationName string `json:"s3DestinationName,omitempty" gorm:"-"`
- PolicyID string `json:"policyId,omitempty" gorm:"column:policy_id;type:text;index"`
- Error string `json:"error,omitempty" gorm:"column:error;type:text"`
- ActivityID *string `json:"activityId,omitempty" gorm:"-"`
+ VolumeName string `json:"volumeName" gorm:"column:volume_name;index"`
+ Size int64 `json:"size" gorm:"column:size"`
+ CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`
+ Status VolumeBackupStatus `json:"status" gorm:"column:status;type:text;not null;default:succeeded"`
+ Trigger VolumeBackupTrigger `json:"trigger" gorm:"column:trigger;type:text;not null;default:manual"`
+ Destination volume.BackupDestination `json:"destination" gorm:"column:destination;type:text;not null;default:local"`
+ Format VolumeBackupFormat `json:"format" gorm:"column:format;type:text;not null;default:archive"`
+ LocalSnapshotID string `json:"localSnapshotId,omitempty" gorm:"column:local_snapshot_id;type:text"`
+ RemoteSnapshotID string `json:"remoteSnapshotId,omitempty" gorm:"column:remote_snapshot_id;type:text"`
+ S3DestinationID string `json:"s3DestinationId,omitempty" gorm:"column:s3_destination_id;type:text;index"`
+ S3DestinationName string `json:"s3DestinationName,omitempty" gorm:"-"`
+ PolicyID string `json:"policyId,omitempty" gorm:"column:policy_id;type:text;index"`
+ Error string `json:"error,omitempty" gorm:"column:error;type:text"`
+ ActivityID *string `json:"activityId,omitempty" gorm:"-"`
+ Type backuptypes.ManagementType `json:"type" gorm:"-"`
}
func (*VolumeBackup) TableName() string {
@@ -70,6 +71,7 @@ func (b *VolumeBackup) ToDTO() volume.BackupEntry {
S3DestinationName: b.S3DestinationName,
PolicyID: b.PolicyID,
Error: b.Error,
+ Type: b.Type,
}
}
diff --git a/cli/pkg/variables/cmd.go b/cli/pkg/variables/cmd.go
index b956830ff..8987119ca 100644
--- a/cli/pkg/variables/cmd.go
+++ b/cli/pkg/variables/cmd.go
@@ -1,7 +1,6 @@
package variables
import (
- "encoding/json"
"fmt"
"net/http"
"strconv"
@@ -111,18 +110,13 @@ var listCmd = &cobra.Command{
return errors.WrapIf(err, "failed to list variables")
}
- body, err := cmdutil.ReadJSONBody(resp)
- if err != nil {
+ var result base.ApiResponse[[]env.GlobalVariable]
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
return errors.WrapIf(err, "failed to list variables")
}
if jsonOutput {
- return cmdutil.PrintRawJSON(body)
- }
-
- var result base.ApiResponse[[]env.GlobalVariable]
- if err := json.Unmarshal(body, &result); err != nil {
- return errors.WrapIf(err, "failed to parse response")
+ return cmdutil.PrintJSON(result.Data)
}
headers := []string{"ID", "KEY", "SCOPE", "SECRET", "VALUE"}
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 2e9503632..b634db30a 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -3316,14 +3316,17 @@
"backups_upload_s3_success": "Backup uploaded to S3",
"backups_upload_s3_failed": "Failed to upload backup to S3",
"system_backups_title": "Backups",
- "system_backups_description": "Create encrypted recovery snapshots of Arcane's database, files, settings, and runtime secrets.",
+ "system_backups_description": "Create and schedule Arcane recovery snapshots and Docker volume backups.",
"system_backups_id": "Backup ID",
"system_backups_configure": "Configure schedule",
"system_backups_schedules": "Backup schedules",
"system_backups_add_schedule": "Create schedule",
"system_backups_schedule_removed": "System backup schedule removed.",
- "system_backups_no_schedules": "No system backup schedules configured yet.",
+ "system_backups_no_schedules": "No backup schedules configured yet.",
"system_backups_schedule_description": "Each schedule has its own destination and retention policy.",
+ "system_backups_schedule_type_description": "Create a schedule for Arcane recovery data or matching Docker volumes.",
+ "system_backups_type_system_description": "Back up Arcane's recovery data.",
+ "system_backups_type_volume_description": "Back up a live selection of Docker volumes.",
"system_backups_dialog_description": "The separate recovery key encrypts this Rustic repository and is required to restore it on a fresh Arcane instance.",
"system_backups_recovery_key": "Recovery key",
"system_backups_recovery_key_saved_description": "Leave empty to use the configured recovery key.",
@@ -3357,8 +3360,8 @@
"system_backups_deleted": "System backup deleted.",
"system_backups_delete_failed": "Failed to delete system backup.",
"system_backups_backup_configuration": "Backup configuration",
- "system_backups_custom_configuration": "Custom destination",
- "system_backups_custom_configuration_description": "Choose a destination for this backup only.",
+ "system_backups_custom_configuration": "Custom configuration",
+ "system_backups_custom_configuration_description": "Configure this backup without changing a saved schedule.",
"system_backups_discover": "Find S3 backups",
"system_backups_discover_title": "Find existing S3 backups",
"system_backups_discover_description": "Open an Arcane system-recovery repository with its separate recovery key and add its snapshots to this table.",
@@ -3395,5 +3398,40 @@
"network_disconnect_failed": "Failed to disconnect container",
"network_live_change_note": "Live network changes are lost when the container is recreated unless they are also saved via Edit.",
"common_connect": "Connect",
- "common_disconnect": "Disconnect"
+ "common_disconnect": "Disconnect",
+ "backups_system_managed": "System-managed",
+ "backups_volume_managed": "Volume-managed",
+ "backups_backup_type": "Backup type",
+ "backups_backup_type_description": "Choose whether to back up Arcane recovery data or Docker volumes.",
+ "backups_resource": "Resource",
+ "backups_open_volume": "Open volume backups",
+ "system_volume_backups_title": "Volume backups",
+ "system_volume_backups_description": "Back up matching local Docker volumes with reusable schedules and retention policies.",
+ "system_volume_backups_enabled_description": "Run backups for every matching volume on this schedule.",
+ "system_volume_backups_saved": "System-managed volume backups saved.",
+ "system_volume_backups_schedule_removed": "Volume backup schedule removed.",
+ "system_volume_backups_save_failed": "Failed to save system-managed volume backups.",
+ "system_volume_backups_options_failed": "Failed to load the local volume list.",
+ "system_volume_backups_run_now": "Run now",
+ "system_volume_backups_run_failed": "Failed to run system-managed volume backups.",
+ "system_volume_backups_run_result": "Matched {matched}; {succeeded} succeeded, {failed} failed, and {skipped} skipped.",
+ "system_volume_backups_summary": "{schedule} · Keep {retention} · {mode}",
+ "system_volume_backups_selection_mode": "Volume selection",
+ "system_volume_backups_selection_description": "Rules are evaluated against Docker's current volume list at the start of every run.",
+ "system_volume_backups_selection_all": "All volumes",
+ "system_volume_backups_selection_all_description": "Include every current and future non-internal volume.",
+ "system_volume_backups_selection_allowlist": "Allowlist",
+ "system_volume_backups_selection_allowlist_description": "Include only the selected volume names.",
+ "system_volume_backups_selection_blocklist": "Blocklist",
+ "system_volume_backups_selection_blocklist_description": "Include every volume except the selected names.",
+ "system_volume_backups_included_volumes": "Included volumes",
+ "system_volume_backups_excluded_volumes": "Excluded volumes",
+ "system_volume_backups_allowlist_help": "Checked volumes are included. New volumes are excluded until selected.",
+ "system_volume_backups_blocklist_help": "Checked volumes are excluded. New volumes are included automatically.",
+ "system_volume_backups_search_volumes": "Search volumes",
+ "system_volume_backups_anonymous": "Anonymous",
+ "system_volume_backups_unavailable": "Unavailable",
+ "system_volume_backups_no_matching_volumes": "No matching volumes.",
+ "system_volume_backups_ignore_anonymous": "Ignore anonymous volumes",
+ "system_volume_backups_ignore_anonymous_description": "Anonymous Docker volumes remain visible above but are skipped during backup runs."
}
diff --git a/frontend/src/lib/components/arcane-table/cells/backup-management-cell.svelte b/frontend/src/lib/components/arcane-table/cells/backup-management-cell.svelte
new file mode 100644
index 000000000..b1c333f95
--- /dev/null
+++ b/frontend/src/lib/components/arcane-table/cells/backup-management-cell.svelte
@@ -0,0 +1,9 @@
+<script lang="ts">
+ import { Badge } from '#lib/components/ui/badge';
+ import type { BackupManagementType } from '#lib/types/backup';
+ import { backupManagementLabel } from '#lib/utils/backups';
+
+ let { type }: { type?: BackupManagementType } = $props();
+</script>
+
+<Badge variant="purple">{backupManagementLabel(type)}</Badge>
diff --git a/frontend/src/lib/components/backup-policy-card.svelte b/frontend/src/lib/components/backup-policy-card.svelte
index 88605ee58..552c798b8 100644
--- a/frontend/src/lib/components/backup-policy-card.svelte
+++ b/frontend/src/lib/components/backup-policy-card.svelte
@@ -15,11 +15,13 @@
let {
policy,
+ resourceType,
showStopContainers = false,
onEdit,
editDisabled = false
}: {
policy: CardPolicy;
+ resourceType?: 'system' | 'volume';
showStopContainers?: boolean;
onEdit?: () => void;
editDisabled?: boolean;
@@ -28,10 +30,18 @@
const s3Name = $derived(policy.s3DestinationName || policy.s3Bucket || policy.s3DestinationId || '');
</script>
-<div class="grid min-w-0 grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-1.5 gap-y-0.5 rounded-md border px-2 py-1">
+<div
+ class="grid min-w-0 grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-1.5 gap-y-0.5 rounded-md border px-2 py-1"
+ data-testid={resourceType ? `backup-policy-${resourceType}-${policy.id}` : undefined}
+>
<Badge variant={policy.enabled ? 'green' : 'gray'}>{policy.enabled ? m.common_enabled() : m.common_disabled()}</Badge>
<code class="truncate">{policy.schedule}</code>
<div class="flex items-center gap-1.5 justify-self-end">
+ {#if resourceType}
+ <Badge variant="purple">
+ {resourceType === 'system' ? m.system() : m.resource_volume_cap()}
+ </Badge>
+ {/if}
<Badge variant="blue">{backupDestinationLabel(backupDestinationFromFlags(policy.localEnabled, policy.s3Enabled))}</Badge>
{#if onEdit}
<ArcaneButton
diff --git a/frontend/src/lib/components/backup-policy-dialog.svelte b/frontend/src/lib/components/backup-policy-dialog.svelte
index 29a0cc378..73793a82f 100644
--- a/frontend/src/lib/components/backup-policy-dialog.svelte
+++ b/frontend/src/lib/components/backup-policy-dialog.svelte
@@ -1,11 +1,12 @@
-<script lang="ts" generics="TPolicy extends BackupPolicy">
+<script lang="ts" generics="TPolicy extends BackupPolicy, TUpdate extends { id: string } = BackupPolicyUpdate">
+ import { untrack, type Snippet } from 'svelte';
import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog';
import { ArcaneButton } from '#lib/components/arcane-button';
import BackupPolicyFields from '#lib/components/backup-policy-fields.svelte';
import type { BackupPolicy, BackupPolicyForm, BackupPolicyUpdate } from '#lib/types/backup';
import type { S3Destination } from '#lib/types/s3-destination';
import { s3DestinationService } from '#lib/services/s3-destination-service';
- import { backupDestinationFromFlags, backupPolicyDestinationValues } from '#lib/utils/backups';
+ import { backupDestinationFromFlags, backupPolicyDestinationValues, backupPolicyUpdateFromPolicy } from '#lib/utils/backups';
import { toast } from 'svelte-sonner';
import * as m from '#lib/paraglide/messages.js';
@@ -24,9 +25,16 @@
defaultEnabled = true,
showStopContainers = false,
destinations,
+ resetKey,
+ beforeFields,
+ afterFields,
+ policyPayload = (policy) => backupPolicyUpdateFromPolicy(policy, showStopContainers) as unknown as TUpdate,
+ extendUpdate = (update) => update as unknown as TUpdate,
updatePolicies,
messages,
- onSaved
+ onSaved,
+ onReset,
+ contentClass = 'sm:max-w-[720px]'
}: {
open: boolean;
idPrefix: string;
@@ -40,9 +48,16 @@
defaultEnabled?: boolean;
showStopContainers?: boolean;
destinations?: S3Destination[];
- updatePolicies: (policies: BackupPolicyUpdate[]) => Promise<TPolicy[]>;
+ resetKey?: string;
+ beforeFields?: Snippet;
+ afterFields?: Snippet;
+ policyPayload?: (policy: TPolicy) => TUpdate;
+ extendUpdate?: (update: BackupPolicyUpdate) => TUpdate;
+ updatePolicies: (policies: TUpdate[]) => Promise<TPolicy[]>;
messages: { saved: string; saveFailed: string; removed: string };
onSaved: (policies: TPolicy[]) => void;
+ onReset?: (policy?: TPolicy) => void;
+ contentClass?: string;
} = $props();
let saving = $state(false);
@@ -98,50 +113,41 @@
$effect(() => {
if (!open) return;
- const policy = policies.find((item) => item.id === policyId);
- form = policy
- ? {
- id: policy.id,
- enabled: policy.enabled,
- schedule: policy.schedule,
- retentionCount: policy.retentionCount,
- stopContainers: policy.stopContainers ?? false,
- s3DestinationId: policy.s3DestinationId || '',
- destination: backupDestinationFromFlags(policy.localEnabled, policy.s3Enabled)
- }
- : newPolicy();
- if (!destinations) void loadDestinations();
+ resetKey;
+ untrack(() => {
+ const policy = policies.find((item) => item.id === policyId);
+ form = policy
+ ? {
+ id: policy.id,
+ enabled: policy.enabled,
+ schedule: policy.schedule,
+ retentionCount: policy.retentionCount,
+ stopContainers: policy.stopContainers ?? false,
+ s3DestinationId: policy.s3DestinationId || '',
+ destination: backupDestinationFromFlags(policy.localEnabled, policy.s3Enabled)
+ }
+ : newPolicy();
+ onReset?.(policy);
+ if (!destinations) void loadDestinations();
+ });
});
function updateForm(values: Partial<BackupPolicyForm>) {
form = { ...form, ...values, serverError: undefined };
}
- function policyPayload(policy: BackupPolicy): BackupPolicyUpdate {
- return {
- id: policy.id,
- enabled: policy.enabled,
- schedule: policy.schedule,
- retentionCount: policy.retentionCount,
- localEnabled: policy.localEnabled,
- s3Enabled: policy.s3Enabled,
- s3DestinationId: policy.s3DestinationId ?? '',
- ...(showStopContainers ? { stopContainers: policy.stopContainers ?? false } : {})
- };
- }
-
async function savePolicies() {
if (formInvalid) return;
saving = true;
try {
- const current: BackupPolicyUpdate = {
+ const current = extendUpdate({
id: form.id,
enabled: form.enabled,
schedule: form.schedule,
retentionCount: Number(form.retentionCount),
...backupPolicyDestinationValues(form.destination, form.s3DestinationId),
...(showStopContainers ? { stopContainers: form.stopContainers ?? false } : {})
- };
+ });
const existing = policies.map(policyPayload);
const next = policyId ? existing.map((policy) => (policy.id === policyId ? current : policy)) : [...existing, current];
onSaved(await updatePolicies(next));
@@ -171,9 +177,12 @@
}
</script>
-<ResponsiveDialog bind:open title={policyId ? m.jobs_edit_schedule() : addTitle} {description} contentClass="sm:max-w-[720px]">
+<ResponsiveDialog bind:open title={policyId ? m.jobs_edit_schedule() : addTitle} {description} {contentClass}>
{#snippet children()}
<div class="space-y-4 py-2">
+ {#if beforeFields}
+ {@render beforeFields()}
+ {/if}
<BackupPolicyFields
{idPrefix}
{form}
@@ -188,6 +197,9 @@
{destinationsLoading}
onChange={updateForm}
/>
+ {#if afterFields}
+ {@render afterFields()}
+ {/if}
</div>
{/snippet}
{#snippet footer()}
diff --git a/frontend/src/lib/components/backup-policy-fields.svelte b/frontend/src/lib/components/backup-policy-fields.svelte
index 67cbd0ce7..15b87af09 100644
--- a/frontend/src/lib/components/backup-policy-fields.svelte
+++ b/frontend/src/lib/components/backup-policy-fields.svelte
@@ -49,6 +49,7 @@
/>
{#if enabledError}<p class="text-sm text-destructive">{enabledError}</p>{/if}
<TextInputWithLabel
+ id={`${idPrefix}-schedule`}
value={form.schedule}
onChange={(schedule) => onChange({ schedule })}
error={scheduleError}
@@ -59,6 +60,7 @@
placeholder={schedulePlaceholder}
/>
<TextInputWithLabel
+ id={`${idPrefix}-retention`}
value={form.retentionCount}
onChange={(retentionCount) => onChange({ retentionCount: Number(retentionCount) })}
error={retentionError}
diff --git a/frontend/src/lib/services/system-backup-service.ts b/frontend/src/lib/services/system-backup-service.ts
index eb2aa7930..8056532b3 100644
--- a/frontend/src/lib/services/system-backup-service.ts
+++ b/frontend/src/lib/services/system-backup-service.ts
@@ -2,10 +2,16 @@ import BaseAPIService from './api-service';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';
import type {
CreateSystemBackup,
+ BackupHistoryEntry,
SystemBackupPolicyCollection,
SystemBackupRecoveryKey,
SystemBackupRun,
- UpdateSystemBackupPolicy
+ UpdateSystemBackupPolicy,
+ SystemVolumeBackupPolicyCollection,
+ UpdateSystemVolumeBackupPolicy,
+ SystemVolumeBackupOption,
+ SystemVolumeBackupRunResult,
+ RunSystemVolumeBackups
} from '#lib/types/system-backup';
import { transformPaginationParams } from '#lib/utils/tables';
import type { BackupFileBrowseRequest, BackupFileEntry, BackupRestoreSelection } from '#lib/types/backup';
@@ -16,6 +22,27 @@ class SystemBackupService extends BaseAPIService {
return response.data;
}
+ async listHistory(options?: SearchPaginationSortRequest): Promise<Paginated<BackupHistoryEntry>> {
+ const response = await this.api.get('/backups/history', { params: transformPaginationParams(options) });
+ return response.data;
+ }
+
+ async getSystemVolumeConfig(): Promise<SystemVolumeBackupPolicyCollection> {
+ return this.handleResponse(this.api.get('/backups/volumes/config'));
+ }
+
+ async updateSystemVolumeConfig(policies: UpdateSystemVolumeBackupPolicy[]): Promise<SystemVolumeBackupPolicyCollection> {
+ return this.handleResponse(this.api.put('/backups/volumes/config', { policies }));
+ }
+
+ async listSystemVolumeOptions(): Promise<SystemVolumeBackupOption[]> {
+ return this.handleResponse(this.api.get('/backups/volumes/options'));
+ }
+
+ async runSystemVolumeBackups(request: RunSystemVolumeBackups = {}): Promise<SystemVolumeBackupRunResult> {
+ return this.handleResponse(this.api.post('/backups/volumes/run', request));
+ }
+
async getPolicies(): Promise<SystemBackupPolicyCollection> {
return this.handleResponse(this.api.get('/backups/policies'));
}
diff --git a/frontend/src/lib/types/backup.ts b/frontend/src/lib/types/backup.ts
index b27df011b..a5970db2c 100644
--- a/frontend/src/lib/types/backup.ts
+++ b/frontend/src/lib/types/backup.ts
@@ -3,6 +3,7 @@ import type { Paginated } from './shared';
export type BackupDestination = 'local' | 's3' | 'local_s3';
export type BackupStatus = 'running' | 'succeeded' | 'failed';
export type BackupTrigger = 'manual' | 'scheduled' | 'safety';
+export type BackupManagementType = 'system' | 'volume';
export type BackupRun = {
id: string;
@@ -18,6 +19,7 @@ export type BackupRun = {
s3DestinationName?: string;
policyId?: string;
error?: string;
+ type?: BackupManagementType;
};
export type BackupPolicyForm = {
diff --git a/frontend/src/lib/types/system-backup.ts b/frontend/src/lib/types/system-backup.ts
index c105888eb..0e6f190ec 100644
--- a/frontend/src/lib/types/system-backup.ts
+++ b/frontend/src/lib/types/system-backup.ts
@@ -1,9 +1,61 @@
-import type { BackupDestination, BackupRun } from './backup';
+import type { BackupDestination, BackupManagementType, BackupPolicy, BackupRun } from './backup';
export type SystemBackupDestination = BackupDestination;
export type SystemBackupRun = BackupRun;
+export type BackupHistoryEntry = BackupRun & {
+ type: BackupManagementType;
+ resourceType: 'system' | 'volume';
+ resourceName: string;
+};
+
+export type SystemVolumeBackupSelectionMode = 'all' | 'allowlist' | 'blocklist';
+
+export type SystemVolumeBackupPolicy = BackupPolicy & {
+ s3DestinationName?: string;
+ selectionMode: SystemVolumeBackupSelectionMode;
+ volumeNames: string[];
+ ignoreAnonymous: boolean;
+ lastRun?: SystemBackupRun;
+};
+
+export type UpdateSystemVolumeBackupPolicy = Omit<SystemVolumeBackupPolicy, 's3DestinationName' | 'lastRun'> & {
+ s3DestinationId: string;
+};
+
+export type SystemVolumeBackupPolicyCollection = {
+ policies: SystemVolumeBackupPolicy[];
+};
+
+export type SystemVolumeBackupOption = {
+ name: string;
+ anonymous: boolean;
+ available: boolean;
+};
+
+export type SystemVolumeBackupRunResult = {
+ matched: number;
+ succeeded: number;
+ failed: number;
+ skipped: number;
+ failures: { volumeName: string; error: string }[];
+};
+
+export type SystemVolumeBackupCustomRun = {
+ destination: BackupDestination;
+ s3DestinationId?: string;
+ stopContainers: boolean;
+ selectionMode: SystemVolumeBackupSelectionMode;
+ volumeNames: string[];
+ ignoreAnonymous: boolean;
+};
+
+export type RunSystemVolumeBackups = {
+ policyId?: string;
+ custom?: SystemVolumeBackupCustomRun;
+};
+
export type SystemBackupPolicy = {
id: string;
enabled: boolean;
diff --git a/frontend/src/lib/utils/backups.ts b/frontend/src/lib/utils/backups.ts
index 07d2f6500..5bee117d0 100644
--- a/frontend/src/lib/utils/backups.ts
+++ b/frontend/src/lib/utils/backups.ts
@@ -1,5 +1,13 @@
import { m } from '#lib/paraglide/messages';
-import type { BackupDestination, BackupRun, BackupStatus, BackupTrigger } from '#lib/types/backup';
+import type {
+ BackupDestination,
+ BackupManagementType,
+ BackupPolicy,
+ BackupPolicyUpdate,
+ BackupRun,
+ BackupStatus,
+ BackupTrigger
+} from '#lib/types/backup';
import type { S3Destination } from '#lib/types/s3-destination';
export function backupStatusLabel(status: BackupStatus): string {
@@ -20,6 +28,17 @@ export function backupTriggerLabel(trigger: BackupTrigger): string {
return m.backups_trigger_manual();
}
+export function backupManagementLabel(type?: BackupManagementType): string {
+ return type === 'system' ? m.backups_system_managed() : m.backups_volume_managed();
+}
+
+export function backupManagementFilterOptions() {
+ return [
+ { label: m.backups_system_managed(), value: 'system' },
+ { label: m.backups_volume_managed(), value: 'volume' }
+ ];
+}
+
export function backupDestinationLabel(destination: BackupDestination): string {
if (destination === 'local_s3') return m.backups_destination_local_s3();
if (destination === 's3') return m.backups_destination_s3();
@@ -85,3 +104,16 @@ export function backupPolicyDestinationValues(destination: BackupDestination, s3
s3DestinationId: destination === 'local' ? '' : s3DestinationId
};
}
+
+export function backupPolicyUpdateFromPolicy(policy: BackupPolicy, includeStopContainers = false): BackupPolicyUpdate {
+ return {
+ id: policy.id,
+ enabled: policy.enabled,
+ schedule: policy.schedule,
+ retentionCount: policy.retentionCount,
+ localEnabled: policy.localEnabled,
+ s3Enabled: policy.s3Enabled,
+ s3DestinationId: policy.s3DestinationId ?? '',
+ ...(includeStopContainers ? { stopContainers: policy.stopContainers ?? false } : {})
+ };
+}
diff --git a/frontend/src/routes/(app)/settings/backups/+page.svelte b/frontend/src/routes/(app)/settings/backups/+page.svelte
index a3027ca48..5fa47689d 100644
--- a/frontend/src/routes/(app)/settings/backups/+page.svelte
+++ b/frontend/src/routes/(app)/settings/backups/+page.svelte
@@ -10,17 +10,25 @@
import { Input } from '#lib/components/ui/input';
import { ResponsiveDialog } from '#lib/components/ui/responsive-dialog';
import { ArcaneButton } from '#lib/components/arcane-button';
+ import LabeledSwitch from '#lib/components/form/labeled-switch.svelte';
import SelectWithLabel from '#lib/components/form/select-with-label.svelte';
import TextInputWithLabel from '#lib/components/form/text-input-with-label.svelte';
import { systemBackupService } from '#lib/services/system-backup-service';
import { hasPermission } from '#lib/utils/auth';
import { backupDestinationOptions, backupPolicyDestinationDisplay, s3DestinationOptions } from '#lib/utils/backups';
import type { SearchPaginationSortRequest } from '#lib/types/shared';
- import type { SystemBackupDestination, SystemBackupRun } from '#lib/types/system-backup';
+ import type {
+ BackupHistoryEntry,
+ SystemBackupDestination,
+ SystemVolumeBackupOption,
+ SystemVolumeBackupSelectionMode
+ } from '#lib/types/system-backup';
+ import { environmentStore } from '#lib/stores/environment.store.svelte';
import * as m from '#lib/paraglide/messages.js';
import SystemBackupTable from './system-backup-table.svelte';
- import BackupPolicyDialog from '#lib/components/backup-policy-dialog.svelte';
import BackupPolicyCard from '#lib/components/backup-policy-card.svelte';
+ import SystemBackupScheduleDialog from './system-backup-schedule-dialog.svelte';
+ import SystemVolumeScopeFields from './system-volume-scope-fields.svelte';
import BackupFilePicker from '#lib/components/backup-file-picker.svelte';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast';
import type { BackupFileProvider } from '#lib/types/backup';
@@ -31,22 +39,32 @@
const queryClient = useQueryClient();
let backups = $state(untrack(() => data.backups));
let policyCollection = $state(untrack(() => data.policyCollection));
+ let systemVolumePolicyCollection = $state(untrack(() => data.systemVolumePolicyCollection));
+ let systemVolumeOptions = $state<SystemVolumeBackupOption[]>([]);
let requestOptions = $state<SearchPaginationSortRequest>(untrack(() => data.requestOptions));
- let policyOpen = $state(false);
- let editingPolicyId = $state<string | undefined>();
+ let scheduleOpen = $state(false);
+ let scheduleType = $state<'system' | 'volume'>('system');
+ let editingScheduleId = $state<string | undefined>();
let keyOpen = $state(false);
let actionOpen = $state(false);
let action = $state<'create' | 'restore' | 'upload' | 'delete' | 'discover'>('create');
- let selected = $state<SystemBackupRun | null>(null);
+ let selected = $state<BackupHistoryEntry | null>(null);
+ let backupType = $state<'system' | 'volume'>('system');
let backupConfiguration = $state('custom');
let destination = $state<SystemBackupDestination>('local');
let s3DestinationId = $state('');
+ let stopContainers = $state(false);
+ let selectionMode = $state<SystemVolumeBackupSelectionMode>('all');
+ let volumeNames = $state<string[]>([]);
+ let ignoreAnonymous = $state(true);
+ let systemVolumeOptionsLoading = $state(false);
+ let systemVolumeOptionsLoaded = $state(false);
let recoveryKey = $state('');
let newRecoveryKey = $state('');
let loading = $state(false);
let generatingKey = $state(false);
let restoreFilesOpen = $state(false);
- let restoreFilesTarget = $state<SystemBackupRun | null>(null);
+ let restoreFilesTarget = $state<BackupHistoryEntry | null>(null);
let restoreFilesRecoveryKey = $state('');
let restoreFilesProvider = $state<BackupFileProvider | null>(null);
let restoreFilesSelectedPaths = $state<string[]>([]);
@@ -58,13 +76,17 @@
const canManageRecoveryKey = $derived(hasPermission('system-backups:recovery-key'));
const destinationOptions = $derived(backupDestinationOptions(data.destinations.length > 0));
const s3Options = $derived(s3DestinationOptions(data.destinations));
+ const backupTypeOptions = $derived([
+ { label: m.system(), value: 'system', description: m.system_backups_type_system_description() },
+ { label: m.resource_volume_cap(), value: 'volume', description: m.system_backups_type_volume_description() }
+ ]);
const configurationOptions = $derived([
{
label: m.system_backups_custom_configuration(),
value: 'custom',
description: m.system_backups_custom_configuration_description()
},
- ...policyCollection.policies.map((item) => ({
+ ...(backupType === 'system' ? policyCollection.policies : systemVolumePolicyCollection.policies).map((item) => ({
label: item.schedule,
value: item.id,
description: backupPolicyDestinationDisplay(item)
@@ -90,6 +112,7 @@
: ''
);
const actionKeyInvalid = $derived.by(() => {
+ if (action === 'create' && backupType === 'volume') return false;
if (actionNeedsTypedKey) return !policyCollection.recoveryKeyStored && !recoveryKeyPattern.test(recoveryKey.trim());
// Deleting is always allowed; the backend only asks for the key when
// the run still has snapshots to forget.
@@ -105,9 +128,10 @@
);
const invalid = $derived(Boolean(actionKeyInvalid || keyError || destinationError));
- function openPolicy(id?: string) {
- editingPolicyId = id;
- policyOpen = true;
+ function openSchedule(type: 'system' | 'volume' = 'system', id?: string) {
+ scheduleType = type;
+ editingScheduleId = id;
+ scheduleOpen = true;
}
// Generating persists the key in the same step; the dialog only ever shows
@@ -128,11 +152,16 @@
}
}
- function openAction(next: typeof action, backup: SystemBackupRun | null = null) {
+ function openAction(next: typeof action, backup: BackupHistoryEntry | null = null) {
action = next;
selected = backup;
+ backupType = 'system';
backupConfiguration = 'custom';
destination = 'local';
+ stopContainers = false;
+ selectionMode = 'all';
+ volumeNames = [];
+ ignoreAnonymous = true;
s3DestinationId =
backup?.s3DestinationId ||
policyCollection.policies.find((item) => item.s3DestinationId)?.s3DestinationId ||
@@ -144,7 +173,7 @@
// The picker resets its own selection and search whenever the provider
// changes, so the dialog only manages target, key, and provider.
- async function openRestoreFiles(backup: SystemBackupRun) {
+ async function openRestoreFiles(backup: BackupHistoryEntry) {
restoreFilesTarget = backup;
restoreFilesRecoveryKey = '';
restoreFilesProvider = null;
@@ -216,10 +245,43 @@
if (action === 'restore') return m.system_backups_restore_description();
if (action === 'delete') return m.system_backups_delete_description();
if (action === 'discover') return m.system_backups_discover_description();
- return m.system_backups_dialog_description();
+ return backupType === 'volume' ? m.system_volume_backups_description() : m.system_backups_dialog_description();
}
async function refresh() {
- backups = await systemBackupService.list(requestOptions);
+ backups = await systemBackupService.listHistory(requestOptions);
+ }
+
+ async function loadSystemVolumeOptions() {
+ if (systemVolumeOptionsLoading || systemVolumeOptionsLoaded) return;
+ systemVolumeOptionsLoading = true;
+ try {
+ systemVolumeOptions = await systemBackupService.listSystemVolumeOptions();
+ systemVolumeOptionsLoaded = true;
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : m.system_volume_backups_options_failed());
+ } finally {
+ systemVolumeOptionsLoading = false;
+ }
+ }
+
+ function changeBackupType(value: string) {
+ backupType = value as 'system' | 'volume';
+ backupConfiguration = 'custom';
+ destination = 'local';
+ s3DestinationId = data.destinations[0]?.id ?? '';
+ if (backupType === 'volume') void loadSystemVolumeOptions();
+ }
+
+ async function openVolumeBackups(backup: BackupHistoryEntry) {
+ const localEnvironment = environmentStore.getLocalEnvironment();
+ if (!localEnvironment) return;
+ try {
+ await environmentStore.setEnvironment(localEnvironment);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : m.environments_connect_error());
+ return;
+ }
+ await goto(`/volumes/${encodeURIComponent(backup.resourceName)}?tab=backups`);
}
// With a stored key the S3 repositories are scanned automatically, so
@@ -244,12 +306,37 @@
loading = true;
try {
if (action === 'create') {
- await systemBackupService.create(
- backupConfiguration === 'custom'
- ? { destination, s3DestinationId: destination === 'local' ? '' : s3DestinationId, recoveryKey }
- : { policyId: backupConfiguration, recoveryKey }
- );
- toast.success(m.system_backups_created());
+ if (backupType === 'system') {
+ await systemBackupService.create(
+ backupConfiguration === 'custom'
+ ? { destination, s3DestinationId: destination === 'local' ? '' : s3DestinationId, recoveryKey }
+ : { policyId: backupConfiguration, recoveryKey }
+ );
+ toast.success(m.system_backups_created());
+ } else {
+ const result = await systemBackupService.runSystemVolumeBackups(
+ backupConfiguration === 'custom'
+ ? {
+ custom: {
+ destination,
+ s3DestinationId: destination === 'local' ? '' : s3DestinationId,
+ stopContainers,
+ selectionMode,
+ volumeNames,
+ ignoreAnonymous
+ }
+ }
+ : { policyId: backupConfiguration }
+ );
+ toast.success(
+ m.system_volume_backups_run_result({
+ matched: result.matched,
+ succeeded: result.succeeded,
+ failed: result.failed,
+ skipped: result.skipped
+ })
+ );
+ }
await refresh();
} else if (action === 'restore' && selected) {
await systemBackupService.restore(selected.id, recoveryKey);
@@ -278,7 +365,9 @@
? m.backups_upload_s3_failed()
: action === 'discover'
? m.system_backups_discover_failed()
- : m.system_backups_create_failed();
+ : backupType === 'volume'
+ ? m.system_volume_backups_run_failed()
+ : m.system_backups_create_failed();
toast.error(error instanceof Error ? error.message : fallback);
} finally {
loading = false;
@@ -323,7 +412,7 @@
label: m.common_create(),
disabled: isReadOnly,
options: [
- { label: m.jobs_schedule(), onclick: () => openPolicy() },
+ { label: m.jobs_schedule(), onclick: () => openSchedule() },
{ label: m.volumes_workspace_backup(), onclick: () => openAction('create') }
]
}
@@ -354,7 +443,7 @@
bind:open={keyOpen}
title={m.system_backups_recovery_key()}
description={m.system_backups_recovery_key_saved()}
- contentClass="sm:max-w-[560px]"
+ contentClass={action === 'create' ? 'sm:max-w-[760px]' : 'sm:max-w-[560px]'}
>
{#snippet children()}
<div class="space-y-3 py-2">
@@ -385,13 +474,21 @@
bind:open={actionOpen}
title={dialogTitle()}
description={dialogDescription()}
- contentClass="sm:max-w-[560px]"
+ contentClass={action === 'create' ? 'sm:max-w-[760px]' : 'sm:max-w-[560px]'}
>
{#snippet children()}
<div class="space-y-5 py-2">
{#if action === 'create'}
<SelectWithLabel
- id="manual-system-backup-configuration"
+ id="manual-backup-type"
+ value={backupType}
+ onValueChange={changeBackupType}
+ label={m.backups_backup_type()}
+ description={m.backups_backup_type_description()}
+ options={backupTypeOptions}
+ />
+ <SelectWithLabel
+ id="manual-backup-configuration"
value={backupConfiguration}
onValueChange={(value) => (backupConfiguration = value)}
label={m.system_backups_backup_configuration()}
@@ -399,12 +496,21 @@
/>
{#if backupConfiguration === 'custom'}
<SelectWithLabel
- id="manual-system-backup-destination"
+ id="manual-backup-destination"
value={destination}
onValueChange={(value) => (destination = value as SystemBackupDestination)}
label={m.backups_destination_label()}
options={destinationOptions}
/>
+ {#if backupType === 'volume'}
+ <LabeledSwitch
+ id="manual-volume-backup-stop-containers"
+ checked={stopContainers}
+ onCheckedChange={(value) => (stopContainers = value)}
+ label={m.volume_backup_stop_containers()}
+ description={m.volume_backup_stop_containers_description()}
+ />
+ {/if}
{/if}
{/if}
{#if action === 'upload' || action === 'discover' || (action === 'create' && backupConfiguration === 'custom' && destination !== 'local')}
@@ -417,6 +523,21 @@
options={s3Options}
/>
{/if}
+ {#if action === 'create' && backupType === 'volume' && backupConfiguration === 'custom'}
+ <SystemVolumeScopeFields
+ idPrefix="manual-volume-backup"
+ {selectionMode}
+ {volumeNames}
+ {ignoreAnonymous}
+ options={systemVolumeOptions}
+ loading={systemVolumeOptionsLoading}
+ onChange={(values) => {
+ selectionMode = values.selectionMode ?? selectionMode;
+ volumeNames = values.volumeNames ?? volumeNames;
+ ignoreAnonymous = values.ignoreAnonymous ?? ignoreAnonymous;
+ }}
+ />
+ {/if}
{#if actionNeedsTypedKey}
<TextInputWithLabel
value={recoveryKey}
@@ -429,7 +550,7 @@
type="password"
autocomplete="current-password"
/>
- {:else if action !== 'delete' && !policyCollection.recoveryKeyStored}
+ {:else if action !== 'delete' && !(action === 'create' && backupType === 'volume') && !policyCollection.recoveryKeyStored}
<div class="flex items-center justify-between gap-3 rounded-md border px-3 py-2">
<p class="text-sm text-muted-foreground">{m.system_backups_recovery_key_needed()}</p>
<ArcaneButton
@@ -545,10 +666,24 @@
<div class="space-y-2">
<h2 class="text-lg font-semibold">{m.system_backups_schedules()}</h2>
- {#if policyCollection.policies.length}
+ {#if policyCollection.policies.length || systemVolumePolicyCollection.policies.length}
<div class="grid grid-cols-1 gap-1.5 text-xs text-muted-foreground sm:grid-cols-2 xl:grid-cols-3">
{#each policyCollection.policies as policy (policy.id)}
- <BackupPolicyCard {policy} onEdit={() => openPolicy(policy.id)} editDisabled={isReadOnly} />
+ <BackupPolicyCard
+ {policy}
+ resourceType="system"
+ onEdit={() => openSchedule('system', policy.id)}
+ editDisabled={isReadOnly}
+ />
+ {/each}
+ {#each systemVolumePolicyCollection.policies as policy (policy.id)}
+ <BackupPolicyCard
+ {policy}
+ resourceType="volume"
+ showStopContainers
+ onEdit={() => openSchedule('volume', policy.id)}
+ editDisabled={isReadOnly}
+ />
{/each}
</div>
{:else}
@@ -559,35 +694,32 @@
<SystemBackupTable
bind:backups
bind:requestOptions
- onChanged={(options) => systemBackupService.list(options)}
+ onChanged={(options) => systemBackupService.listHistory(options)}
onRestore={(item) => openAction('restore', item)}
onRestoreFiles={openRestoreFiles}
onUpload={(item) => openAction('upload', item)}
onDelete={(item) => openAction('delete', item)}
+ onOpenVolume={openVolumeBackups}
/>
</div>
{/snippet}
{#snippet additionalContent()}
- <BackupPolicyDialog
- bind:open={policyOpen}
- idPrefix="system-backup-policy"
- policies={policyCollection.policies}
- policyId={editingPolicyId}
- addTitle={m.system_backups_add_schedule()}
- description={m.system_backups_schedule_description()}
- enabledDescription={m.system_backups_enabled_description()}
- enabledError={policyCollection.recoveryKeyStored ? null : m.system_backups_recovery_key_schedule_required()}
- defaultSchedule="0 0 3 * * *"
- defaultEnabled={policyCollection.recoveryKeyStored}
- destinations={data.destinations}
- updatePolicies={async (policies) => (await systemBackupService.updatePolicies(policies)).policies}
- messages={{
- saved: m.system_backups_policy_saved(),
- saveFailed: m.system_backups_policy_failed(),
- removed: m.system_backups_schedule_removed()
- }}
- onSaved={(policies) => (policyCollection = { ...policyCollection, policies })}
- />
+ {#if scheduleOpen}
+ <SystemBackupScheduleDialog
+ bind:open={scheduleOpen}
+ initialType={scheduleType}
+ policyId={editingScheduleId}
+ systemPolicies={policyCollection.policies}
+ volumePolicies={systemVolumePolicyCollection.policies}
+ recoveryKeyStored={policyCollection.recoveryKeyStored}
+ destinations={data.destinations}
+ volumeOptions={systemVolumeOptions}
+ volumeOptionsLoading={systemVolumeOptionsLoading}
+ onLoadVolumeOptions={loadSystemVolumeOptions}
+ onSystemSaved={(policies) => (policyCollection = { ...policyCollection, policies })}
+ onVolumeSaved={(policies) => (systemVolumePolicyCollection = { policies })}
+ />
+ {/if}
{@render recoveryKeyDialog()}
{@render actionDialog()}
diff --git a/frontend/src/routes/(app)/settings/backups/+page.ts b/frontend/src/routes/(app)/settings/backups/+page.ts
index 7cb2f0f63..a62d4b913 100644
--- a/frontend/src/routes/(app)/settings/backups/+page.ts
+++ b/frontend/src/routes/(app)/settings/backups/+page.ts
@@ -9,10 +9,11 @@ export const load: PageLoad = async () => {
pagination: { page: 1, limit: 20 },
sort: { column: 'createdAt', direction: 'desc' }
} satisfies SearchPaginationSortRequest);
- const [backups, policyCollection, destinations] = await Promise.all([
- systemBackupService.list(requestOptions),
+ const [backups, policyCollection, destinations, systemVolumePolicyCollection] = await Promise.all([
+ systemBackupService.listHistory(requestOptions),
systemBackupService.getPolicies(),
- s3DestinationService.listAll()
+ s3DestinationService.listAll(),
+ systemBackupService.getSystemVolumeConfig()
]);
- return { backups, policyCollection, destinations, requestOptions };
+ return { backups, policyCollection, destinations, systemVolumePolicyCollection, requestOptions };
};
diff --git a/frontend/src/routes/(app)/settings/backups/system-backup-schedule-dialog.svelte b/frontend/src/routes/(app)/settings/backups/system-backup-schedule-dialog.svelte
new file mode 100644
index 000000000..ba81ab084
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/backups/system-backup-schedule-dialog.svelte
@@ -0,0 +1,185 @@
+<script lang="ts">
+ import { untrack } from 'svelte';
+ import BackupPolicyDialog from '#lib/components/backup-policy-dialog.svelte';
+ import SelectWithLabel from '#lib/components/form/select-with-label.svelte';
+ import { systemBackupService } from '#lib/services/system-backup-service';
+ import type { BackupPolicyUpdate } from '#lib/types/backup';
+ import type { S3Destination } from '#lib/types/s3-destination';
+ import type {
+ SystemBackupPolicy,
+ SystemVolumeBackupOption,
+ SystemVolumeBackupPolicy,
+ SystemVolumeBackupSelectionMode,
+ UpdateSystemBackupPolicy,
+ UpdateSystemVolumeBackupPolicy
+ } from '#lib/types/system-backup';
+ import { backupPolicyUpdateFromPolicy } from '#lib/utils/backups';
+ import SystemVolumeScopeFields from './system-volume-scope-fields.svelte';
+ import * as m from '#lib/paraglide/messages.js';
+
+ type BackupType = 'system' | 'volume';
+
+ let {
+ open = $bindable(),
+ initialType,
+ policyId,
+ systemPolicies,
+ volumePolicies,
+ recoveryKeyStored,
+ destinations,
+ volumeOptions,
+ volumeOptionsLoading,
+ onLoadVolumeOptions,
+ onSystemSaved,
+ onVolumeSaved
+ }: {
+ open: boolean;
+ initialType: BackupType;
+ policyId?: string;
+ systemPolicies: SystemBackupPolicy[];
+ volumePolicies: SystemVolumeBackupPolicy[];
+ recoveryKeyStored: boolean;
+ destinations: S3Destination[];
+ volumeOptions: SystemVolumeBackupOption[];
+ volumeOptionsLoading: boolean;
+ onLoadVolumeOptions: () => Promise<void>;
+ onSystemSaved: (policies: SystemBackupPolicy[]) => void;
+ onVolumeSaved: (policies: SystemVolumeBackupPolicy[]) => void;
+ } = $props();
+
+ const editing = untrack(() => Boolean(policyId));
+ let backupType = $state<BackupType>(untrack(() => initialType));
+ let selectionMode = $state<SystemVolumeBackupSelectionMode>('all');
+ let volumeNames = $state<string[]>([]);
+ let ignoreAnonymous = $state(true);
+ const typeOptions = $derived([
+ { label: m.system(), value: 'system', description: m.system_backups_type_system_description() },
+ { label: m.resource_volume_cap(), value: 'volume', description: m.system_backups_type_volume_description() }
+ ]);
+
+ $effect(() => {
+ if (backupType === 'volume') void onLoadVolumeOptions();
+ });
+
+ function changeType(value: string) {
+ if (editing) return;
+ backupType = value as BackupType;
+ selectionMode = 'all';
+ volumeNames = [];
+ ignoreAnonymous = true;
+ }
+
+ function volumePayload(policy: SystemVolumeBackupPolicy): UpdateSystemVolumeBackupPolicy {
+ return {
+ ...backupPolicyUpdateFromPolicy(policy, true),
+ selectionMode: policy.selectionMode,
+ volumeNames: policy.volumeNames,
+ ignoreAnonymous: policy.ignoreAnonymous
+ };
+ }
+
+ function extendVolumeUpdate(update: BackupPolicyUpdate): UpdateSystemVolumeBackupPolicy {
+ return {
+ ...update,
+ stopContainers: update.stopContainers ?? false,
+ selectionMode,
+ volumeNames,
+ ignoreAnonymous
+ };
+ }
+
+ function resetVolumeScope(policy?: SystemVolumeBackupPolicy) {
+ selectionMode = policy?.selectionMode ?? 'all';
+ volumeNames = policy ? [...policy.volumeNames] : [];
+ ignoreAnonymous = policy?.ignoreAnonymous ?? true;
+ }
+
+ async function updateSystemPolicies(policies: UpdateSystemBackupPolicy[]) {
+ return (await systemBackupService.updatePolicies(policies)).policies;
+ }
+
+ async function updateVolumePolicies(policies: UpdateSystemVolumeBackupPolicy[]) {
+ return (await systemBackupService.updateSystemVolumeConfig(policies)).policies;
+ }
+</script>
+
+{#snippet TypeField()}
+ <SelectWithLabel
+ id="system-backup-schedule-type"
+ value={backupType}
+ onValueChange={changeType}
+ label={m.backups_backup_type()}
+ description={m.backups_backup_type_description()}
+ options={typeOptions}
+ disabled={editing}
+ />
+{/snippet}
+
+{#snippet VolumeScope()}
+ <SystemVolumeScopeFields
+ idPrefix="system-volume-backup-schedule"
+ {selectionMode}
+ {volumeNames}
+ {ignoreAnonymous}
+ options={volumeOptions}
+ loading={volumeOptionsLoading}
+ onChange={(values) => {
+ selectionMode = values.selectionMode ?? selectionMode;
+ volumeNames = values.volumeNames ?? volumeNames;
+ ignoreAnonymous = values.ignoreAnonymous ?? ignoreAnonymous;
+ }}
+ />
+{/snippet}
+
+{#if backupType === 'system'}
+ <BackupPolicyDialog
+ bind:open
+ idPrefix="system-backup-policy"
+ policies={systemPolicies}
+ {policyId}
+ addTitle={m.system_backups_add_schedule()}
+ description={m.system_backups_schedule_type_description()}
+ enabledDescription={m.system_backups_enabled_description()}
+ enabledError={recoveryKeyStored ? null : m.system_backups_recovery_key_schedule_required()}
+ defaultSchedule="0 0 3 * * *"
+ defaultEnabled={recoveryKeyStored}
+ {destinations}
+ resetKey={backupType}
+ beforeFields={TypeField}
+ updatePolicies={updateSystemPolicies}
+ messages={{
+ saved: m.system_backups_policy_saved(),
+ saveFailed: m.system_backups_policy_failed(),
+ removed: m.system_backups_schedule_removed()
+ }}
+ onSaved={onSystemSaved}
+ contentClass="sm:max-w-[760px]"
+ />
+{:else}
+ <BackupPolicyDialog
+ bind:open
+ idPrefix="system-volume-backup-policy"
+ policies={volumePolicies}
+ {policyId}
+ addTitle={m.system_backups_add_schedule()}
+ description={m.system_backups_schedule_type_description()}
+ enabledDescription={m.system_volume_backups_enabled_description()}
+ defaultSchedule="0 0 2 * * *"
+ showStopContainers
+ {destinations}
+ resetKey={backupType}
+ beforeFields={TypeField}
+ afterFields={VolumeScope}
+ policyPayload={volumePayload}
+ extendUpdate={extendVolumeUpdate}
+ updatePolicies={updateVolumePolicies}
+ messages={{
+ saved: m.system_volume_backups_saved(),
+ saveFailed: m.system_volume_backups_save_failed(),
+ removed: m.system_volume_backups_schedule_removed()
+ }}
+ onSaved={onVolumeSaved}
+ onReset={resetVolumeScope}
+ contentClass="sm:max-w-[760px]"
+ />
+{/if}
diff --git a/frontend/src/routes/(app)/settings/backups/system-backup-table.svelte b/frontend/src/routes/(app)/settings/backups/system-backup-table.svelte
index fcbaa89f5..03ee12f0c 100644
--- a/frontend/src/routes/(app)/settings/backups/system-backup-table.svelte
+++ b/frontend/src/routes/(app)/settings/backups/system-backup-table.svelte
@@ -8,11 +8,18 @@
import BackupDestinationCell from '#lib/components/arcane-table/cells/backup-destination-cell.svelte';
import BackupSizeCell from '#lib/components/arcane-table/cells/backup-size-cell.svelte';
import CreatedAtCell from '#lib/components/arcane-table/cells/created-at-cell.svelte';
+ import BackupManagementCell from '#lib/components/arcane-table/cells/backup-management-cell.svelte';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared';
- import type { SystemBackupRun } from '#lib/types/system-backup';
- import { BackupIcon, RestartIcon, TrashIcon, UploadIcon, ClockIcon, FileTextIcon } from '#lib/icons';
+ import type { BackupHistoryEntry } from '#lib/types/system-backup';
+ import { BackupIcon, RestartIcon, TrashIcon, UploadIcon, ClockIcon, VolumesIcon, FileTextIcon } from '#lib/icons';
import { bytes, formatDateTimeShort } from '#lib/utils/formatting';
- import { backupDestinationDisplay, backupStatusLabel, backupStatusVariant, backupTriggerLabel } from '#lib/utils/backups';
+ import {
+ backupManagementFilterOptions,
+ backupManagementLabel,
+ backupStatusLabel,
+ backupStatusVariant,
+ backupTriggerLabel
+ } from '#lib/utils/backups';
import * as m from '#lib/paraglide/messages.js';
let {
@@ -22,28 +29,40 @@
onRestore,
onRestoreFiles,
onUpload,
- onDelete
+ onDelete,
+ onOpenVolume
}: {
- backups: Paginated<SystemBackupRun>;
+ backups: Paginated<BackupHistoryEntry>;
requestOptions: SearchPaginationSortRequest;
- onChanged: (options: SearchPaginationSortRequest) => Promise<Paginated<SystemBackupRun>>;
- onRestore: (backup: SystemBackupRun) => void;
- onRestoreFiles: (backup: SystemBackupRun) => void;
- onUpload: (backup: SystemBackupRun) => void;
- onDelete: (backup: SystemBackupRun) => void;
+ onChanged: (options: SearchPaginationSortRequest) => Promise<Paginated<BackupHistoryEntry>>;
+ onRestore: (backup: BackupHistoryEntry) => void;
+ onRestoreFiles: (backup: BackupHistoryEntry) => void;
+ onUpload: (backup: BackupHistoryEntry) => void;
+ onDelete: (backup: BackupHistoryEntry) => void;
+ onOpenVolume: (backup: BackupHistoryEntry) => void;
} = $props();
let mobileFieldVisibility = $state<Record<string, boolean>>({});
const columns = [
{ accessorKey: 'id', title: m.system_backups_id(), sortable: false, cell: IdCell },
+ { accessorKey: 'resourceName', title: m.backups_resource(), sortable: true, cell: ResourceCell },
+ {
+ accessorKey: 'type',
+ title: m.common_type(),
+ sortable: true,
+ cell: TypeCell,
+ filterOptions: backupManagementFilterOptions()
+ },
{ accessorKey: 'status', title: m.common_status(), sortable: true, cell: StatusCell },
{ accessorKey: 'trigger', title: m.volume_backup_trigger(), sortable: true, cell: TriggerCell },
{ accessorKey: 'destination', title: m.backups_destination_label(), sortable: true, cell: DestinationCell },
{ accessorKey: 'size', title: m.common_size(), sortable: true, cell: SizeCell },
{ accessorKey: 'createdAt', title: m.common_created(), sortable: true, cellComponent: CreatedAtCell },
{ accessorKey: 'error', title: m.common_error(), sortable: false, cell: ErrorCell }
- ] satisfies ColumnSpec<SystemBackupRun>[];
+ ] satisfies ColumnSpec<BackupHistoryEntry>[];
const mobileFields = [
+ { id: 'resourceName', label: m.backups_resource(), defaultVisible: true },
+ { id: 'type', label: m.common_type(), defaultVisible: true },
{ id: 'status', label: m.common_status(), defaultVisible: true },
{ id: 'trigger', label: m.volume_backup_trigger(), defaultVisible: true },
{ id: 'destination', label: m.backups_destination_label(), defaultVisible: true },
@@ -51,41 +70,55 @@
];
</script>
-{#snippet IdCell({ item }: { item: SystemBackupRun })}<code class="text-xs">{item.id.slice(0, 18)}…</code>{/snippet}
-{#snippet StatusCell({ item }: { item: SystemBackupRun })}<BackupStatusCell status={item.status} />{/snippet}
-{#snippet TriggerCell({ item }: { item: SystemBackupRun })}<BackupTriggerCell trigger={item.trigger} />{/snippet}
-{#snippet DestinationCell({ item }: { item: SystemBackupRun })}<BackupDestinationCell {item} />{/snippet}
-{#snippet SizeCell({ item }: { item: SystemBackupRun })}<BackupSizeCell size={item.size} />{/snippet}
-{#snippet ErrorCell({ item }: { item: SystemBackupRun })}<span class="max-w-72 truncate text-red-500">{item.error || '-'}</span
+{#snippet IdCell({ item }: { item: BackupHistoryEntry })}<code class="text-xs">{item.id.slice(0, 18)}…</code>{/snippet}
+{#snippet ResourceCell({ item }: { item: BackupHistoryEntry })}<span class="font-medium">{item.resourceName}</span>{/snippet}
+{#snippet TypeCell({ item }: { item: BackupHistoryEntry })}
+ <BackupManagementCell type={item.type} />
+{/snippet}
+{#snippet StatusCell({ item }: { item: BackupHistoryEntry })}<BackupStatusCell status={item.status} />{/snippet}
+{#snippet TriggerCell({ item }: { item: BackupHistoryEntry })}<BackupTriggerCell trigger={item.trigger} />{/snippet}
+{#snippet DestinationCell({ item }: { item: BackupHistoryEntry })}<BackupDestinationCell {item} />{/snippet}
+{#snippet SizeCell({ item }: { item: BackupHistoryEntry })}<BackupSizeCell size={item.size} />{/snippet}
+{#snippet ErrorCell({ item }: { item: BackupHistoryEntry })}<span class="max-w-72 truncate text-red-500">{item.error || '-'}</span
>{/snippet}
-{#snippet RowActions({ item }: { item: SystemBackupRun })}
+{#snippet RowActions({ item }: { item: BackupHistoryEntry })}
<RowActionsMenu>
- <DropdownMenu.Item onclick={() => onRestore(item)} disabled={item.status !== 'succeeded'}
- ><RestartIcon class="size-4" />{m.volumes_backups_restore()}</DropdownMenu.Item
- >
- <DropdownMenu.Item onclick={() => onRestoreFiles(item)} disabled={item.status !== 'succeeded'}
- ><FileTextIcon class="size-4" />{m.volume_restore_files()}</DropdownMenu.Item
- >
- {#if item.localSnapshotId && !item.remoteSnapshotId}
- <DropdownMenu.Item onclick={() => onUpload(item)}><UploadIcon class="size-4" />{m.backups_upload_s3()}</DropdownMenu.Item>
+ {#if item.resourceType === 'system'}
+ <DropdownMenu.Item onclick={() => onRestore(item)} disabled={item.status !== 'succeeded'}
+ ><RestartIcon class="size-4" />{m.volumes_backups_restore()}</DropdownMenu.Item
+ >
+ <DropdownMenu.Item onclick={() => onRestoreFiles(item)} disabled={item.status !== 'succeeded'}
+ ><FileTextIcon class="size-4" />{m.volume_restore_files()}</DropdownMenu.Item
+ >
+ {#if item.localSnapshotId && !item.remoteSnapshotId}
+ <DropdownMenu.Item onclick={() => onUpload(item)}><UploadIcon class="size-4" />{m.backups_upload_s3()}</DropdownMenu.Item>
+ {/if}
+ <DropdownMenu.Separator />
+ <DropdownMenu.Item variant="destructive" onclick={() => onDelete(item)}
+ ><TrashIcon class="size-4" />{m.common_delete()}</DropdownMenu.Item
+ >
+ {:else}
+ <DropdownMenu.Item onclick={() => onOpenVolume(item)}
+ ><VolumesIcon class="size-4" />{m.backups_open_volume()}</DropdownMenu.Item
+ >
{/if}
- <DropdownMenu.Separator />
- <DropdownMenu.Item variant="destructive" onclick={() => onDelete(item)}
- ><TrashIcon class="size-4" />{m.common_delete()}</DropdownMenu.Item
- >
</RowActionsMenu>
{/snippet}
-{#snippet MobileCard({ item, mobileFieldVisibility }: { item: SystemBackupRun; mobileFieldVisibility: MobileFieldVisibility })}
+{#snippet MobileCard({ item, mobileFieldVisibility }: { item: BackupHistoryEntry; mobileFieldVisibility: MobileFieldVisibility })}
<UniversalMobileCard
{item}
icon={{ component: BackupIcon, variant: 'blue' }}
- title={(item) => backupDestinationDisplay(item)}
+ title={(item) => item.resourceName}
badges={[
(item) => ({
variant: backupStatusVariant(item.status),
text: backupStatusLabel(item.status)
+ }),
+ (item) => ({
+ variant: 'purple',
+ text: backupManagementLabel(item.type)
})
]}
fields={[
diff --git a/frontend/src/routes/(app)/settings/backups/system-volume-scope-fields.svelte b/frontend/src/routes/(app)/settings/backups/system-volume-scope-fields.svelte
new file mode 100644
index 000000000..515c45f80
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/backups/system-volume-scope-fields.svelte
@@ -0,0 +1,124 @@
+<script lang="ts">
+ import LabeledSwitch from '#lib/components/form/labeled-switch.svelte';
+ import SelectWithLabel from '#lib/components/form/select-with-label.svelte';
+ import { Input } from '#lib/components/ui/input';
+ import { ScrollArea } from '#lib/components/ui/scroll-area';
+ import * as Checkbox from '#lib/components/ui/checkbox';
+ import { Label } from '#lib/components/ui/label';
+ import { Badge } from '#lib/components/ui/badge';
+ import { LoadingSpinnerIcon } from '#lib/icons';
+ import type { SystemVolumeBackupOption, SystemVolumeBackupSelectionMode } from '#lib/types/system-backup';
+ import * as m from '#lib/paraglide/messages.js';
+
+ let {
+ idPrefix,
+ selectionMode,
+ volumeNames,
+ ignoreAnonymous,
+ options,
+ loading = false,
+ onChange
+ }: {
+ idPrefix: string;
+ selectionMode: SystemVolumeBackupSelectionMode;
+ volumeNames: string[];
+ ignoreAnonymous: boolean;
+ options: SystemVolumeBackupOption[];
+ loading?: boolean;
+ onChange: (values: {
+ selectionMode?: SystemVolumeBackupSelectionMode;
+ volumeNames?: string[];
+ ignoreAnonymous?: boolean;
+ }) => void;
+ } = $props();
+
+ let search = $state('');
+ const selectionOptions = $derived([
+ {
+ label: m.system_volume_backups_selection_all(),
+ value: 'all',
+ description: m.system_volume_backups_selection_all_description()
+ },
+ {
+ label: m.system_volume_backups_selection_allowlist(),
+ value: 'allowlist',
+ description: m.system_volume_backups_selection_allowlist_description()
+ },
+ {
+ label: m.system_volume_backups_selection_blocklist(),
+ value: 'blocklist',
+ description: m.system_volume_backups_selection_blocklist_description()
+ }
+ ]);
+ const filteredOptions = $derived.by(() => {
+ const term = search.trim().toLowerCase();
+ return term ? options.filter((option) => option.name.toLowerCase().includes(term)) : options;
+ });
+
+ function toggleVolume(name: string, checked: boolean) {
+ onChange({
+ volumeNames: checked
+ ? Array.from(new Set([...volumeNames, name])).sort()
+ : volumeNames.filter((candidate) => candidate !== name)
+ });
+ }
+</script>
+
+<div class="space-y-5 border-t pt-5">
+ <SelectWithLabel
+ id={`${idPrefix}-selection-mode`}
+ value={selectionMode}
+ onValueChange={(value) => onChange({ selectionMode: value as SystemVolumeBackupSelectionMode })}
+ label={m.system_volume_backups_selection_mode()}
+ description={m.system_volume_backups_selection_description()}
+ options={selectionOptions}
+ />
+
+ {#if selectionMode !== 'all'}
+ <div class="space-y-2">
+ <div>
+ <Label>
+ {selectionMode === 'allowlist'
+ ? m.system_volume_backups_included_volumes()
+ : m.system_volume_backups_excluded_volumes()}
+ </Label>
+ <p class="mt-0.5 text-xs text-muted-foreground">
+ {selectionMode === 'allowlist' ? m.system_volume_backups_allowlist_help() : m.system_volume_backups_blocklist_help()}
+ </p>
+ </div>
+ <Input bind:value={search} placeholder={m.system_volume_backups_search_volumes()} />
+ <ScrollArea class="h-56 rounded-md border">
+ {#if loading}
+ <div class="flex h-24 items-center justify-center"><LoadingSpinnerIcon class="size-5 animate-spin" /></div>
+ {:else}
+ <div class="divide-y divide-border/50">
+ {#each filteredOptions as option (option.name)}
+ <label class="flex cursor-pointer items-center gap-3 px-3 py-2.5 hover:bg-muted/40">
+ <Checkbox.Root
+ checked={volumeNames.includes(option.name)}
+ onCheckedChange={(value) => toggleVolume(option.name, value === true)}
+ />
+ <span class="min-w-0 flex-1 truncate text-sm">{option.name}</span>
+ {#if option.anonymous}<Badge variant="amber" size="sm">{m.system_volume_backups_anonymous()}</Badge>{/if}
+ {#if !option.available}<Badge variant="gray" size="sm">{m.system_volume_backups_unavailable()}</Badge>{/if}
+ </label>
+ {/each}
+ {#if filteredOptions.length === 0}
+ <p class="px-3 py-8 text-center text-sm text-muted-foreground">
+ {m.system_volume_backups_no_matching_volumes()}
+ </p>
+ {/if}
+ </div>
+ {/if}
+ </ScrollArea>
+ </div>
+ {/if}
+
+ <LabeledSwitch
+ id={`${idPrefix}-ignore-anonymous`}
+ checked={ignoreAnonymous}
+ onCheckedChange={(value) => onChange({ ignoreAnonymous: value })}
+ label={m.system_volume_backups_ignore_anonymous()}
+ description={m.system_volume_backups_ignore_anonymous_description()}
+ />
+</div>
diff --git a/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte b/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
index 142af2d5a..b6e3421ed 100644
--- a/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
+++ b/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
@@ -48,11 +48,14 @@
import BackupDestinationCell from '#lib/components/arcane-table/cells/backup-destination-cell.svelte';
import BackupSizeCell from '#lib/components/arcane-table/cells/backup-size-cell.svelte';
import CreatedAtCell from '#lib/components/arcane-table/cells/created-at-cell.svelte';
+ import BackupManagementCell from '#lib/components/arcane-table/cells/backup-management-cell.svelte';
import { cn } from '#lib/utils';
import { bulkConfirmAndRun } from '#lib/utils/bulk-actions';
import { extractApiErrorMessage } from '#lib/utils/api';
import {
backupDestinationDisplay,
+ backupManagementFilterOptions,
+ backupManagementLabel,
backupTriggerLabel,
s3DestinationOptions as buildS3DestinationOptions
} from '#lib/utils/backups';
@@ -292,6 +295,13 @@
const columns = [
{ accessorKey: 'id', title: m.common_id(), sortable: true, cell: IdCell },
+ {
+ accessorKey: 'type',
+ title: m.common_type(),
+ sortable: false,
+ cell: TypeCell,
+ filterOptions: backupManagementFilterOptions()
+ },
{ accessorKey: 'status', title: m.common_status(), sortable: true, cell: StatusCell },
{ accessorKey: 'trigger', title: m.volume_backup_trigger(), sortable: true, cell: TriggerCell },
{ accessorKey: 'destination', title: m.backups_destination_label(), sortable: true, cell: DestinationCell },
@@ -308,6 +318,7 @@
] satisfies ColumnSpec<BackupEntry>[];
const mobileFields = [
+ { id: 'type', label: m.common_type(), defaultVisible: true },
{ id: 'status', label: m.common_status(), defaultVisible: true },
{ id: 'trigger', label: m.volume_backup_trigger(), defaultVisible: true },
{ id: 'destination', label: m.backups_destination_label(), defaultVisible: true },
@@ -338,6 +349,10 @@
<BackupStatusCell status={item.status} />
{/snippet}
+{#snippet TypeCell({ item }: { item: BackupEntry })}
+ <BackupManagementCell type={item.type} />
+{/snippet}
+
{#snippet TriggerCell({ item }: { item: BackupEntry })}
<BackupTriggerCell trigger={item.trigger} />
{/snippet}
@@ -461,6 +476,12 @@
{item}
icon={{ component: VolumesIcon, variant: 'blue' }}
title={(item) => item.id}
+ badges={[
+ (item) => ({
+ variant: 'purple',
+ text: backupManagementLabel(item.type)
+ })
+ ]}
fields={[
{
label: m.volume_backup_trigger(),
diff --git a/tests/spec/backup-file-picker.spec.ts b/tests/spec/backup-file-picker.spec.ts
index 6a16abb44..2830be5fc 100644
--- a/tests/spec/backup-file-picker.spec.ts
+++ b/tests/spec/backup-file-picker.spec.ts
@@ -389,7 +389,7 @@ async function mockSystemBackupPage(
openPage = true
) {
await mockAppShell(page);
- await page.route(/\/api\/backups(?:\?.*)?$/, async (route) => {
+ await page.route(/\/api\/backups\/history(?:\?.*)?$/, async (route) => {
await route.fulfill({
json: {
success: true,
@@ -401,7 +401,10 @@ async function mockSystemBackupPage(
status: 'succeeded',
trigger: 'manual',
destination: 'local',
- localSnapshotId: 'system-snapshot'
+ localSnapshotId: 'system-snapshot',
+ type: 'system',
+ resourceType: 'system',
+ resourceName: 'Arcane system'
}
],
pagination: { currentPage: 1, totalPages: 1, totalItems: 1, itemsPerPage: 20 }
diff --git a/tests/spec/cli.spec.ts b/tests/spec/cli.spec.ts
index 7f14512af..9c3503529 100644
--- a/tests/spec/cli.spec.ts
+++ b/tests/spec/cli.spec.ts
@@ -220,9 +220,7 @@ const readOnlyJsonSmokeCommands: JsonSmokeCommand[] = [
name: 'variables list',
args: ['variables', 'list', '--json'],
expectation: (value) => {
- const envelope = value as { success?: boolean; data?: unknown };
- expect(envelope.success).toBe(true);
- expect(envelope.data === null || Array.isArray(envelope.data)).toBe(true);
+ expect(value === null || Array.isArray(value)).toBe(true);
}
},
{
diff --git a/tests/spec/system-volume-backups.spec.ts b/tests/spec/system-volume-backups.spec.ts
new file mode 100644
index 000000000..611266847
--- /dev/null
+++ b/tests/spec/system-volume-backups.spec.ts
@@ -0,0 +1,266 @@
+import { expect, test, type Page } from '@playwright/test';
+
+type ManagementType = 'system' | 'volume';
+
+type SystemVolumeBackupPolicy = {
+ id: string;
+ enabled: boolean;
+ schedule: string;
+ retentionCount: number;
+ stopContainers: boolean;
+ localEnabled: boolean;
+ s3Enabled: boolean;
+ selectionMode: 'all' | 'allowlist' | 'blocklist';
+ volumeNames: string[];
+ ignoreAnonymous: boolean;
+};
+
+type SystemVolumeBackupPolicyCollection = { policies: SystemVolumeBackupPolicy[] };
+
+type HistoryEntry = {
+ id: string;
+ size: number;
+ createdAt: string;
+ status: string;
+ trigger: string;
+ destination: string;
+ format: string;
+ policyId?: string;
+ type: ManagementType;
+ resourceType: 'system' | 'volume';
+ resourceName: string;
+};
+
+const defaultPolicy: SystemVolumeBackupPolicy = {
+ id: 'volume-nightly',
+ enabled: false,
+ schedule: '0 0 2 * * *',
+ retentionCount: 7,
+ stopContainers: false,
+ localEnabled: true,
+ s3Enabled: false,
+ selectionMode: 'all',
+ volumeNames: [],
+ ignoreAnonymous: true
+};
+
+function paginated<T>(data: T[]) {
+ return {
+ data,
+ pagination: {
+ currentPage: 1,
+ totalPages: data.length > 0 ? 1 : 0,
+ totalItems: data.length,
+ itemsPerPage: 20
+ }
+ };
+}
+
+function historyEntry(resourceName: string, type: ManagementType): HistoryEntry {
+ return {
+ id: `${type}-${resourceName}`,
+ size: 1024,
+ createdAt: new Date().toISOString(),
+ status: 'succeeded',
+ trigger: type === 'system' ? 'scheduled' : 'manual',
+ destination: 'local',
+ format: 'rustic',
+ policyId: type === 'system' ? 'system-volume:test' : undefined,
+ type,
+ resourceType: 'volume',
+ resourceName
+ };
+}
+
+async function createVolumeViaApi(page: Page, volumeName: string) {
+ const response = await page.request.post('/api/environments/0/volumes', {
+ data: { name: volumeName, driver: 'local' }
+ });
+ expect(response.ok(), await response.text()).toBeTruthy();
+}
+
+async function removeVolumeViaApi(page: Page, volumeName: string) {
+ await page.request
+ .delete(`/api/environments/0/volumes/${encodeURIComponent(volumeName)}?force=true`)
+ .catch(() => undefined);
+}
+
+async function mockSystemBackupPage(
+ page: Page,
+ collection: SystemVolumeBackupPolicyCollection,
+ options: { name: string; anonymous: boolean; available: boolean }[],
+ history: HistoryEntry[] = []
+) {
+ let savedCollection = structuredClone(collection);
+ const runRequests: unknown[] = [];
+
+ await page.route('**/api/backups/volumes/config', async (route) => {
+ if (route.request().method() === 'PUT') {
+ const input = (await route.request().postDataJSON()) as {
+ policies: SystemVolumeBackupPolicy[];
+ };
+ savedCollection = {
+ policies: input.policies.map((policy, index) => ({
+ ...policy,
+ id: policy.id || `volume-created-${index}`
+ }))
+ };
+ }
+ await route.fulfill({ json: savedCollection });
+ });
+ await page.route('**/api/backups/policies', async (route) => {
+ await route.fulfill({
+ json: {
+ policies: [
+ {
+ id: 'system-nightly',
+ enabled: true,
+ schedule: '0 0 3 * * *',
+ retentionCount: 7,
+ localEnabled: true,
+ s3Enabled: false
+ }
+ ],
+ recoveryKeyStored: true
+ }
+ });
+ });
+ await page.route('**/api/backups/volumes/options', (route) => route.fulfill({ json: options }));
+ await page.route('**/api/backups/volumes/run', async (route) => {
+ runRequests.push(await route.request().postDataJSON());
+ return route.fulfill({
+ json: { matched: 2, succeeded: 1, failed: 0, skipped: 1, failures: [] }
+ });
+ });
+ await page.route('**/api/backups/history**', (route) => {
+ const type = new URL(route.request().url()).searchParams.get('type');
+ const rows =
+ type === 'system' || type === 'volume' ? history.filter((row) => row.type === type) : history;
+ return route.fulfill({ json: paginated(rows) });
+ });
+
+ return { savedCollection: () => savedCollection, runRequests: () => runRequests };
+}
+
+test.describe('System-managed volume backups', () => {
+ test('creates multiple volume schedules and runs a saved schedule', async ({ page }) => {
+ const liveName = `e2e-live-volume-${Date.now()}`;
+ const anonymousName = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
+ const unavailableName = 'deleted-volume';
+ const mock = await mockSystemBackupPage(
+ page,
+ {
+ policies: [
+ {
+ ...defaultPolicy,
+ enabled: false,
+ selectionMode: 'allowlist',
+ volumeNames: [unavailableName]
+ }
+ ]
+ },
+ [
+ { name: liveName, anonymous: false, available: true },
+ { name: anonymousName, anonymous: true, available: true },
+ { name: unavailableName, anonymous: false, available: false }
+ ]
+ );
+
+ await page.goto('/settings/backups');
+ const systemCard = page.getByTestId('backup-policy-system-system-nightly');
+ const volumeCard = page.getByTestId('backup-policy-volume-volume-nightly');
+ await expect(systemCard.getByText('System')).toHaveClass(/text-purple-/);
+ await expect(volumeCard.getByText('Volume')).toHaveClass(/text-purple-/);
+ await volumeCard.getByRole('button', { name: 'Edit Schedule' }).click();
+ const dialog = page.getByRole('dialog', { name: 'Edit Schedule' });
+
+ await expect(dialog.getByText(unavailableName)).toBeVisible();
+ await expect(dialog.getByText('Unavailable', { exact: true })).toBeVisible();
+ await expect(dialog.getByText('Anonymous', { exact: true })).toBeVisible();
+ await dialog.getByLabel('Volume selection').click();
+ await page.getByRole('option', { name: 'Blocklist' }).click();
+ await expect(dialog.getByLabel('Volume selection')).toContainText('Blocklist');
+ await expect(dialog.getByText('Excluded volumes')).toBeVisible();
+ await dialog.locator('label').filter({ hasText: liveName }).getByRole('checkbox').click();
+ await dialog.getByRole('button', { name: 'Save' }).click();
+ await expect(dialog).toBeHidden();
+ expect(mock.savedCollection().policies[0]?.volumeNames).toEqual([unavailableName, liveName]);
+
+ await page.getByRole('button', { name: 'Create', exact: true }).click();
+ await page.getByRole('menuitem', { name: 'Schedule' }).click();
+ const createSchedule = page.getByRole('dialog', { name: 'Create schedule' });
+ await createSchedule.getByLabel('Backup type').click();
+ await page.getByRole('option', { name: 'Volume' }).click();
+ await createSchedule.getByLabel('Schedule', { exact: true }).fill('0 30 4 * * *');
+ await createSchedule.getByRole('button', { name: 'Save' }).click();
+ await expect(createSchedule).toBeHidden();
+ expect(mock.savedCollection().policies).toHaveLength(2);
+ await expect(page.getByText('Volume', { exact: true })).toHaveCount(2);
+
+ await page.getByRole('button', { name: 'Create', exact: true }).click();
+ await page.getByRole('menuitem', { name: 'Backup' }).click();
+ const createBackup = page.getByRole('dialog', { name: 'Create Backup' });
+ await createBackup.getByLabel('Backup type').click();
+ await page.getByRole('option', { name: 'Volume' }).click();
+ await createBackup.getByLabel('Backup configuration').click();
+ await page.getByRole('option', { name: '0 0 2 * * *' }).click();
+ await createBackup.getByRole('button', { name: 'Create Backup' }).click();
+ await expect(page.getByText('Matched 2; 1 succeeded, 0 failed, and 1 skipped.')).toBeVisible();
+ expect(mock.runRequests()).toContainEqual({ policyId: 'volume-nightly' });
+
+ await page.getByRole('button', { name: 'Create', exact: true }).click();
+ await page.getByRole('menuitem', { name: 'Backup' }).click();
+ const customBackup = page.getByRole('dialog', { name: 'Create Backup' });
+ await customBackup.getByLabel('Backup type').click();
+ await page.getByRole('option', { name: 'Volume' }).click();
+ await customBackup.getByLabel('Volume selection').click();
+ await page.getByRole('option', { name: 'Allowlist' }).click();
+ await customBackup.locator('label').filter({ hasText: liveName }).getByRole('checkbox').click();
+ await customBackup.getByRole('button', { name: 'Create Backup' }).click();
+ expect(mock.runRequests()).toContainEqual({
+ custom: {
+ destination: 'local',
+ s3DestinationId: '',
+ stopContainers: false,
+ selectionMode: 'allowlist',
+ volumeNames: [liveName],
+ ignoreAnonymous: true
+ }
+ });
+ });
+
+ test('filters unified history and opens the owning volume backup tab', async ({ page }) => {
+ const volumeName = `e2e-system-history-${Date.now()}`;
+ await createVolumeViaApi(page, volumeName);
+ try {
+ await mockSystemBackupPage(
+ page,
+ { policies: [] },
+ [],
+ [historyEntry('central-volume', 'system'), historyEntry(volumeName, 'volume')]
+ );
+ await page.goto('/settings/backups');
+
+ await page.getByTestId('facet-type-trigger').click();
+ await page.getByTestId('facet-type-option-system').click();
+ const historyTable = page.getByRole('table');
+ await expect(historyTable.getByText('central-volume')).toBeVisible();
+ await expect(historyTable.getByText(volumeName)).toHaveCount(0);
+
+ await page.getByTestId('facet-type-option-system').click();
+ await page.getByTestId('facet-type-option-volume').click();
+ await expect(historyTable.getByText(volumeName)).toBeVisible();
+ await expect(historyTable.getByText('central-volume')).toHaveCount(0);
+
+ await page.keyboard.press('Escape');
+ const row = page.getByRole('row').filter({ hasText: volumeName });
+ await row.getByRole('button', { name: 'Open menu' }).click();
+ await page.getByRole('menuitem', { name: 'Open volume backups' }).click();
+ await expect(page).toHaveURL(
+ new RegExp(`/volumes/${encodeURIComponent(volumeName)}\\?tab=backups`)
+ );
+ } finally {
+ await removeVolumeViaApi(page, volumeName);
+ }
+ });
+});
diff --git a/types/backup/system_volume_backup.go b/types/backup/system_volume_backup.go
new file mode 100644
index 000000000..acac23276
--- /dev/null
+++ b/types/backup/system_volume_backup.go
@@ -0,0 +1,115 @@
+package backup
+
+import "time"
+
+// ManagementType identifies which Arcane configuration orchestrated a backup.
+type ManagementType string
+
+const (
+ ManagementTypeSystem ManagementType = "system"
+ ManagementTypeVolume ManagementType = "volume"
+)
+
+// SystemVolumePolicyPrefix marks volume-backup records created by the centralized system policy.
+const SystemVolumePolicyPrefix = "system-volume:"
+
+// SystemVolumeSelectionMode controls how configured volume names affect live Docker volumes.
+type SystemVolumeSelectionMode string
+
+const (
+ SystemVolumeSelectionAll SystemVolumeSelectionMode = "all"
+ SystemVolumeSelectionAllowlist SystemVolumeSelectionMode = "allowlist"
+ SystemVolumeSelectionBlocklist SystemVolumeSelectionMode = "blocklist"
+)
+
+// SystemVolumeBackupPolicy is one manager-owned policy for local Docker volumes.
+type SystemVolumeBackupPolicy struct {
+ ID string `json:"id"`
+ Enabled bool `json:"enabled"`
+ Schedule string `json:"schedule"`
+ RetentionCount int `json:"retentionCount"`
+ StopContainers bool `json:"stopContainers"`
+ LocalEnabled bool `json:"localEnabled"`
+ S3Enabled bool `json:"s3Enabled"`
+ S3DestinationID string `json:"s3DestinationId,omitempty"`
+ S3DestinationName string `json:"s3DestinationName,omitempty"`
+ SelectionMode SystemVolumeSelectionMode `json:"selectionMode"`
+ VolumeNames []string `json:"volumeNames"`
+ IgnoreAnonymous bool `json:"ignoreAnonymous"`
+ LastRun *SystemBackupRun `json:"lastRun,omitempty"`
+}
+
+// UpdateSystemVolumeBackupPolicy is the writable centralized policy shape.
+type UpdateSystemVolumeBackupPolicy struct {
+ UpdateBackupPolicy
+
+ SelectionMode SystemVolumeSelectionMode `json:"selectionMode"`
+ VolumeNames []string `json:"volumeNames"`
+ IgnoreAnonymous bool `json:"ignoreAnonymous"`
+}
+
+type SystemVolumeBackupPolicyCollection struct {
+ Policies []SystemVolumeBackupPolicy `json:"policies"`
+}
+
+type UpdateSystemVolumeBackupPolicies struct {
+ Policies []UpdateSystemVolumeBackupPolicy `json:"policies"`
+}
+
+// SystemVolumeBackupCustomRun is a transient policy used by Create -> Backup.
+type SystemVolumeBackupCustomRun struct {
+ Destination SystemBackupDestination `json:"destination"`
+ S3DestinationID string `json:"s3DestinationId,omitempty"`
+ StopContainers bool `json:"stopContainers"`
+ SelectionMode SystemVolumeSelectionMode `json:"selectionMode"`
+ VolumeNames []string `json:"volumeNames"`
+ IgnoreAnonymous bool `json:"ignoreAnonymous"`
+}
+
+// RunSystemVolumeBackupsRequest selects a saved policy or supplies a transient custom policy.
+type RunSystemVolumeBackupsRequest struct {
+ PolicyID string `json:"policyId,omitempty"`
+ Custom *SystemVolumeBackupCustomRun `json:"custom,omitempty"`
+}
+
+// SystemVolumeBackupOption describes a selectable live or unavailable configured volume.
+type SystemVolumeBackupOption struct {
+ Name string `json:"name"`
+ Anonymous bool `json:"anonymous"`
+ Available bool `json:"available"`
+}
+
+// SystemVolumeBackupFailure records one candidate that could not be backed up.
+type SystemVolumeBackupFailure struct {
+ VolumeName string `json:"volumeName"`
+ Error string `json:"error"`
+}
+
+// SystemVolumeBackupRunResult summarizes a centralized multi-volume execution.
+type SystemVolumeBackupRunResult struct {
+ Matched int `json:"matched"`
+ Succeeded int `json:"succeeded"`
+ Failed int `json:"failed"`
+ Skipped int `json:"skipped"`
+ Failures []SystemVolumeBackupFailure `json:"failures"`
+}
+
+// HistoryEntry is a common view over Arcane recovery and volume backup records.
+type HistoryEntry struct {
+ ID string `json:"id" sortable:"true"`
+ Size int64 `json:"size" sortable:"true"`
+ CreatedAt time.Time `json:"createdAt" sortable:"true"`
+ Status string `json:"status" sortable:"true"`
+ Trigger string `json:"trigger" sortable:"true"`
+ Destination SystemBackupDestination `json:"destination" sortable:"true"`
+ Format string `json:"format,omitempty"`
+ LocalSnapshotID string `json:"localSnapshotId,omitempty"`
+ RemoteSnapshotID string `json:"remoteSnapshotId,omitempty"`
+ S3DestinationID string `json:"s3DestinationId,omitempty"`
+ S3DestinationName string `json:"s3DestinationName,omitempty"`
+ PolicyID string `json:"policyId,omitempty"`
+ Error string `json:"error,omitempty"`
+ Type ManagementType `json:"type" sortable:"true"`
+ ResourceType string `json:"resourceType"`
+ ResourceName string `json:"resourceName" sortable:"true"`
+}
diff --git a/types/volume/backup.go b/types/volume/backup.go
index 90ec5688e..c923d6f7e 100644
--- a/types/volume/backup.go
+++ b/types/volume/backup.go
@@ -28,20 +28,21 @@ const (
)
type BackupEntry struct {
- ID string `json:"id" doc:"Unique identifier of the backup"`
- VolumeName string `json:"volumeName" doc:"Name of the volume"`
- Size int64 `json:"size" doc:"Total size of the backup contents"`
- CreatedAt string `json:"createdAt" doc:"When the backup was created"`
- Status string `json:"status" doc:"Backup result status"`
- Trigger string `json:"trigger" doc:"How the backup was started"`
- Destination BackupDestination `json:"destination" doc:"Requested backup storage target"`
- Format BackupFormat `json:"format" doc:"Storage format of the backup: legacy tar.gz archive or Rustic snapshot"`
- LocalSnapshotID string `json:"localSnapshotId,omitempty" doc:"Snapshot ID in the local Rustic repository"`
- RemoteSnapshotID string `json:"remoteSnapshotId,omitempty" doc:"Snapshot ID in the S3 Rustic repository"`
- S3DestinationID string `json:"s3DestinationId,omitempty" doc:"S3 destination used by the backup"`
- S3DestinationName string `json:"s3DestinationName,omitempty" doc:"Name of the S3 destination used by the backup"`
- PolicyID string `json:"policyId,omitempty" doc:"Backup policy that created the backup"`
- Error string `json:"error,omitempty" doc:"Backup error when the run failed"`
+ ID string `json:"id" doc:"Unique identifier of the backup"`
+ VolumeName string `json:"volumeName" doc:"Name of the volume"`
+ Size int64 `json:"size" doc:"Total size of the backup contents"`
+ CreatedAt string `json:"createdAt" doc:"When the backup was created"`
+ Status string `json:"status" doc:"Backup result status"`
+ Trigger string `json:"trigger" doc:"How the backup was started"`
+ Destination BackupDestination `json:"destination" doc:"Requested backup storage target"`
+ Format BackupFormat `json:"format" doc:"Storage format of the backup: legacy tar.gz archive or Rustic snapshot"`
+ LocalSnapshotID string `json:"localSnapshotId,omitempty" doc:"Snapshot ID in the local Rustic repository"`
+ RemoteSnapshotID string `json:"remoteSnapshotId,omitempty" doc:"Snapshot ID in the S3 Rustic repository"`
+ S3DestinationID string `json:"s3DestinationId,omitempty" doc:"S3 destination used by the backup"`
+ S3DestinationName string `json:"s3DestinationName,omitempty" doc:"Name of the S3 destination used by the backup"`
+ PolicyID string `json:"policyId,omitempty" doc:"Backup policy that created the backup"`
+ Error string `json:"error,omitempty" doc:"Backup error when the run failed"`
+ Type backup.ManagementType `json:"type" doc:"Whether the backup was system-managed or volume-managed"`
}
type BackupPolicy struct {