| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378 |
- #!/usr/bin/env python3
- """Remove only acknowledged cloud copies and explicitly disposable task data."""
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import os
- from pathlib import Path
- import shutil
- import time
- from urllib.parse import urlparse
- CLOUD_HOSTS = {"s3.fmode.cn", "file-cloud.fmode.cn"}
- GC_STATE = Path("cache/deliverable-hook")
- GC_LOG = Path("logs/fmode-safe-gc.log")
- TASK_ROOT = Path("work/tasks")
- UPLOAD_ROOTS = (Path("work/uploads"), Path("work/deliverables"), TASK_ROOT)
- CACHE_ROOT = Path("cache/regenerable")
- MANIFEST_NAME = ".fmode-task.json"
- DEFAULT_MIN_AGE = 3600
- DEFAULT_DISK_THRESHOLD = 80.0
- def _within(path: Path, root: Path) -> bool:
- try:
- path.relative_to(root)
- return True
- except ValueError:
- return False
- def _safe_directory(root: Path, path: Path) -> bool:
- """Reject symlinks in every ancestor, including an allowlisted root's parent."""
- if not _within(path, root):
- return False
- try:
- current = path
- while current != root:
- if current.is_symlink():
- return False
- current = current.parent
- return path.is_dir()
- except OSError:
- return False
- def _valid_cloud_url(value: object) -> bool:
- if not isinstance(value, str):
- return False
- try:
- parsed = urlparse(value)
- return parsed.scheme == "https" and parsed.hostname in CLOUD_HOSTS and bool(parsed.path)
- except ValueError:
- return False
- def _confirmed_content(path: Path, record: dict) -> bool:
- if record.get("cloudAck") is not True or record.get("hubRegistered") is not True:
- return False
- expected = record.get("sha256")
- if not isinstance(expected, str) or len(expected) != 64:
- return False
- try:
- digest = hashlib.sha256()
- with path.open("rb") as stream:
- for chunk in iter(lambda: stream.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest() == expected.lower()
- except OSError:
- return False
- def _epoch(value: object) -> float | None:
- if isinstance(value, bool) or not isinstance(value, (int, float)):
- return None
- number = float(value)
- if number > 10_000_000_000:
- number /= 1000.0
- return number if number > 0 else None
- def _walk_pushed(value: object):
- if isinstance(value, dict):
- if isinstance(value.get("path"), str) and isinstance(value.get("url"), str):
- yield value
- for item in value.values():
- yield from _walk_pushed(item)
- elif isinstance(value, list):
- for item in value:
- yield from _walk_pushed(item)
- def _pushed_records(root: Path):
- state_dir = root / GC_STATE
- if not _safe_directory(root, state_dir):
- return
- for state_file in state_dir.glob("*.json"):
- if state_file.is_symlink() or not state_file.is_file():
- continue
- try:
- data = json.loads(state_file.read_text(encoding="utf-8"))
- except (OSError, UnicodeError, json.JSONDecodeError):
- continue
- for record in _walk_pushed(data.get("pushed") if isinstance(data, dict) else None):
- yield state_file, record
- def _safe_uploaded_path(root: Path, raw: str) -> Path | None:
- candidate = Path(raw)
- if not candidate.is_absolute():
- return None
- try:
- absolute = Path(os.path.abspath(candidate))
- allowed = [Path(os.path.abspath(root / item)) for item in UPLOAD_ROOTS]
- if not any(_within(absolute, base) for base in allowed):
- return None
- if absolute == root:
- return None
- parent = absolute
- while parent != root and _within(parent, root):
- if parent.is_symlink():
- return None
- parent = parent.parent
- if parent != root or not absolute.exists() or not absolute.is_file():
- return None
- return absolute
- except (OSError, RuntimeError):
- return None
- def _record_uploaded_files(root: Path, now: float, min_age: int):
- grouped: dict[Path, list[tuple[Path, dict]]] = {}
- for state_file, record in _pushed_records(root):
- if record.get("gc") is True or not _valid_cloud_url(record.get("url")):
- continue
- path = _safe_uploaded_path(root, record.get("path", ""))
- if path is None:
- continue
- ack_at = _epoch(record.get("uploadedAt") or record.get("ts") or record.get("ackAt"))
- if ack_at is None:
- continue
- try:
- modified_at = path.stat().st_mtime
- # An old URL does not acknowledge a version edited after the upload.
- # pushed[].ts is stored as integer milliseconds by the uploader.
- if int(modified_at * 1000) > int(ack_at * 1000):
- continue
- last_use = max(ack_at, modified_at)
- except OSError:
- continue
- task_root = root / TASK_ROOT
- if _within(path, task_root):
- relative = path.relative_to(task_root)
- if len(relative.parts) < 2 or not _task_is_collectable(
- root, task_root / relative.parts[0], now, min_age):
- continue
- if now - last_use >= min_age and _confirmed_content(path, record):
- grouped.setdefault(path, []).append((state_file, record))
- return grouped
- def _task_inventory(task_dir: Path, now: float, min_age: int):
- inventory = set()
- for current, dirs, files in os.walk(task_dir, topdown=True, followlinks=False):
- base = Path(current)
- if now - base.stat().st_mtime < min_age:
- return None
- safe_dirs = []
- for name in dirs:
- child = base / name
- if child.is_symlink():
- return None
- safe_dirs.append(name)
- dirs[:] = safe_dirs
- for name in files:
- child = base / name
- if child.name == MANIFEST_NAME and child.parent == task_dir:
- continue
- if child.is_symlink() or not child.is_file():
- return None
- if now - child.stat().st_mtime < min_age:
- return None
- inventory.add(child.relative_to(task_dir).as_posix())
- return inventory
- def _task_is_collectable(root: Path, task_dir: Path, now: float, min_age: int) -> bool:
- if not _safe_directory(root, task_dir):
- return False
- try:
- manifest_path = task_dir / MANIFEST_NAME
- if manifest_path.is_symlink() or not manifest_path.is_file():
- return False
- manifest_mtime = manifest_path.stat().st_mtime
- if now - manifest_mtime < min_age:
- return False
- manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
- except (OSError, UnicodeError, json.JSONDecodeError):
- return False
- if not isinstance(manifest, dict) or manifest.get("status") != "completed":
- return False
- if manifest.get("activeSessionIds") != []:
- return False
- activity = _epoch(manifest.get("lastActivityAt"))
- if activity is None or now - activity < min_age:
- return False
- declared = set()
- files = manifest.get("files")
- if not isinstance(files, list):
- return False
- for item in files:
- if not isinstance(item, dict) or not isinstance(item.get("path"), str):
- return False
- rel = Path(item["path"])
- if rel.is_absolute() or ".." in rel.parts or not rel.parts:
- return False
- target = (task_dir / rel).resolve(strict=False)
- if not _within(target, task_dir.resolve(strict=True)):
- return False
- declared.add(rel.as_posix())
- if item.get("disposable") is True:
- continue
- if item.get("cloudAck") is not True or not _valid_cloud_url(item.get("url")):
- return False
- if target.exists() and not _confirmed_content(target, item):
- return False
- # The manifest's confirmation must describe the current file version.
- if target.is_file() and target.stat().st_mtime > manifest_mtime:
- return False
- inventory = _task_inventory(task_dir, now, min_age)
- if inventory is None or not inventory.issubset(declared):
- return False
- # A manifest may retain records for files already collected through pushed[]; that is safe.
- return True
- def _regenerable_cache_files(root: Path, now: float, min_age: int):
- cache_root = root / CACHE_ROOT
- if not _safe_directory(root, cache_root):
- return []
- out = []
- for current, dirs, files in os.walk(cache_root, topdown=True, followlinks=False):
- base = Path(current)
- dirs[:] = [name for name in dirs if not (base / name).is_symlink()]
- if (base / ".active").exists():
- dirs[:] = []
- continue
- for name in files:
- path = base / name
- if path.is_symlink() or name.startswith("."):
- continue
- try:
- if path.is_file() and now - path.stat().st_mtime >= min_age:
- out.append(path)
- except OSError:
- continue
- return out
- def _mark_gc(records: list[tuple[Path, dict]], now: float) -> None:
- by_file: dict[Path, set[tuple[str, str, float | None]]] = {}
- for state_file, record in records:
- signature = (
- str(record.get("path") or ""),
- str(record.get("url") or ""),
- _epoch(record.get("uploadedAt") or record.get("ts") or record.get("ackAt")),
- )
- by_file.setdefault(state_file, set()).add(signature)
- for state_file, changed in by_file.items():
- try:
- data = json.loads(state_file.read_text(encoding="utf-8"))
- for item in _walk_pushed(data.get("pushed") if isinstance(data, dict) else None):
- signature = (
- str(item.get("path") or ""),
- str(item.get("url") or ""),
- _epoch(item.get("uploadedAt") or item.get("ts") or item.get("ackAt")),
- )
- if signature in changed:
- item["gc"] = True
- item["gcAt"] = int(now * 1000)
- temp = state_file.with_suffix(state_file.suffix + ".tmp")
- temp.write_text(json.dumps(data, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
- os.replace(temp, state_file)
- except (OSError, UnicodeError, json.JSONDecodeError):
- continue
- def cleanup(root: Path, *, now: float | None = None, apply: bool = False,
- min_age: int = DEFAULT_MIN_AGE, disk_percent: float | None = None,
- disk_threshold: float = DEFAULT_DISK_THRESHOLD) -> dict:
- root = root.resolve(strict=False)
- now = time.time() if now is None else now
- if disk_percent is None:
- try:
- usage = shutil.disk_usage(root)
- disk_percent = usage.used / usage.total * 100 if usage.total else 0.0
- except OSError:
- disk_percent = 0.0
- mode = "emergency" if disk_threshold > 0 and disk_percent >= disk_threshold else "scheduled"
- uploaded = _record_uploaded_files(root, now, min_age)
- cache_files = _regenerable_cache_files(root, now, min_age)
- tasks_root = root / TASK_ROOT
- task_dirs = []
- if _safe_directory(root, tasks_root):
- task_dirs = [p for p in tasks_root.iterdir() if _task_is_collectable(root, p, now, min_age)]
- removed = []
- skipped = {"unacknowledged": 0, "active_or_unknown_task": 0}
- for path, records in uploaded.items():
- removed.append((path, "uploaded"))
- removed.extend((path, "regenerable-cache") for path in cache_files)
- removed.extend((path, "completed-task") for path in task_dirs)
- removed_count = len(removed) if not apply else 0
- if apply:
- for path, reason in removed:
- try:
- if reason == "completed-task":
- # Task roots are allowlisted and the complete file inventory was validated above.
- shutil.rmtree(path)
- else:
- path.unlink()
- if reason == "uploaded":
- _mark_gc(uploaded[path], now)
- removed_count += 1
- except OSError:
- continue
- return {
- "mode": mode,
- "diskPercent": round(float(disk_percent), 2),
- "dryRun": not apply,
- "removed": removed_count,
- "uploadedFiles": len(uploaded),
- "cacheFiles": len(cache_files),
- "taskDirs": len(task_dirs),
- "skipped": skipped,
- "removedPaths": [str(path) for path, _ in removed],
- }
- def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--apply", action="store_true", help="actually remove eligible files; default is dry-run")
- parser.add_argument("--min-age", type=int, default=DEFAULT_MIN_AGE)
- parser.add_argument("--disk-threshold", type=float, default=DEFAULT_DISK_THRESHOLD)
- parser.add_argument("--quiet", action="store_true")
- args = parser.parse_args()
- if args.min_age < 3600:
- parser.error("--min-age cannot be less than the one-hour safety window")
- if not 0 <= args.disk_threshold <= 100:
- parser.error("--disk-threshold must be between 0 and 100")
- home = Path(os.environ.get("HERMES_HOME", "/opt/data"))
- result = cleanup(home, apply=args.apply, min_age=args.min_age, disk_threshold=args.disk_threshold)
- line = ("[safe-gc] mode={mode} disk={diskPercent}% dry_run={dryRun} "
- "removed={removed} uploaded={uploadedFiles} cache={cacheFiles} tasks={taskDirs}").format(**result)
- if not args.quiet or result["removed"]:
- print(line)
- if args.apply and result["removed"]:
- log = home / GC_LOG
- try:
- log.parent.mkdir(parents=True, exist_ok=True)
- with log.open("a", encoding="utf-8") as stream:
- stream.write(line + "\n")
- for path in result["removedPaths"]:
- stream.write("removed=" + path + "\n")
- except OSError:
- pass
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|