python
import os
import time
import hashlib
from pathlib import Path
from concurrent.futures import ProcessPoolExecutor, as_completed
from tqdm import tqdm
import multiprocessing as mp
import shutil
def compute_file_hash(file_path: str, hash_algo: str = 'sha256') -> str:
"""Compute checksum of a file."""
h = hashlib.new(hash_algo)
with open(file_path, 'rb') as f:
while chunk := f.read(4096):
h.update(chunk)
return h.hexdigest()
def throttled_copy(src_path: str, dst_path: str, max_bps: float) -> None:
"""Copy file with runtime bandwidth throttling (approximate per-worker rate)."""
if max_bps <= 0:
shutil.copy2(src_path, dst_path)
return
chunk_size = 1024 * 256 # 256 KB chunks
sleep_interval = chunk_size / max_bps if max_bps > 0 else 0
with open(src_path, 'rb') as src_file, open(dst_path, 'wb') as dst_file:
while True:
chunk = src_file.read(chunk_size)
if not chunk:
break
dst_file.write(chunk)
time.sleep(sleep_interval)
def migrate_single_file(task: tuple) -> tuple[bool, str | None]:
"""Worker function: migrate one file with checksum validation."""
src_path, dst_path, expected_hash, _, hash_algo, max_bps = task # size not used here
try:
Path(dst_path).parent.mkdir(parents=True, exist_ok=True)
throttled_copy(src_path, dst_path, max_bps)
actual_hash = compute_file_hash(dst_path, hash_algo)
if actual_hash != expected_hash:
raise RuntimeError(f"Checksum mismatch: {expected_hash} != {actual_hash}")
return True, None
except Exception as e:
Path(dst_path).unlink(missing_ok=True) # Cleanup partial file
return False, str(e)
def merkle_root(leaves: list[str]) -> str:
"""Compute Merkle tree root hash from sorted list of 'path:hash' strings for consistency proof."""
hashes = [h.encode() for h in leaves]
while len(hashes) > 1:
new_hashes = []
for i in range(0, len(hashes), 2):
left = hashes[i]
right = hashes[i + 1] if i + 1 < len(hashes) else left # Pad with duplicate
combined = left + right
new_hashes.append(hashlib.sha256(combined).digest())
hashes = new_hashes
return hashes[0].hex()
class ParallelDataMigrationToolkit:
"""
Parallel data migration toolkit with:
- Parallel file copying using ProcessPoolExecutor
- Per-file checksum validation
- Overall consistency proof via Merkle tree root hash
- Runtime throttling (approximate total BPS distributed across workers)
- Abort triggers (e.g., error rate threshold)
"""
def __init__(
self,
source: str,
dest: str,
num_workers: int = None,
hash_algo: str = 'sha256',
max_bps: float = 0.0, # Total bytes per second (0 = unlimited)
abort_error_rate: float = 0.05 # Abort if error rate exceeds this
):
self.source = Path(source)
self.dest = Path(dest)
self.num_workers = num_workers or mp.cpu_count()
self.hash_algo = hash_algo
self.max_bps = max_bps
self.abort_error_rate = abort_error_rate
self.manifest = {} # {relpath: hash}
self.total_size_gb = 0.0
def prepare(self) -> list[tuple]:
"""Scan source, compute checksum manifest, prepare tasks."""
tasks = []
self.manifest.clear()
total_size = 0
for root, _, filenames in os.walk(self.source):
for filename in filenames:
src_path = Path(root) / filename
rel_path = src_path.relative_to(self.source)
dst_path = self.dest / rel_path
file_hash = compute_file_hash(str(src_path), self.hash_algo)
self.manifest[str(rel_path)] = file_hash
size = src_path.stat().st_size
total_size += size
max_bps_worker = self.max_bps / self.num_workers if self.num_workers > 0 else 0
tasks.append((str(src_path), str(dst_path), file_hash, size, self.hash_algo, max_bps_worker))
self.total_size_gb = total_size / (1024 ** 3)
print(f"Prepared {len(tasks)} files. Total: {self.total_size_gb:.2f} GiB")
return tasks
def migrate(self) -> dict:
"""Execute parallel migration with throttling and abort triggers."""
tasks = self.prepare()
if not tasks:
return {"success": True, "errors": 0, "aborted": False}
errors = 0
total = 0
with ProcessPoolExecutor(max_workers=self.num_workers) as executor:
future_to_task = {
executor.submit(migrate_single_file, task): task for task in tasks
}
for future in tqdm(
as_completed(future_to_task), total=len(tasks), desc="Migrating files"
):
success, error_msg = future.result()
total += 1
if not success:
errors += 1
if error_msg:
print(f"Error: {error_msg[:100]}...")
error_rate = errors / total
if error_rate > self.abort_error_rate:
print(
f"\n🚨 Abort triggered! Error rate {error_rate:.2%} > {self.abort_error_rate:.2%}"
)
executor.shutdown(wait=False)
remaining = len(tasks) - total
return {
"success": False,
"errors": errors,
"total": total,
"remaining": remaining,
"aborted": True,
"error_rate": error_rate,
}
success = errors == 0
print(f"✅ Migration complete. Errors: {errors}/{total} ({errors/total:.2%})")
return {
"success": success,
"errors": errors,
"total": total,
"aborted": False,
}
def prove_consistency(self) -> tuple[bool, str, str]:
"""Final consistency proof: compare Merkle roots and file sets."""
if not self.manifest:
raise ValueError("Run prepare() or migrate() first")
src_leaves = sorted(f"{path}:{h}" for path, h in self.manifest.items())
src_root = merkle_root(src_leaves)
# Compute dest manifest
dest_manifest = {}
for root, _, filenames in os.walk(self.dest):
for filename in filenames:
dst_path = Path(root) / filename
rel_path = dst_path.relative_to(self.dest)
dest_hash = compute_file_hash(str(dst_path), self.hash_algo)
dest_manifest[str(rel_path)] = dest_hash
dest_leaves = sorted(f"{path}:{h}" for path, h in dest_manifest.items())
dest_root = merkle_root(dest_leaves)
files_match = set(self.manifest) == set(dest_manifest)
roots_match = src_root == dest_root
consistent = files_match and roots_match
print(f"🔍 Source Merkle root: {src_root}")
print(f"🔍 Dest Merkle root: {dest_root}")
print(f"📁 Files match: {files_match}")
return consistent, src_root, dest_root
# Example CLI usage
if __name__ == "__main__":
toolkit = ParallelDataMigrationToolkit(
source="./source_dir", # Replace with your paths
dest="./dest_dir",
num_workers=4,
max_bps=50 * 1024 * 1024, # 50 MB/s total throttle
abort_error_rate=0.01, # Abort >1% errors
hash_algo="sha256",
)
result = toolkit.migrate()
print("Migration result:", result)
if result.get("success"):
consistent, src_root, dest_root = toolkit.prove_consistency()
print(f"Overall consistent: {consistent}")