orchestrator

package
v0.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 2, 2026 License: MIT Imports: 48 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrAccessControlApplyNotCommitted = errors.New("access control changes not committed")
View Source
var ErrAgeRecipientSetupAborted = errors.New("encryption setup aborted by user")
View Source
var ErrDecryptAborted = errors.New("decrypt workflow aborted by user")
View Source
var ErrFirewallApplyNotCommitted = errors.New("firewall configuration not committed")
View Source
var ErrHAApplyNotCommitted = errors.New("HA configuration not committed")
View Source
var ErrNetworkApplyNotCommitted = errors.New("network configuration not committed")
View Source
var ErrRestoreAborted = errors.New("restore workflow aborted by user")

Functions

func BackupAgeRecipientFile added in v0.12.5

func BackupAgeRecipientFile(path string) error

BackupAgeRecipientFile backs up an existing AGE recipient file (if present).

func BuildArchiverConfig

func BuildArchiverConfig(
	compressionType types.CompressionType,
	compressionLevel int,
	compressionThreads int,
	compressionMode string,
	dryRun bool,
	encryptArchive bool,
	ageRecipients []age.Recipient,
	excludePatterns []string,
) *backup.ArchiverConfig

BuildArchiverConfig builds a pure ArchiverConfig from the provided inputs.

func CheckSystemRequirements

func CheckSystemRequirements(manifest *backup.Manifest) []string

CheckSystemRequirements checks if the system meets requirements for restore

func CleanupMountGuards added in v0.13.0

func CleanupMountGuards(ctx context.Context, logger *logging.Logger, dryRun bool) error

CleanupMountGuards removes ProxSave mount guards created under mountGuardBaseDir.

Safety: this will only unmount guard bind mounts when they are the currently-visible mount on the mountpoint (i.e. the guard is the top-most mount at that mountpoint). If a real mount is stacked on top, the guard will be left in place.

func CleanupOldSafetyBackups

func CleanupOldSafetyBackups(logger *logging.Logger, olderThan time.Duration) error

CleanupOldSafetyBackups removes safety backups older than the specified duration

func ClearRestoreAbortInfo added in v0.12.8

func ClearRestoreAbortInfo()

ClearRestoreAbortInfo clears the stored abort info.

func ConfirmRestoreOperation

func ConfirmRestoreOperation(ctx context.Context, logger *logging.Logger) (bool, error)

ConfirmRestoreOperation asks for user confirmation before proceeding

func ConfirmRestoreOperationWithReader added in v0.13.0

func ConfirmRestoreOperationWithReader(ctx context.Context, reader *bufio.Reader, logger *logging.Logger) (bool, error)

func DedupeRecipientStrings added in v0.12.5

func DedupeRecipientStrings(values []string) []string

DedupeRecipientStrings removes empty values and duplicates from recipient strings.

func DeriveDeterministicRecipientFromPassphrase

func DeriveDeterministicRecipientFromPassphrase(passphrase string) (string, error)

DeriveDeterministicRecipientFromPassphrase derives an AGE recipient from a passphrase (exported for TUI wizard)

func GetSelectedPaths

func GetSelectedPaths(categories []Category) []string

GetSelectedPaths returns all paths from selected categories

func GetSystemInfo

func GetSystemInfo() map[string]string

GetSystemInfo returns detailed information about the current system

func GetSystemTypeString

func GetSystemTypeString(st SystemType) string

GetSystemTypeString returns a human-readable system type string

func ParseLogCounts

func ParseLogCounts(logPath string, categoryLimit int) (categories []notify.LogCategory, errorCount, warningCount int)

ParseLogCounts parses a log file and returns error/warning counts and categorized issues This is used both during backup completion and notification generation

func PathMatchesCategory

func PathMatchesCategory(filePath string, category Category) bool

PathMatchesCategory checks if a given file path matches any path in a category

func RecreateDatastoreDirectories

func RecreateDatastoreDirectories(logger *logging.Logger) error

RecreateDatastoreDirectories parses datastore.cfg and recreates datastore directories (PBS)

func RecreateDirectoriesFromConfig

func RecreateDirectoriesFromConfig(systemType SystemType, logger *logging.Logger) error

RecreateDirectoriesFromConfig recreates storage/datastore directories based on system type

func RecreateStorageDirectories

func RecreateStorageDirectories(logger *logging.Logger) error

RecreateStorageDirectories parses storage.cfg and recreates storage directories (PVE)

func RestoreSafetyBackup

func RestoreSafetyBackup(logger *logging.Logger, backupPath string, destRoot string) (err error)

RestoreSafetyBackup restores files from a safety backup (for rollback)

func RunDecryptWorkflow

func RunDecryptWorkflow(ctx context.Context, cfg *config.Config, logger *logging.Logger, version string) error

RunDecryptWorkflow is the legacy entrypoint that builds default deps.

func RunDecryptWorkflowTUI

func RunDecryptWorkflowTUI(ctx context.Context, cfg *config.Config, logger *logging.Logger, version, configPath, buildSig string) (err error)

RunDecryptWorkflowTUI runs the decrypt workflow using a TUI flow.

func RunDecryptWorkflowWithDeps

func RunDecryptWorkflowWithDeps(ctx context.Context, deps *Deps, version string) (err error)

RunDecryptWorkflowWithDeps executes the decrypt workflow using injected dependencies.

func RunRestoreWorkflow

func RunRestoreWorkflow(ctx context.Context, cfg *config.Config, logger *logging.Logger, version string) (err error)

func RunRestoreWorkflowTUI

func RunRestoreWorkflowTUI(ctx context.Context, cfg *config.Config, logger *logging.Logger, version, configPath, buildSig string) (err error)

RunRestoreWorkflowTUI runs the restore workflow using a TUI flow.

func ShowRestorePlan

func ShowRestorePlan(logger *logging.Logger, config *SelectiveRestoreConfig)

ShowRestorePlan displays a detailed plan of what will be restored

func SmartMergeFstab added in v0.12.7

func SmartMergeFstab(ctx context.Context, logger *logging.Logger, reader *bufio.Reader, currentFstabPath, backupFstabPath string, dryRun bool) error

SmartMergeFstab is the main entry point for the intelligent fstab restore workflow

func ValidateCompatibility

func ValidateCompatibility(manifest *backup.Manifest) error

ValidateCompatibility checks if a backup is compatible with the current system

func ValidatePassphraseStrength added in v0.12.5

func ValidatePassphraseStrength(passphrase string) error

ValidatePassphraseStrength validates passphrase strength rules used by AGE setup.

func ValidateRecipientString added in v0.12.5

func ValidateRecipientString(value string) error

ValidateRecipientString checks whether a recipient string is supported.

func WriteRecipientFile added in v0.12.5

func WriteRecipientFile(path string, recipients []string) error

WriteRecipientFile persists recipients to disk using the standard format.

Types

type AccessControlApplyNotCommittedError added in v0.13.0

type AccessControlApplyNotCommittedError struct {
	RollbackLog      string
	RollbackMarker   string
	RollbackArmed    bool
	RollbackDeadline time.Time
}

func (*AccessControlApplyNotCommittedError) Error added in v0.13.0

func (*AccessControlApplyNotCommittedError) Unwrap added in v0.13.0

type BackupError

type BackupError struct {
	Phase string         // "collection", "archive", "compression", "verification"
	Err   error          // Underlying error
	Code  types.ExitCode // Specific exit code
}

BackupError represents a backup error with specific phase and exit code

func (*BackupError) Error

func (e *BackupError) Error() string

func (*BackupError) Unwrap

func (e *BackupError) Unwrap() error

type BackupSelectionUI added in v0.13.0

type BackupSelectionUI interface {
	TaskRunner
	ShowMessage(ctx context.Context, title, message string) error
	ShowError(ctx context.Context, title, message string) error
	SelectBackupSource(ctx context.Context, options []decryptPathOption) (decryptPathOption, error)
	SelectBackupCandidate(ctx context.Context, candidates []*decryptCandidate) (*decryptCandidate, error)
}

BackupSelectionUI groups prompts used to pick a backup source and a specific backup.

type BackupStats

type BackupStats struct {
	Hostname                  string
	ProxmoxType               types.ProxmoxType
	ProxmoxVersion            string
	BundleCreated             bool
	Timestamp                 time.Time
	Version                   string
	StartTime                 time.Time
	EndTime                   time.Time
	FilesCollected            int
	FilesFailed               int
	FilesNotFound             int
	DirsCreated               int
	BytesCollected            int64
	ArchiveSize               int64
	UncompressedSize          int64
	CompressedSize            int64
	Duration                  time.Duration
	ArchivePath               string
	RequestedCompression      types.CompressionType
	RequestedCompressionMode  string
	Compression               types.CompressionType
	CompressionLevel          int
	CompressionMode           string
	CompressionThreads        int
	CompressionRatio          float64
	CompressionRatioPercent   float64
	CompressionSavingsPercent float64
	ReportPath                string
	ManifestPath              string
	Checksum                  string
	LocalPath                 string
	SecondaryPath             string
	CloudPath                 string
	LocalStatus               string
	LocalStatusSummary        string // Summary message for early errors
	SecondaryStatus           string
	CloudStatus               string

	// System identification
	ServerID  string
	ServerMAC string

	// Cluster mode (only meaningful for PVE)
	ClusterMode string // "cluster" or "standalone"

	// File counts for notifications
	FilesIncluded int
	FilesMissing  int

	// Storage statistics
	SecondaryEnabled    bool
	LocalBackups        int
	LocalFreeSpace      uint64
	LocalTotalSpace     uint64
	SecondaryBackups    int
	SecondaryFreeSpace  uint64
	SecondaryTotalSpace uint64
	CloudEnabled        bool
	CloudBackups        int
	MaxLocalBackups     int
	MaxSecondaryBackups int
	MaxCloudBackups     int

	// Retention policy info (for notifications)
	LocalRetentionPolicy       string
	LocalGFSDaily              int
	LocalGFSWeekly             int
	LocalGFSMonthly            int
	LocalGFSYearly             int
	LocalGFSCurrentDaily       int
	LocalGFSCurrentWeekly      int
	LocalGFSCurrentMonthly     int
	LocalGFSCurrentYearly      int
	SecondaryRetentionPolicy   string
	SecondaryGFSDaily          int
	SecondaryGFSWeekly         int
	SecondaryGFSMonthly        int
	SecondaryGFSYearly         int
	SecondaryGFSCurrentDaily   int
	SecondaryGFSCurrentWeekly  int
	SecondaryGFSCurrentMonthly int
	SecondaryGFSCurrentYearly  int
	CloudRetentionPolicy       string
	CloudGFSDaily              int
	CloudGFSWeekly             int
	CloudGFSMonthly            int
	CloudGFSYearly             int
	CloudGFSCurrentDaily       int
	CloudGFSCurrentWeekly      int
	CloudGFSCurrentMonthly     int
	CloudGFSCurrentYearly      int

	// Error/warning counts
	ErrorCount   int
	WarningCount int
	LogFilePath  string

	// Exit code
	ExitCode       int
	ScriptVersion  string
	TelegramStatus string
	EmailStatus    string

	// Version update information
	NewVersionAvailable bool
	CurrentVersion      string
	LatestVersion       string
}

BackupStats contains statistics from backup operations

func InitializeBackupStats

func InitializeBackupStats(
	hostname string,
	pType types.ProxmoxType,
	proxmoxVersion string,
	version string,
	startTime time.Time,
	cfg *config.Config,
	compressionType types.CompressionType,
	compressionMode string,
	compressionLevel int,
	compressionThreads int,
	backupPath string,
	serverID, serverMAC string,
) *BackupStats

InitializeBackupStats builds the initial BackupStats snapshot without side effects.

type Category

type Category struct {
	ID          string       // Unique identifier
	Name        string       // Display name
	Description string       // User-friendly description
	Type        CategoryType // PVE, PBS, or Common
	Paths       []string     // File/directory paths in the archive
	IsAvailable bool         // Whether this category is present in the backup
	ExportOnly  bool         // If true, never restored directly to system paths
}

Category represents a backup category with its metadata

func AnalyzeArchivePaths

func AnalyzeArchivePaths(archivePaths []string, allCategories []Category) []Category

AnalyzeArchivePaths determines available categories from the provided archive entries.

func AnalyzeBackupCategories

func AnalyzeBackupCategories(archivePath string, logger *logging.Logger) (categories []Category, err error)

AnalyzeBackupCategories detects which categories are available in the backup

func GetAllCategories

func GetAllCategories() []Category

GetAllCategories returns all available categories

func GetBaseModeCategories

func GetBaseModeCategories() []Category

GetBaseModeCategories returns categories for system base mode

func GetCategoriesForMode

func GetCategoriesForMode(mode RestoreMode, systemType SystemType, availableCategories []Category) []Category

GetCategoriesForMode returns categories based on the selected restore mode

func GetCategoriesForSystem

func GetCategoriesForSystem(systemType string) []Category

GetCategoriesForSystem returns categories appropriate for the system type

func GetCategoryByID

func GetCategoryByID(id string, categories []Category) *Category

GetCategoryByID finds a category by its ID

func GetCommonCategories

func GetCommonCategories() []Category

GetCommonCategories returns categories common to both PVE and PBS

func GetPBSCategories

func GetPBSCategories() []Category

GetPBSCategories returns only PBS-specific categories

func GetPVECategories

func GetPVECategories() []Category

GetPVECategories returns only PVE-specific categories

func GetStorageModeCategories

func GetStorageModeCategories(systemType string) []Category

GetStorageModeCategories returns categories for storage/datastore mode

func ShowCategorySelectionMenu

func ShowCategorySelectionMenu(ctx context.Context, logger *logging.Logger, availableCategories []Category, systemType SystemType) ([]Category, error)

ShowCategorySelectionMenu displays an interactive category selection menu

func ShowCategorySelectionMenuWithReader added in v0.13.0

func ShowCategorySelectionMenuWithReader(ctx context.Context, reader *bufio.Reader, logger *logging.Logger, availableCategories []Category, systemType SystemType) ([]Category, error)

type CategoryType

type CategoryType string

CategoryType represents the type of category

const (
	CategoryTypePVE    CategoryType = "pve"
	CategoryTypePBS    CategoryType = "pbs"
	CategoryTypeCommon CategoryType = "common"
)

type ClusterRestoreMode added in v0.13.0

type ClusterRestoreMode int
const (
	ClusterRestoreAbort ClusterRestoreMode = iota
	ClusterRestoreSafe
	ClusterRestoreRecovery
)

type CommandRunner

type CommandRunner interface {
	Run(ctx context.Context, name string, args ...string) ([]byte, error)
}

CommandRunner executes system commands (non-bash scripts).

type DecryptWorkflowUI added in v0.13.0

type DecryptWorkflowUI interface {
	BackupSelectionUI
	PromptDestinationDir(ctx context.Context, defaultDir string) (string, error)
	ResolveExistingPath(ctx context.Context, path, description, failure string) (ExistingPathDecision, string, error)
	PromptDecryptSecret(ctx context.Context, displayName, previousError string) (string, error)
}

DecryptWorkflowUI groups prompts used by the decrypt workflow.

type Deps

type Deps struct {
	Logger   *logging.Logger
	Config   *config.Config
	DryRun   bool
	FS       FS
	Prompter Prompter
	System   SystemDetector
	Time     TimeProvider
	Command  CommandRunner
}

Deps groups optional orchestrator dependencies.

type EarlyErrorState

type EarlyErrorState struct {
	Phase     string         // e.g., "config", "security", "encryption", "storage_init"
	Error     error          // The actual error that occurred
	ExitCode  types.ExitCode // Exit code to return
	Timestamp time.Time      // When the error occurred
}

EarlyErrorState represents an error that occurred before the backup started This is used to send notifications for initialization/configuration errors

func (*EarlyErrorState) HasError

func (e *EarlyErrorState) HasError() bool

HasError returns true if an error has been recorded

type ExistingPathDecision added in v0.13.0

type ExistingPathDecision int
const (
	PathDecisionOverwrite ExistingPathDecision = iota
	PathDecisionNewPath
	PathDecisionCancel
)

type FS

type FS interface {
	Stat(path string) (os.FileInfo, error)
	ReadFile(path string) ([]byte, error)
	Open(path string) (*os.File, error)
	OpenFile(path string, flag int, perm fs.FileMode) (*os.File, error)
	Create(name string) (*os.File, error)
	WriteFile(path string, data []byte, perm fs.FileMode) error
	MkdirAll(path string, perm fs.FileMode) error
	Remove(path string) error
	RemoveAll(path string) error
	ReadDir(path string) ([]os.DirEntry, error)
	Link(oldname, newname string) error
	Symlink(oldname, newname string) error
	Readlink(path string) (string, error)
	CreateTemp(dir, pattern string) (*os.File, error)
	MkdirTemp(dir, pattern string) (string, error)
	Rename(oldpath, newpath string) error
}

FS abstracts filesystem operations to simplify testing.

type FirewallApplyNotCommittedError added in v0.13.0

type FirewallApplyNotCommittedError struct {
	RollbackLog      string
	RollbackMarker   string
	RollbackArmed    bool
	RollbackDeadline time.Time
}

func (*FirewallApplyNotCommittedError) Error added in v0.13.0

func (*FirewallApplyNotCommittedError) Unwrap added in v0.13.0

type FstabAnalysisResult added in v0.12.7

type FstabAnalysisResult struct {
	RootComparable    bool
	RootMatch         bool
	RootDeviceCurrent string
	RootDeviceBackup  string
	SwapComparable    bool
	SwapMatch         bool
	SwapDeviceCurrent string
	SwapDeviceBackup  string
	ProposedMounts    []FstabEntry
	SkippedMounts     []FstabEntry
}

FstabAnalysisResult holds the outcome of comparing two fstabs

type FstabEntry added in v0.12.7

type FstabEntry struct {
	Device     string
	MountPoint string
	Type       string
	Options    string
	Dump       string
	Pass       string
	RawLine    string // Preserves original formatting if needed, though we might reconstruct
	IsComment  bool
}

FstabEntry represents a single non-comment line in /etc/fstab

type HAApplyNotCommittedError added in v0.13.0

type HAApplyNotCommittedError struct {
	RollbackLog      string
	RollbackMarker   string
	RollbackArmed    bool
	RollbackDeadline time.Time
}

func (*HAApplyNotCommittedError) Error added in v0.13.0

func (e *HAApplyNotCommittedError) Error() string

func (*HAApplyNotCommittedError) Unwrap added in v0.13.0

func (e *HAApplyNotCommittedError) Unwrap() error

type NetworkApplyNotCommittedError added in v0.12.7

type NetworkApplyNotCommittedError struct {
	RollbackLog      string
	RollbackMarker   string
	RestoredIP       string
	OriginalIP       string // IP from backup file (will be restored by rollback)
	RollbackArmed    bool
	RollbackDeadline time.Time // when rollback will execute
}

func (*NetworkApplyNotCommittedError) Error added in v0.12.7

func (*NetworkApplyNotCommittedError) Unwrap added in v0.12.7

type NotificationAdapter

type NotificationAdapter struct {
	// contains filtered or unexported fields
}

NotificationAdapter adapts notify.Notifier to NotificationChannel interface

func NewNotificationAdapter

func NewNotificationAdapter(notifier notify.Notifier, logger *logging.Logger) *NotificationAdapter

NewNotificationAdapter creates a new NotificationAdapter

func (*NotificationAdapter) Name added in v0.12.0

func (n *NotificationAdapter) Name() string

func (*NotificationAdapter) Notify

func (n *NotificationAdapter) Notify(ctx context.Context, stats *BackupStats) error

Notify implements the NotificationChannel interface

type NotificationChannel

type NotificationChannel interface {
	Name() string
	Notify(ctx context.Context, stats *BackupStats) error
}

NotificationChannel rappresenta un canale di notifica (es. Telegram, email).

type Orchestrator

type Orchestrator struct {
	// contains filtered or unexported fields
}

Orchestrator coordinates the backup process using Go components

func New

func New(logger *logging.Logger, dryRun bool) *Orchestrator

New creates a new Orchestrator

func NewWithDeps

func NewWithDeps(deps Deps) *Orchestrator

NewWithDeps builds an orchestrator using custom dependencies while preserving defaults.

func (*Orchestrator) DispatchEarlyErrorNotification

func (o *Orchestrator) DispatchEarlyErrorNotification(ctx context.Context, earlyErr *EarlyErrorState) *BackupStats

DispatchEarlyErrorNotification sends notifications for errors that occurred before backup started This creates a minimal BackupStats with error information for notification purposes

func (*Orchestrator) EnsureAgeRecipientsReady

func (o *Orchestrator) EnsureAgeRecipientsReady(ctx context.Context) error

func (*Orchestrator) FinalizeAfterRun

func (o *Orchestrator) FinalizeAfterRun(ctx context.Context, stats *BackupStats)

FinalizeAfterRun dispatches notifications (when applicable) and ensures the log file is closed/copied to the configured destinations. Safe to call multiple times.

func (*Orchestrator) FinalizeAndCloseLog

func (o *Orchestrator) FinalizeAndCloseLog(ctx context.Context)

FinalizeAndCloseLog closes the active log file (if any) and copies it to secondary/cloud storage destinations.

func (*Orchestrator) RegisterNotificationChannel

func (o *Orchestrator) RegisterNotificationChannel(channel NotificationChannel)

RegisterNotificationChannel aggiunge un canale di notifica da eseguire dopo il backup.

func (*Orchestrator) RegisterStorageTarget

func (o *Orchestrator) RegisterStorageTarget(target StorageTarget)

RegisterStorageTarget aggiunge una destinazione da eseguire dopo il backup.

func (*Orchestrator) ReleaseBackupLock

func (o *Orchestrator) ReleaseBackupLock() error

ReleaseBackupLock releases the backup lock file

func (*Orchestrator) RunGoBackup

func (o *Orchestrator) RunGoBackup(ctx context.Context, pType types.ProxmoxType, hostname string) (stats *BackupStats, err error)

RunGoBackup performs the entire backup using Go components (collector + archiver)

func (*Orchestrator) RunPreBackupChecks

func (o *Orchestrator) RunPreBackupChecks(ctx context.Context) error

RunPreBackupChecks performs all pre-backup validation checks

func (*Orchestrator) SaveStatsReport

func (o *Orchestrator) SaveStatsReport(stats *BackupStats) error

SaveStatsReport writes a JSON report with backup statistics to the log directory.

func (*Orchestrator) SetBackupConfig

func (o *Orchestrator) SetBackupConfig(backupPath, logPath string, compression types.CompressionType, level int, threads int, mode string, excludePatterns []string)

SetBackupConfig configures paths and compression for Go-based backup

func (*Orchestrator) SetChecker

func (o *Orchestrator) SetChecker(checker *checks.Checker)

SetChecker sets the pre-backup checker

func (*Orchestrator) SetConfig

func (o *Orchestrator) SetConfig(cfg *config.Config)

SetConfig attaches the loaded configuration to the orchestrator

func (*Orchestrator) SetForceNewAgeRecipient

func (o *Orchestrator) SetForceNewAgeRecipient(force bool)

func (*Orchestrator) SetIdentity

func (o *Orchestrator) SetIdentity(serverID, serverMAC string)

SetIdentity configures server identity information for downstream consumers.

func (*Orchestrator) SetOptimizationConfig

func (o *Orchestrator) SetOptimizationConfig(cfg backup.OptimizationConfig)

SetOptimizationConfig configures optional preprocessing (chunking/dedup/prefilter)

func (*Orchestrator) SetProxmoxVersion

func (o *Orchestrator) SetProxmoxVersion(version string)

func (*Orchestrator) SetStartTime

func (o *Orchestrator) SetStartTime(t time.Time)

SetStartTime injects the timestamp to reuse across logs/backups.

func (*Orchestrator) SetTempDirRegistry

func (o *Orchestrator) SetTempDirRegistry(reg *TempDirRegistry)

SetTempDirRegistry allows callers (main/tests) to inject a custom registry.

func (*Orchestrator) SetUpdateInfo added in v0.11.9

func (o *Orchestrator) SetUpdateInfo(newVersion bool, current, latest string)

SetUpdateInfo records version update information discovered by the CLI layer. This allows the orchestrator to propagate structured update data into BackupStats and, transitively, into notifications/metrics.

func (*Orchestrator) SetVersion

func (o *Orchestrator) SetVersion(version string)

SetVersion sets the current tool version (for metadata reporting)

type ProgressReporter added in v0.13.0

type ProgressReporter func(message string)

ProgressReporter is used by long-running operations (e.g., cloud scans) to provide user-facing progress updates.

type Prompter

type Prompter interface {
	SelectRestoreMode(ctx context.Context, logger *logging.Logger, systemType SystemType) (RestoreMode, error)
	SelectCategories(ctx context.Context, logger *logging.Logger, available []Category, systemType SystemType) ([]Category, error)
	ConfirmRestore(ctx context.Context, logger *logging.Logger) (bool, error)
}

Prompter encapsulates interactive prompts.

type RestoreAbortInfo added in v0.12.8

type RestoreAbortInfo struct {
	NetworkRollbackArmed  bool
	NetworkRollbackLog    string
	NetworkRollbackMarker string
	OriginalIP            string    // IP from backup file (will be restored by rollback)
	CurrentIP             string    // IP after apply (before rollback)
	RollbackDeadline      time.Time // when rollback will execute
}

RestoreAbortInfo contains information about an aborted restore with network rollback.

func GetLastRestoreAbortInfo added in v0.12.8

func GetLastRestoreAbortInfo() *RestoreAbortInfo

GetLastRestoreAbortInfo returns info about the last restore abort, if any.

type RestoreMode

type RestoreMode string

RestoreMode represents the pre-defined restore modes

const (
	RestoreModeFull    RestoreMode = "full"
	RestoreModeStorage RestoreMode = "storage"
	RestoreModeBase    RestoreMode = "base"
	RestoreModeCustom  RestoreMode = "custom"
)

func ShowRestoreModeMenu

func ShowRestoreModeMenu(ctx context.Context, logger *logging.Logger, systemType SystemType) (RestoreMode, error)

ShowRestoreModeMenu displays the restore mode selection menu

func ShowRestoreModeMenuWithReader added in v0.13.0

func ShowRestoreModeMenuWithReader(ctx context.Context, reader *bufio.Reader, logger *logging.Logger, systemType SystemType) (RestoreMode, error)

type RestorePlan

type RestorePlan struct {
	Mode                RestoreMode
	SystemType          SystemType
	NormalCategories    []Category
	StagedCategories    []Category
	ExportCategories    []Category
	ClusterBackup       bool
	ClusterSafeMode     bool
	NeedsClusterRestore bool
	NeedsPBSServices    bool
}

RestorePlan contains a pure, side-effect-free description of a restore run.

func PlanRestore

func PlanRestore(
	manifest *backup.Manifest,
	selectedCategories []Category,
	systemType SystemType,
	mode RestoreMode,
) *RestorePlan

PlanRestore computes the restore plan without performing any I/O or prompts.

func (*RestorePlan) ApplyClusterSafeMode

func (p *RestorePlan) ApplyClusterSafeMode(enable bool)

ApplyClusterSafeMode toggles SAFE cluster handling and recomputes derived fields.

func (*RestorePlan) HasCategoryID added in v0.12.7

func (p *RestorePlan) HasCategoryID(id string) bool

type RestoreWorkflowUI added in v0.13.0

type RestoreWorkflowUI interface {
	BackupSelectionUI

	PromptDecryptSecret(ctx context.Context, displayName, previousError string) (string, error)
	SelectRestoreMode(ctx context.Context, systemType SystemType) (RestoreMode, error)
	SelectCategories(ctx context.Context, available []Category, systemType SystemType) ([]Category, error)

	ShowRestorePlan(ctx context.Context, config *SelectiveRestoreConfig) error
	ConfirmRestore(ctx context.Context) (bool, error)
	ConfirmCompatibility(ctx context.Context, warning error) (bool, error)
	SelectClusterRestoreMode(ctx context.Context) (ClusterRestoreMode, error)
	ConfirmContinueWithoutSafetyBackup(ctx context.Context, cause error) (bool, error)
	ConfirmContinueWithPBSServicesRunning(ctx context.Context) (bool, error)

	ConfirmFstabMerge(ctx context.Context, title, message string, timeout time.Duration, defaultYes bool) (bool, error)

	SelectExportNode(ctx context.Context, exportRoot, currentNode string, exportNodes []string) (string, error)
	ConfirmApplyVMConfigs(ctx context.Context, sourceNode, currentNode string, count int) (bool, error)
	ConfirmApplyStorageCfg(ctx context.Context, storageCfgPath string) (bool, error)
	ConfirmApplyDatacenterCfg(ctx context.Context, datacenterCfgPath string) (bool, error)

	ConfirmAction(ctx context.Context, title, message, yesLabel, noLabel string, timeout time.Duration, defaultYes bool) (bool, error)
	RepairNICNames(ctx context.Context, archivePath string) (*nicRepairResult, error)
	PromptNetworkCommit(ctx context.Context, remaining time.Duration, health networkHealthReport, nicRepair *nicRepairResult, diagnosticsDir string) (bool, error)
}

RestoreWorkflowUI groups prompts used by the restore workflow.

type SafetyBackupResult

type SafetyBackupResult struct {
	BackupPath    string
	FilesBackedUp int
	TotalSize     int64
	Timestamp     time.Time
}

SafetyBackupResult contains information about the safety backup

func CreateFirewallRollbackBackup added in v0.13.0

func CreateFirewallRollbackBackup(logger *logging.Logger, selectedCategories []Category, destRoot string) (*SafetyBackupResult, error)

func CreateHARollbackBackup added in v0.13.0

func CreateHARollbackBackup(logger *logging.Logger, selectedCategories []Category, destRoot string) (*SafetyBackupResult, error)

func CreateNetworkRollbackBackup added in v0.12.7

func CreateNetworkRollbackBackup(logger *logging.Logger, selectedCategories []Category, destRoot string) (*SafetyBackupResult, error)

func CreatePVEAccessControlRollbackBackup added in v0.13.0

func CreatePVEAccessControlRollbackBackup(logger *logging.Logger, selectedCategories []Category, destRoot string) (*SafetyBackupResult, error)

func CreateSafetyBackup

func CreateSafetyBackup(logger *logging.Logger, selectedCategories []Category, destRoot string) (result *SafetyBackupResult, err error)

CreateSafetyBackup creates a backup of files that will be overwritten

type SelectiveRestoreConfig

type SelectiveRestoreConfig struct {
	Mode               RestoreMode
	SelectedCategories []Category
	SystemType         SystemType
	Metadata           *backup.Manifest
}

SelectiveRestoreConfig holds the configuration for selective restore

type StorageAdapter

type StorageAdapter struct {
	// contains filtered or unexported fields
}

StorageAdapter adapts a storage.Storage backend to the StorageTarget interface

func NewStorageAdapter

func NewStorageAdapter(backend storage.Storage, logger *logging.Logger, cfg *config.Config) *StorageAdapter

NewStorageAdapter creates a new storage adapter

func (*StorageAdapter) SetFilesystemInfo

func (s *StorageAdapter) SetFilesystemInfo(info *storage.FilesystemInfo)

SetFilesystemInfo preloads filesystem info detected earlier.

func (*StorageAdapter) SetInitialStats

func (s *StorageAdapter) SetInitialStats(stats *storage.StorageStats)

SetInitialStats caches storage stats gathered during initialization.

func (*StorageAdapter) Sync

func (s *StorageAdapter) Sync(ctx context.Context, stats *BackupStats) error

Sync implements the StorageTarget interface It performs filesystem detection, stores the backup, and applies retention

type StorageTarget

type StorageTarget interface {
	Sync(ctx context.Context, stats *BackupStats) error
}

StorageTarget rappresenta una destinazione esterna (es. storage secondario, cloud).

type SystemDetector

type SystemDetector interface {
	DetectCurrentSystem() SystemType
}

SystemDetector abstracts system-type detection.

type SystemType

type SystemType string

SystemType represents the type of Proxmox system

const (
	SystemTypePVE     SystemType = "pve"
	SystemTypePBS     SystemType = "pbs"
	SystemTypeUnknown SystemType = "unknown"
)

func DetectBackupType

func DetectBackupType(manifest *backup.Manifest) SystemType

DetectBackupType detects the type of backup from manifest

func DetectCurrentSystem

func DetectCurrentSystem() SystemType

DetectCurrentSystem detects the type of the current system (PVE or PBS)

type TaskRunner added in v0.13.0

type TaskRunner interface {
	RunTask(ctx context.Context, title, initialMessage string, run func(ctx context.Context, report ProgressReporter) error) error
}

TaskRunner runs a function while presenting progress feedback to the user (CLI/TUI). Implementations may provide a cancel action that cancels the provided context.

type TempDirRegistry

type TempDirRegistry struct {
	// contains filtered or unexported fields
}

TempDirRegistry tracks temporary directories created by the orchestrator and can remove orphaned directories left behind by crashed processes.

func NewTempDirRegistry

func NewTempDirRegistry(logger *logging.Logger, registryPath string) (*TempDirRegistry, error)

NewTempDirRegistry initializes a registry at the given path.

func (*TempDirRegistry) CleanupOrphaned

func (r *TempDirRegistry) CleanupOrphaned(maxAge time.Duration) (int, error)

CleanupOrphaned removes entries whose processes are gone or directories are too old. Returns the number of directories successfully removed.

func (*TempDirRegistry) Deregister

func (r *TempDirRegistry) Deregister(dir string) error

Deregister removes the directory from the registry.

func (*TempDirRegistry) Register

func (r *TempDirRegistry) Register(dir string) error

Register stores the temporary directory info for later cleanup.

type TimeProvider

type TimeProvider interface {
	Now() time.Time
}

TimeProvider abstracts time acquisition for determinism in tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL