Files
GPU-Node/model-worker/worker.py

1427 lines
30 KiB
Python

import os
import re
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
PROGRESS_INTERVAL = 1
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',
progress REAL,
downloaded_bytes INTEGER,
total_bytes INTEGER,
error TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
started_at TEXT,
finished_at TEXT
)
"""
)
columns = {
row["name"]
for row in db.execute(
"PRAGMA table_info(jobs)"
).fetchall()
}
if "progress" not in columns:
db.execute(
"ALTER TABLE jobs ADD COLUMN progress REAL"
)
if "downloaded_bytes" not in columns:
db.execute(
"""
ALTER TABLE jobs
ADD COLUMN downloaded_bytes INTEGER
"""
)
if "total_bytes" not in columns:
db.execute(
"""
ALTER TABLE jobs
ADD COLUMN total_bytes INTEGER
"""
)
# Если worker был убит во время выполнения,
# возвращаем незавершённые jobs обратно в очередь.
db.execute(
"""
UPDATE jobs
SET status = 'pending',
started_at = NULL
WHERE status = 'running'
"""
)
db.execute(
"""
UPDATE jobs
SET status = 'pending',
started_at = NULL
WHERE status = 'cancelling'
"""
)
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: "
f"{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',
'cancelling'
)
ORDER BY id DESC
LIMIT 1
""",
(
filename,
model_type,
action,
),
).fetchone()
def find_active_add_job(
filename: str,
model_type: str,
):
with db_connect() as db:
return db.execute(
"""
SELECT *
FROM jobs
WHERE filename = ?
AND model_type = ?
AND action = 'add'
AND status IN (
'pending',
'running',
'cancelling'
)
ORDER BY id DESC
LIMIT 1
""",
(
filename,
model_type,
),
).fetchone()
def update_progress(
job_id: int,
progress: float | None,
downloaded_bytes: int | None = None,
total_bytes: int | None = None,
):
with db_connect() as db:
db.execute(
"""
UPDATE jobs
SET progress = ?,
downloaded_bytes = ?,
total_bytes = ?
WHERE id = ?
""",
(
progress,
downloaded_bytes,
total_bytes,
job_id,
),
)
db.commit()
def request_cancel(job_id: int):
with db_connect() as db:
db.execute(
"""
UPDATE jobs
SET status = 'cancelling'
WHERE id = ?
AND status = 'running'
""",
(job_id,),
)
db.commit()
def mark_cancelled(job_id: int):
with db_connect() as db:
db.execute(
"""
UPDATE jobs
SET status = 'cancelled',
finished_at = CURRENT_TIMESTAMP
WHERE id = ?
""",
(job_id,),
)
db.commit()
def cancel_pending_job(job_id: int):
with db_connect() as db:
db.execute(
"""
UPDATE jobs
SET status = 'cancelled',
finished_at = CURRENT_TIMESTAMP
WHERE id = ?
AND status = 'pending'
""",
(job_id,))
db.commit()
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: "
f"{human_size(partial.stat().st_size)}"
)
return 0
def delete_partial(
filename: str,
model_type: str,
):
partial = find_partial(
filename,
model_type,
)
if partial is None:
return False
try:
partial.unlink()
except FileNotFoundError:
return False
return True
def enqueue_rm(
filename: str,
model_type: str | None = None,
) -> int:
# Если тип указан явно — это самый важный случай:
# мы можем отменить скачивание даже если модели
# ещё физически нет.
if model_type is not None:
try:
validate_model_type(model_type)
except ValueError as exc:
print(
f"ERROR: {exc}",
file=sys.stderr,
)
return 1
active_add = find_active_add_job(
filename,
model_type,
)
if active_add:
status = active_add["status"]
if status == "pending":
cancel_pending_job(
active_add["id"]
)
deleted = delete_partial(
filename,
model_type,
)
print(
f"Cancelled job "
f"#{active_add['id']}"
)
if deleted:
print(
f"Removed partial file: "
f".{filename}.part"
)
return 0
if status == "running":
request_cancel(
active_add["id"]
)
print(
f"Cancellation requested for "
f"job #{active_add['id']}"
)
print(
"Worker will stop the download "
"and remove the partial file."
)
return 0
if status == "cancelling":
print(
f"Cancellation already requested "
f"for job #{active_add['id']}"
)
return 0
matches = find_model(
filename,
model_type,
)
if matches:
found_type, _ = matches[0]
else:
partial = find_partial(
filename,
model_type,
)
if partial:
try:
partial.unlink()
except FileNotFoundError:
pass
print(
f"Removed partial file: "
f"{partial}"
)
return 0
print(
f"ERROR: Model not found: "
f"{filename}",
file=sys.stderr,
)
return 1
else:
matches = find_model(filename)
if not matches:
print(
f"ERROR: Model not found: {filename}",
file=sys.stderr,
)
return 1
if 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, _ = 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 is_cancel_requested(job_id: int) -> bool:
with db_connect() as db:
row = db.execute(
"""
SELECT status
FROM jobs
WHERE id = ?
""",
(job_id,),
).fetchone()
return (
row is not None
and row["status"] == "cancelling"
)
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: "
f"{destination}"
)
existing_size = (
partial.stat().st_size
if partial.exists()
else 0
)
if existing_size:
job_log(
job["id"],
f"Resuming from "
f"{human_size(existing_size)}",
)
else:
job_log(
job["id"],
"Starting download",
)
command = [
"curl",
"--fail",
"--location",
"--progress-bar",
"--retry", "5",
"--retry-delay", "5",
"--retry-all-errors",
"--continue-at", "-",
"--output", str(partial),
url,
]
process = subprocess.Popen(
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
)
last_progress_update = 0.0
last_downloaded = existing_size
last_progress = None
buffer = ""
try:
while True:
chunk = process.stderr.read(1)
if chunk == "":
break
buffer += chunk
if chunk not in "\r\n":
continue
matches = re.findall(
r"(\d+(?:\.\d+)?)%",
buffer,
)
if matches:
last_progress = float(
matches[-1]
)
buffer = ""
now = time.monotonic()
if (
now - last_progress_update
>= PROGRESS_INTERVAL
):
try:
downloaded = (
partial.stat().st_size
)
except OSError:
downloaded = None
last_downloaded = (
downloaded
if downloaded is not None
else last_downloaded
)
update_progress(
job["id"],
last_progress,
last_downloaded,
)
last_progress_update = now
if is_cancel_requested(
job["id"]
):
job_log(
job["id"],
"Cancellation requested",
)
process.terminate()
try:
process.wait(
timeout=5
)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
raise InterruptedError(
"Download cancelled"
)
returncode = process.wait()
if is_cancel_requested(job["id"]):
raise InterruptedError(
"Download cancelled"
)
if returncode != 0:
raise RuntimeError(
f"curl exited with code "
f"{returncode}"
)
finally:
if process.poll() is None:
process.kill()
process.wait()
if not partial.exists():
raise RuntimeError(
"Download completed but partial "
"file does not exist"
)
final_size = partial.stat().st_size
if destination.exists():
raise RuntimeError(
f"Destination already exists: "
f"{destination}"
)
partial.rename(destination)
update_progress(
job["id"],
100.0,
final_size,
final_size,
)
job_log(
job["id"],
f"Download complete: "
f"{human_size(final_size)}",
)
def cleanup_cancelled_download(job):
model_type = job["model_type"]
filename = job["filename"]
try:
partial = find_partial(
filename,
model_type,
)
except ValueError:
return
if partial is None:
return
try:
size = partial.stat().st_size
except OSError:
size = 0
try:
partial.unlink()
except FileNotFoundError:
return
job_log(
job["id"],
f"Removed partial file: "
f"{partial.name} "
f"({human_size(size)})",
)
def run_delete(job):
model_type = job["model_type"]
filename = job["filename"]
directory = validate_model_type(model_type)
destination = directory / filename
partial = directory / f".{filename}.part"
# rm должен также убирать оставшийся .part
if partial.exists():
try:
size = partial.stat().st_size
except OSError:
size = 0
partial.unlink()
job_log(
job["id"],
f"Removed partial file: "
f"{partial.name} "
f"({human_size(size)})",
)
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: "
f"{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',
progress = CASE
WHEN action = 'add'
THEN 100.0
ELSE progress
END,
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: "
f"{job['action']}"
)
except InterruptedError:
cleanup_cancelled_download(job)
mark_cancelled(job["id"])
job_log(
job["id"],
"CANCELLED",
)
return
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 format_progress(job):
if job["status"] == "done":
return "100.0%"
if job["progress"] is not None:
return f"{job['progress']:6.1f}%"
return "-"
def command_queue(
watch: bool = False,
) -> int:
while True:
with db_connect() as db:
jobs = db.execute(
"""
SELECT *
FROM jobs
ORDER BY id DESC
LIMIT 20
"""
).fetchall()
if watch:
print(
"\033[2J\033[H",
end="",
)
if not jobs:
print("Queue is empty.")
else:
print(
"ID STATUS ACTION "
"PROGRESS TYPE"
)
print(
"---------------------------------------------------------------"
)
for job in jobs:
progress = format_progress(job)
print(
f"{job['id']:<6} "
f"{job['status']:<12} "
f"{job['action']:<8} "
f"{progress:<10} "
f"{job['model_type']}/"
f"{job['filename']}"
)
if (
job["status"] == "failed"
and job["error"]
):
print(
f" ERROR: "
f"{job['error']}"
)
if not watch:
return 0
time.sleep(1)
def command_queue_clear(
status: str | None = None,
) -> int:
with db_connect() as db:
if status is None:
cursor = db.execute(
"""
DELETE FROM jobs
WHERE status IN (
'done',
'failed',
'cancelled'
)
"""
)
elif status in (
"done",
"failed",
"cancelled",
):
cursor = db.execute(
"""
DELETE FROM jobs
WHERE status = ?
""",
(status,),
)
else:
print(
"ERROR: Can only clear "
"done, failed or cancelled jobs.",
file=sys.stderr,
)
return 1
db.commit()
print(
f"Removed {cursor.rowcount} jobs."
)
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 print_usage():
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 queue --watch",
file=sys.stderr,
)
print(
" worker.py queue --clear",
file=sys.stderr,
)
print(
" worker.py queue --clear-done",
file=sys.stderr,
)
print(
" worker.py queue --clear-failed",
file=sys.stderr,
)
print(
" worker.py queue --clear-cancelled",
file=sys.stderr,
)
print(
" worker.py add <URL> <type>",
file=sys.stderr,
)
print(
" worker.py rm <filename> [type]",
file=sys.stderr,
)
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":
if len(sys.argv) > 2:
option = sys.argv[2]
if option == "--watch":
raise SystemExit(
command_queue(True)
)
if option == "--clear":
raise SystemExit(
command_queue_clear()
)
if option == "--clear-done":
raise SystemExit(
command_queue_clear("done")
)
if option == "--clear-failed":
raise SystemExit(
command_queue_clear("failed")
)
if option == "--clear-cancelled":
raise SystemExit(
command_queue_clear("cancelled")
)
print_usage()
raise SystemExit(1)
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()
raise SystemExit(1)
worker_loop()
if __name__ == "__main__":
main()