gaiascale-api / services /cleanup.py
devmm03's picture
chore: add app files
7529108
Raw History Blame Contribute Delete
5.15 kB
"""
GaiaScale Uploads Cleanup Worker
Background worker that purges temporary uploaded imagery and generated
GeoTIFF/NPZ cache products every day at 02:00 AM.
"""
from __future__ import annotations
from datetime import datetime, time, timedelta
import logging
from pathlib import Path
import threading
import time as _time
from typing import Dict, Any, Tuple
try:
from backend.config import UPLOADS_DIR
from backend.services.inference import inference_engine
except ImportError:
from config import UPLOADS_DIR
from services.inference import inference_engine
logger = logging.getLogger("gaiascale.cleanup")
PROTECTED_FILENAMES = {".gitkeep", ".gitignore"}
def get_seconds_until_next_2am(target_hour: int = 2, target_minute: int = 0) -> Tuple[float, datetime]:
"""Calculate the number of seconds until the next occurrence of target_hour:target_minute."""
now = datetime.now()
target = datetime.combine(now.date(), time(hour=target_hour, minute=target_minute, second=0))
if now >= target:
target += timedelta(days=1)
seconds = (target - now).total_seconds()
return max(0.0, seconds), target
def cleanup_uploads_now(min_age_seconds: int = 0) -> Dict[str, Any]:
"""
Scans UPLOADS_DIR and deletes files, protecting .gitkeep and subdirectories.
Args:
min_age_seconds: Files modified more recently than this are preserved
(useful to avoid deleting files during an active upload).
"""
if not UPLOADS_DIR.exists():
return {"status": "no_directory", "files_deleted": 0, "bytes_freed": 0, "mb_freed": 0.0}
now_ts = _time.time()
deleted_count = 0
bytes_freed = 0
errors = []
for file_path in UPLOADS_DIR.iterdir():
if file_path.is_file():
if file_path.name in PROTECTED_FILENAMES:
continue
try:
stat = file_path.stat()
file_age = now_ts - stat.st_mtime
if file_age < min_age_seconds:
continue
size = stat.st_size
file_path.unlink()
deleted_count += 1
bytes_freed += size
except Exception as e:
errors.append(f"{file_path.name}: {str(e)}")
# Clear inference_engine in-memory tensor cache
try:
inference_engine.cache.clear()
except Exception:
pass
mb_freed = bytes_freed / (1024 * 1024)
summary = {
"status": "success",
"files_deleted": deleted_count,
"bytes_freed": bytes_freed,
"mb_freed": round(mb_freed, 2),
"errors": errors,
"timestamp": datetime.now().isoformat(),
}
print(f"[Cleanup Worker] Cleaned uploads: {deleted_count} files removed ({round(mb_freed, 2)} MB freed).")
return summary
class CleanupWorker:
"""
Daemon thread worker that executes cleanup_uploads_now daily at target_hour:target_minute (default 02:00 AM).
"""
def __init__(self, target_hour: int = 2, target_minute: int = 0):
self.target_hour = target_hour
self.target_minute = target_minute
self._stop_event = threading.Event()
self._thread: threading.Thread | None = None
def _run_loop(self):
print(f"[Cleanup Worker] Initialized. Scheduled to run daily at {self.target_hour:02d}:{self.target_minute:02d} local time.")
while not self._stop_event.is_set():
wait_seconds, target = get_seconds_until_next_2am(self.target_hour, self.target_minute)
print(f"[Cleanup Worker] Next daily cleanup scheduled for {target.strftime('%Y-%m-%d %H:%M:%S')} (in {int(wait_seconds)}s).")
# Sleep in intervals so stop_event can be checked without freezing on shutdown
while wait_seconds > 0:
if self._stop_event.is_set():
return
sleep_chunk = min(wait_seconds, 30.0)
_time.sleep(sleep_chunk)
wait_seconds -= sleep_chunk
if not self._stop_event.is_set():
print(f"[Cleanup Worker] Daily 02:00 AM maintenance triggered. Purging uploads...")
# Protect files created within the last 5 minutes in case an upload is in progress
cleanup_uploads_now(min_age_seconds=300)
def start(self):
"""Starts the background worker thread if not already running."""
if self._thread is not None and self._thread.is_alive():
return
self._stop_event.clear()
self._thread = threading.Thread(
target=self._run_loop,
name="GaiaScale-CleanupWorker",
daemon=True
)
self._thread.start()
def stop(self):
"""Signals the background worker to stop gracefully."""
self._stop_event.set()
if self._thread is not None and self._thread.is_alive():
self._thread.join(timeout=2.0)
@property
def is_running(self) -> bool:
return self._thread is not None and self._thread.is_alive()
# Global cleanup worker instance
cleanup_worker = CleanupWorker(target_hour=2, target_minute=0)