Documentation
¶
Overview ¶
Package backup provides cloud restore functionality for uploading restored files to cloud storage.
Package backup provides Restic backup functionality and scheduling.
Package backup provides cross-agent restore functionality.
Package backup provides Restic backup functionality and scheduling.
Package backup provides Restic backup functionality and scheduling.
Package backup provides Restic backup functionality and scheduling.
Package backup provides geo-replication functionality for backup repositories.
Package backup provides immutability management for backup snapshots.
Package backup provides Restic backup functionality and scheduling.
Package backup provides Restic backup functionality and scheduling.
Package backup provides backup functionality including FUSE mount support.
Package backup provides partial restore functionality for Restic backups.
Package backup provides Restic backup functionality and scheduling.
Package backup provides retention policy enforcement for Restic backups.
Package backup provides Restic backup functionality and scheduling.
Package backup provides Restic backup functionality and scheduling. Storage backends are in the backends subpackage.
Package backup provides Restic backup functionality and scheduling.
Package backup provides automated test restore functionality for verifying backup integrity.
Package backup provides automated test restore notification functionality.
Index ¶
- Constants
- Variables
- func BackendConfig(backend Backend) ([]byte, error)
- func CalculateDedupRatio(rawDataSize, restoreSize int64) float64
- func CalculateSpaceSaved(rawDataSize, restoreSize int64) int64
- func CalculateSpaceSavedPercent(rawDataSize, restoreSize int64) float64
- func ConvertPathsToIncludePatterns(paths []string) []string
- func GetRestoreAgentIDs(restore *models.Restore) (sourceAgentID, targetAgentID uuid.UUID)
- func IsCrossAgentRestore(restore *models.Restore) bool
- func MergeRetentionPolicy(base, override *models.RetentionPolicy) *models.RetentionPolicy
- func ParseRetentionConfig(cfg map[string]int) (*models.RetentionPolicy, error)
- func ParseSizeFromDiffLine(line string) int64
- func PrepareTargetDirectory(targetPath string, createIfNotExists bool) error
- func RetentionPolicyDescription(policy *models.RetentionPolicy) string
- func ValidateRetentionPolicy(policy *models.RetentionPolicy) error
- type B2Backend
- type Backend
- type BackupOptions
- type BackupStats
- type BackupValidator
- func (bv *BackupValidator) SetNotifier(notifier ValidationNotifier)
- func (bv *BackupValidator) ValidateAndNotify(ctx context.Context, backup *models.Backup, cfg ResticConfig, ...) (*ValidateBackupResult, error)
- func (bv *BackupValidator) ValidateBackup(ctx context.Context, backup *models.Backup, cfg ResticConfig, ...) (*models.BackupValidation, error)
- type CheckOptions
- type CheckResult
- type CheckpointConfig
- type CheckpointManager
- func (m *CheckpointManager) AssociateBackup(ctx context.Context, checkpointID, backupID uuid.UUID) error
- func (m *CheckpointManager) CancelCheckpoint(ctx context.Context, checkpointID uuid.UUID) error
- func (m *CheckpointManager) CompleteBackup(ctx context.Context, backupID uuid.UUID) error
- func (m *CheckpointManager) GetIncompleteBackups(ctx context.Context, agentID uuid.UUID) ([]*models.BackupCheckpoint, error)
- func (m *CheckpointManager) GetResumableCheckpoint(ctx context.Context, scheduleID uuid.UUID) (*models.BackupCheckpoint, error)
- func (m *CheckpointManager) GetResumeInfo(ctx context.Context, checkpointID uuid.UUID) (*ResumeInfo, error)
- func (m *CheckpointManager) InterruptBackup(ctx context.Context, backupID uuid.UUID, errMsg string) error
- func (m *CheckpointManager) PrepareResume(ctx context.Context, checkpoint *models.BackupCheckpoint) error
- func (m *CheckpointManager) SetTotals(ctx context.Context, backupID uuid.UUID, totalFiles, totalBytes int64) error
- func (m *CheckpointManager) Start(ctx context.Context) error
- func (m *CheckpointManager) StartCheckpoint(ctx context.Context, scheduleID, agentID, repositoryID uuid.UUID) (*models.BackupCheckpoint, error)
- func (m *CheckpointManager) Stop()
- func (m *CheckpointManager) TrackBackup(backupID uuid.UUID, checkpoint *models.BackupCheckpoint)
- func (m *CheckpointManager) UpdateProgress(ctx context.Context, backupID uuid.UUID, filesProcessed, bytesProcessed int64, ...) (bool, error)
- type CheckpointStore
- type CloudRestore
- type CloudRestoreOptions
- type CloudRestoreProgress
- type CloudRestoreResult
- type CloudRestoreTarget
- type CloudRestoreTargetType
- type ConcurrencyManager
- func (m *ConcurrencyManager) AcquireSlot(ctx context.Context, orgID, agentID, scheduleID uuid.UUID) (bool, *models.BackupQueueEntry, error)
- func (m *ConcurrencyManager) CanStartBackup(ctx context.Context, orgID, agentID uuid.UUID) (bool, bool, error)
- func (m *ConcurrencyManager) CancelQueuedBackup(ctx context.Context, entryID uuid.UUID) error
- func (m *ConcurrencyManager) GetConcurrencyStatus(ctx context.Context, orgID, agentID uuid.UUID) (*models.ConcurrencyStatus, error)
- func (m *ConcurrencyManager) GetQueuedBackups(ctx context.Context, orgID uuid.UUID) ([]*models.BackupQueueEntry, error)
- func (m *ConcurrencyManager) ProcessQueuedBackups(ctx context.Context) ([]*models.BackupQueueEntry, error)
- func (m *ConcurrencyManager) ReleaseSlot(ctx context.Context, orgID, agentID uuid.UUID) error
- func (m *ConcurrencyManager) SyncRunningCounts(ctx context.Context) error
- type ConcurrencyStore
- type CrossRestoreJob
- type CrossRestoreProgress
- type CrossRestoreRequest
- type CrossRestoreService
- func (s *CrossRestoreService) ApplyPathMappings(originalPath string, mappings []models.PathMapping) string
- func (s *CrossRestoreService) CreateCrossRestoreJob(ctx context.Context, req CrossRestoreRequest) (*models.Restore, error)
- func (s *CrossRestoreService) ValidatePathMappings(mappings []models.PathMapping) error
- func (s *CrossRestoreService) ValidateTargetAgentAccess(ctx context.Context, targetAgentID, repositoryID uuid.UUID) error
- func (s *CrossRestoreService) ValidateUserAccess(ctx context.Context, userID, sourceAgentID, targetAgentID uuid.UUID) error
- type CrossRestoreStore
- type DRTestScheduler
- func (s *DRTestScheduler) GetActiveDRSchedules() int
- func (s *DRTestScheduler) ReloadDRSchedules(ctx context.Context) error
- func (s *DRTestScheduler) Start(ctx context.Context) error
- func (s *DRTestScheduler) Stop() context.Context
- func (s *DRTestScheduler) TriggerDRTest(ctx context.Context, runbookID uuid.UUID) error
- type DRTestStore
- type DecryptFunc
- type DiffChangeType
- type DiffEntry
- type DiffResult
- type DiffStats
- type DropboxBackend
- type DryRunExcluded
- type DryRunFile
- type DryRunResult
- type ExtendedRepoStats
- type FileDiffResult
- type FileHistory
- type FileSearchFilter
- type FileSearchResponse
- type FileSearchResult
- type FileVersion
- type ForgetResult
- type GeoReplicationStore
- type GeoReplicator
- func (g *GeoReplicator) CheckReplicationHealth(ctx context.Context, config *models.GeoReplicationConfig, maxSnapshots int, ...) (bool, *ReplicationLag, error)
- func (g *GeoReplicator) GetReplicationStatus(ctx context.Context, repositoryID uuid.UUID) (*models.GeoReplicationConfig, *ReplicationLag, error)
- func (g *GeoReplicator) GetReplicationSummary(ctx context.Context, orgID uuid.UUID) (*ReplicationSummary, error)
- func (g *GeoReplicator) ReplicateSnapshot(ctx context.Context, config *models.GeoReplicationConfig, snapshotID string) error
- func (g *GeoReplicator) Start(ctx context.Context, checkInterval time.Duration)
- func (g *GeoReplicator) Stop()
- func (g *GeoReplicator) TriggerReplication(ctx context.Context, repositoryID uuid.UUID) error
- type ImmutabilityManager
- func (m *ImmutabilityManager) CheckDeleteAllowed(ctx context.Context, repositoryID uuid.UUID, snapshotID string) error
- func (m *ImmutabilityManager) CleanupExpiredLocks(ctx context.Context) (int, error)
- func (m *ImmutabilityManager) ExtendLock(ctx context.Context, repositoryID uuid.UUID, snapshotID string, ...) (*models.SnapshotImmutability, error)
- func (m *ImmutabilityManager) GetActiveLocksForOrg(ctx context.Context, orgID uuid.UUID) ([]*models.SnapshotImmutability, error)
- func (m *ImmutabilityManager) GetActiveLocksForRepository(ctx context.Context, repositoryID uuid.UUID) ([]*models.SnapshotImmutability, error)
- func (m *ImmutabilityManager) GetLockStatus(ctx context.Context, repositoryID uuid.UUID, snapshotID string) (*models.SnapshotImmutability, error)
- func (m *ImmutabilityManager) GetStatus(ctx context.Context, repositoryID uuid.UUID, snapshotID string) (*ImmutabilityStatus, error)
- func (m *ImmutabilityManager) LockSnapshot(ctx context.Context, orgID uuid.UUID, repositoryID uuid.UUID, ...) (*models.SnapshotImmutability, error)
- type ImmutabilityStatus
- type ImmutabilityStore
- type ImportOptions
- type ImportPreview
- type ImportResult
- type Importer
- func (i *Importer) CheckRepository(ctx context.Context, backend backends.Backend, password string) error
- func (i *Importer) FilterSnapshots(snapshots []Snapshot, opts ImportOptions) []Snapshot
- func (i *Importer) GetSnapshots(ctx context.Context, backend backends.Backend, password string, ...) ([]Snapshot, error)
- func (i *Importer) Preview(ctx context.Context, backend backends.Backend, password string) (*ImportPreview, error)
- func (i *Importer) VerifyAccess(ctx context.Context, backend backends.Backend, password string) error
- type LargeFile
- type LargeFileScanner
- type LicenseChecker
- type LocalBackend
- type MountInfo
- type MountManager
- func (m *MountManager) Cleanup() error
- func (m *MountManager) ExtendMount(id uuid.UUID, extension time.Duration) error
- func (m *MountManager) GetMount(id uuid.UUID) (*MountInfo, bool)
- func (m *MountManager) IsSnapshotMounted(snapshotID string) bool
- func (m *MountManager) ListMounts() []*MountInfo
- func (m *MountManager) Mount(ctx context.Context, id uuid.UUID, cfg backends.ResticConfig, ...) (*MountInfo, error)
- func (m *MountManager) Unmount(ctx context.Context, id uuid.UUID) error
- func (m *MountManager) UnmountAll(ctx context.Context) error
- type NetworkDrives
- func (nd *NetworkDrives) DetectMounts(ctx context.Context) ([]models.NetworkMount, error)
- func (nd *NetworkDrives) GetNetworkPathsFromSchedule(paths []string, mounts []models.NetworkMount) []NetworkPathInfo
- func (nd *NetworkDrives) RefreshMountStatuses(ctx context.Context, mounts []models.NetworkMount) []models.NetworkMount
- func (nd *NetworkDrives) ValidateMountForBackup(ctx context.Context, path string, mounts []models.NetworkMount) (bool, *models.NetworkMount, error)
- type NetworkPathInfo
- type PartialRestoreOptions
- type PartialRestoreResult
- type PartialRestoreValidator
- func (v *PartialRestoreValidator) CalculateRestoreSize(ctx context.Context, cfg ResticConfig, snapshotID string, paths []string) (totalFiles int, totalDirs int, totalSize int64, err error)
- func (v *PartialRestoreValidator) GetPathsInfo(ctx context.Context, cfg ResticConfig, snapshotID string, paths []string) ([]SnapshotFile, error)
- func (v *PartialRestoreValidator) ValidatePaths(ctx context.Context, cfg ResticConfig, snapshotID string, paths []string) (found []string, notFound []string, err error)
- type ProgressReader
- type RawStats
- type RawStatsMode
- type Region
- type RegionPair
- type ReplicationLag
- type ReplicationStatus
- type ReplicationSummary
- type RepoStats
- type RestBackend
- type Restic
- func (r *Restic) Backup(ctx context.Context, cfg ResticConfig, paths, excludes []string, tags []string) (*BackupStats, error)
- func (r *Restic) BackupWithOptions(ctx context.Context, cfg ResticConfig, paths, excludes []string, tags []string, ...) (*BackupStats, error)
- func (r *Restic) Check(ctx context.Context, cfg ResticConfig) error
- func (r *Restic) CheckWithOptions(ctx context.Context, cfg ResticConfig, opts CheckOptions) (*CheckResult, error)
- func (r *Restic) Copy(ctx context.Context, sourceCfg, targetCfg ResticConfig, snapshotID string) error
- func (r *Restic) Diff(ctx context.Context, cfg ResticConfig, snapshotID1, snapshotID2 string) (*DiffResult, error)
- func (r *Restic) DiffFile(ctx context.Context, cfg ResticConfig, ...) (*FileDiffResult, error)
- func (r *Restic) DryRun(ctx context.Context, cfg ResticConfig, paths, excludes []string) (*DryRunResult, error)
- func (r *Restic) FindFileInSnapshots(ctx context.Context, cfg ResticConfig, pathPrefix string) ([]FileVersion, error)
- func (r *Restic) Forget(ctx context.Context, cfg ResticConfig, retention *models.RetentionPolicy) (*ForgetResult, error)
- func (r *Restic) GetExtendedStats(ctx context.Context, cfg ResticConfig) (*ExtendedRepoStats, error)
- func (r *Restic) GetFileFromSnapshot(ctx context.Context, cfg ResticConfig, snapshotID, filePath string) ([]byte, error)
- func (r *Restic) GetFileHistory(ctx context.Context, cfg ResticConfig, filePath string) (*FileHistory, error)
- func (r *Restic) Init(ctx context.Context, cfg ResticConfig) error
- func (r *Restic) ListFiles(ctx context.Context, cfg ResticConfig, snapshotID, pathPrefix string) ([]SnapshotFile, error)
- func (r *Restic) PartialRestore(ctx context.Context, cfg ResticConfig, opts PartialRestoreOptions) (*PartialRestoreResult, error)
- func (r *Restic) PreviewPartialRestore(ctx context.Context, cfg ResticConfig, snapshotID string, paths []string, ...) (*RestorePreview, error)
- func (r *Restic) Prune(ctx context.Context, cfg ResticConfig, retention *models.RetentionPolicy) (*ForgetResult, error)
- func (r *Restic) Restore(ctx context.Context, cfg ResticConfig, snapshotID string, opts RestoreOptions) error
- func (r *Restic) RestoreFileVersion(ctx context.Context, cfg ResticConfig, snapshotID, filePath, targetPath string) error
- func (r *Restic) RestorePreviewResult(ctx context.Context, cfg ResticConfig, snapshotID string, opts RestoreOptions) (*RestorePreview, error)
- func (r *Restic) SearchFiles(ctx context.Context, cfg ResticConfig, filter FileSearchFilter) (*FileSearchResponse, error)
- func (r *Restic) Snapshots(ctx context.Context, cfg ResticConfig) ([]Snapshot, error)
- func (r *Restic) Stats(ctx context.Context, cfg ResticConfig) (*RepoStats, error)
- func (r *Restic) StatsWithRawData(ctx context.Context, cfg ResticConfig) (*RawStatsMode, error)
- func (r *Restic) StatsWithRestoreSize(ctx context.Context, cfg ResticConfig) (*RawStatsMode, error)
- type ResticConfig
- type RestoreOptions
- type RestorePreview
- type RestorePreviewFile
- type ResumeDecision
- type ResumeInfo
- type RetentionEnforcer
- type RetentionResult
- type S3Backend
- type SFTPBackend
- type ScanResult
- type ScheduleStore
- type Scheduler
- func (s *Scheduler) EnableValidation(config ValidationConfig)
- func (s *Scheduler) GetActiveSchedules() int
- func (s *Scheduler) GetNextRun(scheduleID uuid.UUID) (time.Time, bool)
- func (s *Scheduler) Reload(ctx context.Context) error
- func (s *Scheduler) SetBackupValidator(validator *BackupValidator)
- func (s *Scheduler) SetConcurrencyManager(cm *ConcurrencyManager)
- func (s *Scheduler) SetLicenseChecker(checker LicenseChecker)
- func (s *Scheduler) SetMaintenanceService(maint *maintenance.Service)
- func (s *Scheduler) SetValidationConfig(config ValidationConfig)
- func (s *Scheduler) Start(ctx context.Context) error
- func (s *Scheduler) Stop() context.Context
- func (s *Scheduler) TriggerBackup(ctx context.Context, scheduleID uuid.UUID) error
- type SchedulerConfig
- type Snapshot
- type SnapshotFile
- type SnapshotFileGroup
- type StatsCollector
- func (c *StatsCollector) CollectForRepository(ctx context.Context, repositoryID uuid.UUID) error
- func (c *StatsCollector) CollectNow(ctx context.Context) error
- func (c *StatsCollector) GetNextRun() (time.Time, bool)
- func (c *StatsCollector) IsRunning() bool
- func (c *StatsCollector) Start(ctx context.Context) error
- func (c *StatsCollector) Stop() context.Context
- type StatsCollectorConfig
- type StatsStore
- type TestRestoreConfig
- type TestRestoreNotificationService
- type TestRestoreNotifier
- type TestRestoreNotifierAdapter
- type TestRestoreScheduler
- func (trs *TestRestoreScheduler) GetNextRun(settingID uuid.UUID) (time.Time, bool)
- func (trs *TestRestoreScheduler) GetRepositoryTestRestoreStatus(ctx context.Context, repoID uuid.UUID) (*models.TestRestoreStatus, error)
- func (trs *TestRestoreScheduler) Reload(ctx context.Context) error
- func (trs *TestRestoreScheduler) Start(ctx context.Context) error
- func (trs *TestRestoreScheduler) Stop() context.Context
- func (trs *TestRestoreScheduler) TriggerTestRestore(ctx context.Context, repoID uuid.UUID, samplePercentage int) (*models.TestRestoreResult, error)
- type TestRestoreStore
- type TieringConfig
- type TieringScheduler
- func (s *TieringScheduler) ExpireColdRestoreRequests(ctx context.Context)
- func (s *TieringScheduler) GenerateCostReports(ctx context.Context)
- func (s *TieringScheduler) GetRestoreStatus(ctx context.Context, snapshotID string, repositoryID uuid.UUID) (*models.ColdRestoreRequest, error)
- func (s *TieringScheduler) InitializeSnapshotTier(ctx context.Context, snapshotID string, repositoryID, orgID uuid.UUID, ...) error
- func (s *TieringScheduler) ManualTierChange(ctx context.Context, snapshotID string, repositoryID uuid.UUID, ...) error
- func (s *TieringScheduler) ProcessColdRestoreRequests(ctx context.Context)
- func (s *TieringScheduler) ProcessTieringRules(ctx context.Context)
- func (s *TieringScheduler) RequestColdRestore(ctx context.Context, orgID uuid.UUID, snapshotID string, ...) (*models.ColdRestoreRequest, error)
- func (s *TieringScheduler) Start(ctx context.Context) error
- func (s *TieringScheduler) Stop() context.Context
- func (s *TieringScheduler) TriggerCostReport(ctx context.Context)
- func (s *TieringScheduler) TriggerProcessing(ctx context.Context)
- type TieringStore
- type ValidateBackupResult
- type ValidationConfig
- type ValidationNotifier
- type ValidationStore
- type VerificationConfig
- type VerificationNotifier
- type VerificationScheduler
- func (vs *VerificationScheduler) GetNextRun(scheduleID uuid.UUID) (time.Time, bool)
- func (vs *VerificationScheduler) GetRepositoryVerificationStatus(ctx context.Context, repoID uuid.UUID) (*models.RepositoryVerificationStatus, error)
- func (vs *VerificationScheduler) Reload(ctx context.Context) error
- func (vs *VerificationScheduler) Start(ctx context.Context) error
- func (vs *VerificationScheduler) Stop() context.Context
- func (vs *VerificationScheduler) TriggerVerification(ctx context.Context, repoID uuid.UUID, verType models.VerificationType) (*models.Verification, error)
- type VerificationStore
Constants ¶
const MaxFileSizeForDiff = 10 * 1024 * 1024 // 10 MB
MaxFileSizeForDiff is the maximum file size (in bytes) we'll attempt to diff. Files larger than this will only show metadata comparison.
Variables ¶
var ( ErrRegionNotFound = errors.New("region not found") ErrRegionPairNotFound = errors.New("region pair not found") ErrReplicationDisabled = errors.New("geo-replication is disabled for this repository") ErrReplicationInProgress = errors.New("replication already in progress") )
Common errors for geo-replication operations.
var ( RegionUSEast1 = Region{ Code: "us-east-1", Name: "US East (N. Virginia)", DisplayName: "N. Virginia", Latitude: 37.4316, Longitude: -78.6569, } RegionUSWest2 = Region{ Code: "us-west-2", Name: "US West (Oregon)", DisplayName: "Oregon", Latitude: 45.5231, Longitude: -122.6765, } RegionEUWest1 = Region{ Code: "eu-west-1", Name: "EU (Ireland)", DisplayName: "Ireland", Latitude: 53.3498, Longitude: -6.2603, } RegionEUCentral1 = Region{ Code: "eu-central-1", Name: "EU (Frankfurt)", DisplayName: "Frankfurt", Latitude: 50.1109, Longitude: 8.6821, } RegionAPSoutheast1 = Region{ Code: "ap-southeast-1", Name: "Asia Pacific (Singapore)", DisplayName: "Singapore", Latitude: 1.3521, Longitude: 103.8198, } RegionAPNortheast1 = Region{ Code: "ap-northeast-1", Name: "Asia Pacific (Tokyo)", DisplayName: "Tokyo", Latitude: 35.6762, Longitude: 139.6503, } )
Predefined regions for geo-replication.
var ( // ErrSnapshotLocked is returned when attempting to delete a locked snapshot. ErrSnapshotLocked = errors.New("snapshot is locked and cannot be deleted") // ErrImmutabilityNotFound is returned when the lock doesn't exist. ErrImmutabilityNotFound = errors.New("immutability lock not found") // ErrCannotShortenLock is returned when attempting to shorten a lock period. ErrCannotShortenLock = errors.New("cannot shorten immutability period; can only extend") )
var ( ErrPathNotInSnapshot = errors.New("path not found in snapshot") ErrInvalidPath = errors.New("invalid path specification") ErrTargetExists = errors.New("target directory already exists") )
Common errors for partial restore operations.
var ErrInvalidPathMapping = errors.New("invalid path mapping")
ErrInvalidPathMapping is returned when a path mapping is invalid.
var ErrRepositoryNotInitialized = errors.New("repository not initialized")
ErrRepositoryNotInitialized is returned when the repository has not been initialized.
var ErrSnapshotNotFound = errors.New("snapshot not found")
ErrSnapshotNotFound is returned when a snapshot cannot be found.
var ErrSourceAgentNotFound = errors.New("source agent not found")
ErrSourceAgentNotFound is returned when the source agent cannot be found.
var ErrTargetAgentNoRepoAccess = errors.New("target agent does not have access to the repository")
ErrTargetAgentNoRepoAccess is returned when the target agent doesn't have access to the repository.
var ErrTargetAgentNotFound = errors.New("target agent not found")
ErrTargetAgentNotFound is returned when the target agent cannot be found.
var ErrUserNoAccessToSourceAgent = errors.New("user does not have access to source agent")
ErrUserNoAccessToSourceAgent is returned when the user doesn't have access to the source agent.
var ErrUserNoAccessToTargetAgent = errors.New("user does not have access to target agent")
ErrUserNoAccessToTargetAgent is returned when the user doesn't have access to the target agent.
Functions ¶
func BackendConfig ¶
BackendConfig converts a Backend to its JSON representation. This is a wrapper around backends.BackendConfig for backwards compatibility.
func CalculateDedupRatio ¶
CalculateDedupRatio calculates the deduplication ratio from raw and restore sizes. Returns 0 if restore size is 0 to avoid division by zero.
func CalculateSpaceSaved ¶
CalculateSpaceSaved calculates the space saved through deduplication.
func CalculateSpaceSavedPercent ¶
CalculateSpaceSavedPercent calculates the percentage of space saved.
func ConvertPathsToIncludePatterns ¶
ConvertPathsToIncludePatterns converts user-selected paths to restic --include patterns. Restic uses glob-style patterns for --include.
func GetRestoreAgentIDs ¶
GetRestoreAgentIDs returns both source and target agent IDs for a restore. For non-cross-agent restores, both IDs will be the same.
func IsCrossAgentRestore ¶
IsCrossAgentRestore returns true if the restore is a cross-agent restore.
func MergeRetentionPolicy ¶
func MergeRetentionPolicy(base, override *models.RetentionPolicy) *models.RetentionPolicy
MergeRetentionPolicy merges a partial policy into a base policy. Non-zero values in the override policy replace values in the base.
func ParseRetentionConfig ¶
func ParseRetentionConfig(cfg map[string]int) (*models.RetentionPolicy, error)
ParseRetentionConfig parses retention configuration from a map. This is useful for parsing configuration from JSON or environment variables.
func ParseSizeFromDiffLine ¶
ParseSizeFromDiffLine attempts to parse file size from a diff line. Returns 0 if size cannot be determined.
func PrepareTargetDirectory ¶
PrepareTargetDirectory ensures the target directory exists and is ready for restore.
func RetentionPolicyDescription ¶
func RetentionPolicyDescription(policy *models.RetentionPolicy) string
RetentionPolicyDescription returns a human-readable description of the policy.
func ValidateRetentionPolicy ¶
func ValidateRetentionPolicy(policy *models.RetentionPolicy) error
ValidateRetentionPolicy validates a retention policy configuration.
Types ¶
type Backend ¶
Backend is an alias to backends.Backend for backwards compatibility.
func ParseBackend ¶
func ParseBackend(repoType models.RepositoryType, configJSON []byte) (Backend, error)
ParseBackend parses a backend configuration from JSON based on the repository type. This is a wrapper around backends.ParseBackend for backwards compatibility.
type BackupOptions ¶
type BackupOptions struct {
BandwidthLimitKB *int // Upload bandwidth limit in KB/s (nil = unlimited)
CompressionLevel *string // Compression level: off, auto, max (nil = restic default "auto")
MaxFileSizeMB *int // Maximum file size in MB to include (nil/0 = no limit)
}
BackupOptions contains optional parameters for backup operations.
type BackupStats ¶
type BackupStats struct {
SnapshotID string
FilesNew int
FilesChanged int
SizeBytes int64
Duration time.Duration
}
BackupStats contains statistics from a backup operation.
type BackupValidator ¶
type BackupValidator struct {
// contains filtered or unexported fields
}
BackupValidator performs automated validation of backups.
func NewBackupValidator ¶
func NewBackupValidator( restic *Restic, config ValidationConfig, store ValidationStore, logger zerolog.Logger, ) *BackupValidator
NewBackupValidator creates a new BackupValidator.
func (*BackupValidator) SetNotifier ¶
func (bv *BackupValidator) SetNotifier(notifier ValidationNotifier)
SetNotifier sets the notification service for validation failures.
func (*BackupValidator) ValidateAndNotify ¶
func (bv *BackupValidator) ValidateAndNotify( ctx context.Context, backup *models.Backup, cfg ResticConfig, sourcePaths []string, ) (*ValidateBackupResult, error)
ValidateAndNotify validates a backup and sends notifications if it fails.
func (*BackupValidator) ValidateBackup ¶
func (bv *BackupValidator) ValidateBackup( ctx context.Context, backup *models.Backup, cfg ResticConfig, sourcePaths []string, ) (*models.BackupValidation, error)
ValidateBackup performs comprehensive validation of a completed backup. It verifies the backup completed successfully, checks snapshot existence, validates metadata, compares file counts, and spot-checks random files.
type CheckOptions ¶
type CheckOptions struct {
ReadData bool // If true, verify data blobs
ReadDataSubset string // Subset of data to check (e.g., "2.5%")
}
CheckOptions configures a restic check operation.
type CheckResult ¶
type CheckResult struct {
Duration time.Duration `json:"duration"`
Errors []string `json:"errors,omitempty"`
}
CheckResult contains results from a check operation.
type CheckpointConfig ¶
type CheckpointConfig struct {
// SaveInterval is how often to save checkpoint progress during a backup.
SaveInterval time.Duration
// ExpirationDuration is how long checkpoints remain valid for resume.
ExpirationDuration time.Duration
// CleanupInterval is how often to clean up expired checkpoints.
CleanupInterval time.Duration
// MaxResumeAttempts is the maximum number of times a backup can be resumed.
MaxResumeAttempts int
}
CheckpointConfig holds configuration for checkpoint management.
func DefaultCheckpointConfig ¶
func DefaultCheckpointConfig() CheckpointConfig
DefaultCheckpointConfig returns sensible defaults for checkpoint configuration.
type CheckpointManager ¶
type CheckpointManager struct {
// contains filtered or unexported fields
}
CheckpointManager manages backup checkpoints for resumable backups.
func NewCheckpointManager ¶
func NewCheckpointManager(store CheckpointStore, config CheckpointConfig, logger zerolog.Logger) *CheckpointManager
NewCheckpointManager creates a new checkpoint manager.
func (*CheckpointManager) AssociateBackup ¶
func (m *CheckpointManager) AssociateBackup(ctx context.Context, checkpointID, backupID uuid.UUID) error
AssociateBackup associates a backup record with a checkpoint.
func (*CheckpointManager) CancelCheckpoint ¶
CancelCheckpoint cancels a checkpoint, making it non-resumable.
func (*CheckpointManager) CompleteBackup ¶
CompleteBackup marks a backup as completed and stops tracking.
func (*CheckpointManager) GetIncompleteBackups ¶
func (m *CheckpointManager) GetIncompleteBackups(ctx context.Context, agentID uuid.UUID) ([]*models.BackupCheckpoint, error)
GetIncompleteBackups returns all incomplete backups for an agent that can be resumed.
func (*CheckpointManager) GetResumableCheckpoint ¶
func (m *CheckpointManager) GetResumableCheckpoint(ctx context.Context, scheduleID uuid.UUID) (*models.BackupCheckpoint, error)
GetResumableCheckpoint returns a resumable checkpoint for a schedule if one exists.
func (*CheckpointManager) GetResumeInfo ¶
func (m *CheckpointManager) GetResumeInfo(ctx context.Context, checkpointID uuid.UUID) (*ResumeInfo, error)
GetResumeInfo returns information about a resumable backup.
func (*CheckpointManager) InterruptBackup ¶
func (m *CheckpointManager) InterruptBackup(ctx context.Context, backupID uuid.UUID, errMsg string) error
InterruptBackup marks a backup as interrupted with an error.
func (*CheckpointManager) PrepareResume ¶
func (m *CheckpointManager) PrepareResume(ctx context.Context, checkpoint *models.BackupCheckpoint) error
PrepareResume prepares a checkpoint for resumption.
func (*CheckpointManager) SetTotals ¶
func (m *CheckpointManager) SetTotals(ctx context.Context, backupID uuid.UUID, totalFiles, totalBytes int64) error
SetTotals sets the estimated totals for a tracked backup.
func (*CheckpointManager) Start ¶
func (m *CheckpointManager) Start(ctx context.Context) error
Start starts the checkpoint manager background tasks.
func (*CheckpointManager) StartCheckpoint ¶
func (m *CheckpointManager) StartCheckpoint(ctx context.Context, scheduleID, agentID, repositoryID uuid.UUID) (*models.BackupCheckpoint, error)
StartCheckpoint creates a new checkpoint for a backup.
func (*CheckpointManager) Stop ¶
func (m *CheckpointManager) Stop()
Stop stops the checkpoint manager.
func (*CheckpointManager) TrackBackup ¶
func (m *CheckpointManager) TrackBackup(backupID uuid.UUID, checkpoint *models.BackupCheckpoint)
TrackBackup starts tracking progress for a backup with a checkpoint.
func (*CheckpointManager) UpdateProgress ¶
func (m *CheckpointManager) UpdateProgress(ctx context.Context, backupID uuid.UUID, filesProcessed, bytesProcessed int64, lastPath string) (bool, error)
UpdateProgress updates the progress of a tracked backup. Returns true if the checkpoint was saved to the database.
type CheckpointStore ¶
type CheckpointStore interface {
// CreateCheckpoint creates a new backup checkpoint.
CreateCheckpoint(ctx context.Context, checkpoint *models.BackupCheckpoint) error
// UpdateCheckpoint updates an existing checkpoint.
UpdateCheckpoint(ctx context.Context, checkpoint *models.BackupCheckpoint) error
// GetCheckpointByID returns a checkpoint by ID.
GetCheckpointByID(ctx context.Context, id uuid.UUID) (*models.BackupCheckpoint, error)
// GetActiveCheckpointForSchedule returns the active checkpoint for a schedule if one exists.
GetActiveCheckpointForSchedule(ctx context.Context, scheduleID uuid.UUID) (*models.BackupCheckpoint, error)
// GetActiveCheckpointsForAgent returns all active checkpoints for an agent.
GetActiveCheckpointsForAgent(ctx context.Context, agentID uuid.UUID) ([]*models.BackupCheckpoint, error)
// GetExpiredCheckpoints returns all checkpoints that have expired.
GetExpiredCheckpoints(ctx context.Context) ([]*models.BackupCheckpoint, error)
// DeleteCheckpoint deletes a checkpoint by ID.
DeleteCheckpoint(ctx context.Context, id uuid.UUID) error
}
CheckpointStore defines the interface for checkpoint persistence.
type CloudRestore ¶
type CloudRestore struct {
// contains filtered or unexported fields
}
CloudRestore wraps cloud restore operations.
func NewCloudRestore ¶
func NewCloudRestore(restic *Restic, logger zerolog.Logger) *CloudRestore
NewCloudRestore creates a new CloudRestore instance.
func (*CloudRestore) RestoreToCloud ¶
func (cr *CloudRestore) RestoreToCloud(ctx context.Context, cfg backends.ResticConfig, opts CloudRestoreOptions) (*CloudRestoreResult, error)
RestoreToCloud restores a snapshot and uploads it to cloud storage.
type CloudRestoreOptions ¶
type CloudRestoreOptions struct {
SnapshotID string `json:"snapshot_id"`
Include []string `json:"include,omitempty"`
Exclude []string `json:"exclude,omitempty"`
Target CloudRestoreTarget `json:"target"`
TempDir string `json:"temp_dir,omitempty"` // Defaults to os.TempDir()
VerifyUpload bool `json:"verify_upload"` // Verify upload integrity with checksums
Concurrency int `json:"concurrency"` // Number of concurrent uploads (default: 5)
ProgressChan chan<- CloudRestoreProgress `json:"-"` // Optional channel to receive progress updates
}
CloudRestoreOptions configures a cloud restore operation.
type CloudRestoreProgress ¶
type CloudRestoreProgress struct {
TotalFiles int64 `json:"total_files"`
TotalBytes int64 `json:"total_bytes"`
UploadedFiles int64 `json:"uploaded_files"`
UploadedBytes int64 `json:"uploaded_bytes"`
CurrentFile string `json:"current_file"`
Status string `json:"status"` // "restoring", "uploading", "verifying", "completed", "failed"
StartedAt time.Time `json:"started_at"`
ErrorMessage string `json:"error_message,omitempty"`
VerifiedChecksum bool `json:"verified_checksum"`
// contains filtered or unexported fields
}
CloudRestoreProgress represents the progress of a cloud restore upload operation.
func (*CloudRestoreProgress) Get ¶
func (p *CloudRestoreProgress) Get() CloudRestoreProgress
Get returns a copy of the progress with thread safety.
func (*CloudRestoreProgress) PercentComplete ¶
func (p *CloudRestoreProgress) PercentComplete() float64
PercentComplete returns the upload completion percentage.
func (*CloudRestoreProgress) Update ¶
func (p *CloudRestoreProgress) Update(fn func(*CloudRestoreProgress))
Update updates the progress with thread safety.
type CloudRestoreResult ¶
type CloudRestoreResult struct {
UploadedFiles int64 `json:"uploaded_files"`
UploadedBytes int64 `json:"uploaded_bytes"`
Duration time.Duration `json:"duration"`
TargetLocation string `json:"target_location"`
Verified bool `json:"verified"`
}
CloudRestoreResult contains the result of a cloud restore operation.
type CloudRestoreTarget ¶
type CloudRestoreTarget struct {
Type CloudRestoreTargetType `json:"type"`
// S3/B2 configuration
Bucket string `json:"bucket,omitempty"`
Prefix string `json:"prefix,omitempty"`
Region string `json:"region,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
AccessKeyID string `json:"access_key_id,omitempty"`
SecretAccessKey string `json:"secret_access_key,omitempty"`
UseSSL bool `json:"use_ssl,omitempty"`
// B2 specific
AccountID string `json:"account_id,omitempty"`
ApplicationKey string `json:"application_key,omitempty"`
// Restic repository configuration
Repository string `json:"repository,omitempty"`
RepositoryPassword string `json:"repository_password,omitempty"`
}
CloudRestoreTarget represents the target cloud storage for a restore operation.
type CloudRestoreTargetType ¶
type CloudRestoreTargetType string
CloudRestoreTargetType represents the type of cloud storage target.
const ( // CloudRestoreTargetS3 represents an S3-compatible storage target. CloudRestoreTargetS3 CloudRestoreTargetType = "s3" // CloudRestoreTargetB2 represents a Backblaze B2 storage target. CloudRestoreTargetB2 CloudRestoreTargetType = "b2" // CloudRestoreTargetRestic represents another Restic repository as a target. CloudRestoreTargetRestic CloudRestoreTargetType = "restic" )
type ConcurrencyManager ¶
type ConcurrencyManager struct {
// contains filtered or unexported fields
}
ConcurrencyManager manages backup concurrency limits and queuing.
func NewConcurrencyManager ¶
func NewConcurrencyManager(store ConcurrencyStore, notifier *notifications.Service, logger zerolog.Logger) *ConcurrencyManager
NewConcurrencyManager creates a new concurrency manager.
func (*ConcurrencyManager) AcquireSlot ¶
func (m *ConcurrencyManager) AcquireSlot(ctx context.Context, orgID, agentID, scheduleID uuid.UUID) (bool, *models.BackupQueueEntry, error)
AcquireSlot attempts to acquire a backup slot. Returns true if acquired. If limit is reached, queues the backup and returns false.
func (*ConcurrencyManager) CanStartBackup ¶
func (m *ConcurrencyManager) CanStartBackup(ctx context.Context, orgID, agentID uuid.UUID) (bool, bool, error)
CanStartBackup checks if a backup can start given current limits. Returns (canStart, shouldQueue, error).
func (*ConcurrencyManager) CancelQueuedBackup ¶
CancelQueuedBackup cancels a backup waiting in queue.
func (*ConcurrencyManager) GetConcurrencyStatus ¶
func (m *ConcurrencyManager) GetConcurrencyStatus(ctx context.Context, orgID, agentID uuid.UUID) (*models.ConcurrencyStatus, error)
GetConcurrencyStatus returns the current concurrency status for an org/agent.
func (*ConcurrencyManager) GetQueuedBackups ¶
func (m *ConcurrencyManager) GetQueuedBackups(ctx context.Context, orgID uuid.UUID) ([]*models.BackupQueueEntry, error)
GetQueuedBackups returns all queued backups for an organization.
func (*ConcurrencyManager) ProcessQueuedBackups ¶
func (m *ConcurrencyManager) ProcessQueuedBackups(ctx context.Context) ([]*models.BackupQueueEntry, error)
ProcessQueuedBackups checks all queues and starts eligible backups. This should be called periodically to handle any stuck queue entries.
func (*ConcurrencyManager) ReleaseSlot ¶
ReleaseSlot releases a backup slot and starts the next queued backup if any.
func (*ConcurrencyManager) SyncRunningCounts ¶
func (m *ConcurrencyManager) SyncRunningCounts(ctx context.Context) error
SyncRunningCounts synchronizes in-memory counts with database.
type ConcurrencyStore ¶
type ConcurrencyStore interface {
// GetOrganizationByID returns an organization by ID.
GetOrganizationByID(ctx context.Context, id uuid.UUID) (*models.Organization, error)
// GetAgentByID returns an agent by ID.
GetAgentByID(ctx context.Context, id uuid.UUID) (*models.Agent, error)
// GetRunningBackupsCountByOrg returns the count of running backups for an org.
GetRunningBackupsCountByOrg(ctx context.Context, orgID uuid.UUID) (int, error)
// GetRunningBackupsCountByAgent returns the count of running backups for an agent.
GetRunningBackupsCountByAgent(ctx context.Context, agentID uuid.UUID) (int, error)
// CreateBackupQueueEntry creates a new queue entry.
CreateBackupQueueEntry(ctx context.Context, entry *models.BackupQueueEntry) error
// GetQueuedBackupsByOrg returns queued backups for an org.
GetQueuedBackupsByOrg(ctx context.Context, orgID uuid.UUID) ([]*models.BackupQueueEntry, error)
// GetQueuedBackupsByAgent returns queued backups for an agent.
GetQueuedBackupsByAgent(ctx context.Context, agentID uuid.UUID) ([]*models.BackupQueueEntry, error)
// GetOldestQueuedBackup returns the oldest queued backup for an org.
GetOldestQueuedBackup(ctx context.Context, orgID uuid.UUID) (*models.BackupQueueEntry, error)
// UpdateBackupQueueEntry updates a queue entry.
UpdateBackupQueueEntry(ctx context.Context, entry *models.BackupQueueEntry) error
// DeleteBackupQueueEntry deletes a queue entry.
DeleteBackupQueueEntry(ctx context.Context, id uuid.UUID) error
// GetQueuePosition returns the position in queue for a given entry.
GetQueuePosition(ctx context.Context, orgID, entryID uuid.UUID) (int, error)
// GetConcurrencyQueueSummary returns queue statistics.
GetConcurrencyQueueSummary(ctx context.Context, orgID uuid.UUID) (*models.ConcurrencyQueueSummary, error)
// GetScheduleByID returns a schedule by ID.
GetScheduleByID(ctx context.Context, id uuid.UUID) (*models.Schedule, error)
}
ConcurrencyStore defines the interface for concurrency-related data access.
type CrossRestoreJob ¶
type CrossRestoreJob struct {
ID uuid.UUID `json:"id"`
SourceAgentID uuid.UUID `json:"source_agent_id"`
TargetAgentID uuid.UUID `json:"target_agent_id"`
RepositoryID uuid.UUID `json:"repository_id"`
SnapshotID string `json:"snapshot_id"`
TargetPath string `json:"target_path"`
IncludePaths []string `json:"include_paths,omitempty"`
ExcludePaths []string `json:"exclude_paths,omitempty"`
PathMappings []models.PathMapping `json:"path_mappings,omitempty"`
Status models.RestoreStatus `json:"status"`
Progress *CrossRestoreProgress `json:"progress,omitempty"`
StartedAt *time.Time `json:"started_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
CrossRestoreJob represents a cross-agent restore job with tracking information.
type CrossRestoreProgress ¶
type CrossRestoreProgress struct {
FilesRestored int64 `json:"files_restored"`
BytesRestored int64 `json:"bytes_restored"`
TotalFiles int64 `json:"total_files,omitempty"`
TotalBytes int64 `json:"total_bytes,omitempty"`
CurrentFile string `json:"current_file,omitempty"`
}
CrossRestoreProgress tracks the progress of a cross-agent restore operation.
type CrossRestoreRequest ¶
type CrossRestoreRequest struct {
SourceAgentID uuid.UUID `json:"source_agent_id"`
TargetAgentID uuid.UUID `json:"target_agent_id"`
RepositoryID uuid.UUID `json:"repository_id"`
SnapshotID string `json:"snapshot_id"`
TargetPath string `json:"target_path"`
IncludePaths []string `json:"include_paths,omitempty"`
ExcludePaths []string `json:"exclude_paths,omitempty"`
PathMappings []models.PathMapping `json:"path_mappings,omitempty"`
}
CrossRestoreRequest contains the parameters for a cross-agent restore operation.
type CrossRestoreService ¶
type CrossRestoreService struct {
// contains filtered or unexported fields
}
CrossRestoreService handles cross-agent restore operations.
func NewCrossRestoreService ¶
func NewCrossRestoreService(store CrossRestoreStore, logger zerolog.Logger) *CrossRestoreService
NewCrossRestoreService creates a new CrossRestoreService.
func (*CrossRestoreService) ApplyPathMappings ¶
func (s *CrossRestoreService) ApplyPathMappings(originalPath string, mappings []models.PathMapping) string
ApplyPathMappings transforms paths according to the provided mappings.
func (*CrossRestoreService) CreateCrossRestoreJob ¶
func (s *CrossRestoreService) CreateCrossRestoreJob(ctx context.Context, req CrossRestoreRequest) (*models.Restore, error)
CreateCrossRestoreJob creates a new cross-agent restore job.
func (*CrossRestoreService) ValidatePathMappings ¶
func (s *CrossRestoreService) ValidatePathMappings(mappings []models.PathMapping) error
ValidatePathMappings validates that path mappings are well-formed.
func (*CrossRestoreService) ValidateTargetAgentAccess ¶
func (s *CrossRestoreService) ValidateTargetAgentAccess(ctx context.Context, targetAgentID, repositoryID uuid.UUID) error
ValidateTargetAgentAccess validates that the target agent has access to the repository.
func (*CrossRestoreService) ValidateUserAccess ¶
func (s *CrossRestoreService) ValidateUserAccess(ctx context.Context, userID, sourceAgentID, targetAgentID uuid.UUID) error
ValidateUserAccess validates that the user has access to both source and target agents.
type CrossRestoreStore ¶
type CrossRestoreStore interface {
GetAgentByID(ctx context.Context, id uuid.UUID) (*models.Agent, error)
GetRepositoryByID(ctx context.Context, id uuid.UUID) (*models.Repository, error)
GetUserByID(ctx context.Context, id uuid.UUID) (*models.User, error)
CreateRestore(ctx context.Context, restore *models.Restore) error
UpdateRestore(ctx context.Context, restore *models.Restore) error
GetRestoreByID(ctx context.Context, id uuid.UUID) (*models.Restore, error)
GetBackupBySnapshotID(ctx context.Context, snapshotID string) (*models.Backup, error)
}
CrossRestoreStore defines the interface for cross-restore persistence operations.
type DRTestScheduler ¶
type DRTestScheduler struct {
// contains filtered or unexported fields
}
DRTestScheduler manages DR test schedules using cron.
func NewDRTestScheduler ¶
func NewDRTestScheduler(store DRTestStore, restic *Restic, config SchedulerConfig, logger zerolog.Logger) *DRTestScheduler
NewDRTestScheduler creates a new DR test scheduler.
func (*DRTestScheduler) GetActiveDRSchedules ¶
func (s *DRTestScheduler) GetActiveDRSchedules() int
GetActiveDRSchedules returns the number of active DR test schedules.
func (*DRTestScheduler) ReloadDRSchedules ¶
func (s *DRTestScheduler) ReloadDRSchedules(ctx context.Context) error
ReloadDRSchedules reloads all DR test schedules from the database.
func (*DRTestScheduler) Start ¶
func (s *DRTestScheduler) Start(ctx context.Context) error
Start starts the DR test scheduler.
func (*DRTestScheduler) Stop ¶
func (s *DRTestScheduler) Stop() context.Context
Stop stops the DR test scheduler gracefully.
func (*DRTestScheduler) TriggerDRTest ¶
TriggerDRTest manually triggers a DR test for the given runbook.
type DRTestStore ¶
type DRTestStore interface {
GetEnabledDRTestSchedules(ctx context.Context) ([]*models.DRTestSchedule, error)
GetDRRunbookByID(ctx context.Context, id uuid.UUID) (*models.DRRunbook, error)
CreateDRTest(ctx context.Context, test *models.DRTest) error
UpdateDRTest(ctx context.Context, test *models.DRTest) error
UpdateDRTestSchedule(ctx context.Context, schedule *models.DRTestSchedule) error
GetScheduleByID(ctx context.Context, id uuid.UUID) (*models.Schedule, error)
GetRepository(ctx context.Context, id uuid.UUID) (*models.Repository, error)
}
DRTestStore defines the interface for DR test scheduling.
type DecryptFunc ¶
DecryptFunc is a function that decrypts repository configuration.
type DiffChangeType ¶
type DiffChangeType string
DiffChangeType represents the type of change in a diff.
const ( DiffChangeAdded DiffChangeType = "added" DiffChangeRemoved DiffChangeType = "removed" DiffChangeModified DiffChangeType = "modified" )
type DiffEntry ¶
type DiffEntry struct {
Path string `json:"path"`
ChangeType DiffChangeType `json:"change_type"`
Type string `json:"type"` // "file" or "dir"
OldSize int64 `json:"old_size,omitempty"`
NewSize int64 `json:"new_size,omitempty"`
SizeChange int64 `json:"size_change,omitempty"`
OldModTime string `json:"old_mod_time,omitempty"`
NewModTime string `json:"new_mod_time,omitempty"`
}
DiffEntry represents a single changed file/directory in the diff.
type DiffResult ¶
type DiffResult struct {
SnapshotID1 string `json:"snapshot_id_1"`
SnapshotID2 string `json:"snapshot_id_2"`
Stats DiffStats `json:"stats"`
Changes []DiffEntry `json:"changes"`
}
DiffResult contains the result of comparing two snapshots.
func ParseDiffFromText ¶
func ParseDiffFromText(output string, snapshotID1, snapshotID2 string) (*DiffResult, error)
ParseDiffFromText parses restic diff output from text format (non-JSON). This is a fallback for when JSON output is not available.
type DiffStats ¶
type DiffStats struct {
FilesAdded int `json:"files_added"`
FilesRemoved int `json:"files_removed"`
FilesModified int `json:"files_modified"`
DirsAdded int `json:"dirs_added"`
DirsRemoved int `json:"dirs_removed"`
TotalSizeAdded int64 `json:"total_size_added"`
TotalSizeRemoved int64 `json:"total_size_removed"`
}
DiffStats contains summary statistics for a diff operation.
type DropboxBackend ¶
type DropboxBackend = backends.DropboxBackend
Type aliases for backwards compatibility.
type DryRunExcluded ¶
DryRunExcluded represents a file that was excluded from backup.
type DryRunFile ¶
type DryRunFile struct {
Path string `json:"path"`
Type string `json:"type"` // "file" or "dir"
Size int64 `json:"size"`
Action string `json:"action"` // "new", "changed", or "unchanged"
}
DryRunFile represents a file that would be backed up in a dry run.
type DryRunResult ¶
type DryRunResult struct {
FilesToBackup []DryRunFile `json:"files_to_backup"`
ExcludedFiles []DryRunExcluded `json:"excluded_files"`
TotalFiles int `json:"total_files"`
TotalSize int64 `json:"total_size"`
NewFiles int `json:"new_files"`
ChangedFiles int `json:"changed_files"`
UnchangedFiles int `json:"unchanged_files"`
Duration time.Duration `json:"duration"`
}
DryRunResult contains the results of a dry run backup operation.
type ExtendedRepoStats ¶
type ExtendedRepoStats struct {
// Basic stats
TotalSize int64 `json:"total_size"`
TotalFileCount int `json:"total_file_count"`
// Raw data mode stats (actual storage used)
RawDataSize int64 `json:"raw_data_size"`
// Restore size mode stats (original data size before dedup)
RestoreSize int64 `json:"restore_size"`
// Calculated dedup metrics
DedupRatio float64 `json:"dedup_ratio"`
SpaceSaved int64 `json:"space_saved"`
SpaceSavedPct float64 `json:"space_saved_pct"`
// Snapshot count
SnapshotCount int `json:"snapshot_count"`
}
ExtendedRepoStats contains comprehensive repository statistics including dedup metrics.
type FileDiffResult ¶
type FileDiffResult struct {
Path string `json:"path"`
IsBinary bool `json:"is_binary"`
ChangeType string `json:"change_type"` // "modified", "added", "removed"
OldSize int64 `json:"old_size,omitempty"`
NewSize int64 `json:"new_size,omitempty"`
OldHash string `json:"old_hash,omitempty"`
NewHash string `json:"new_hash,omitempty"`
UnifiedDiff string `json:"unified_diff,omitempty"` // For text files
OldContent string `json:"old_content,omitempty"` // For side-by-side view
NewContent string `json:"new_content,omitempty"` // For side-by-side view
}
FileDiffResult represents the result of comparing a file between two snapshots.
type FileHistory ¶
type FileHistory struct {
FilePath string `json:"file_path"`
Versions []FileVersion `json:"versions"`
}
FileHistory contains the history of a file across all snapshots.
type FileSearchFilter ¶
type FileSearchFilter struct {
Query string // Filename pattern to search for
PathPrefix string // Optional path prefix to filter results
SnapshotIDs []string // Optional list of snapshot IDs to search in
DateFrom *time.Time // Optional date range start
DateTo *time.Time // Optional date range end
SizeMin *int64 // Optional minimum file size
SizeMax *int64 // Optional maximum file size
Limit int // Maximum number of results (0 = unlimited)
}
FileSearchFilter contains filter options for file search.
type FileSearchResponse ¶
type FileSearchResponse struct {
Query string `json:"query"`
TotalCount int `json:"total_count"`
Snapshots []SnapshotFileGroup `json:"snapshots"`
}
FileSearchResponse contains grouped search results.
type FileSearchResult ¶
type FileSearchResult struct {
SnapshotID string `json:"snapshot_id"`
SnapshotTime time.Time `json:"snapshot_time"`
Hostname string `json:"hostname"`
FileName string `json:"file_name"`
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileType string `json:"file_type"` // "file" or "dir"
ModTime time.Time `json:"mod_time"`
}
FileSearchResult represents a file found in a snapshot.
type FileVersion ¶
type FileVersion struct {
SnapshotID string `json:"snapshot_id"`
SnapshotTime time.Time `json:"snapshot_time"`
FilePath string `json:"file_path"`
Size int64 `json:"size"`
ModTime time.Time `json:"mod_time"`
Mode uint32 `json:"mode"`
}
FileVersion represents a single version of a file across snapshots.
type ForgetResult ¶
type ForgetResult struct {
SnapshotsRemoved int `json:"snapshots_removed"`
SnapshotsKept int `json:"snapshots_kept"`
RemovedIDs []string `json:"removed_ids,omitempty"`
}
ForgetResult contains the results of a forget/prune operation.
type GeoReplicationStore ¶
type GeoReplicationStore interface {
CreateGeoReplicationConfig(ctx context.Context, config *models.GeoReplicationConfig) error
GetGeoReplicationConfig(ctx context.Context, id uuid.UUID) (*models.GeoReplicationConfig, error)
GetGeoReplicationConfigByRepository(ctx context.Context, repositoryID uuid.UUID) (*models.GeoReplicationConfig, error)
UpdateGeoReplicationConfig(ctx context.Context, config *models.GeoReplicationConfig) error
DeleteGeoReplicationConfig(ctx context.Context, id uuid.UUID) error
ListGeoReplicationConfigsByOrg(ctx context.Context, orgID uuid.UUID) ([]*models.GeoReplicationConfig, error)
ListPendingReplications(ctx context.Context) ([]*models.GeoReplicationConfig, error)
RecordReplicationEvent(ctx context.Context, event *models.ReplicationEvent) error
GetReplicationLag(ctx context.Context, configID uuid.UUID) (*ReplicationLag, error)
}
GeoReplicationStore defines the interface for geo-replication persistence.
type GeoReplicator ¶
type GeoReplicator struct {
// contains filtered or unexported fields
}
GeoReplicator handles automatic geo-replication of backups.
func NewGeoReplicator ¶
func NewGeoReplicator(restic *Restic, store GeoReplicationStore, logger zerolog.Logger) *GeoReplicator
NewGeoReplicator creates a new GeoReplicator.
func (*GeoReplicator) CheckReplicationHealth ¶
func (g *GeoReplicator) CheckReplicationHealth(ctx context.Context, config *models.GeoReplicationConfig, maxSnapshots int, maxDuration time.Duration) (bool, *ReplicationLag, error)
CheckReplicationHealth checks if replication is within acceptable limits and creates alerts if not.
func (*GeoReplicator) GetReplicationStatus ¶
func (g *GeoReplicator) GetReplicationStatus(ctx context.Context, repositoryID uuid.UUID) (*models.GeoReplicationConfig, *ReplicationLag, error)
GetReplicationStatus returns the current replication status for a repository.
func (*GeoReplicator) GetReplicationSummary ¶
func (g *GeoReplicator) GetReplicationSummary(ctx context.Context, orgID uuid.UUID) (*ReplicationSummary, error)
GetReplicationSummary returns a summary of all replication configs for an org.
func (*GeoReplicator) ReplicateSnapshot ¶
func (g *GeoReplicator) ReplicateSnapshot(ctx context.Context, config *models.GeoReplicationConfig, snapshotID string) error
ReplicateSnapshot copies a specific snapshot from source to target repository.
func (*GeoReplicator) Start ¶
func (g *GeoReplicator) Start(ctx context.Context, checkInterval time.Duration)
Start begins the background replication processor.
func (*GeoReplicator) Stop ¶
func (g *GeoReplicator) Stop()
Stop gracefully stops the replication processor.
func (*GeoReplicator) TriggerReplication ¶
TriggerReplication manually triggers replication for a repository.
type ImmutabilityManager ¶
type ImmutabilityManager struct {
// contains filtered or unexported fields
}
ImmutabilityManager manages immutability locks for snapshots.
func NewImmutabilityManager ¶
func NewImmutabilityManager(store ImmutabilityStore, logger zerolog.Logger) *ImmutabilityManager
NewImmutabilityManager creates a new ImmutabilityManager.
func (*ImmutabilityManager) CheckDeleteAllowed ¶
func (m *ImmutabilityManager) CheckDeleteAllowed( ctx context.Context, repositoryID uuid.UUID, snapshotID string, ) error
CheckDeleteAllowed checks if a snapshot can be deleted. Returns nil if deletion is allowed, or an error with details if not.
func (*ImmutabilityManager) CleanupExpiredLocks ¶
func (m *ImmutabilityManager) CleanupExpiredLocks(ctx context.Context) (int, error)
CleanupExpiredLocks removes expired immutability locks.
func (*ImmutabilityManager) ExtendLock ¶
func (m *ImmutabilityManager) ExtendLock( ctx context.Context, repositoryID uuid.UUID, snapshotID string, additionalDays int, reason string, ) (*models.SnapshotImmutability, error)
ExtendLock extends an existing immutability lock. The new lock period must be longer than the current one.
func (*ImmutabilityManager) GetActiveLocksForOrg ¶
func (m *ImmutabilityManager) GetActiveLocksForOrg( ctx context.Context, orgID uuid.UUID, ) ([]*models.SnapshotImmutability, error)
GetActiveLocksForOrg returns all active locks for an organization.
func (*ImmutabilityManager) GetActiveLocksForRepository ¶
func (m *ImmutabilityManager) GetActiveLocksForRepository( ctx context.Context, repositoryID uuid.UUID, ) ([]*models.SnapshotImmutability, error)
GetActiveLocksForRepository returns all active locks for a repository.
func (*ImmutabilityManager) GetLockStatus ¶
func (m *ImmutabilityManager) GetLockStatus( ctx context.Context, repositoryID uuid.UUID, snapshotID string, ) (*models.SnapshotImmutability, error)
GetLockStatus returns the immutability status for a snapshot.
func (*ImmutabilityManager) GetStatus ¶
func (m *ImmutabilityManager) GetStatus( ctx context.Context, repositoryID uuid.UUID, snapshotID string, ) (*ImmutabilityStatus, error)
GetStatus returns a summary status for a snapshot.
func (*ImmutabilityManager) LockSnapshot ¶
func (m *ImmutabilityManager) LockSnapshot( ctx context.Context, orgID uuid.UUID, repositoryID uuid.UUID, snapshotID string, shortID string, days int, lockedBy *uuid.UUID, reason string, ) (*models.SnapshotImmutability, error)
LockSnapshot creates an immutability lock on a snapshot.
type ImmutabilityStatus ¶
type ImmutabilityStatus struct {
IsLocked bool `json:"is_locked"`
LockedUntil *time.Time `json:"locked_until,omitempty"`
RemainingDays int `json:"remaining_days,omitempty"`
Reason string `json:"reason,omitempty"`
LockedAt *time.Time `json:"locked_at,omitempty"`
}
ImmutabilityStatus represents the lock status of a snapshot for API responses.
type ImmutabilityStore ¶
type ImmutabilityStore interface {
// CreateSnapshotImmutability creates a new immutability lock.
CreateSnapshotImmutability(ctx context.Context, lock *models.SnapshotImmutability) error
// GetSnapshotImmutability returns the immutability lock for a snapshot.
GetSnapshotImmutability(ctx context.Context, repositoryID uuid.UUID, snapshotID string) (*models.SnapshotImmutability, error)
// GetSnapshotImmutabilityByID returns an immutability lock by ID.
GetSnapshotImmutabilityByID(ctx context.Context, id uuid.UUID) (*models.SnapshotImmutability, error)
// UpdateSnapshotImmutability updates an existing immutability lock.
UpdateSnapshotImmutability(ctx context.Context, lock *models.SnapshotImmutability) error
// DeleteExpiredImmutabilityLocks removes expired locks.
DeleteExpiredImmutabilityLocks(ctx context.Context) (int, error)
// GetActiveImmutabilityLocksByRepositoryID returns all active locks for a repository.
GetActiveImmutabilityLocksByRepositoryID(ctx context.Context, repositoryID uuid.UUID) ([]*models.SnapshotImmutability, error)
// GetActiveImmutabilityLocksByOrgID returns all active locks for an organization.
GetActiveImmutabilityLocksByOrgID(ctx context.Context, orgID uuid.UUID) ([]*models.SnapshotImmutability, error)
// IsSnapshotLocked checks if a snapshot has an active lock.
IsSnapshotLocked(ctx context.Context, repositoryID uuid.UUID, snapshotID string) (bool, error)
// GetRepository returns a repository by ID.
GetRepository(ctx context.Context, id uuid.UUID) (*models.Repository, error)
}
ImmutabilityStore defines the interface for immutability persistence operations.
type ImportOptions ¶
type ImportOptions struct {
// SnapshotIDs specifies which snapshots to import (empty = all).
SnapshotIDs []string `json:"snapshot_ids,omitempty"`
// Hostnames filters snapshots by hostname (empty = all).
Hostnames []string `json:"hostnames,omitempty"`
// AgentID is the agent to associate imported snapshots with.
// If empty, snapshots will be imported without an agent association.
AgentID string `json:"agent_id,omitempty"`
}
ImportOptions configures which snapshots to import.
type ImportPreview ¶
type ImportPreview struct {
// SnapshotCount is the total number of snapshots in the repository.
SnapshotCount int `json:"snapshot_count"`
// Snapshots is a list of snapshots found in the repository.
Snapshots []Snapshot `json:"snapshots"`
// Hostnames contains unique hostnames found in snapshots.
Hostnames []string `json:"hostnames"`
// TotalSize is the total deduplicated size of the repository in bytes.
TotalSize int64 `json:"total_size"`
// TotalFileCount is the total number of files across all snapshots.
TotalFileCount int `json:"total_file_count"`
}
ImportPreview contains information about an existing repository that can be imported.
type ImportResult ¶
type ImportResult struct {
// SnapshotsImported is the number of snapshots imported.
SnapshotsImported int `json:"snapshots_imported"`
// Snapshots contains details of the imported snapshots.
Snapshots []Snapshot `json:"snapshots"`
}
ImportResult contains the results of a repository import operation.
type Importer ¶
type Importer struct {
// contains filtered or unexported fields
}
Importer handles importing existing Restic repositories.
func NewImporter ¶
NewImporter creates a new Importer.
func (*Importer) CheckRepository ¶
func (i *Importer) CheckRepository(ctx context.Context, backend backends.Backend, password string) error
CheckRepository verifies the integrity of an existing repository.
func (*Importer) FilterSnapshots ¶
func (i *Importer) FilterSnapshots(snapshots []Snapshot, opts ImportOptions) []Snapshot
FilterSnapshots filters snapshots based on import options.
func (*Importer) GetSnapshots ¶
func (i *Importer) GetSnapshots(ctx context.Context, backend backends.Backend, password string, opts ImportOptions) ([]Snapshot, error)
GetSnapshots retrieves snapshots from the repository, optionally filtered by options.
type LargeFile ¶
type LargeFile struct {
Path string `json:"path"`
SizeBytes int64 `json:"size_bytes"`
SizeMB int64 `json:"size_mb"`
}
LargeFile represents a file that exceeds the size limit.
type LargeFileScanner ¶
type LargeFileScanner struct {
// contains filtered or unexported fields
}
LargeFileScanner scans paths to identify files exceeding a size limit.
func NewLargeFileScanner ¶
func NewLargeFileScanner(logger zerolog.Logger) *LargeFileScanner
NewLargeFileScanner creates a new LargeFileScanner.
func (*LargeFileScanner) FormatExcludedFiles ¶
func (s *LargeFileScanner) FormatExcludedFiles(result *ScanResult, maxFiles int) []string
FormatExcludedFiles formats the list of excluded files for display/logging. Returns a truncated list if there are too many files.
func (*LargeFileScanner) Scan ¶
func (s *LargeFileScanner) Scan(ctx context.Context, paths []string, excludes []string, maxSizeMB int) (*ScanResult, error)
Scan scans the given paths for files exceeding maxSizeMB. It respects the exclude patterns when scanning. Returns a list of large files that will be excluded by restic's --exclude-larger-than flag.
type LicenseChecker ¶
LicenseChecker provides license feature checking for non-HTTP contexts.
type LocalBackend ¶
type LocalBackend = backends.LocalBackend
Type aliases for backwards compatibility.
type MountInfo ¶
type MountInfo struct {
ID uuid.UUID
SnapshotID string
MountPath string
StartTime time.Time
ExpiresAt time.Time
// contains filtered or unexported fields
}
MountInfo tracks information about an active mount.
type MountManager ¶
type MountManager struct {
// contains filtered or unexported fields
}
MountManager manages FUSE mounts for restic snapshots.
func NewMountManager ¶
func NewMountManager(basePath string, logger zerolog.Logger) *MountManager
NewMountManager creates a new MountManager.
func NewMountManagerWithBinary ¶
func NewMountManagerWithBinary(binary, basePath string, logger zerolog.Logger) *MountManager
NewMountManagerWithBinary creates a new MountManager with a custom restic binary.
func (*MountManager) Cleanup ¶
func (m *MountManager) Cleanup() error
Cleanup removes any stale mount directories.
func (*MountManager) ExtendMount ¶
ExtendMount extends the expiration time of an active mount.
func (*MountManager) GetMount ¶
func (m *MountManager) GetMount(id uuid.UUID) (*MountInfo, bool)
GetMount returns information about an active mount.
func (*MountManager) IsSnapshotMounted ¶
func (m *MountManager) IsSnapshotMounted(snapshotID string) bool
IsSnapshotMounted checks if a snapshot is currently mounted.
func (*MountManager) ListMounts ¶
func (m *MountManager) ListMounts() []*MountInfo
ListMounts returns all active mounts.
func (*MountManager) Mount ¶
func (m *MountManager) Mount(ctx context.Context, id uuid.UUID, cfg backends.ResticConfig, snapshotID string, timeout time.Duration) (*MountInfo, error)
Mount starts a restic mount process for the given snapshot.
func (*MountManager) UnmountAll ¶
func (m *MountManager) UnmountAll(ctx context.Context) error
UnmountAll unmounts all active mounts.
type NetworkDrives ¶
type NetworkDrives struct {
// contains filtered or unexported fields
}
NetworkDrives provides network mount detection and validation.
func NewNetworkDrives ¶
func NewNetworkDrives(logger zerolog.Logger) *NetworkDrives
NewNetworkDrives creates a new NetworkDrives instance.
func (*NetworkDrives) DetectMounts ¶
func (nd *NetworkDrives) DetectMounts(ctx context.Context) ([]models.NetworkMount, error)
DetectMounts detects all network mounts on the system.
func (*NetworkDrives) GetNetworkPathsFromSchedule ¶
func (nd *NetworkDrives) GetNetworkPathsFromSchedule(paths []string, mounts []models.NetworkMount) []NetworkPathInfo
GetNetworkPathsFromSchedule returns paths from a schedule that are on network mounts.
func (*NetworkDrives) RefreshMountStatuses ¶
func (nd *NetworkDrives) RefreshMountStatuses(ctx context.Context, mounts []models.NetworkMount) []models.NetworkMount
RefreshMountStatuses updates the status of all mounts.
func (*NetworkDrives) ValidateMountForBackup ¶
func (nd *NetworkDrives) ValidateMountForBackup(ctx context.Context, path string, mounts []models.NetworkMount) (bool, *models.NetworkMount, error)
ValidateMountForBackup checks if a path is on a network mount and if it's available. Returns (isValid, mount, error). If the path is not on a network mount, mount will be nil.
type NetworkPathInfo ¶
type NetworkPathInfo struct {
Path string
Mount *models.NetworkMount
}
NetworkPathInfo contains information about a path on a network mount.
type PartialRestoreOptions ¶
type PartialRestoreOptions struct {
// SnapshotID is the ID of the snapshot to restore from.
SnapshotID string
// Paths is the list of paths to restore (files or directories).
Paths []string
// TargetPath is the destination directory. Empty means restore to original location.
TargetPath string
// Overwrite allows overwriting existing files at the target.
Overwrite bool
}
PartialRestoreOptions configures a partial restore operation.
type PartialRestoreResult ¶
type PartialRestoreResult struct {
// RestoredFiles is the number of files successfully restored.
RestoredFiles int
// RestoredDirs is the number of directories created.
RestoredDirs int
// TotalSize is the total size of restored data in bytes.
TotalSize int64
// Skipped contains paths that were skipped (e.g., already exist).
Skipped []string
// Errors contains any non-fatal errors encountered.
Errors []string
}
PartialRestoreResult contains the results of a partial restore operation.
type PartialRestoreValidator ¶
type PartialRestoreValidator struct {
// contains filtered or unexported fields
}
PartialRestoreValidator provides validation for partial restore operations.
func NewPartialRestoreValidator ¶
func NewPartialRestoreValidator(restic *Restic, logger zerolog.Logger) *PartialRestoreValidator
NewPartialRestoreValidator creates a new validator for partial restore operations.
func (*PartialRestoreValidator) CalculateRestoreSize ¶
func (v *PartialRestoreValidator) CalculateRestoreSize(ctx context.Context, cfg ResticConfig, snapshotID string, paths []string) (totalFiles int, totalDirs int, totalSize int64, err error)
CalculateRestoreSize calculates the total size of files that would be restored.
func (*PartialRestoreValidator) GetPathsInfo ¶
func (v *PartialRestoreValidator) GetPathsInfo(ctx context.Context, cfg ResticConfig, snapshotID string, paths []string) ([]SnapshotFile, error)
GetPathsInfo returns detailed information about the specified paths in a snapshot.
func (*PartialRestoreValidator) ValidatePaths ¶
func (v *PartialRestoreValidator) ValidatePaths(ctx context.Context, cfg ResticConfig, snapshotID string, paths []string) (found []string, notFound []string, err error)
ValidatePaths checks that all specified paths exist in the snapshot. Returns the validated paths that were found and any paths that were not found.
type ProgressReader ¶
type ProgressReader struct {
// contains filtered or unexported fields
}
ProgressReader wraps an io.Reader to track read progress.
func NewProgressReader ¶
func NewProgressReader(reader io.Reader, onRead func(bytesRead int64)) *ProgressReader
NewProgressReader creates a new ProgressReader.
type RawStats ¶
type RawStats struct {
TotalSize int64 `json:"total_size"`
TotalFileCount int `json:"total_file_count"`
}
RawStats represents the raw statistics from a restic repository.
type RawStatsMode ¶
type RawStatsMode struct {
TotalSize int64 `json:"total_size"`
TotalFileCount int `json:"total_file_count"`
TotalBlobCount int64 `json:"total_blob_count,omitempty"`
SnapshotsCount int `json:"snapshots_count,omitempty"`
TotalUncompressed int64 `json:"total_uncompressed_size,omitempty"`
}
RawStatsMode represents statistics with mode information from restic stats --mode.
type Region ¶
type Region struct {
Code string `json:"code"`
Name string `json:"name"`
DisplayName string `json:"display_name"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
}
Region represents a geographic region for backup storage.
func GetRegionByCode ¶
GetRegionByCode returns a region by its code.
func GetSecondaryRegion ¶
GetSecondaryRegion returns the default secondary region for a given primary region.
type RegionPair ¶
RegionPair defines a primary-secondary region relationship for geo-replication.
func DefaultRegionPairs ¶
func DefaultRegionPairs() []RegionPair
DefaultRegionPairs returns the default region pairs for geo-replication. These pairs are designed for disaster recovery with geographic separation.
type ReplicationLag ¶
type ReplicationLag struct {
SnapshotsBehind int `json:"snapshots_behind"`
TimeBehind time.Duration `json:"time_behind"`
LastSyncAt *time.Time `json:"last_sync_at,omitempty"`
OldestPending *time.Time `json:"oldest_pending,omitempty"`
}
ReplicationLag represents the replication delay metrics.
type ReplicationStatus ¶
type ReplicationStatus string
ReplicationStatus represents the current status of a geo-replication operation.
const ( ReplicationStatusPending ReplicationStatus = "pending" ReplicationStatusSyncing ReplicationStatus = "syncing" ReplicationStatusSynced ReplicationStatus = "synced" ReplicationStatusFailed ReplicationStatus = "failed" ReplicationStatusDisabled ReplicationStatus = "disabled" )
type ReplicationSummary ¶
type ReplicationSummary struct {
TotalConfigs int `json:"total_configs"`
EnabledConfigs int `json:"enabled_configs"`
SyncedCount int `json:"synced_count"`
SyncingCount int `json:"syncing_count"`
PendingCount int `json:"pending_count"`
FailedCount int `json:"failed_count"`
Configs []*models.GeoReplicationConfig `json:"configs,omitempty"`
}
ReplicationSummary provides a summary of replication status across all configs.
type RepoStats ¶
type RepoStats struct {
TotalSize int64 `json:"total_size"`
TotalFileCount int `json:"total_file_count"`
}
RepoStats contains basic repository statistics.
type RestBackend ¶
type RestBackend = backends.RestBackend
Type aliases for backwards compatibility.
type Restic ¶
type Restic struct {
// contains filtered or unexported fields
}
Restic wraps the restic CLI for backup operations.
func NewResticWithBinary ¶
NewResticWithBinary creates a new Restic wrapper with a custom binary path.
func (*Restic) Backup ¶
func (r *Restic) Backup(ctx context.Context, cfg ResticConfig, paths, excludes []string, tags []string) (*BackupStats, error)
Backup runs a backup operation with the given paths and excludes.
func (*Restic) BackupWithOptions ¶
func (r *Restic) BackupWithOptions(ctx context.Context, cfg ResticConfig, paths, excludes []string, tags []string, opts *BackupOptions) (*BackupStats, error)
BackupWithOptions runs a backup operation with additional options.
func (*Restic) Check ¶
func (r *Restic) Check(ctx context.Context, cfg ResticConfig) error
Check runs a basic integrity check on the repository.
func (*Restic) CheckWithOptions ¶
func (r *Restic) CheckWithOptions(ctx context.Context, cfg ResticConfig, opts CheckOptions) (*CheckResult, error)
CheckWithOptions runs a repository integrity check with configurable options.
func (*Restic) Copy ¶
func (r *Restic) Copy(ctx context.Context, sourceCfg, targetCfg ResticConfig, snapshotID string) error
Copy copies a snapshot from one repository to another.
func (*Restic) Diff ¶
func (r *Restic) Diff(ctx context.Context, cfg ResticConfig, snapshotID1, snapshotID2 string) (*DiffResult, error)
Diff compares two snapshots and returns the differences.
func (*Restic) DiffFile ¶
func (r *Restic) DiffFile(ctx context.Context, cfg ResticConfig, snapshotID1, snapshotID2, filePath string) (*FileDiffResult, error)
DiffFile extracts a file from two snapshots and generates a diff.
func (*Restic) DryRun ¶
func (r *Restic) DryRun(ctx context.Context, cfg ResticConfig, paths, excludes []string) (*DryRunResult, error)
DryRun performs a dry run backup operation to preview what would be backed up.
func (*Restic) FindFileInSnapshots ¶
func (r *Restic) FindFileInSnapshots(ctx context.Context, cfg ResticConfig, pathPrefix string) ([]FileVersion, error)
FindFileInSnapshots searches for files matching a path pattern across all snapshots. This is useful for discovering files when the exact path is not known.
func (*Restic) Forget ¶
func (r *Restic) Forget(ctx context.Context, cfg ResticConfig, retention *models.RetentionPolicy) (*ForgetResult, error)
Forget removes old snapshots according to the retention policy and returns stats.
func (*Restic) GetExtendedStats ¶
func (r *Restic) GetExtendedStats(ctx context.Context, cfg ResticConfig) (*ExtendedRepoStats, error)
GetExtendedStats collects comprehensive repository statistics including dedup metrics.
func (*Restic) GetFileFromSnapshot ¶
func (r *Restic) GetFileFromSnapshot(ctx context.Context, cfg ResticConfig, snapshotID, filePath string) ([]byte, error)
GetFileFromSnapshot extracts a file from a snapshot and returns its content.
func (*Restic) GetFileHistory ¶
func (r *Restic) GetFileHistory(ctx context.Context, cfg ResticConfig, filePath string) (*FileHistory, error)
GetFileHistory queries restic for all snapshots containing a specific file and returns the file's metadata from each snapshot.
func (*Restic) Init ¶
func (r *Restic) Init(ctx context.Context, cfg ResticConfig) error
Init initializes a new Restic repository.
func (*Restic) ListFiles ¶
func (r *Restic) ListFiles(ctx context.Context, cfg ResticConfig, snapshotID, pathPrefix string) ([]SnapshotFile, error)
ListFiles lists files in a snapshot, optionally filtered by path prefix.
func (*Restic) PartialRestore ¶
func (r *Restic) PartialRestore(ctx context.Context, cfg ResticConfig, opts PartialRestoreOptions) (*PartialRestoreResult, error)
PartialRestore performs a partial restore of specific paths from a snapshot.
func (*Restic) PreviewPartialRestore ¶
func (r *Restic) PreviewPartialRestore(ctx context.Context, cfg ResticConfig, snapshotID string, paths []string, targetPath string) (*RestorePreview, error)
PreviewPartialRestore generates a preview of what would be restored in a partial restore.
func (*Restic) Prune ¶
func (r *Restic) Prune(ctx context.Context, cfg ResticConfig, retention *models.RetentionPolicy) (*ForgetResult, error)
Prune removes old snapshots according to the retention policy and prunes unused data.
func (*Restic) Restore ¶
func (r *Restic) Restore(ctx context.Context, cfg ResticConfig, snapshotID string, opts RestoreOptions) error
Restore restores a snapshot to the given target path.
func (*Restic) RestoreFileVersion ¶
func (r *Restic) RestoreFileVersion(ctx context.Context, cfg ResticConfig, snapshotID, filePath, targetPath string) error
RestoreFileVersion restores a specific file version from a snapshot.
func (*Restic) RestorePreviewResult ¶
func (r *Restic) RestorePreviewResult(ctx context.Context, cfg ResticConfig, snapshotID string, opts RestoreOptions) (*RestorePreview, error)
RestorePreviewResult returns a preview of what would be restored. This uses restic's --dry-run flag combined with file listing to generate a preview.
func (*Restic) SearchFiles ¶
func (r *Restic) SearchFiles(ctx context.Context, cfg ResticConfig, filter FileSearchFilter) (*FileSearchResponse, error)
SearchFiles searches for files matching a pattern across all snapshots using restic find.
func (*Restic) StatsWithRawData ¶
func (r *Restic) StatsWithRawData(ctx context.Context, cfg ResticConfig) (*RawStatsMode, error)
StatsWithRawData runs restic stats with --mode raw-data to get actual storage used.
func (*Restic) StatsWithRestoreSize ¶
func (r *Restic) StatsWithRestoreSize(ctx context.Context, cfg ResticConfig) (*RawStatsMode, error)
StatsWithRestoreSize runs restic stats with --mode restore-size to get original data size.
type ResticConfig ¶
type ResticConfig = backends.ResticConfig
ResticConfig is an alias to backends.ResticConfig for backwards compatibility.
type RestoreOptions ¶
type RestoreOptions struct {
TargetPath string // Destination path for restore
Include []string // Paths to include (empty = all)
Exclude []string // Paths to exclude
DryRun bool // If true, only preview what would be restored
}
RestoreOptions configures a restore operation.
type RestorePreview ¶
type RestorePreview struct {
SnapshotID string `json:"snapshot_id"`
TargetPath string `json:"target_path"`
TotalFiles int `json:"total_files"`
TotalDirs int `json:"total_dirs"`
TotalSize int64 `json:"total_size"`
ConflictCount int `json:"conflict_count"`
Files []RestorePreviewFile `json:"files"`
}
RestorePreview contains the preview results from a dry-run restore.
type RestorePreviewFile ¶
type RestorePreviewFile struct {
Path string `json:"path"`
Type string `json:"type"` // "file" or "dir"
Size int64 `json:"size"`
ModTime time.Time `json:"mtime"`
Mode uint32 `json:"mode"`
HasConflict bool `json:"has_conflict,omitempty"` // True if file exists at target
}
RestorePreviewFile represents a file that would be restored.
type ResumeDecision ¶
type ResumeDecision string
ResumeDecision represents the user's choice for handling an incomplete backup.
const ( // ResumeDecisionResume indicates the user wants to resume the interrupted backup. ResumeDecisionResume ResumeDecision = "resume" // ResumeDecisionRestart indicates the user wants to restart the backup from scratch. ResumeDecisionRestart ResumeDecision = "restart" // ResumeDecisionSkip indicates the user wants to skip the backup for now. ResumeDecisionSkip ResumeDecision = "skip" )
type ResumeInfo ¶
type ResumeInfo struct {
Checkpoint *models.BackupCheckpoint
ProgressPercent *float64
FilesProcessed int64
BytesProcessed int64
TotalFiles *int64
TotalBytes *int64
InterruptedAt time.Time
InterruptedError string
ResumeCount int
CanResume bool
}
ResumeInfo contains information about a resumable backup.
type RetentionEnforcer ¶
type RetentionEnforcer struct {
// contains filtered or unexported fields
}
RetentionEnforcer applies retention policies after successful backups.
func NewRetentionEnforcer ¶
func NewRetentionEnforcer(restic *Restic, logger zerolog.Logger) *RetentionEnforcer
NewRetentionEnforcer creates a new RetentionEnforcer.
func (*RetentionEnforcer) ApplyPolicy ¶
func (r *RetentionEnforcer) ApplyPolicy(ctx context.Context, cfg ResticConfig, policy *models.RetentionPolicy, prune bool) (*RetentionResult, error)
ApplyPolicy enforces the retention policy on a repository after a successful backup. It removes old snapshots according to the policy and optionally prunes unreferenced data.
type RetentionResult ¶
type RetentionResult struct {
Applied bool `json:"applied"`
SnapshotsRemoved int `json:"snapshots_removed"`
SnapshotsKept int `json:"snapshots_kept"`
RemovedIDs []string `json:"removed_ids,omitempty"`
Error string `json:"error,omitempty"`
}
RetentionResult contains the results of a retention enforcement operation.
type SFTPBackend ¶
type SFTPBackend = backends.SFTPBackend
Type aliases for backwards compatibility.
type ScanResult ¶
type ScanResult struct {
LargeFiles []LargeFile `json:"large_files"`
TotalExcluded int `json:"total_excluded"`
TotalSizeMB int64 `json:"total_size_mb"`
}
ScanResult contains the results of scanning for large files.
type ScheduleStore ¶
type ScheduleStore interface {
// GetEnabledSchedules returns all enabled schedules.
GetEnabledSchedules(ctx context.Context) ([]models.Schedule, error)
// GetRepository returns a repository by ID.
GetRepository(ctx context.Context, id uuid.UUID) (*models.Repository, error)
// CreateBackup creates a new backup record.
CreateBackup(ctx context.Context, backup *models.Backup) error
// UpdateBackup updates an existing backup record.
UpdateBackup(ctx context.Context, backup *models.Backup) error
// GetOrCreateReplicationStatus gets or creates a replication status record.
GetOrCreateReplicationStatus(ctx context.Context, scheduleID, sourceRepoID, targetRepoID uuid.UUID) (*models.ReplicationStatus, error)
// UpdateReplicationStatus updates a replication status record.
UpdateReplicationStatus(ctx context.Context, rs *models.ReplicationStatus) error
// GetAgentByID returns an agent by ID.
GetAgentByID(ctx context.Context, id uuid.UUID) (*models.Agent, error)
// GetEnabledBackupScriptsByScheduleID returns all enabled backup scripts for a schedule.
GetEnabledBackupScriptsByScheduleID(ctx context.Context, scheduleID uuid.UUID) ([]*models.BackupScript, error)
// Checkpoint methods for resumable backups
CheckpointStore
// Validation methods for backup validation
ValidationStore
}
ScheduleStore defines the interface for loading schedule data.
type Scheduler ¶
type Scheduler struct {
// contains filtered or unexported fields
}
Scheduler manages backup schedules using cron.
func NewScheduler ¶
func NewScheduler(store ScheduleStore, restic *Restic, config SchedulerConfig, notifier *notifications.Service, logger zerolog.Logger) *Scheduler
NewScheduler creates a new backup scheduler. The notifier parameter is optional and can be nil if notifications are not needed.
func (*Scheduler) EnableValidation ¶
func (s *Scheduler) EnableValidation(config ValidationConfig)
EnableValidation enables backup validation with the given configuration. This creates a BackupValidator and configures it for the scheduler.
func (*Scheduler) GetActiveSchedules ¶
GetActiveSchedules returns the number of active schedules in the cron scheduler.
func (*Scheduler) GetNextRun ¶
GetNextRun returns the next scheduled run time for a given schedule ID.
func (*Scheduler) SetBackupValidator ¶
func (s *Scheduler) SetBackupValidator(validator *BackupValidator)
SetBackupValidator sets the backup validator for automated validation after backups. This should be called before Start() if backup validation is desired.
func (*Scheduler) SetConcurrencyManager ¶
func (s *Scheduler) SetConcurrencyManager(cm *ConcurrencyManager)
SetConcurrencyManager sets the concurrency manager for backup limits. This should be called before Start() if concurrency limiting is desired.
func (*Scheduler) SetLicenseChecker ¶
func (s *Scheduler) SetLicenseChecker(checker LicenseChecker)
SetLicenseChecker sets the license checker for premium feature gating.
func (*Scheduler) SetMaintenanceService ¶
func (s *Scheduler) SetMaintenanceService(maint *maintenance.Service)
SetMaintenanceService sets the maintenance service for checking maintenance windows. This should be called before Start() if maintenance mode checking is desired.
func (*Scheduler) SetValidationConfig ¶
func (s *Scheduler) SetValidationConfig(config ValidationConfig)
SetValidationConfig sets the validation configuration. This should be called before Start() if custom validation settings are desired.
type SchedulerConfig ¶
type SchedulerConfig struct {
// RefreshInterval is how often to reload schedules from the database.
RefreshInterval time.Duration
// PasswordFunc retrieves the repository password.
PasswordFunc func(repoID uuid.UUID) (string, error)
// DecryptFunc decrypts the repository configuration.
DecryptFunc DecryptFunc
}
SchedulerConfig holds configuration for the backup scheduler.
func DefaultSchedulerConfig ¶
func DefaultSchedulerConfig() SchedulerConfig
DefaultSchedulerConfig returns a SchedulerConfig with sensible defaults.
type Snapshot ¶
type Snapshot struct {
ID string `json:"id"`
ShortID string `json:"short_id"`
Time time.Time `json:"time"`
Hostname string `json:"hostname"`
Username string `json:"username"`
Paths []string `json:"paths"`
Tags []string `json:"tags,omitempty"`
}
Snapshot represents a Restic snapshot.
type SnapshotFile ¶
type SnapshotFile struct {
Name string `json:"name"`
Type string `json:"type"` // "file" or "dir"
Path string `json:"path"`
Size int64 `json:"size"`
Mode uint32 `json:"mode"`
ModTime time.Time `json:"mtime"`
AccessTime time.Time `json:"atime"`
ChangeTime time.Time `json:"ctime"`
}
SnapshotFile represents a file or directory in a snapshot.
type SnapshotFileGroup ¶
type SnapshotFileGroup struct {
SnapshotID string `json:"snapshot_id"`
SnapshotTime time.Time `json:"snapshot_time"`
Hostname string `json:"hostname"`
FileCount int `json:"file_count"`
Files []FileSearchResult `json:"files"`
}
SnapshotFileGroup groups files by snapshot.
type StatsCollector ¶
type StatsCollector struct {
// contains filtered or unexported fields
}
StatsCollector collects repository storage statistics on a schedule.
func NewStatsCollector ¶
func NewStatsCollector(store StatsStore, restic *Restic, config StatsCollectorConfig, logger zerolog.Logger) *StatsCollector
NewStatsCollector creates a new StatsCollector.
func (*StatsCollector) CollectForRepository ¶
CollectForRepository collects stats for a single repository.
func (*StatsCollector) CollectNow ¶
func (c *StatsCollector) CollectNow(ctx context.Context) error
CollectNow triggers an immediate stats collection for all repositories.
func (*StatsCollector) GetNextRun ¶
func (c *StatsCollector) GetNextRun() (time.Time, bool)
GetNextRun returns the next scheduled stats collection time.
func (*StatsCollector) IsRunning ¶
func (c *StatsCollector) IsRunning() bool
IsRunning returns whether the stats collector is currently running.
func (*StatsCollector) Start ¶
func (c *StatsCollector) Start(ctx context.Context) error
Start starts the stats collector scheduler.
func (*StatsCollector) Stop ¶
func (c *StatsCollector) Stop() context.Context
Stop stops the stats collector scheduler.
type StatsCollectorConfig ¶
type StatsCollectorConfig struct {
// CronSchedule is the cron expression for when to collect stats (default: daily at 2am).
CronSchedule string
// PasswordFunc retrieves the repository password.
PasswordFunc func(repoID uuid.UUID) (string, error)
// DecryptFunc decrypts the repository configuration.
DecryptFunc DecryptFunc
}
StatsCollectorConfig holds configuration for the stats collector.
func DefaultStatsCollectorConfig ¶
func DefaultStatsCollectorConfig() StatsCollectorConfig
DefaultStatsCollectorConfig returns a StatsCollectorConfig with sensible defaults.
type StatsStore ¶
type StatsStore interface {
// GetRepositoriesByOrgID returns all repositories for an organization.
GetRepositoriesByOrgID(ctx context.Context, orgID uuid.UUID) ([]*models.Repository, error)
// GetRepositoryByID returns a repository by ID.
GetRepositoryByID(ctx context.Context, id uuid.UUID) (*models.Repository, error)
// CreateStorageStats creates a new storage stats record.
CreateStorageStats(ctx context.Context, stats *models.StorageStats) error
// GetAllOrganizations returns all organizations (for collecting stats across all orgs).
GetAllOrganizations(ctx context.Context) ([]*models.Organization, error)
}
StatsStore defines the interface for storage stats persistence operations.
type TestRestoreConfig ¶
type TestRestoreConfig struct {
// RefreshInterval is how often to reload settings from the database.
RefreshInterval time.Duration
// TempDir is the directory for test restores.
TempDir string
// PasswordFunc retrieves the repository password.
PasswordFunc func(repoID uuid.UUID) (string, error)
// DecryptFunc decrypts the repository configuration.
DecryptFunc DecryptFunc
// Notifier sends alerts on test restore failure (optional).
Notifier TestRestoreNotifier
// AlertAfterConsecutiveFails triggers alerts after this many consecutive failures.
AlertAfterConsecutiveFails int
}
TestRestoreConfig holds configuration for the test restore scheduler.
func DefaultTestRestoreConfig ¶
func DefaultTestRestoreConfig() TestRestoreConfig
DefaultTestRestoreConfig returns a TestRestoreConfig with sensible defaults.
type TestRestoreNotificationService ¶
type TestRestoreNotificationService interface {
NotifyTestRestoreFailed(ctx context.Context, result *models.TestRestoreResult, repo *models.Repository, consecutiveFails int)
}
TestRestoreNotificationService defines the interface for sending test restore notifications.
type TestRestoreNotifier ¶
type TestRestoreNotifier interface {
// NotifyTestRestoreFailed sends an alert about a failed test restore.
NotifyTestRestoreFailed(ctx context.Context, result *models.TestRestoreResult, repo *models.Repository, consecutiveFails int) error
}
TestRestoreNotifier sends alerts when test restores fail.
type TestRestoreNotifierAdapter ¶
type TestRestoreNotifierAdapter struct {
// contains filtered or unexported fields
}
TestRestoreNotifierAdapter adapts the notification service to the TestRestoreNotifier interface.
func NewTestRestoreNotifierAdapter ¶
func NewTestRestoreNotifierAdapter(svc TestRestoreNotificationService) *TestRestoreNotifierAdapter
NewTestRestoreNotifierAdapter creates a new TestRestoreNotifierAdapter.
func (*TestRestoreNotifierAdapter) NotifyTestRestoreFailed ¶
func (n *TestRestoreNotifierAdapter) NotifyTestRestoreFailed(ctx context.Context, result *models.TestRestoreResult, repo *models.Repository, consecutiveFails int) error
NotifyTestRestoreFailed sends an alert about a failed test restore.
type TestRestoreScheduler ¶
type TestRestoreScheduler struct {
// contains filtered or unexported fields
}
TestRestoreScheduler manages automated test restore schedules using cron.
func NewTestRestoreScheduler ¶
func NewTestRestoreScheduler( store TestRestoreStore, restic *Restic, config TestRestoreConfig, logger zerolog.Logger, ) *TestRestoreScheduler
NewTestRestoreScheduler creates a new test restore scheduler.
func (*TestRestoreScheduler) GetNextRun ¶
GetNextRun returns the next scheduled run time for a test restore setting.
func (*TestRestoreScheduler) GetRepositoryTestRestoreStatus ¶
func (trs *TestRestoreScheduler) GetRepositoryTestRestoreStatus(ctx context.Context, repoID uuid.UUID) (*models.TestRestoreStatus, error)
GetRepositoryTestRestoreStatus returns the test restore status for a repository.
func (*TestRestoreScheduler) Reload ¶
func (trs *TestRestoreScheduler) Reload(ctx context.Context) error
Reload reloads all test restore settings from the database.
func (*TestRestoreScheduler) Start ¶
func (trs *TestRestoreScheduler) Start(ctx context.Context) error
Start starts the test restore scheduler and loads initial settings.
func (*TestRestoreScheduler) Stop ¶
func (trs *TestRestoreScheduler) Stop() context.Context
Stop stops the test restore scheduler gracefully.
func (*TestRestoreScheduler) TriggerTestRestore ¶
func (trs *TestRestoreScheduler) TriggerTestRestore(ctx context.Context, repoID uuid.UUID, samplePercentage int) (*models.TestRestoreResult, error)
TriggerTestRestore manually triggers a test restore for the given repository.
type TestRestoreStore ¶
type TestRestoreStore interface {
// GetEnabledTestRestoreSettings returns all enabled test restore settings.
GetEnabledTestRestoreSettings(ctx context.Context) ([]*models.TestRestoreSettings, error)
// GetTestRestoreSettingsByRepoID returns test restore settings for a repository.
GetTestRestoreSettingsByRepoID(ctx context.Context, repoID uuid.UUID) (*models.TestRestoreSettings, error)
// CreateTestRestoreSettings creates new test restore settings.
CreateTestRestoreSettings(ctx context.Context, settings *models.TestRestoreSettings) error
// UpdateTestRestoreSettings updates existing test restore settings.
UpdateTestRestoreSettings(ctx context.Context, settings *models.TestRestoreSettings) error
// DeleteTestRestoreSettings deletes test restore settings.
DeleteTestRestoreSettings(ctx context.Context, id uuid.UUID) error
// GetRepository returns a repository by ID.
GetRepository(ctx context.Context, id uuid.UUID) (*models.Repository, error)
// CreateTestRestoreResult creates a new test restore result record.
CreateTestRestoreResult(ctx context.Context, result *models.TestRestoreResult) error
// UpdateTestRestoreResult updates an existing test restore result record.
UpdateTestRestoreResult(ctx context.Context, result *models.TestRestoreResult) error
// GetTestRestoreResultsByRepoID returns test restore results for a repository.
GetTestRestoreResultsByRepoID(ctx context.Context, repoID uuid.UUID, limit int) ([]*models.TestRestoreResult, error)
// GetLatestTestRestoreResultByRepoID returns the most recent test restore result for a repository.
GetLatestTestRestoreResultByRepoID(ctx context.Context, repoID uuid.UUID) (*models.TestRestoreResult, error)
// GetConsecutiveFailedTestRestores returns the count of consecutive failed test restores.
GetConsecutiveFailedTestRestores(ctx context.Context, repoID uuid.UUID) (int, error)
}
TestRestoreStore defines the interface for test restore persistence operations.
type TieringConfig ¶
type TieringConfig struct {
// ProcessInterval is how often to process tiering rules.
ProcessInterval time.Duration
// ReportInterval is how often to generate cost reports.
ReportInterval time.Duration
// ColdRestoreCheckInterval is how often to check cold restore status.
ColdRestoreCheckInterval time.Duration
// BatchSize is the number of snapshots to process per batch.
BatchSize int
// DryRun skips actual tier transitions (for testing).
DryRun bool
}
TieringConfig holds configuration for the tiering scheduler.
func DefaultTieringConfig ¶
func DefaultTieringConfig() TieringConfig
DefaultTieringConfig returns a TieringConfig with sensible defaults.
type TieringScheduler ¶
type TieringScheduler struct {
// contains filtered or unexported fields
}
TieringScheduler manages automatic storage tier transitions.
func NewTieringScheduler ¶
func NewTieringScheduler(store TieringStore, restic *Restic, config TieringConfig, logger zerolog.Logger) *TieringScheduler
NewTieringScheduler creates a new tiering scheduler.
func (*TieringScheduler) ExpireColdRestoreRequests ¶
func (s *TieringScheduler) ExpireColdRestoreRequests(ctx context.Context)
ExpireColdRestoreRequests marks expired cold restore requests.
func (*TieringScheduler) GenerateCostReports ¶
func (s *TieringScheduler) GenerateCostReports(ctx context.Context)
GenerateCostReports generates cost optimization reports for all organizations.
func (*TieringScheduler) GetRestoreStatus ¶
func (s *TieringScheduler) GetRestoreStatus(ctx context.Context, snapshotID string, repositoryID uuid.UUID) (*models.ColdRestoreRequest, error)
GetRestoreStatus returns the status of a cold restore request.
func (*TieringScheduler) InitializeSnapshotTier ¶
func (s *TieringScheduler) InitializeSnapshotTier(ctx context.Context, snapshotID string, repositoryID, orgID uuid.UUID, sizeBytes int64, snapshotTime time.Time) error
InitializeSnapshotTier creates a tier record for a newly created snapshot.
func (*TieringScheduler) ManualTierChange ¶
func (s *TieringScheduler) ManualTierChange(ctx context.Context, snapshotID string, repositoryID uuid.UUID, toTier models.StorageTierType, reason string) error
ManualTierChange allows manual tier transition for a snapshot.
func (*TieringScheduler) ProcessColdRestoreRequests ¶
func (s *TieringScheduler) ProcessColdRestoreRequests(ctx context.Context)
ProcessColdRestoreRequests processes pending cold/archive restore requests.
func (*TieringScheduler) ProcessTieringRules ¶
func (s *TieringScheduler) ProcessTieringRules(ctx context.Context)
ProcessTieringRules evaluates and applies tier transition rules for all organizations.
func (*TieringScheduler) RequestColdRestore ¶
func (s *TieringScheduler) RequestColdRestore(ctx context.Context, orgID uuid.UUID, snapshotID string, repositoryID, requestedBy uuid.UUID, priority string) (*models.ColdRestoreRequest, error)
RequestColdRestore initiates a restore request for cold/archive data.
func (*TieringScheduler) Start ¶
func (s *TieringScheduler) Start(ctx context.Context) error
Start starts the tiering scheduler.
func (*TieringScheduler) Stop ¶
func (s *TieringScheduler) Stop() context.Context
Stop stops the tiering scheduler gracefully.
func (*TieringScheduler) TriggerCostReport ¶
func (s *TieringScheduler) TriggerCostReport(ctx context.Context)
TriggerCostReport manually triggers cost report generation.
func (*TieringScheduler) TriggerProcessing ¶
func (s *TieringScheduler) TriggerProcessing(ctx context.Context)
TriggerProcessing manually triggers tiering processing (for testing/admin).
type TieringStore ¶
type TieringStore interface {
// Tier configuration
GetStorageTierConfigs(ctx context.Context, orgID uuid.UUID) ([]*models.StorageTierConfig, error)
GetStorageTierConfig(ctx context.Context, id uuid.UUID) (*models.StorageTierConfig, error)
CreateStorageTierConfig(ctx context.Context, config *models.StorageTierConfig) error
UpdateStorageTierConfig(ctx context.Context, config *models.StorageTierConfig) error
CreateDefaultTierConfigs(ctx context.Context, orgID uuid.UUID) error
// Tier rules
GetTierRules(ctx context.Context, orgID uuid.UUID) ([]*models.TierRule, error)
GetTierRule(ctx context.Context, id uuid.UUID) (*models.TierRule, error)
CreateTierRule(ctx context.Context, rule *models.TierRule) error
UpdateTierRule(ctx context.Context, rule *models.TierRule) error
DeleteTierRule(ctx context.Context, id uuid.UUID) error
GetEnabledTierRules(ctx context.Context, orgID uuid.UUID) ([]*models.TierRule, error)
// Snapshot tiers
GetSnapshotTier(ctx context.Context, snapshotID string, repositoryID uuid.UUID) (*models.SnapshotTier, error)
GetSnapshotTierByID(ctx context.Context, id uuid.UUID) (*models.SnapshotTier, error)
CreateSnapshotTier(ctx context.Context, tier *models.SnapshotTier) error
UpdateSnapshotTier(ctx context.Context, tier *models.SnapshotTier) error
GetSnapshotsForTiering(ctx context.Context, orgID uuid.UUID, currentTier models.StorageTierType, olderThanDays int) ([]*models.SnapshotTier, error)
GetSnapshotTiersByRepository(ctx context.Context, repositoryID uuid.UUID) ([]*models.SnapshotTier, error)
GetSnapshotTiersByOrg(ctx context.Context, orgID uuid.UUID) ([]*models.SnapshotTier, error)
// Tier transitions
CreateTierTransition(ctx context.Context, transition *models.TierTransition) error
UpdateTierTransition(ctx context.Context, transition *models.TierTransition) error
GetPendingTierTransitions(ctx context.Context, orgID uuid.UUID) ([]*models.TierTransition, error)
GetTierTransitionHistory(ctx context.Context, snapshotID string, repositoryID uuid.UUID, limit int) ([]*models.TierTransition, error)
// Cold restore requests
CreateColdRestoreRequest(ctx context.Context, request *models.ColdRestoreRequest) error
UpdateColdRestoreRequest(ctx context.Context, request *models.ColdRestoreRequest) error
GetColdRestoreRequest(ctx context.Context, id uuid.UUID) (*models.ColdRestoreRequest, error)
GetColdRestoreRequestBySnapshot(ctx context.Context, snapshotID string, repositoryID uuid.UUID) (*models.ColdRestoreRequest, error)
GetPendingColdRestoreRequests(ctx context.Context, orgID uuid.UUID) ([]*models.ColdRestoreRequest, error)
GetActiveColdRestoreRequests(ctx context.Context, orgID uuid.UUID) ([]*models.ColdRestoreRequest, error)
ExpireColdRestoreRequests(ctx context.Context) (int, error)
// Cost reports
CreateTierCostReport(ctx context.Context, report *models.TierCostReport) error
GetLatestTierCostReport(ctx context.Context, orgID uuid.UUID) (*models.TierCostReport, error)
GetTierCostReports(ctx context.Context, orgID uuid.UUID, limit int) ([]*models.TierCostReport, error)
// Stats
GetTierStatsSummary(ctx context.Context, orgID uuid.UUID) (*models.TierStatsSummary, error)
// Organization helper
GetAllOrganizations(ctx context.Context) ([]*models.Organization, error)
}
TieringStore defines the interface for tiering data operations.
type ValidateBackupResult ¶
type ValidateBackupResult struct {
Validation *models.BackupValidation
Passed bool
AlertSent bool
}
ValidateBackupResult contains the result of a validation operation along with the backup and any alerts that should be sent.
type ValidationConfig ¶
type ValidationConfig struct {
// SpotCheckCount is the number of random files to verify.
SpotCheckCount int
// FileCountErrorMargin is the acceptable percentage difference in file counts.
// For example, 0.01 allows 1% difference.
FileCountErrorMargin float64
// RunIntegrityCheck determines if restic check should run after validation.
RunIntegrityCheck bool
// IntegrityCheckSubset is the subset of data to verify (e.g., "2%").
// Empty string means no data verification.
IntegrityCheckSubset string
}
ValidationConfig holds configuration for backup validation.
func DefaultValidationConfig ¶
func DefaultValidationConfig() ValidationConfig
DefaultValidationConfig returns a ValidationConfig with sensible defaults.
type ValidationNotifier ¶
type ValidationNotifier interface {
// NotifyValidationFailed sends an alert about a failed backup validation.
NotifyValidationFailed(ctx context.Context, v *models.BackupValidation, backup *models.Backup, errMsg string) error
}
ValidationNotifier sends alerts when backup validations fail.
type ValidationStore ¶
type ValidationStore interface {
// CreateBackupValidation creates a new backup validation record.
CreateBackupValidation(ctx context.Context, v *models.BackupValidation) error
// UpdateBackupValidation updates an existing backup validation record.
UpdateBackupValidation(ctx context.Context, v *models.BackupValidation) error
// GetBackupValidationByBackupID returns the validation for a backup.
GetBackupValidationByBackupID(ctx context.Context, backupID uuid.UUID) (*models.BackupValidation, error)
// GetLatestBackupValidationByRepoID returns the most recent validation for a repository.
GetLatestBackupValidationByRepoID(ctx context.Context, repoID uuid.UUID) (*models.BackupValidation, error)
}
ValidationStore defines the interface for validation persistence operations.
type VerificationConfig ¶
type VerificationConfig struct {
// RefreshInterval is how often to reload schedules from the database.
RefreshInterval time.Duration
// TempDir is the directory for test restores.
TempDir string
// PasswordFunc retrieves the repository password.
PasswordFunc func(repoID uuid.UUID) (string, error)
// DecryptFunc decrypts the repository configuration.
DecryptFunc DecryptFunc
// Notifier sends alerts on verification failure (optional).
Notifier VerificationNotifier
// AlertAfterConsecutiveFails triggers alerts after this many consecutive failures.
AlertAfterConsecutiveFails int
}
VerificationConfig holds configuration for the verification scheduler.
func DefaultVerificationConfig ¶
func DefaultVerificationConfig() VerificationConfig
DefaultVerificationConfig returns a VerificationConfig with sensible defaults.
type VerificationNotifier ¶
type VerificationNotifier interface {
// NotifyVerificationFailed sends an alert about a failed verification.
NotifyVerificationFailed(ctx context.Context, v *models.Verification, repo *models.Repository, consecutiveFails int) error
}
VerificationNotifier sends alerts when verifications fail.
type VerificationScheduler ¶
type VerificationScheduler struct {
// contains filtered or unexported fields
}
VerificationScheduler manages verification schedules using cron.
func NewVerificationScheduler ¶
func NewVerificationScheduler( store VerificationStore, restic *Restic, config VerificationConfig, logger zerolog.Logger, ) *VerificationScheduler
NewVerificationScheduler creates a new verification scheduler.
func (*VerificationScheduler) GetNextRun ¶
GetNextRun returns the next scheduled run time for a verification schedule.
func (*VerificationScheduler) GetRepositoryVerificationStatus ¶
func (vs *VerificationScheduler) GetRepositoryVerificationStatus(ctx context.Context, repoID uuid.UUID) (*models.RepositoryVerificationStatus, error)
GetRepositoryVerificationStatus returns the verification status for a repository.
func (*VerificationScheduler) Reload ¶
func (vs *VerificationScheduler) Reload(ctx context.Context) error
Reload reloads all verification schedules from the database.
func (*VerificationScheduler) Start ¶
func (vs *VerificationScheduler) Start(ctx context.Context) error
Start starts the verification scheduler and loads initial schedules.
func (*VerificationScheduler) Stop ¶
func (vs *VerificationScheduler) Stop() context.Context
Stop stops the verification scheduler gracefully.
func (*VerificationScheduler) TriggerVerification ¶
func (vs *VerificationScheduler) TriggerVerification(ctx context.Context, repoID uuid.UUID, verType models.VerificationType) (*models.Verification, error)
TriggerVerification manually triggers a verification for the given repository.
type VerificationStore ¶
type VerificationStore interface {
// GetEnabledVerificationSchedules returns all enabled verification schedules.
GetEnabledVerificationSchedules(ctx context.Context) ([]*models.VerificationSchedule, error)
// GetVerificationSchedulesByRepoID returns verification schedules for a repository.
GetVerificationSchedulesByRepoID(ctx context.Context, repoID uuid.UUID) ([]*models.VerificationSchedule, error)
// GetRepository returns a repository by ID.
GetRepository(ctx context.Context, id uuid.UUID) (*models.Repository, error)
// CreateVerification creates a new verification record.
CreateVerification(ctx context.Context, v *models.Verification) error
// UpdateVerification updates an existing verification record.
UpdateVerification(ctx context.Context, v *models.Verification) error
// GetLatestVerificationByRepoID returns the most recent verification for a repository.
GetLatestVerificationByRepoID(ctx context.Context, repoID uuid.UUID) (*models.Verification, error)
// GetConsecutiveFailedVerifications returns the count of consecutive failed verifications.
GetConsecutiveFailedVerifications(ctx context.Context, repoID uuid.UUID) (int, error)
}
VerificationStore defines the interface for verification persistence operations.
Source Files
¶
- cloud_restore.go
- compare.go
- concurrency.go
- cross_restore.go
- diff.go
- filehistory.go
- filesearch.go
- geo.go
- immutability.go
- import.go
- largefile_scanner.go
- mount.go
- network_drives.go
- partial_restore.go
- restic.go
- resume.go
- retention.go
- scheduler.go
- scheduler_drtest.go
- stats.go
- stats_collector.go
- storage.go
- test_backup.go
- test_restore.go
- test_restore_notifier.go
- tiering.go
- verification.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package apps provides application-specific backup implementations.
|
Package apps provides application-specific backup implementations. |
|
Package backends provides storage backend implementations for Restic backups.
|
Package backends provides storage backend implementations for Restic backups. |
|
Package databases provides database-specific backup implementations.
|
Package databases provides database-specific backup implementations. |
|
Package docker provides Docker Compose stack backup and restore functionality.
|
Package docker provides Docker Compose stack backup and restore functionality. |
|
Package vms provides VM backup functionality for various hypervisors.
|
Package vms provides VM backup functionality for various hypervisors. |