import os import sqlite3 import subprocess import sys import time from pathlib import Path from urllib.parse import urlparse, unquote MODELS_DIR = Path("/models") STATE_DIR = Path("/state") DB_PATH = STATE_DIR / "queue.db" POLL_INTERVAL = 2 IGNORED_NAMES = { ".gitkeep", } IGNORED_EXTENSIONS = { ".txt", } def db_connect(): STATE_DIR.mkdir(parents=True, exist_ok=True) db = sqlite3.connect(DB_PATH) db.row_factory = sqlite3.Row db.execute("PRAGMA journal_mode=WAL") db.execute("PRAGMA busy_timeout=5000") return db def init_db(): with db_connect() as db: db.execute( """ CREATE TABLE IF NOT EXISTS jobs ( id INTEGER PRIMARY KEY AUTOINCREMENT, action TEXT NOT NULL, model_type TEXT NOT NULL, filename TEXT NOT NULL, url TEXT, status TEXT NOT NULL DEFAULT 'pending', error TEXT, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, started_at TEXT, finished_at TEXT ) """ ) db.commit() def is_model_file(path: Path) -> bool: if not path.is_file(): return False if path.is_symlink(): return False if path.name in IGNORED_NAMES: return False if path.suffix.lower() in IGNORED_EXTENSIONS: return False return True def human_size(size: int) -> str: units = ["B", "KB", "MB", "GB", "TB", "PB"] value = float(size) for unit in units: if value < 1024 or unit == units[-1]: return f"{value:.2f} {unit}" value /= 1024 return f"{value:.2f} PB" def collect_models(model_type: str | None = None): groups = [] if not MODELS_DIR.exists(): return groups for directory in sorted(MODELS_DIR.iterdir()): if not directory.is_dir(): continue if directory.is_symlink(): continue if model_type is not None and directory.name != model_type: continue files = [] for path in sorted(directory.rglob("*")): if is_model_file(path): try: files.append( (path, path.stat().st_size) ) except OSError as exc: print( f"WARNING: Cannot read {path}: {exc}", file=sys.stderr, ) if not files: continue total = sum(size for _, size in files) groups.append( { "name": directory.name, "files": files, "size": total, } ) return groups def command_list(model_type: str | None = None) -> int: groups = collect_models(model_type) if model_type and not groups: print(f"ERROR: No models found for type: {model_type}") print() available = [ group["name"] for group in collect_models() ] print( "Available types: " + (", ".join(available) or "(none)") ) return 1 total_size = 0 total_files = 0 if not groups: print("No models found.") print() print("Total: 0 B (0 files)") return 0 for group in groups: print( f"\n{group['name']}/ — " f"{len(group['files'])} files — " f"{human_size(group['size'])}" ) for path, size in group["files"]: relative = path.relative_to(MODELS_DIR) print( f" {relative} — " f"{human_size(size)}" ) total_size += group["size"] total_files += len(group["files"]) print() print( f"Total: " f"{human_size(total_size)} " f"({total_files} files)" ) return 0 def get_filename_from_url(url: str) -> str: parsed = urlparse(url) filename = Path( unquote(parsed.path) ).name if not filename: raise ValueError( "Cannot determine filename from URL" ) return filename def get_model_types(): if not MODELS_DIR.exists(): return [] return sorted( path.name for path in MODELS_DIR.iterdir() if path.is_dir() and not path.is_symlink() ) def validate_model_type(model_type: str): directory = MODELS_DIR / model_type if not directory.is_dir() or directory.is_symlink(): available = get_model_types() raise ValueError( f"Unknown model type: {model_type}\n" f"Available types: " f"{', '.join(available) or '(none)'}" ) return directory def enqueue_add(url: str, model_type: str) -> int: directory = validate_model_type(model_type) filename = get_filename_from_url(url) destination = directory / filename with db_connect() as db: cursor = db.execute( """ INSERT INTO jobs ( action, model_type, filename, url ) VALUES (?, ?, ?, ?) """, ( "add", model_type, filename, url, ), ) db.commit() job_id = cursor.lastrowid print(f"Queued job #{job_id}") print(f"Action: add") print(f"Type: {model_type}") print(f"File: {filename}") print(f"URL: {url}") print(f"Target: {destination}") return 0 def find_model(filename: str, model_type: str | None = None): groups = collect_models(model_type) matches = [] for group in groups: for path, _ in group["files"]: if path.name == filename: matches.append( (group["name"], path) ) return matches def enqueue_rm(filename: str, model_type: str | None = None) -> int: matches = find_model( filename, model_type, ) if not matches: print( f"ERROR: Model not found: {filename}", file=sys.stderr, ) return 1 if model_type is None and len(matches) > 1: print( f"ERROR: Model '{filename}' exists " f"in multiple types:", file=sys.stderr, ) for found_type, path in matches: print( f" {found_type}: {path}", file=sys.stderr, ) print( "\nSpecify model type explicitly.", file=sys.stderr, ) return 1 found_type, path = matches[0] with db_connect() as db: cursor = db.execute( """ INSERT INTO jobs ( action, model_type, filename ) VALUES (?, ?, ?) """, ( "rm", found_type, filename, ), ) db.commit() job_id = cursor.lastrowid print(f"Queued job #{job_id}") print(f"Action: rm") print(f"Type: {found_type}") print(f"File: {filename}") print(f"Target: {path}") return 0 def run_download(job): model_type = job["model_type"] filename = job["filename"] url = job["url"] directory = validate_model_type(model_type) destination = directory / filename partial = directory / f".{filename}.part" if destination.exists(): raise RuntimeError( f"Destination already exists: {destination}" ) print( f"[job #{job['id']}] Downloading " f"{filename}" ) print(f"[job #{job['id']}] URL: {url}") command = [ "curl", "--fail", "--location", "--retry", "5", "--retry-delay", "5", "--retry-all-errors", "--continue-at", "-", "--output", str(partial), url, ] result = subprocess.run( command, check=False, ) if result.returncode != 0: raise RuntimeError( f"curl exited with code " f"{result.returncode}" ) if not partial.exists(): raise RuntimeError( "Download completed but partial file " "does not exist" ) partial.rename(destination) print( f"[job #{job['id']}] Download complete: " f"{destination}" ) def run_delete(job): model_type = job["model_type"] filename = job["filename"] directory = validate_model_type(model_type) destination = directory / filename if not destination.exists(): print( f"[job #{job['id']}] " f"File already gone: {destination}" ) return if not destination.is_file(): raise RuntimeError( f"Not a regular file: {destination}" ) destination.unlink() print( f"[job #{job['id']}] Deleted: " f"{destination}" ) def claim_job(): with db_connect() as db: db.execute("BEGIN IMMEDIATE") job = db.execute( """ SELECT * FROM jobs WHERE status = 'pending' ORDER BY id LIMIT 1 """ ).fetchone() if job is None: db.commit() return None db.execute( """ UPDATE jobs SET status = 'running', started_at = CURRENT_TIMESTAMP WHERE id = ? """, (job["id"],), ) db.commit() return job def finish_job(job_id: int): with db_connect() as db: db.execute( """ UPDATE jobs SET status = 'done', finished_at = CURRENT_TIMESTAMP WHERE id = ? """, (job_id,), ) db.commit() def fail_job(job_id: int, error: str): with db_connect() as db: db.execute( """ UPDATE jobs SET status = 'failed', error = ?, finished_at = CURRENT_TIMESTAMP WHERE id = ? """, ( error, job_id, ), ) db.commit() def process_job(job): try: if job["action"] == "add": run_download(job) elif job["action"] == "rm": run_delete(job) else: raise RuntimeError( f"Unknown action: {job['action']}" ) except Exception as exc: error = str(exc) print( f"[job #{job['id']}] ERROR: {error}", file=sys.stderr, ) fail_job( job["id"], error, ) return finish_job(job["id"]) def worker_loop(): print("Model worker started.") print(f"Models: {MODELS_DIR}") print(f"Database: {DB_PATH}") while True: job = claim_job() if job is None: time.sleep(POLL_INTERVAL) continue print( f"[job #{job['id']}] " f"{job['action']} " f"{job['model_type']}/" f"{job['filename']}" ) process_job(job) def main(): init_db() command = sys.argv[1] if len(sys.argv) > 1 else None if command == "list": model_type = sys.argv[2] if len(sys.argv) > 2 else None raise SystemExit( command_list(model_type) ) if command == "add": if len(sys.argv) != 4: print( "Usage: worker.py add ", file=sys.stderr, ) raise SystemExit(1) raise SystemExit( enqueue_add( sys.argv[2], sys.argv[3], ) ) if command == "rm": if len(sys.argv) not in (3, 4): print( "Usage: worker.py rm [type]", file=sys.stderr, ) raise SystemExit(1) filename = sys.argv[2] model_type = ( sys.argv[3] if len(sys.argv) == 4 else None ) raise SystemExit( enqueue_rm( filename, model_type, ) ) if command is not None: print( "Usage:", file=sys.stderr, ) print( " worker.py", file=sys.stderr, ) print( " worker.py list [type]", file=sys.stderr, ) print( " worker.py add ", file=sys.stderr, ) print( " worker.py rm [type]", file=sys.stderr, ) raise SystemExit(1) worker_loop() if __name__ == "__main__": main()