Spaces:
Running
Running
Update super_squash_history
#1
by EnzGamers - opened
11 unmodified lines12131415161718191 unmodified line212223242526272829303132333435361 unmodified line38394041424344451 unmodified line4748495051525354555657585960616263643 unmodified lines686970717273747576777879808182838485868788899091929394959697981 unmodified line10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813917 unmodified lines1571581591601611621631641651661673 unmodified lines1711721731741751766 unmodified lines1831841851861871881894 unmodified lines19419519619719819920020120220320420520626 unmodified lines23323423523623723823911 unmodified linesWORKDIR /app# 3. Create the Python sync script (FIXED: tarball mirrors real FS layout# + marker-based legacy healer + file-level verify)RUN cat > /app/sync.py <<'PY'import osimport shutil1 unmodified lineimport tempfileimport timeimport sysfrom pathlib import Pathfrom huggingface_hub import HfApi, hf_hub_downloadREPO_ID = os.environ.get("DATASET_REPO")TOKEN = os.environ.get("HF_TOKEN")BACKUP_FILE = "/tmp/omniroute_backup.tar.gz"DATA_DIR = Path("/app/data")CONFIG_DIR = Path("/root/.omniroute")def safe_extract(tar, path):"""Extract `tar` into `path`, rejecting members that would escape it."""base = Path(path).resolve()1 unmodified linetarget = (base / member.name).resolve()if not str(target).startswith(str(base)):raise RuntimeError(f"Unsafe tar member: {member.name}")# Python 3.12+ requires the `filter` argument (and we WANT data filter,# which strips leading slashes / .. and refuses absolute paths).if sys.version_info >= (3, 12):tar.extractall(path, filter="data")else:1 unmodified linedef heal_legacy_layout():"""Older backups were packed as `./data/...` and `./.omniroute/...`, which theold code extracted to `/data` and `/.omniroute` instead of `/app/data` and`/root/.omniroute`.IMPORTANT: run.sh `mkdir -p`s both target dirs BEFORE we run, so we cannotjust check `dst.exists()` — the target is always there (empty). We mustcheck the actual *file* the app needs:- /app/data/storage.sqlite (target) vs /data/storage.sqlite (misplaced)- /root/.omniroute/server.env (target) vs /.omniroute/server.env (misplaced)If the misplaced copy exists and the target marker is missing, we swap.If the target is already populated, we REFUSE to clobber it."""plans = [(Path("/data"), "storage.sqlite", Path("/app/data")),(Path("/.omniroute"), "server.env", Path("/root/.omniroute")),3 unmodified linesdst_marker = dst / marker_nameif not src_marker.exists():continue # nothing misplaced for this pairif dst_marker.exists():print(f">>> [Sync] Healer: target {dst_marker} already present, "f"leaving {src} alone (would not clobber real data)",flush=True,)continueprint(f">>> [Sync] Healer: misplaced legacy content at {src}", flush=True)# Target dir exists but is missing its marker -> it must be empty.# Try to remove it so shutil.move produces a clean swap; if it's not# empty (unexpected), bail out instead of nesting src inside dst.if dst.exists():try:dst.rmdir()print(f">>> [Sync] Healer: removed empty target {dst}", flush=True)except OSError:print(f">>> [Sync] Healer: ABORT — {dst} is not empty, "f"refusing to clobber",flush=True,)continuedst.parent.mkdir(parents=True, exist_ok=True)1 unmodified lineprint(f">>> [Sync] Healer: relocated {src} -> {dst}", flush=True)def upload():if not REPO_ID or not TOKEN:print(">>> [Sync] DATASET_REPO or HF_TOKEN not configured. Skipping backup.")returnwith tempfile.TemporaryDirectory() as tmpdir:tmp_path = Path(tmpdir)# Mirror the REAL filesystem layout. After upload, the tar contains:# ./app/data/...# ./root/.omniroute/...# so extracting to "/" puts files back where the app expects them.if DATA_DIR.exists():target = tmp_path / "app" / "data"target.parent.mkdir(parents=True, exist_ok=True)shutil.copytree(DATA_DIR, target)print(f">>> [Sync] Packed {DATA_DIR} -> app/data", flush=True)if CONFIG_DIR.exists():target = tmp_path / "root" / ".omniroute"target.parent.mkdir(parents=True, exist_ok=True)shutil.copytree(CONFIG_DIR, target)print(f">>> [Sync] Packed {CONFIG_DIR} -> root/.omniroute", flush=True)try:with tarfile.open(BACKUP_FILE, "w:gz") as tar:tar.add(str(tmp_path), arcname=".")HfApi(token=TOKEN).upload_file(path_or_fileobj=BACKUP_FILE,path_in_repo="omniroute_backup.tar.gz",repo_id=REPO_ID,repo_type="dataset",)print(f">>> [Sync] Backup successful: {time.strftime('%Y-%m-%d %H:%M:%S')}", flush=True)except Exception as e:print(f">>> [Sync] Backup failed: {e}", flush=True)17 unmodified linesprint(f">>> [Sync] Extracting {len(members)} members to / ...", flush=True)safe_extract(tar, "/")# Self-heal: handle backups created before the path fix.heal_legacy_layout()# Verify the app can actually see the restored files.# Check the REAL files, not just the dirs (mkdir -p makes them lie).critical = [(DATA_DIR, "storage.sqlite"),(CONFIG_DIR, "server.env"),3 unmodified linesstatus = "OK" if marker.exists() else "MISSING"print(f">>> [Sync] Verify {marker}: {status}", flush=True)print(">>> [Sync] Data restore successful.", flush=True)except Exception as e:print(f">>> [Sync] Skipping restore (might be first run): {e}", flush=True)6 unmodified linesdownload()PY# 4. Create the startup shell script (FIXED: don't clobber restored server.env)RUN cat > /app/run.sh <<'SH'#!/bin/shset -e4 unmodified linesecho '=== 1. Restoring Data & Config ==='python3 /app/sync.py downloadecho '=== 2. Starting Scheduled Backup (Every 10 minutes) ==='(while true; do sleep 600; python3 /app/sync.py upload; done) &echo '=== 3. Generating & Persisting Secrets ==='# Only mint fresh secrets if restore didn't bring a server.env with us.# Otherwise we'd rotate JWT_SECRET etc. on every container restart and# invalidate every active session / API key / initial-password.if [ ! -f /root/.omniroute/server.env ]; thenecho '>>> No restored server.env found, generating fresh secrets'export JWT_SECRET="${JWT_SECRET:-$(openssl rand -base64 48 | tr -d '\n')}"26 unmodified linesecho '>>> Restored server.env found, keeping restored secrets'fi# Source whichever server.env we ended up with (restored or freshly minted).set -a. "/root/.omniroute/server.env"set +a11 unmodified lines121314151617181 unmodified line2021222324252627282930313233343536373839404142434445464748495051525354555657581 unmodified line6061626364651 unmodified line6768697071723 unmodified lines76777879808182838485868788899091929394959697981 unmodified line10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917 unmodified lines1871881891901911921931943 unmodified lines1981992002012022032042052062072082092102112122132142152166 unmodified lines2232242252262272282294 unmodified lines23423523623723823924024124224326 unmodified lines27027127227327427511 unmodified linesWORKDIR /app# 3. Create the Python sync script (OPTIMIZED: Hash check + History Squash to save 100GB+)RUN cat > /app/sync.py <<'PY'import osimport shutil1 unmodified lineimport tempfileimport timeimport sysimport hashlibfrom pathlib import Pathfrom huggingface_hub import HfApi, hf_hub_downloadREPO_ID = os.environ.get("DATASET_REPO")TOKEN = os.environ.get("HF_TOKEN")BACKUP_FILE = "/tmp/omniroute_backup.tar.gz"STATE_FILE = Path("/tmp/last_backup_hash.txt")DATA_DIR = Path("/app/data")CONFIG_DIR = Path("/root/.omniroute")def get_dir_state_hash():"""Calculate a hash of file contents to avoid uploading when nothing changed."""hasher = hashlib.sha256()for base_dir in (DATA_DIR, CONFIG_DIR):if not base_dir.exists():continuefor root, _, files in sorted(os.walk(base_dir)):for f in sorted(files):if f.endswith((".log", ".tmp", "-journal")):continuefp = Path(root) / ftry:hasher.update(str(fp).encode())with open(fp, "rb") as file_obj:while chunk := file_obj.read(65536):hasher.update(chunk)except OSError:passreturn hasher.hexdigest()def safe_extract(tar, path):"""Extract `tar` into `path`, rejecting members that would escape it."""base = Path(path).resolve()1 unmodified linetarget = (base / member.name).resolve()if not str(target).startswith(str(base)):raise RuntimeError(f"Unsafe tar member: {member.name}")if sys.version_info >= (3, 12):tar.extractall(path, filter="data")else:1 unmodified linedef heal_legacy_layout():plans = [(Path("/data"), "storage.sqlite", Path("/app/data")),(Path("/.omniroute"), "server.env", Path("/root/.omniroute")),3 unmodified linesdst_marker = dst / marker_nameif not src_marker.exists():continueif dst_marker.exists():print(f">>> [Sync] Healer: target {dst_marker} already present, "f"leaving {src} alone",flush=True,)continueprint(f">>> [Sync] Healer: misplaced legacy content at {src}", flush=True)if dst.exists():try:dst.rmdir()except OSError:print(f">>> [Sync] Healer: ABORT — {dst} is not empty", flush=True)continuedst.parent.mkdir(parents=True, exist_ok=True)1 unmodified lineprint(f">>> [Sync] Healer: relocated {src} -> {dst}", flush=True)def ignore_junk(dir_path, contents):"""Ignore temporary or log files to keep backup size small."""return [c for c in contents if c.endswith((".log", ".tmp"))]def upload(force=False):if not REPO_ID or not TOKEN:print(">>> [Sync] DATASET_REPO or HF_TOKEN not configured. Skipping backup.")return# 1. Check if data actually changed since last backupcurrent_hash = get_dir_state_hash()if not force and STATE_FILE.exists():last_hash = STATE_FILE.read_text().strip()if current_hash == last_hash:print(">>> [Sync] No changes detected in database/config. Skipping upload to save space.", flush=True)returnwith tempfile.TemporaryDirectory() as tmpdir:tmp_path = Path(tmpdir)if DATA_DIR.exists():target = tmp_path / "app" / "data"target.parent.mkdir(parents=True, exist_ok=True)shutil.copytree(DATA_DIR, target, ignore=ignore_junk)print(f">>> [Sync] Packed {DATA_DIR} -> app/data", flush=True)if CONFIG_DIR.exists():target = tmp_path / "root" / ".omniroute"target.parent.mkdir(parents=True, exist_ok=True)shutil.copytree(CONFIG_DIR, target, ignore=ignore_junk)print(f">>> [Sync] Packed {CONFIG_DIR} -> root/.omniroute", flush=True)try:with tarfile.open(BACKUP_FILE, "w:gz") as tar:tar.add(str(tmp_path), arcname=".")api = HfApi(token=TOKEN)# 2. Upload the latest backup fileapi.upload_file(path_or_fileobj=BACKUP_FILE,path_in_repo="omniroute_backup.tar.gz",repo_id=REPO_ID,repo_type="dataset",commit_message="Update backup",)print(f">>> [Sync] Backup uploaded: {time.strftime('%Y-%m-%d %H:%M:%S')}", flush=True)# 3. CRITICAL: Squash git history to delete old versions and free the 100GB!api.super_squash_history(repo_id=REPO_ID,repo_type="dataset",commit_message="Squash history to free storage space",)print(">>> [Sync] Git history squashed successfully (old versions purged).", flush=True)# Save state hash after successful uploadSTATE_FILE.write_text(current_hash)# Clean up local temp tar fileif os.path.exists(BACKUP_FILE):os.remove(BACKUP_FILE)except Exception as e:print(f">>> [Sync] Backup failed: {e}", flush=True)17 unmodified linesprint(f">>> [Sync] Extracting {len(members)} members to / ...", flush=True)safe_extract(tar, "/")heal_legacy_layout()critical = [(DATA_DIR, "storage.sqlite"),(CONFIG_DIR, "server.env"),3 unmodified linesstatus = "OK" if marker.exists() else "MISSING"print(f">>> [Sync] Verify {marker}: {status}", flush=True)# Record initial hash after restore AND immediately squash old 100GB history!STATE_FILE.write_text(get_dir_state_hash())try:print(">>> [Sync] Cleaning up legacy 100GB+ history on Dataset...", flush=True)HfApi(token=TOKEN).super_squash_history(repo_id=REPO_ID,repo_type="dataset",commit_message="Initial cleanup of 100GB+ history",)print(">>> [Sync] Legacy history cleaned up!", flush=True)except Exception as sq_err:print(f">>> [Sync] Note: History squash skipped or failed: {sq_err}", flush=True)print(">>> [Sync] Data restore successful.", flush=True)except Exception as e:print(f">>> [Sync] Skipping restore (might be first run): {e}", flush=True)6 unmodified linesdownload()PY# 4. Create the startup shell scriptRUN cat > /app/run.sh <<'SH'#!/bin/shset -e4 unmodified linesecho '=== 1. Restoring Data & Config ==='python3 /app/sync.py downloadecho '=== 2. Starting Scheduled Backup (Every 30 minutes, only on changes) ==='(while true; do sleep 1800; python3 /app/sync.py upload; done) &echo '=== 3. Generating & Persisting Secrets ==='if [ ! -f /root/.omniroute/server.env ]; thenecho '>>> No restored server.env found, generating fresh secrets'export JWT_SECRET="${JWT_SECRET:-$(openssl rand -base64 48 | tr -d '\n')}"26 unmodified linesecho '>>> Restored server.env found, keeping restored secrets'fiset -a. "/root/.omniroute/server.env"set +a
Dockerfile+82-46