feat: implement persistent state tracking, hostname inclusion in sync messages, and interval jittering
Browse files6 unmodified lines78910111210 unmodified lines23242526272812 unmodified lines414243444546472 unmodified lines505152535455565758596061626364148 unmodified lines21321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625723 unmodified lines2812822832842852862876 unmodified linesimport osimport shutilimport signalimport sysimport tempfileimport threading10 unmodified linesHERMES_HOME = Path(os.environ.get("HERMES_HOME", "/opt/data"))STATUS_FILE = Path("/tmp/huggingmes-sync-status.json")INTERVAL = int(os.environ.get("SYNC_INTERVAL", "600"))INITIAL_DELAY = int(os.environ.get("SYNC_START_DELAY", "10"))HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()12 unmodified lines"node_modules","venv",}EXCLUDED_TOP_LEVEL = {"logs"}if not INCLUDE_ENV:EXCLUDED_TOP_LEVEL.add(".env")2 unmodified lines_REPO_ID_CACHE: str | None = Nonedef write_status(status: str, message: str) -> None:payload = {"status": status,"message": message,"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),}tmp_path = STATUS_FILE.with_suffix(".tmp")tmp_path.write_text(json.dumps(payload), encoding="utf-8")tmp_path.replace(STATUS_FILE)def resolve_backup_repo() -> str:148 unmodified linesdef sync_once(last_fingerprint: str | None = None, last_marker: tuple[int, int, int] | None = None):if not HF_TOKEN:write_status("disabled", "HF_TOKEN is not configured.")return (last_fingerprint or "", last_marker or (0, 0, 0))repo_id = ensure_repo_exists()current_marker = metadata_marker(HERMES_HOME)if last_marker is not None and current_marker == last_marker:write_status("synced", "No Hermes state changes detected.")return (last_fingerprint or "", current_marker)current_fingerprint = fingerprint_dir(HERMES_HOME)if last_fingerprint is not None and current_fingerprint == last_fingerprint:write_status("synced", "No Hermes state changes detected.")return (last_fingerprint, current_marker)write_status("syncing", f"Uploading Hermes state to {repo_id}")snapshot_dir = create_snapshot_dir(HERMES_HOME)try:try:HF_API.upload_large_folder(repo_id=repo_id,repo_type="dataset",folder_path=str(snapshot_dir),num_workers=2,print_report=False,)except AttributeError:upload_folder(folder_path=str(snapshot_dir),repo_id=repo_id,repo_type="dataset",token=HF_TOKEN,commit_message=f"HuggingMes sync {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}",ignore_patterns=[".git/*", ".git"],)finally:shutil.rmtree(snapshot_dir, ignore_errors=True)write_status("success", f"Uploaded Hermes state to {repo_id}")return (current_fingerprint, current_marker)23 unmodified linesexcept Exception as exc:write_status("error", f"Sync failed: {exc}")print(f"Hermes sync failed: {exc}")if STOP_EVENT.wait(INTERVAL):breakreturn 06 unmodified lines789101112131410 unmodified lines2526272829303112 unmodified lines444546474849502 unmodified lines5354555657585960616263646566676869707172737475767778798081828384858687888990919293148 unmodified lines24224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528623 unmodified lines3103113123133143153163173183196 unmodified linesimport osimport shutilimport signalimport randomimport socketimport sysimport tempfileimport threading10 unmodified linesHERMES_HOME = Path(os.environ.get("HERMES_HOME", "/opt/data"))STATUS_FILE = Path("/tmp/huggingmes-sync-status.json")STATE_FILE = HERMES_HOME / ".huggingmes-sync-state.json"INTERVAL = int(os.environ.get("SYNC_INTERVAL", "600"))INITIAL_DELAY = int(os.environ.get("SYNC_START_DELAY", "10"))HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()12 unmodified lines"node_modules","venv",}EXCLUDED_TOP_LEVEL = {"logs", STATE_FILE.name}if not INCLUDE_ENV:EXCLUDED_TOP_LEVEL.add(".env")2 unmodified lines_REPO_ID_CACHE: str | None = Nonedef write_status(status: str, message: str, fingerprint: str | None = None, marker: tuple[int, int, int] | None = None) -> None:timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())payload = {"status": status,"message": message,"timestamp": timestamp,}# Update temporary status file for health checks/dashboardtmp_path = STATUS_FILE.with_suffix(".tmp")try:tmp_path.write_text(json.dumps(payload), encoding="utf-8")tmp_path.replace(STATUS_FILE)except OSError:pass# Update persistent state file in HERMES_HOMEif fingerprint or marker:state = {}if STATE_FILE.exists():try:state = json.loads(STATE_FILE.read_text(encoding="utf-8"))except Exception:passif fingerprint:state["last_fingerprint"] = fingerprintif marker:state["last_marker"] = list(marker)state["last_sync"] = timestamptry:STATE_FILE.write_text(json.dumps(state), encoding="utf-8")except OSError:passdef resolve_backup_repo() -> str:148 unmodified linesdef sync_once(last_fingerprint: str | None = None, last_marker: tuple[int, int, int] | None = None):# If no state provided, try to load from persistent state fileif last_fingerprint is None and last_marker is None:if STATE_FILE.exists():try:state = json.loads(STATE_FILE.read_text(encoding="utf-8"))last_fingerprint = state.get("last_fingerprint")m = state.get("last_marker")if m and len(m) == 3:last_marker = tuple(m)except Exception:passrepo_id = ensure_repo_exists()current_marker = metadata_marker(HERMES_HOME)if last_marker is not None and current_marker == last_marker:write_status("synced", "No Hermes state changes detected (marker match).")return (last_fingerprint or "", current_marker)current_fingerprint = fingerprint_dir(HERMES_HOME)if last_fingerprint is not None and current_fingerprint == last_fingerprint:write_status("synced", "No Hermes state changes detected (fingerprint match).")return (last_fingerprint, current_marker)hostname = socket.gethostname()write_status("syncing", f"Uploading Hermes state to {repo_id} from {hostname}")snapshot_dir = create_snapshot_dir(HERMES_HOME)try:upload_folder(folder_path=str(snapshot_dir),repo_id=repo_id,repo_type="dataset",token=HF_TOKEN,commit_message=f"HuggingMes sync [{hostname}] {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}",ignore_patterns=[".git/*", ".git"],)finally:shutil.rmtree(snapshot_dir, ignore_errors=True)write_status("success", f"Uploaded Hermes state to {repo_id}", fingerprint=current_fingerprint, marker=current_marker)return (current_fingerprint, current_marker)23 unmodified linesexcept Exception as exc:write_status("error", f"Sync failed: {exc}")print(f"Hermes sync failed: {exc}")# Add 10% jitter to interval to avoid synchronized commits from multiple containersjitter = random.uniform(0.9, 1.1)if STOP_EVENT.wait(INTERVAL * jitter):breakreturn 0
hermes-sync.py+62-30