From 81d6f9f9798aeddb40c256b24dce3b347a2f9e88 Mon Sep 17 00:00:00 2001 From: Mikan <72257910+Mikan-DS@users.noreply.github.com> Date: Fri, 9 Oct 2026 01:45:03 +0400 Subject: [PATCH] update worker and update now update both ssh and worker --- model-worker/worker.py | 815 ++++++++++++++++++++++++++++++++++++----- ssh/scripts/status.sh | 9 +- 2 files changed, 729 insertions(+), 95 deletions(-) diff --git a/model-worker/worker.py b/model-worker/worker.py index 61b9edf..0b8f925 100644 --- a/model-worker/worker.py +++ b/model-worker/worker.py @@ -1,4 +1,5 @@ import os +import re import sqlite3 import subprocess import sys @@ -12,6 +13,7 @@ STATE_DIR = Path("/state") DB_PATH = STATE_DIR / "queue.db" POLL_INTERVAL = 2 +PROGRESS_INTERVAL = 1 IGNORED_NAMES = { ".gitkeep", @@ -53,7 +55,13 @@ def init_db(): 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 @@ -61,12 +69,51 @@ def init_db(): """ ) + 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 = 'running' + WHERE status = 'cancelling' """ ) @@ -158,7 +205,10 @@ 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( + f"ERROR: No models found for type: " + f"{model_type}" + ) print() available = [ @@ -256,7 +306,10 @@ def get_filename_from_url(url: str) -> str: return filename -def find_model(filename: str, model_type: str | None = None): +def find_model( + filename: str, + model_type: str | None = None, +): matches = [] for group in collect_models(model_type): @@ -269,7 +322,10 @@ def find_model(filename: str, model_type: str | None = None): return matches -def find_partial(filename: str, model_type: str): +def find_partial( + filename: str, + model_type: str, +): directory = validate_model_type(model_type) partial = directory / f".{filename}.part" @@ -293,7 +349,11 @@ def find_existing_job( WHERE filename = ? AND model_type = ? AND action = ? - AND status IN ('pending', 'running') + AND status IN ( + 'pending', + 'running', + 'cancelling' + ) ORDER BY id DESC LIMIT 1 """, @@ -305,7 +365,108 @@ def find_existing_job( ).fetchone() -def enqueue_add(url: str, model_type: str) -> int: +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) @@ -372,49 +533,170 @@ def enqueue_add(url: str, model_type: str) -> int: if partial: print( - f"Resume: {human_size(partial.stat().st_size)}" + 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: - 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: + # Если тип указан явно — это самый важный случай: + # мы можем отменить скачивание даже если модели + # ещё физически нет. + if model_type is not None: + try: + validate_model_type(model_type) + except ValueError as exc: print( - f" {found_type}: {path}", + 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, ) - print( - "\nSpecify model type explicitly.", - file=sys.stderr, - ) + return 1 - return 1 + else: + matches = find_model(filename) - found_type, path = matches[0] + 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, @@ -461,6 +743,23 @@ def enqueue_rm( 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"] @@ -473,7 +772,8 @@ def run_download(job): if destination.exists(): raise RuntimeError( - f"Destination already exists: {destination}" + f"Destination already exists: " + f"{destination}" ) existing_size = ( @@ -485,7 +785,8 @@ def run_download(job): if existing_size: job_log( job["id"], - f"Resuming from {human_size(existing_size)}", + f"Resuming from " + f"{human_size(existing_size)}", ) else: job_log( @@ -497,8 +798,7 @@ def run_download(job): "curl", "--fail", "--location", - "--silent", - "--show-error", + "--progress-bar", "--retry", "5", "--retry-delay", "5", "--retry-all-errors", @@ -507,27 +807,134 @@ def run_download(job): url, ] - result = subprocess.run( + process = subprocess.Popen( command, - check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + text=True, + bufsize=1, ) - if result.returncode != 0: - raise RuntimeError( - f"curl exited with code " - f"{result.returncode}" - ) + 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" + "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: " @@ -535,12 +942,63 @@ def run_download(job): ) +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( @@ -551,7 +1009,8 @@ def run_delete(job): if not destination.is_file(): raise RuntimeError( - f"Not a regular file: {destination}" + f"Not a regular file: " + f"{destination}" ) destination.unlink() @@ -601,6 +1060,11 @@ def finish_job(job_id: int): """ UPDATE jobs SET status = 'done', + progress = CASE + WHEN action = 'add' + THEN 100.0 + ELSE progress + END, finished_at = CURRENT_TIMESTAMP WHERE id = ? """, @@ -610,7 +1074,10 @@ def finish_job(job_id: int): db.commit() -def fail_job(job_id: int, error: str): +def fail_job( + job_id: int, + error: str, +): with db_connect() as db: db.execute( """ @@ -645,9 +1112,21 @@ def process_job(job): else: raise RuntimeError( - f"Unknown action: {job['action']}" + 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) @@ -671,41 +1150,118 @@ def process_job(job): ) -def command_queue() -> int: - with db_connect() as db: - jobs = db.execute( - """ - SELECT * - FROM jobs - ORDER BY id DESC - LIMIT 20 - """ - ).fetchall() +def format_progress(job): + if job["status"] == "done": + return "100.0%" - if not jobs: - print("Queue is empty.") - return 0 + if job["progress"] is not None: + return f"{job['progress']:6.1f}%" - print( - "ID STATUS ACTION TYPE" - ) - print( - "-----------------------------------------------" - ) + return "-" - 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"]: +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( - f" ERROR: {job['error']}" + "\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 @@ -724,10 +1280,58 @@ def worker_loop(): 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 ", + file=sys.stderr, + ) + print( + " worker.py rm [type]", + file=sys.stderr, + ) + + def main(): init_db() - command = sys.argv[1] if len(sys.argv) > 1 else None + command = ( + sys.argv[1] + if len(sys.argv) > 1 + else None + ) if command == "list": model_type = ( @@ -741,6 +1345,37 @@ def main(): ) 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() ) @@ -748,7 +1383,8 @@ def main(): if command == "add": if len(sys.argv) != 4: print( - "Usage: worker.py add ", + "Usage: worker.py " + "add ", file=sys.stderr, ) raise SystemExit(1) @@ -763,7 +1399,8 @@ def main(): if command == "rm": if len(sys.argv) not in (3, 4): print( - "Usage: worker.py rm [type]", + "Usage: worker.py " + "rm [type]", file=sys.stderr, ) raise SystemExit(1) @@ -771,20 +1408,16 @@ def main(): raise SystemExit( enqueue_rm( sys.argv[2], - sys.argv[3] - if len(sys.argv) == 4 - else None, + ( + 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 ", file=sys.stderr) - print(" worker.py rm [type]", file=sys.stderr) - + print_usage() raise SystemExit(1) worker_loop() diff --git a/ssh/scripts/status.sh b/ssh/scripts/status.sh index 95fcf33..76c0802 100644 --- a/ssh/scripts/status.sh +++ b/ssh/scripts/status.sh @@ -17,10 +17,10 @@ update_ssh() { case "$SSH_ROLE" in main) - TARGET_SERVICE="ssh-companion" + TARGET_SSH_SERVICE="ssh-companion" ;; companion) - TARGET_SERVICE="ssh" + TARGET_SSH_SERVICE="ssh" ;; *) echo "ERROR: unknown SSH role: $SSH_ROLE" >&2 @@ -31,7 +31,7 @@ update_ssh() { echo "Current SSH role: $SSH_ROLE" echo "Host project: $HOST_PROJECT_PATH" echo "SSH keys: $SSH_KEYS_HOST" - echo "Updating: $TARGET_SERVICE" + echo "Updating: $TARGET_SSH_SERVICE + model-worker" HOST_PROJECT_PATH="$HOST_PROJECT_PATH" \ PROJECT_HOST_DIR="$HOST_PROJECT_PATH" \ @@ -41,7 +41,8 @@ update_ssh() { up -d \ --build \ --force-recreate \ - "$TARGET_SERVICE" + "$TARGET_SSH_SERVICE" \ + model-worker }