794 lines
16 KiB
Python
794 lines
16 KiB
Python
import os
|
|
import sqlite3
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
from urllib.parse import unquote, urlparse
|
|
|
|
|
|
MODELS_DIR = Path("/models")
|
|
STATE_DIR = Path("/state")
|
|
DB_PATH = STATE_DIR / "queue.db"
|
|
|
|
POLL_INTERVAL = 2
|
|
|
|
IGNORED_NAMES = {
|
|
".gitkeep",
|
|
}
|
|
|
|
IGNORED_EXTENSIONS = {
|
|
".txt",
|
|
}
|
|
|
|
|
|
def log(message: str):
|
|
print(f"[worker] {message}", flush=True)
|
|
|
|
|
|
def job_log(job_id: int, message: str):
|
|
print(f"[job #{job_id}] {message}", flush=True)
|
|
|
|
|
|
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.execute(
|
|
"""
|
|
UPDATE jobs
|
|
SET status = 'pending',
|
|
started_at = NULL
|
|
WHERE status = 'running'
|
|
"""
|
|
)
|
|
|
|
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
|
|
|
|
if path.name.endswith(".part"):
|
|
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 not is_model_file(path):
|
|
continue
|
|
|
|
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 models)")
|
|
return 0
|
|
|
|
for group in groups:
|
|
print(
|
|
f"\n{group['name']}/ — "
|
|
f"{len(group['files'])} models — "
|
|
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} models)"
|
|
)
|
|
|
|
return 0
|
|
|
|
|
|
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 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"
|
|
)
|
|
|
|
if filename in {".", ".."}:
|
|
raise ValueError(
|
|
"Invalid filename from URL"
|
|
)
|
|
|
|
return filename
|
|
|
|
|
|
def find_model(filename: str, model_type: str | None = None):
|
|
matches = []
|
|
|
|
for group in collect_models(model_type):
|
|
for path, _ in group["files"]:
|
|
if path.name == filename:
|
|
matches.append(
|
|
(group["name"], path)
|
|
)
|
|
|
|
return matches
|
|
|
|
|
|
def find_partial(filename: str, model_type: str):
|
|
directory = validate_model_type(model_type)
|
|
|
|
partial = directory / f".{filename}.part"
|
|
|
|
if partial.exists():
|
|
return partial
|
|
|
|
return None
|
|
|
|
|
|
def find_existing_job(
|
|
filename: str,
|
|
model_type: str,
|
|
action: str,
|
|
):
|
|
with db_connect() as db:
|
|
return db.execute(
|
|
"""
|
|
SELECT *
|
|
FROM jobs
|
|
WHERE filename = ?
|
|
AND model_type = ?
|
|
AND action = ?
|
|
AND status IN ('pending', 'running')
|
|
ORDER BY id DESC
|
|
LIMIT 1
|
|
""",
|
|
(
|
|
filename,
|
|
model_type,
|
|
action,
|
|
),
|
|
).fetchone()
|
|
|
|
|
|
def enqueue_add(url: str, model_type: str) -> int:
|
|
directory = validate_model_type(model_type)
|
|
filename = get_filename_from_url(url)
|
|
|
|
destination = directory / filename
|
|
|
|
if destination.exists():
|
|
print(
|
|
f"ERROR: Model already exists: "
|
|
f"{destination}",
|
|
file=sys.stderr,
|
|
)
|
|
return 1
|
|
|
|
existing_job = find_existing_job(
|
|
filename,
|
|
model_type,
|
|
"add",
|
|
)
|
|
|
|
if existing_job:
|
|
print(
|
|
f"Job already queued: "
|
|
f"#{existing_job['id']}"
|
|
)
|
|
|
|
print(
|
|
f"Status: {existing_job['status']}"
|
|
)
|
|
|
|
return 0
|
|
|
|
partial = find_partial(
|
|
filename,
|
|
model_type,
|
|
)
|
|
|
|
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("Action: add")
|
|
print(f"Type: {model_type}")
|
|
print(f"File: {filename}")
|
|
|
|
if partial:
|
|
print(
|
|
f"Resume: {human_size(partial.stat().st_size)}"
|
|
)
|
|
|
|
return 0
|
|
|
|
|
|
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]
|
|
|
|
existing_job = find_existing_job(
|
|
filename,
|
|
found_type,
|
|
"rm",
|
|
)
|
|
|
|
if existing_job:
|
|
print(
|
|
f"Job already queued: "
|
|
f"#{existing_job['id']}"
|
|
)
|
|
print(
|
|
f"Status: {existing_job['status']}"
|
|
)
|
|
return 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("Action: rm")
|
|
print(f"Type: {found_type}")
|
|
print(f"File: {filename}")
|
|
|
|
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}"
|
|
)
|
|
|
|
existing_size = (
|
|
partial.stat().st_size
|
|
if partial.exists()
|
|
else 0
|
|
)
|
|
|
|
if existing_size:
|
|
job_log(
|
|
job["id"],
|
|
f"Resuming from {human_size(existing_size)}",
|
|
)
|
|
else:
|
|
job_log(
|
|
job["id"],
|
|
"Starting download",
|
|
)
|
|
|
|
command = [
|
|
"curl",
|
|
"--fail",
|
|
"--location",
|
|
"--silent",
|
|
"--show-error",
|
|
"--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"
|
|
)
|
|
|
|
final_size = partial.stat().st_size
|
|
|
|
partial.rename(destination)
|
|
|
|
job_log(
|
|
job["id"],
|
|
f"Download complete: "
|
|
f"{human_size(final_size)}",
|
|
)
|
|
|
|
|
|
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():
|
|
job_log(
|
|
job["id"],
|
|
f"File already gone: {destination}",
|
|
)
|
|
return
|
|
|
|
if not destination.is_file():
|
|
raise RuntimeError(
|
|
f"Not a regular file: {destination}"
|
|
)
|
|
|
|
destination.unlink()
|
|
|
|
job_log(
|
|
job["id"],
|
|
f"Deleted: {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):
|
|
job_log(
|
|
job["id"],
|
|
f"{job['action'].upper()} "
|
|
f"{job['model_type']}/{job['filename']}",
|
|
)
|
|
|
|
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)
|
|
|
|
job_log(
|
|
job["id"],
|
|
f"FAILED: {error}",
|
|
)
|
|
|
|
fail_job(
|
|
job["id"],
|
|
error,
|
|
)
|
|
|
|
return
|
|
|
|
finish_job(job["id"])
|
|
|
|
job_log(
|
|
job["id"],
|
|
"DONE",
|
|
)
|
|
|
|
|
|
def command_queue() -> int:
|
|
with db_connect() as db:
|
|
jobs = db.execute(
|
|
"""
|
|
SELECT *
|
|
FROM jobs
|
|
ORDER BY id DESC
|
|
LIMIT 20
|
|
"""
|
|
).fetchall()
|
|
|
|
if not jobs:
|
|
print("Queue is empty.")
|
|
return 0
|
|
|
|
print(
|
|
"ID STATUS ACTION TYPE"
|
|
)
|
|
print(
|
|
"-----------------------------------------------"
|
|
)
|
|
|
|
for job in jobs:
|
|
print(
|
|
f"{job['id']:<6} "
|
|
f"{job['status']:<9} "
|
|
f"{job['action']:<8} "
|
|
f"{job['model_type']}/{job['filename']}"
|
|
)
|
|
|
|
if job["status"] == "failed" and job["error"]:
|
|
print(
|
|
f" ERROR: {job['error']}"
|
|
)
|
|
|
|
return 0
|
|
|
|
|
|
def worker_loop():
|
|
log("Model worker started")
|
|
log(f"Models: {MODELS_DIR}")
|
|
log(f"Database: {DB_PATH}")
|
|
|
|
while True:
|
|
job = claim_job()
|
|
|
|
if job is None:
|
|
time.sleep(POLL_INTERVAL)
|
|
continue
|
|
|
|
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 == "queue":
|
|
raise SystemExit(
|
|
command_queue()
|
|
)
|
|
|
|
if command == "add":
|
|
if len(sys.argv) != 4:
|
|
print(
|
|
"Usage: worker.py add <URL> <type>",
|
|
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 <filename> [type]",
|
|
file=sys.stderr,
|
|
)
|
|
raise SystemExit(1)
|
|
|
|
raise SystemExit(
|
|
enqueue_rm(
|
|
sys.argv[2],
|
|
sys.argv[3]
|
|
if len(sys.argv) == 4
|
|
else None,
|
|
)
|
|
)
|
|
|
|
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 queue", file=sys.stderr)
|
|
print(" worker.py add <URL> <type>", file=sys.stderr)
|
|
print(" worker.py rm <filename> [type]", file=sys.stderr)
|
|
|
|
raise SystemExit(1)
|
|
|
|
worker_loop()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |