12 KiB
12 KiB
Backup Module Implementation Summary
Overview
A complete multi-backend backup management system has been successfully implemented as part of the prov-ecosystem. The module provides a unified interface for backup operations across 5 different backend systems with full support for configuration, scheduling, filtering, and dependency management.
Completed Components
1. Core Infrastructure
Error Handling (src/error.rs)
BackupErrorenum with 14 error variantsBackupResult<T>type alias for simplified error handling- Factory methods for common errors
- Support for error conversion from standard Rust types
Type System (src/types.rs)
Snapshot: Backup snapshot metadataBackupReport: Backup operation resultsPruneReport: Retention policy execution resultsCheckReport: Repository verification resultsRepositoryStats: Repository statisticsRestoreOptions: Restore operation configurationBackupStatus: Backup operation statesDependencyInfo: Binary dependency informationInstallGuide&InstallMethod: Installation instructions
Backend Types (src/backend_type.rs)
BackendTypeenum: restic, borg, tar, cpio, rsyncRepositoryTypeenum: local, S3, SFTP, REST, B2InitSystemTypeenum: auto, systemd, launchd, cron, openrc- Type conversion and feature detection methods
2. Backend Implementations
Trait Definition (src/backend.rs)
BackupBackendasync trait with 9 methods:name()/binary_name(): Identificationis_available(): Backend availability checkinstall_guide(): Installation instructionsinfo(): Backend informationinit_repository(): Repository initializationbackup(): Execute backup operationlist_snapshots(): List available snapshotsrestore(): Restore from snapshotprune(): Apply retention policiescheck(): Verify repository integritystats(): Get repository statistics
Restic Backend (src/backends/restic.rs)
- Full async trait implementation
- Incremental, deduplicating backups with encryption
- S3, SFTP, REST, and B2 remote support
- JSON-based snapshot parsing
- Environment variable configuration
- Retention policy application
- Repository integrity checking
BorgBackup Backend (src/backends/borg.rs)
- Complete async trait implementation
- Archive naming with tags and timestamps
- Encryption via repokey
- JSON-lines snapshot parsing
- Compression and deduplication support
- Retention policy application
- Repository checking and statistics
TAR Backend (src/backends/tar.rs)
- Gzip compression support
- Directory-based snapshot storage
- Include/exclude pattern support
- Archive integrity verification
- Statistics collection
- Simple, standard format
CPIO Backend (src/backends/cpio.rs)
- CPIO archive format support
- Find-based file enumeration
- Pattern-based exclusion
- Archive integrity checking
- Portable archive format
- Directory restoration
Rsync Backend (src/backends/rsync.rs)
- Fast incremental file synchronization
- Archive mode with metadata preservation
- Remote and local support
- Exclusion pattern support
- Directory-based snapshots with timestamps
- Retention policy with directory cleanup
- Directory size calculation
3. Configuration System
Configuration (src/config.rs)
BackupConfig: Main configuration with validationRepositoryConfig: Repository settings with env varsBackupTarget: Backup target definitionRetentionPolicy: Flexible retention configurationScheduleConfig: Schedule automation settingsBackupHooks: Pre/post backup hooksNotificationConfig: Notification settings- Multi-format support: TOML, YAML, JSON
- Comprehensive validation
4. Supporting Modules
File Filtering (src/filter.rs)
FileFilterstruct for pattern matching- Glob-to-regex conversion
- Pattern support:
*,**,?,[...] - Include/exclude pattern evaluation
- Comprehensive test coverage
Dependency Checking (src/dependency.rs)
DependencyCheckerfor backend availability- Binary detection in PATH
- Version string extraction
- Installation guide provision
- Per-backend implementation
Schedule Generation (src/schedule.rs)
ScheduleGeneratorfor schedule automation- Systemd timer generation
- Launchd plist generation
- Cron expression support
- OpenRC init script generation
- Cron-to-systemd calendar conversion
- Init system auto-detection
Library Integration (src/lib.rs)
- Unified module organization
- Public API re-exports
- Comprehensive documentation with examples
- Quick start guide
- Configuration format documentation
5. Schemas
KCL Schema (schemas/backup/main.k)
- Type-safe configuration schema
- Enumerations for all option types
- Nested structure definitions
- Complete inline documentation
- Integration-ready format
Main Ecosystem Schema (schemas/main.k)
- Integration with existing ecosystem
backup_configfield inProvEcosystemConfig- Import statements for backup module
6. Documentation
README.md
- Feature overview with comparison table
- Installation instructions
- Quick start guide with examples
- Complete configuration reference
- API documentation
- Usage examples for common tasks
- Performance considerations
- Testing instructions
INTEGRATION.md
- Standalone usage patterns
- CLI tool implementation example
- Provctl integration guide
- Provisioning system integration
- KCL configuration examples
- Automation workflows
- Testing integration patterns
- Monitoring and alerting integration
7. Build Configuration
Cargo.toml
- Workspace integration
- Dependencies: serde, tokio, async-trait, chrono, uuid, regex, glob, which
- Dev dependencies for testing
- Proper metadata and documentation links
Root Workspace (Cargo.toml)
- Added backup crate to members list
- Integrated with workspace dependencies
Architecture Highlights
Design Patterns
- Trait-based abstraction: Common interface for all backends
- Configuration-driven: TOML/YAML/JSON configuration
- Async-first: Full tokio async support
- Error handling: Typed error enum with context
- Type safety: Serde-based serialization with validation
Extensibility
- Easy to add new backends: Implement
BackupBackendtrait - Custom configuration options via
env_varsandoptions - Hook system for pre/post operations
- Pluggable notification system
Multi-Init System Support
- Systemd timers (Linux)
- Launchd agents (macOS)
- Cron scheduling (universal)
- OpenRC init scripts (lightweight Linux)
- Auto-detection based on system
Repository Types Supported
- Local filesystem: Direct path access
- S3: AWS S3 compatibility
- SFTP: Remote SSH access
- REST: Server-based backends
- B2: Backblaze B2 cloud storage
Key Features
- Config-Driven: All settings via TOML/YAML/JSON
- Multi-Backend: 5 different backup systems supported
- Smart Scheduling: Automatic schedule generation for all systems
- Dependency Management: Verify and guide tool installation
- Pattern Matching: Glob-based include/exclude patterns
- Retention Policies: Flexible snapshot preservation
- Hooks: Pre/post backup operations
- Notifications: Customizable alerts
- Repository Checks: Integrity verification
- Statistics: Size and snapshot tracking
- Async Operations: Non-blocking backup operations
- Type-Safe: Leverages Rust's type system
Testing
All modules include test coverage:
- Unit tests for each backend
- Pattern matching tests
- Configuration validation tests
- Type conversion tests
- Schedule generation tests
- Dependency detection tests
Integration Points
With Provctl
- Backup subcommands
- Configuration management
- Repository initialization
- Backup execution
- Status monitoring
With Provisioning System
- KCL configuration support
- Init system integration
- Service management
- Schedule automation
- Environment variable management
Standalone
- Library for custom applications
- Direct async/await usage
- Configuration file management
- Direct backend instantiation
File Structure
crates/backup/
├── Cargo.toml # Package manifest
├── README.md # User documentation
├── INTEGRATION.md # Integration guide
├── IMPLEMENTATION_SUMMARY.md # This file
└── src/
├── lib.rs # Library root
├── error.rs # Error types
├── types.rs # Core types
├── backend.rs # Backend trait
├── backend_type.rs # Type enumerations
├── config.rs # Configuration
├── filter.rs # File filtering
├── dependency.rs # Dependency checking
├── schedule.rs # Schedule generation
└── backends/
├── mod.rs # Backend module
├── restic.rs # Restic implementation
├── borg.rs # BorgBackup implementation
├── tar.rs # TAR implementation
├── cpio.rs # CPIO implementation
└── rsync.rs # Rsync implementation
schemas/
├── main.k # Ecosystem schema
└── backup/
└── main.k # Backup schema
Usage Example
use backup::config::BackupConfig;
use backup::backends::ResticBackend;
use backup::backend::BackupBackend;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Load configuration
let config = BackupConfig::from_toml("backup.toml")?;
config.validate()?;
// Create backend
let backend = ResticBackend::new(None);
// Verify availability
if backend.is_available().await? {
// Initialize repository
backend.init_repository(&config.repository).await?;
// Run backups
for target in config.targets {
let report = backend.backup(&target).await?;
println!("Backed up {} files", report.files_processed);
}
// Apply retention
backend.prune(&config.retention).await?;
// Verify integrity
let check = backend.check().await?;
if check.valid {
println!("Repository is valid");
}
}
Ok(())
}
Configuration Example
version = "1.0"
name = "production-backup"
backend = "restic"
[repository]
type = "s3"
path = "s3://my-bucket/backups"
password_file = "/etc/backup/password"
[[targets]]
name = "database"
paths = ["/var/lib/postgresql"]
excludes = ["pg_wal/*"]
tags = ["production"]
[retention]
keep_daily = 7
keep_weekly = 4
keep_monthly = 12
[schedule]
enabled = true
cron = "0 2 * * *"
init_system = "systemd"
Performance Characteristics
- Restic: Slowest (encryption overhead) but most features
- BorgBackup: Fast with excellent compression
- Rsync: Fastest for incremental transfers
- TAR: Fast for full backups
- CPIO: Portable, moderate performance
Limitations
- TAR/CPIO: No incremental support
- CPIO: Limited metadata preservation
- Rsync: No deduplication
- Schedule generation: Simple patterns only (complex expressions need manual adjustment)
Next Steps for Integration
- Install required backends:
restic,borg,tar,cpio,rsync - Create backup configuration files using provided examples
- Test with dry runs
- Set up scheduling with init system
- Configure monitoring and alerting
- Document recovery procedures
- Test restore procedures regularly
Conclusion
The backup module provides a production-ready, extensible backup management system with:
- 5 different backup backends
- Configuration-driven design
- Full async support
- Comprehensive documentation
- Integration examples
- Type-safe error handling
- Flexible scheduling
- Multi-init system support
It can be used standalone as a library, integrated with Provctl, or integrated into the Provisioning system.