model worker

This commit is contained in:
Mikan
2026-10-09 01:00:33 +04:00
parent 654126be43
commit 883188e086
7 changed files with 707 additions and 155 deletions

2
.gitignore vendored
View File

@@ -27,6 +27,8 @@ gpu/comfy/user/*
comfyui/run/
!comfyui/run/.gitkeep
# Model worker
gpu/model-worker/*
# Environment / secrets
.env

View File

@@ -111,6 +111,21 @@ services:
restart: "no"
model-worker:
build:
context: ./model-worker
container_name: gpu-node-model-worker
volumes:
- ${HOST_PROJECT_PATH:-./}/gpu/comfy/models:/models
- ${HOST_PROJECT_PATH:-./}/gpu/model-worker:/state
networks:
- gpu-node
restart: always
llama:
profiles:
- llama

13
model-worker/Dockerfile Normal file
View File

@@ -0,0 +1,13 @@
FROM python:3.13-alpine
RUN apk add --no-cache \
curl \
ca-certificates
WORKDIR /app
COPY worker.py /app/worker.py
RUN mkdir -p /models /state
ENTRYPOINT ["python3", "/app/worker.py"]

635
model-worker/worker.py Normal file
View File

@@ -0,0 +1,635 @@
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 <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)
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 <URL> <type>",
file=sys.stderr,
)
print(
" worker.py rm <filename> [type]",
file=sys.stderr,
)
raise SystemExit(1)
worker_loop()
if __name__ == "__main__":
main()

View File

@@ -23,6 +23,8 @@ Usage:
gpuctl start comfy [extra args...]
gpuctl comfy models list [type]
gpuctl comfy models add <URL> <type>
gpuctl comfy models rm <filename> [type]
gpuctl stop <service>
gpuctl restart <service>

View File

@@ -35,169 +35,37 @@ start_comfy() {
--format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
}
model_worker_exec() {
docker exec \
gpu-node-model-worker \
python3 \
/app/worker.py \
"$@"
}
list_comfy_models() {
MODELS_DIR="$PROJECT_DIR/gpu/comfy/models"
model_worker_exec list "$@"
}
if [ ! -d "$MODELS_DIR" ]; then
echo "ERROR: Models directory not found: $MODELS_DIR" >&2
add_comfy_model() {
if [ "$#" -ne 2 ]; then
echo "Usage: gpuctl comfy models add <URL> <type>" >&2
return 1
fi
python3 - "$MODELS_DIR" "${1:-}" <<'PY'
import os
import sys
root = os.path.abspath(sys.argv[1])
selected_type = sys.argv[2] if len(sys.argv) > 2 else ""
IGNORED_NAMES = {".gitkeep"}
IGNORED_EXTENSIONS = {".txt"}
model_worker_exec add "$1" "$2"
}
def is_model_file(name):
if name in IGNORED_NAMES:
return False
remove_comfy_model() {
if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
echo "Usage: gpuctl comfy models rm <filename> [type]" >&2
return 1
fi
return os.path.splitext(name)[1].lower() not in IGNORED_EXTENSIONS
def human_size(size):
units = ["B", "KB", "MB", "GB", "TB"]
value = float(size)
for unit in units:
if value < 1024 or unit == units[-1]:
return f"{value:.2f} {unit}"
value /= 1024
def collect_files(directory):
result = []
for current, dirs, files in os.walk(directory):
dirs[:] = sorted(
name
for name in dirs
if not os.path.islink(os.path.join(current, name))
)
for name in sorted(files):
path = os.path.join(current, name)
if not is_model_file(name):
continue
if os.path.islink(path):
continue
try:
if os.path.isfile(path):
result.append(
(path, os.path.getsize(path))
)
except OSError as exc:
print(
f"WARNING: Cannot read {path}: {exc}",
file=sys.stderr,
)
return result
groups = []
for name in sorted(os.listdir(root)):
directory = os.path.join(root, name)
if not os.path.isdir(directory):
continue
if os.path.islink(directory):
continue
files = collect_files(directory)
if not files:
continue
size = sum(
file_size
for _, file_size in files
)
groups.append(
(name, files, size)
)
if selected_type:
groups = [
group
for group in groups
if group[0] == selected_type
]
if not groups:
print(
f"ERROR: No models found for type: "
f"{selected_type}"
)
available = []
for name in sorted(os.listdir(root)):
path = os.path.join(root, name)
if not os.path.isdir(path):
continue
if os.path.islink(path):
continue
if collect_files(path):
available.append(name)
print(
"Available types: "
+ (", ".join(available) or "(none)")
)
sys.exit(1)
total_size = 0
total_files = 0
for name, files, size in groups:
print(
f"\n{name}/ — "
f"{len(files)} files — "
f"{human_size(size)}"
)
for path, file_size in files:
relative = os.path.relpath(
path,
root,
)
print(
f" {relative} — "
f"{human_size(file_size)}"
)
total_size += size
total_files += len(files)
print(
f"\nTotal: "
f"{human_size(total_size)} "
f"({total_files} files)"
)
PY
model_worker_exec rm "$@"
}
@@ -212,12 +80,24 @@ comfy_models_command() {
return 1
fi
list_comfy_models "${1:-}"
list_comfy_models "$@"
;;
add)
shift
add_comfy_model "$@"
;;
rm)
shift
remove_comfy_model "$@"
;;
*)
echo "Usage:"
echo " gpuctl comfy models list [type]"
echo " gpuctl comfy models add <URL> <type>"
echo " gpuctl comfy models rm <filename> [type]"
return 1
;;
esac
@@ -235,6 +115,8 @@ comfy_command() {
*)
echo "Usage:"
echo " gpuctl comfy models list [type]"
echo " gpuctl comfy models add <URL> <type>"
echo " gpuctl comfy models rm <filename> [type]"
return 1
;;
esac

View File

@@ -65,6 +65,9 @@ get_service_container() {
webdav)
echo "gpu-node-webdav"
;;
model-worker)
echo "gpu-node-model-worker"
;;
*)
return 1
;;