fmode-safe-gc.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #!/usr/bin/env python3
  2. """Remove only acknowledged cloud copies and explicitly disposable task data."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import os
  8. from pathlib import Path
  9. import shutil
  10. import time
  11. from urllib.parse import urlparse
  12. CLOUD_HOSTS = {"s3.fmode.cn", "file-cloud.fmode.cn"}
  13. GC_STATE = Path("cache/deliverable-hook")
  14. GC_LOG = Path("logs/fmode-safe-gc.log")
  15. TASK_ROOT = Path("work/tasks")
  16. UPLOAD_ROOTS = (Path("work/uploads"), Path("work/deliverables"), TASK_ROOT)
  17. CACHE_ROOT = Path("cache/regenerable")
  18. MANIFEST_NAME = ".fmode-task.json"
  19. DEFAULT_MIN_AGE = 3600
  20. DEFAULT_DISK_THRESHOLD = 80.0
  21. def _within(path: Path, root: Path) -> bool:
  22. try:
  23. path.relative_to(root)
  24. return True
  25. except ValueError:
  26. return False
  27. def _safe_directory(root: Path, path: Path) -> bool:
  28. """Reject symlinks in every ancestor, including an allowlisted root's parent."""
  29. if not _within(path, root):
  30. return False
  31. try:
  32. current = path
  33. while current != root:
  34. if current.is_symlink():
  35. return False
  36. current = current.parent
  37. return path.is_dir()
  38. except OSError:
  39. return False
  40. def _valid_cloud_url(value: object) -> bool:
  41. if not isinstance(value, str):
  42. return False
  43. try:
  44. parsed = urlparse(value)
  45. return parsed.scheme == "https" and parsed.hostname in CLOUD_HOSTS and bool(parsed.path)
  46. except ValueError:
  47. return False
  48. def _confirmed_content(path: Path, record: dict) -> bool:
  49. if record.get("cloudAck") is not True or record.get("hubRegistered") is not True:
  50. return False
  51. expected = record.get("sha256")
  52. if not isinstance(expected, str) or len(expected) != 64:
  53. return False
  54. try:
  55. digest = hashlib.sha256()
  56. with path.open("rb") as stream:
  57. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  58. digest.update(chunk)
  59. return digest.hexdigest() == expected.lower()
  60. except OSError:
  61. return False
  62. def _epoch(value: object) -> float | None:
  63. if isinstance(value, bool) or not isinstance(value, (int, float)):
  64. return None
  65. number = float(value)
  66. if number > 10_000_000_000:
  67. number /= 1000.0
  68. return number if number > 0 else None
  69. def _walk_pushed(value: object):
  70. if isinstance(value, dict):
  71. if isinstance(value.get("path"), str) and isinstance(value.get("url"), str):
  72. yield value
  73. for item in value.values():
  74. yield from _walk_pushed(item)
  75. elif isinstance(value, list):
  76. for item in value:
  77. yield from _walk_pushed(item)
  78. def _pushed_records(root: Path):
  79. state_dir = root / GC_STATE
  80. if not _safe_directory(root, state_dir):
  81. return
  82. for state_file in state_dir.glob("*.json"):
  83. if state_file.is_symlink() or not state_file.is_file():
  84. continue
  85. try:
  86. data = json.loads(state_file.read_text(encoding="utf-8"))
  87. except (OSError, UnicodeError, json.JSONDecodeError):
  88. continue
  89. for record in _walk_pushed(data.get("pushed") if isinstance(data, dict) else None):
  90. yield state_file, record
  91. def _safe_uploaded_path(root: Path, raw: str) -> Path | None:
  92. candidate = Path(raw)
  93. if not candidate.is_absolute():
  94. return None
  95. try:
  96. absolute = Path(os.path.abspath(candidate))
  97. allowed = [Path(os.path.abspath(root / item)) for item in UPLOAD_ROOTS]
  98. if not any(_within(absolute, base) for base in allowed):
  99. return None
  100. if absolute == root:
  101. return None
  102. parent = absolute
  103. while parent != root and _within(parent, root):
  104. if parent.is_symlink():
  105. return None
  106. parent = parent.parent
  107. if parent != root or not absolute.exists() or not absolute.is_file():
  108. return None
  109. return absolute
  110. except (OSError, RuntimeError):
  111. return None
  112. def _record_uploaded_files(root: Path, now: float, min_age: int):
  113. grouped: dict[Path, list[tuple[Path, dict]]] = {}
  114. for state_file, record in _pushed_records(root):
  115. if record.get("gc") is True or not _valid_cloud_url(record.get("url")):
  116. continue
  117. path = _safe_uploaded_path(root, record.get("path", ""))
  118. if path is None:
  119. continue
  120. ack_at = _epoch(record.get("uploadedAt") or record.get("ts") or record.get("ackAt"))
  121. if ack_at is None:
  122. continue
  123. try:
  124. modified_at = path.stat().st_mtime
  125. # An old URL does not acknowledge a version edited after the upload.
  126. # pushed[].ts is stored as integer milliseconds by the uploader.
  127. if int(modified_at * 1000) > int(ack_at * 1000):
  128. continue
  129. last_use = max(ack_at, modified_at)
  130. except OSError:
  131. continue
  132. task_root = root / TASK_ROOT
  133. if _within(path, task_root):
  134. relative = path.relative_to(task_root)
  135. if len(relative.parts) < 2 or not _task_is_collectable(
  136. root, task_root / relative.parts[0], now, min_age):
  137. continue
  138. if now - last_use >= min_age and _confirmed_content(path, record):
  139. grouped.setdefault(path, []).append((state_file, record))
  140. return grouped
  141. def _task_inventory(task_dir: Path, now: float, min_age: int):
  142. inventory = set()
  143. for current, dirs, files in os.walk(task_dir, topdown=True, followlinks=False):
  144. base = Path(current)
  145. if now - base.stat().st_mtime < min_age:
  146. return None
  147. safe_dirs = []
  148. for name in dirs:
  149. child = base / name
  150. if child.is_symlink():
  151. return None
  152. safe_dirs.append(name)
  153. dirs[:] = safe_dirs
  154. for name in files:
  155. child = base / name
  156. if child.name == MANIFEST_NAME and child.parent == task_dir:
  157. continue
  158. if child.is_symlink() or not child.is_file():
  159. return None
  160. if now - child.stat().st_mtime < min_age:
  161. return None
  162. inventory.add(child.relative_to(task_dir).as_posix())
  163. return inventory
  164. def _task_is_collectable(root: Path, task_dir: Path, now: float, min_age: int) -> bool:
  165. if not _safe_directory(root, task_dir):
  166. return False
  167. try:
  168. manifest_path = task_dir / MANIFEST_NAME
  169. if manifest_path.is_symlink() or not manifest_path.is_file():
  170. return False
  171. manifest_mtime = manifest_path.stat().st_mtime
  172. if now - manifest_mtime < min_age:
  173. return False
  174. manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
  175. except (OSError, UnicodeError, json.JSONDecodeError):
  176. return False
  177. if not isinstance(manifest, dict) or manifest.get("status") != "completed":
  178. return False
  179. if manifest.get("activeSessionIds") != []:
  180. return False
  181. activity = _epoch(manifest.get("lastActivityAt"))
  182. if activity is None or now - activity < min_age:
  183. return False
  184. declared = set()
  185. files = manifest.get("files")
  186. if not isinstance(files, list):
  187. return False
  188. for item in files:
  189. if not isinstance(item, dict) or not isinstance(item.get("path"), str):
  190. return False
  191. rel = Path(item["path"])
  192. if rel.is_absolute() or ".." in rel.parts or not rel.parts:
  193. return False
  194. target = (task_dir / rel).resolve(strict=False)
  195. if not _within(target, task_dir.resolve(strict=True)):
  196. return False
  197. declared.add(rel.as_posix())
  198. if item.get("disposable") is True:
  199. continue
  200. if item.get("cloudAck") is not True or not _valid_cloud_url(item.get("url")):
  201. return False
  202. if target.exists() and not _confirmed_content(target, item):
  203. return False
  204. # The manifest's confirmation must describe the current file version.
  205. if target.is_file() and target.stat().st_mtime > manifest_mtime:
  206. return False
  207. inventory = _task_inventory(task_dir, now, min_age)
  208. if inventory is None or not inventory.issubset(declared):
  209. return False
  210. # A manifest may retain records for files already collected through pushed[]; that is safe.
  211. return True
  212. def _regenerable_cache_files(root: Path, now: float, min_age: int):
  213. cache_root = root / CACHE_ROOT
  214. if not _safe_directory(root, cache_root):
  215. return []
  216. out = []
  217. for current, dirs, files in os.walk(cache_root, topdown=True, followlinks=False):
  218. base = Path(current)
  219. dirs[:] = [name for name in dirs if not (base / name).is_symlink()]
  220. if (base / ".active").exists():
  221. dirs[:] = []
  222. continue
  223. for name in files:
  224. path = base / name
  225. if path.is_symlink() or name.startswith("."):
  226. continue
  227. try:
  228. if path.is_file() and now - path.stat().st_mtime >= min_age:
  229. out.append(path)
  230. except OSError:
  231. continue
  232. return out
  233. def _mark_gc(records: list[tuple[Path, dict]], now: float) -> None:
  234. by_file: dict[Path, set[tuple[str, str, float | None]]] = {}
  235. for state_file, record in records:
  236. signature = (
  237. str(record.get("path") or ""),
  238. str(record.get("url") or ""),
  239. _epoch(record.get("uploadedAt") or record.get("ts") or record.get("ackAt")),
  240. )
  241. by_file.setdefault(state_file, set()).add(signature)
  242. for state_file, changed in by_file.items():
  243. try:
  244. data = json.loads(state_file.read_text(encoding="utf-8"))
  245. for item in _walk_pushed(data.get("pushed") if isinstance(data, dict) else None):
  246. signature = (
  247. str(item.get("path") or ""),
  248. str(item.get("url") or ""),
  249. _epoch(item.get("uploadedAt") or item.get("ts") or item.get("ackAt")),
  250. )
  251. if signature in changed:
  252. item["gc"] = True
  253. item["gcAt"] = int(now * 1000)
  254. temp = state_file.with_suffix(state_file.suffix + ".tmp")
  255. temp.write_text(json.dumps(data, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
  256. os.replace(temp, state_file)
  257. except (OSError, UnicodeError, json.JSONDecodeError):
  258. continue
  259. def cleanup(root: Path, *, now: float | None = None, apply: bool = False,
  260. min_age: int = DEFAULT_MIN_AGE, disk_percent: float | None = None,
  261. disk_threshold: float = DEFAULT_DISK_THRESHOLD) -> dict:
  262. root = root.resolve(strict=False)
  263. now = time.time() if now is None else now
  264. if disk_percent is None:
  265. try:
  266. usage = shutil.disk_usage(root)
  267. disk_percent = usage.used / usage.total * 100 if usage.total else 0.0
  268. except OSError:
  269. disk_percent = 0.0
  270. mode = "emergency" if disk_threshold > 0 and disk_percent >= disk_threshold else "scheduled"
  271. uploaded = _record_uploaded_files(root, now, min_age)
  272. cache_files = _regenerable_cache_files(root, now, min_age)
  273. tasks_root = root / TASK_ROOT
  274. task_dirs = []
  275. if _safe_directory(root, tasks_root):
  276. task_dirs = [p for p in tasks_root.iterdir() if _task_is_collectable(root, p, now, min_age)]
  277. removed = []
  278. skipped = {"unacknowledged": 0, "active_or_unknown_task": 0}
  279. for path, records in uploaded.items():
  280. removed.append((path, "uploaded"))
  281. removed.extend((path, "regenerable-cache") for path in cache_files)
  282. removed.extend((path, "completed-task") for path in task_dirs)
  283. removed_count = len(removed) if not apply else 0
  284. if apply:
  285. for path, reason in removed:
  286. try:
  287. if reason == "completed-task":
  288. # Task roots are allowlisted and the complete file inventory was validated above.
  289. shutil.rmtree(path)
  290. else:
  291. path.unlink()
  292. if reason == "uploaded":
  293. _mark_gc(uploaded[path], now)
  294. removed_count += 1
  295. except OSError:
  296. continue
  297. return {
  298. "mode": mode,
  299. "diskPercent": round(float(disk_percent), 2),
  300. "dryRun": not apply,
  301. "removed": removed_count,
  302. "uploadedFiles": len(uploaded),
  303. "cacheFiles": len(cache_files),
  304. "taskDirs": len(task_dirs),
  305. "skipped": skipped,
  306. "removedPaths": [str(path) for path, _ in removed],
  307. }
  308. def main() -> int:
  309. parser = argparse.ArgumentParser(description=__doc__)
  310. parser.add_argument("--apply", action="store_true", help="actually remove eligible files; default is dry-run")
  311. parser.add_argument("--min-age", type=int, default=DEFAULT_MIN_AGE)
  312. parser.add_argument("--disk-threshold", type=float, default=DEFAULT_DISK_THRESHOLD)
  313. parser.add_argument("--quiet", action="store_true")
  314. args = parser.parse_args()
  315. if args.min_age < 3600:
  316. parser.error("--min-age cannot be less than the one-hour safety window")
  317. if not 0 <= args.disk_threshold <= 100:
  318. parser.error("--disk-threshold must be between 0 and 100")
  319. home = Path(os.environ.get("HERMES_HOME", "/opt/data"))
  320. result = cleanup(home, apply=args.apply, min_age=args.min_age, disk_threshold=args.disk_threshold)
  321. line = ("[safe-gc] mode={mode} disk={diskPercent}% dry_run={dryRun} "
  322. "removed={removed} uploaded={uploadedFiles} cache={cacheFiles} tasks={taskDirs}").format(**result)
  323. if not args.quiet or result["removed"]:
  324. print(line)
  325. if args.apply and result["removed"]:
  326. log = home / GC_LOG
  327. try:
  328. log.parent.mkdir(parents=True, exist_ok=True)
  329. with log.open("a", encoding="utf-8") as stream:
  330. stream.write(line + "\n")
  331. for path in result["removedPaths"]:
  332. stream.write("removed=" + path + "\n")
  333. except OSError:
  334. pass
  335. return 0
  336. if __name__ == "__main__":
  337. raise SystemExit(main())