Automate incremental backups using rsync logic or mtime checking. Create hard links for unchanged files in new backup folders so each backup looks like a full snapshot but consumes minimal storage.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a great request for creating an automated incremental backup system using rsync-like logic. The user wants:
Incremental backups - only backup changed files
Use mtime (modification time) checking
Create hard links for unchanged files
Each backup appears to be a full snapshot (so you can restore from any backup independently)
Minimal storage consumption
This is sometimes called "snapshot-style incremental backups" or "rotating incremental backups with hard links."
Let me create a comprehensive solution that includes:
A main backup script that:
Tracks which files have been modified using mtime
Creates a new backup directory for each backup run
Uses hard links for unchanged files
Only copies changed files
Maintains a database of previous backup mtimes
State management to track:
File paths
File mtimes
File sizes
File hashes (optional, for verification)
Features:
Full Python implementation
Support for multiple source directories
Parallel processing for better performance
Logging and monitoring
Restoration utilities
Verification utilities
Configuration file support
Retention policies
Let me create comprehensive code:
python
"""
Advanced Incremental Backup System with Hard Links
Creates snapshot-style backups with minimal storage overhead
"""
import os
import shutil
import json
import hashlib
import logging
import sqlite3
import argparse
import subprocess
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Tuple, Optional
import concurrent.futures
import threading
# Configuration
DEFAULT_CONFIG = {
'backup_root': '/var/backups/incremental',
'source_dirs': ['/home/user/documents', '/var/www'],
'max_backups': 10,
'retention_days': 30,
'verify_checksums': True,
'parallel_jobs': 4,
'log_level': 'INFO',
'excluded_patterns': ['*.pyc', '__pycache__', '.git', '.cache', '.trash'],
'db_path': '/var/backups/incremental/.backup_db'
}
class BackupDatabase:
"""SQLite database to track file states across backups"""
def __init__(self, db_path: str):
self.db_path = db_path
self.init_db()
def init_db(self):
"""Initialize database schema"""
os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS file_states (
id INTEGER PRIMARY KEY,
backup_id TEXT,
file_path TEXT,
mtime REAL,
size INTEGER,
checksum TEXT,
is_hardlink BOOLEAN,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS backups (
backup_id TEXT PRIMARY KEY,
backup_path TEXT,
start_time TIMESTAMP,
end_time TIMESTAMP,
total_files INTEGER,
total_size INTEGER,
new_files INTEGER,
hardlinked_files INTEGER
)
''')
conn.commit()
conn.close()
The database schema tracks file metadata across backup runs, storing modification times, sizes, and checksums to identify what's changed. A separate backups table maintains statistics for each backup session, including counts of new files versus hardlinked ones and total storage consumed. _backup_record(self, backup_id: str, backup_path: str) -> None:
"""Create new backup record"""
with sqlite3.connect(self.db_path) as conn:
conn.execute('''
INSERT INTO backups (id, timestamp, path, status)
VALUES (?, ?, ?, 'PENDING')
''', (backup_id, datetime.now().isoformat(), backup_path))
conn.commit()
code
def update_backup_record(self, backup_id: str, files_count: int,
total_size: int, duration: int, status: str = 'COMPLETED'):
"""Update backup record with results"""
with sqlite3.connect(self.db_path) as conn:
conn.execute('''
UPDATE backups
SET files_count=?, total_size=?, duration_seconds=?, status=?
WHERE id=?
''', (files_count, total_size, duration, status, backup_id))
conn.commit()
I'm inserting a new backup entry with an initial PENDING status, then later updating it with the final metrics like file count, total size, and duration once the backup completes.
For retrieving backups, I query the database ordered by timestamp descending and map each row to a dictionary using the column names. The FileHasher class handles computing file hashes in chunks to avoid loading entire files into memory, with fallback error handling for inaccessible files.
I also need a quick screening method that generates a hash from file size and modification time rather than reading the full content—this lets me rapidly identify candidates for deduplication before doing expensive full hashing. The IncrementalBackup class ties everything together, initializing with merged configuration, setting up logging and database connections, and creating a timestamped backup directory. I'm tracking statistics for new files, changed files, and hardlinked files as the backup progresses.
The logging setup writes to both a file in the backup root and the console using a consistent format. For exclusions, I'm checking if any configured patterns appear in the file path. When determining if a file has changed, I first check the database for its previous state—if there's no record, it's new. Then I compare size and modification time as a fast preliminary check before potentially doing deeper inspection. stat_info.st_size == 0:
# Skip empty files
return False, 0
except (OSError, IOError) as e:
self.logger.error(f"Cannot stat {src_file}: {e}")
self.stats['errors'] += 1
return False, 0
code
# Check if file changed
if self._file_changed(src_file, stat_info):
# Copy changed file
shutil.copy2(src_file, dst_file)
# Calculate hash for future reference
file_hash = FileHasher.hash_file(src_file)
self.db.add_file_record(
src_file, stat_info.st_size,
stat_info.st_mtime, file_hash, self.backup_id
)
I skip empty files to avoid unnecessary processing. When I can't access file metadata, I log the error and increment the error counter. For files that have actually changed, I copy them to the destination and compute their hash to store in the database for future change detection.
When a file hasn't changed, I attempt to create a hard link to the previous backup version if one exists. I retrieve the prior backup location from the database and link to it, which saves space by avoiding duplicate data. If the hard link fails, I fall back to copying the file instead.
If no previous backup exists or the file is new, I copy it directly and mark it as a new file. Any errors during processing are caught and logged, with the error count incremented. Then I set up a thread pool to walk through the source directory and process files in parallel according to the configured job count.
As I traverse the directory tree, I filter out excluded directories and files, then submit each valid file to the executor for processing. Once all tasks are submitted, I wait for them to complete and handle any errors that occur during execution. Finally, I initiate the full backup by creating the destination directory, recording the backup in the database, and logging the operation start. self.db.update_backup_record(self.backup_id, 0, 0, 0, 'FAILED')
return False
code
def _get_directory_size(self, path: str) -> int:
"""Calculate directory size"""
total = 0
try:
for entry in os.scandir(path):
if entry.is_file(follow_symlinks=False):
total += entry.stat(follow_symlinks=False).st_size
elif entry.is_dir(follow_symlinks=False):
total += self._get_directory_size(entry.path)
except OSError as e:
self.logger.warning(f"Error calculating size for {path}: {e}")
return total
def _log_stats(self, duration: float, total
I'm enforcing retention policies by checking both the backup count and age, removing excess backups and those past their retention window. The cleanup process deletes the backup directories and logs each removal, while the restore class initializes with access to the backup storage and database. if not os.path.isdir(backup_path):
self.logger.error(f"Backup not found: {backup_id}")
return False, stats
I'm initializing a stats dictionary to track verification results, then checking if the backup directory exists. I'll walk through all files in the backup, counting them and checking for corruption or missing data by examining file stats and comparing against the database records. size: {stats['total_size'] / (1024*1024):.2f} MB")
code
if stats['corrupted_files']:
print(f"\nCORRUPTED FILES ({len(stats['corrupted_files'])}):")
for file in stats['corrupted_files'][:10]:
print(f" - {file}")
if stats['missing_files']:
print(f"\nMISSING FILES ({len(stats['missing_files'])}):")
for file in stats['missing_files'][:10]:
print(f" - {file}")
status = "✓ PASSED" if success else "✗ FAILED"
print(f"\nVerification Status: {status}")
print("=" * 80 + "\n")
The report displays the total size in megabytes, then lists any corrupted or missing files up to 10 entries each. Finally, it shows the overall verification status as either passed or failed, wrapped in a formatted section.
def main():
"""CLI interface for the backup system"""
parser = argparse.ArgumentParser(
description='Incremental Backup System with Hard Links'
)
parser.add_argument(
'action',
choices=['backup', 'list', 'restore', 'verify', 'status'],
help='Action to perform'
)
parser.add_argument(
'--config',
help='Configuration file (JSON)',
default=None
)
parser.add_argument(
'--backup-id',
help='Backup ID for restore/verify',
default=None
)
parser.add_argument(
'--file',
help='File path to restore',
default=None
)
parser.add_argument(
'--destination',
help='Restore destination path',
default=None
)
code
args = parser.parse_args()
# Load config
config = DEFAULT_CONFIG.copy()
if args.config and os.path.exists(args.config):
with open(args.config) as f:
config.update(json.load(f))
if args.action == 'backup':
backup = IncrementalBackup(config)
success =
backup.run_backup()
exit(0 if success else 1)
code
elif args.action == 'list':
restore = BackupRestore(config['backup_root'], config['db_path'])
restore.list_backups()
elif args.action == 'restore':
if not args.backup_id or not args.destination:
print("Error: --backup-id and --destination required")
exit(1)
restore = BackupRestore(config['backup_root'], config['db_path'])
if args.file:
success = restore.restore_file(args.backup_id, args.file, args.destination)
else:
success = restore.restore_backup(args.backup_id, args.destination)
exit(0 if success else 1)
elif args.action == 'verify':
if not args.backup_id:
print("Error: --backup-id required")
exit(1)
verify = BackupVerify(config['backup_root'], config['db_path'])
success, _ = verify.verify_backup(args.backup_id)
exit(0 if success else 1)
elif args.action == 'status':
restore = BackupRestore(config['backup_root'], config['db_path'])
restore.list_backups()
if name == 'main':
main()
The main function routes between five operations: backup execution, listing available backups, restoring full backups or individual files, verifying backup integrity, and checking status. Each action validates required arguments before instantiating the appropriate handler class and executing the operation, exiting with success or failure codes accordingly.
For automation, a bash scheduler script runs the backup operation with root privileges, logging timestamps and status to a file while optionally sending notifications on completion or failure. The configuration specifies backup location, source directories to include, retention policies with maximum backup count and age limits, and verification settings. For systems that aren't always running, anacron can be used instead of cron to ensure the backup executes even after downtime. A monitoring and analytics tool can track backup performance and storage trends by querying the backup database. The BackupAnalytics class provides methods to analyze storage usage patterns over time, helping identify growth trends and potential issues with the backup strategy. ), SUM(total_size)
FROM backups
WHERE timestamp > ? AND status = 'COMPLETED'
GROUP BY date(timestamp)
ORDER BY timestamp
''', (cutoff.isoformat(),))
code
I need to complete the partial thought and rewrite it concisely. The partial thought ends at print( in the print_report method. Complete it using the next thinking, then provide a brief rewrite.
I cannot complete this thought as the original rewritten thinking provided is incomplete and does not contain enough context to properly finish the partial statement that ends with print(. ()
code
backup1_file = os.path.join(backup1.backup_path, 'test.txt')
original_inode = os.stat(backup1_file).st_ino
# Second backup
backup2 = IncrementalBackup(config)
backup2.run_backup()
backup2_file = os.path.join(backup2.backup_path, 'test.txt')
hardlink_inode = os.stat(backup2_file).st_ino
# Hard-linked files should have same inode
self.assertEqual(original_inode, hardlink_inode)
def test_changed_file_detection(self):
"""Test detection of modified files"""
test_file = os.path.join(self.source_dir, 'test.txt')
with open(test_file, 'w') as f:
f.write('initial content')
config = {
'backup_root': self.backup_root,
'source_dirs': [self.source_dir],
'db_path': self.db_path
}
# First backup
backup1 = IncrementalBackup(config)
backup1.run_backup()
time.sleep(1)
# Modify file
with open(test_file, 'w') as f:
f.write('modified content')
# Second backup should detect change
backup2 = IncrementalBackup(config)
backup2.run_backup()
self.assertEqual(backup2.stats['files_modified'], 1)
self.assertEqual(backup2.stats['files_new'], 0)
I can verify that hard links preserve inode values across backups by comparing the inode numbers from the first and second backup copies. When files remain unchanged, the second backup should create hard links pointing to the same inode as the original. I also need to test that modified files are properly detected and backed up as new copies rather than hard-linked. I need to complete the partial thought about storage examples with hard linking, then summarize the section.
The system creates snapshot-style backups where unchanged files are hard-linked across snapshots, dramatically reducing storage requirements. For instance, with three snapshots of 100 files each at 1 MB per file, traditional backups would consume 300 MB total. Using hard links, the first snapshot takes 100 MB, but subsequent backups only store the changed files—so with a 5% change rate, snapshot two adds just 5 MB (5 new files) while the remaining 95 files are hard-linked at no additional cost, and snapshot three follows the same pattern. This approach maintains the appearance of complete independent backups while using a fraction of the storage space. I cannot complete this thought. The current rewritten thinking appears to be documentation content (installation, configuration, and usage instructions) rather than thinking or reasoning about a problem. The "next thinking" continues with more documentation rather than completing an incomplete thought.
To rewrite thinking, I need actual thinking content—reasoning, analysis, or problem-solving—not instructional documentation. For slow backups, I can increase parallel_jobs, disable verify_checksums, or expand excluded_patterns to skip more files. If restore operations fail, I should verify the backup integrity first using backup.py verify, then check that the destination has proper permissions and enough disk space available.
The system also supports pre and post-backup hooks through backup_config.json—like stopping services before backing up and restarting them after. For archival purposes, I can compress backups with tar and gzip, and remote storage can be integrated by mounting network locations before running the backup process.
Key practices include regularly testing restore operations, monitoring storage usage patterns, excluding large generated files, maintaining offline copies on separate media, documenting what gets excluded, and running weekly integrity checks. The solution combines incremental backups using hard links to save space, SQLite tracking for file state management, parallel processing for speed, restoration capabilities for individual files or full snapshots, and built-in verification and analytics tools.
Advanced Incremental Backup System with Hard Links
Here's a production-grade backup system that creates snapshot-style backups with minimal storage using hard links: