feat(scripts): каталог bash-скриптов для нод и гостей (VM/LXC)
Добавлена библиотека скриптов по образцу VMmanager: свои скрипты (CRUD в UI) и синхронизация из git-репозитория, параметризация через env-переменные (без конкатенации в shell), выполнение на нодах Proxmox (SSH), в LXC (pct exec) и в VM (QEMU guest agent, переиспользует существующий execute_script). Журнал запусков встроен в общий список задач /api/all-tasks. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
167
backend/app/services/script_catalog_sync.py
Normal file
167
backend/app/services/script_catalog_sync.py
Normal file
@@ -0,0 +1,167 @@
|
||||
"""
|
||||
Синхронизация каталога скриптов из git-репозитория (аналог appstore_catalog.py
|
||||
sync_catalog(), но проще: bash-файлы с метаданными в заголовочных комментариях
|
||||
вместо отдельных манифестов).
|
||||
|
||||
Конвенция метаданных (первые строки файла, до первой не-комментарной строки
|
||||
после shebang):
|
||||
|
||||
#!/bin/bash
|
||||
# name: Очистка старых логов
|
||||
# description: Удаляет журналы старше 30 дней в /var/log
|
||||
# target: node
|
||||
# category: maintenance
|
||||
# param: DAYS|Дней хранить|number|false|30
|
||||
|
||||
Файлы без `# name:` каталогизируются по имени файла.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import glob as _glob
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from loguru import logger
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import utcnow
|
||||
from ..models import ScriptCatalog, ScriptGitRepo
|
||||
|
||||
_META_RE = re.compile(r"^#\s*(name|description|target|category)\s*:\s*(.*)$", re.IGNORECASE)
|
||||
_PARAM_RE = re.compile(r"^#\s*param\s*:\s*(.*)$", re.IGNORECASE)
|
||||
|
||||
|
||||
def _parse_script_metadata(text: str, fallback_name: str) -> dict:
|
||||
name = fallback_name
|
||||
description = None
|
||||
target = "guest"
|
||||
category = None
|
||||
params: List[dict] = []
|
||||
|
||||
for line in text.splitlines()[:60]:
|
||||
stripped = line.strip()
|
||||
if not stripped.startswith("#"):
|
||||
if stripped and not stripped.startswith("#!"):
|
||||
break
|
||||
continue
|
||||
m = _META_RE.match(stripped)
|
||||
if m:
|
||||
key, val = m.group(1).lower(), m.group(2).strip()
|
||||
if key == "name":
|
||||
name = val
|
||||
elif key == "description":
|
||||
description = val
|
||||
elif key == "target":
|
||||
target = val if val in ("node", "guest") else "guest"
|
||||
elif key == "category":
|
||||
category = val
|
||||
continue
|
||||
pm = _PARAM_RE.match(stripped)
|
||||
if pm:
|
||||
parts = [p.strip() for p in pm.group(1).split("|")]
|
||||
# name|label|type|required|default
|
||||
p_name = parts[0] if len(parts) > 0 else None
|
||||
if not p_name:
|
||||
continue
|
||||
params.append({
|
||||
"name": p_name,
|
||||
"label": parts[1] if len(parts) > 1 and parts[1] else p_name,
|
||||
"type": parts[2] if len(parts) > 2 and parts[2] else "string",
|
||||
"required": (parts[3].lower() == "true") if len(parts) > 3 else False,
|
||||
"default": parts[4] if len(parts) > 4 else None,
|
||||
})
|
||||
|
||||
return {
|
||||
"name": name,
|
||||
"description": description,
|
||||
"target_type": target,
|
||||
"category": category,
|
||||
"params_schema": params,
|
||||
}
|
||||
|
||||
|
||||
def _clone_repo(repo: ScriptGitRepo, dest: str) -> None:
|
||||
subprocess.run(
|
||||
["git", "clone", "--depth", "1", "--branch", repo.branch, repo.url, dest],
|
||||
check=True, capture_output=True, timeout=120, text=True,
|
||||
)
|
||||
|
||||
|
||||
def sync_git_repo(db: Session, repo: ScriptGitRepo) -> dict:
|
||||
"""Синхронизировать один git-источник. Идемпотентно (upsert по slug)."""
|
||||
created = updated = skipped = errors = disappeared = 0
|
||||
tmp_dir = tempfile.mkdtemp(prefix="pve_script_repo_")
|
||||
try:
|
||||
try:
|
||||
_clone_repo(repo, tmp_dir)
|
||||
except subprocess.CalledProcessError as e:
|
||||
err = (e.stderr or str(e))[:1000]
|
||||
repo.last_sync_error = err
|
||||
db.commit()
|
||||
return {"error": err, "created": 0, "updated": 0, "skipped": 0, "errors": 1}
|
||||
except subprocess.TimeoutExpired:
|
||||
repo.last_sync_error = "git clone timeout (>120s)"
|
||||
db.commit()
|
||||
return {"error": repo.last_sync_error, "created": 0, "updated": 0, "skipped": 0, "errors": 1}
|
||||
|
||||
pattern = os.path.join(tmp_dir, repo.path_glob)
|
||||
files = _glob.glob(pattern, recursive=True)
|
||||
|
||||
seen_slugs: List[str] = []
|
||||
for path in files:
|
||||
rel_path = os.path.relpath(path, tmp_dir)
|
||||
slug = f"git-{repo.id}-{rel_path}".replace("/", "-").replace("\\", "-")
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8", errors="ignore") as f:
|
||||
content = f.read()
|
||||
except Exception as e:
|
||||
errors += 1
|
||||
logger.warning(f"[script-sync] read {rel_path} failed: {e}")
|
||||
continue
|
||||
|
||||
meta = _parse_script_metadata(content, fallback_name=os.path.basename(rel_path))
|
||||
|
||||
existing = db.query(ScriptCatalog).filter(ScriptCatalog.slug == slug).first()
|
||||
if existing:
|
||||
existing.name = meta["name"]
|
||||
existing.description = meta["description"]
|
||||
existing.target_type = meta["target_type"]
|
||||
existing.category = meta["category"]
|
||||
existing.params_schema = meta["params_schema"]
|
||||
existing.content = content
|
||||
existing.git_path = rel_path
|
||||
updated += 1
|
||||
else:
|
||||
db.add(ScriptCatalog(
|
||||
slug=slug, name=meta["name"], description=meta["description"],
|
||||
target_type=meta["target_type"], category=meta["category"],
|
||||
params_schema=meta["params_schema"], content=content,
|
||||
source="git", git_repo_id=repo.id, git_path=rel_path,
|
||||
))
|
||||
created += 1
|
||||
seen_slugs.append(slug)
|
||||
db.commit()
|
||||
|
||||
# Удалить из этого источника то, что исчезло из репозитория.
|
||||
stale = db.query(ScriptCatalog).filter(
|
||||
ScriptCatalog.git_repo_id == repo.id,
|
||||
~ScriptCatalog.slug.in_(seen_slugs) if seen_slugs else True,
|
||||
).all()
|
||||
for s in stale:
|
||||
db.delete(s)
|
||||
disappeared += 1
|
||||
db.commit()
|
||||
|
||||
repo.last_synced_at = utcnow()
|
||||
repo.last_sync_error = None
|
||||
db.commit()
|
||||
|
||||
return {"created": created, "updated": updated, "skipped": skipped,
|
||||
"errors": errors, "disappeared": disappeared}
|
||||
finally:
|
||||
shutil.rmtree(tmp_dir, ignore_errors=True)
|
||||
187
backend/app/services/script_engine.py
Normal file
187
backend/app/services/script_engine.py
Normal file
@@ -0,0 +1,187 @@
|
||||
"""
|
||||
Движок выполнения скриптов из каталога (backend/app/models/scripts.py).
|
||||
|
||||
Переиспользует существующую инфраструктуру:
|
||||
- SSHClient (root@node) — выполнение на ноде и `pct exec` для LXC (тот же
|
||||
паттерн, что и backend/app/appstore/pipeline.py: base64 -> файл -> exec,
|
||||
без конкатенации пользовательского ввода в shell-команду).
|
||||
- ProxmoxClient.execute_script() — выполнение на VM через QEMU guest agent
|
||||
(backend/app/proxmox/client.py), уже используется в
|
||||
POST /api/{server_id}/vm/{vmid}/execute-script.
|
||||
|
||||
Безопасность параметров: значения параметров НЕ подставляются в тело скрипта
|
||||
текстово. Вместо этого перед скриптом добавляется блок `export VAR='...'` с
|
||||
экранированием одинарных кавычек, скрипт читает их как обычные переменные
|
||||
окружения — тот же принцип, что и .env в appstore pipeline.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, Optional
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from ..models import ProxmoxServer
|
||||
from ..proxmox import ProxmoxClient
|
||||
from ..ssh_client import SSHClient
|
||||
|
||||
_CMD_TIMEOUT = 60
|
||||
|
||||
|
||||
class ScriptExecError(RuntimeError):
|
||||
"""Ошибка выполнения скрипта с человекочитаемым сообщением."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExecResult:
|
||||
success: bool
|
||||
output: str
|
||||
exit_code: int
|
||||
error: Optional[str] = None
|
||||
|
||||
|
||||
def _shell_quote(value: str) -> str:
|
||||
"""Обернуть значение в одинарные кавычки, безопасно для shell."""
|
||||
return "'" + str(value).replace("'", "'\\''") + "'"
|
||||
|
||||
|
||||
def render_params(content: str, params: Dict[str, str]) -> str:
|
||||
"""Добавить блок export-переменных перед телом скрипта.
|
||||
|
||||
Скрипт обращается к параметрам как к обычным переменным окружения
|
||||
($NAME), значения никогда не конкатенируются в исполняемые команды.
|
||||
"""
|
||||
if not params:
|
||||
return content
|
||||
lines = ["#!/bin/sh", "# --- параметры, подставленные каталогом скриптов ---"]
|
||||
for name, value in params.items():
|
||||
# Имя переменной ограничено тем, что уже провалидировано схемой
|
||||
# (см. api/scripts.py) — здесь только защитное экранирование значения.
|
||||
lines.append(f"export {name}={_shell_quote('' if value is None else value)}")
|
||||
lines.append("# --- конец параметров ---")
|
||||
return "\n".join(lines) + "\n" + content
|
||||
|
||||
|
||||
def _node_ssh(server: ProxmoxServer, client: ProxmoxClient) -> SSHClient:
|
||||
ssh_host = (server.ip_address or server.hostname or "").split(":")[0]
|
||||
return SSHClient(
|
||||
hostname=ssh_host,
|
||||
username="root",
|
||||
password=getattr(client, "_password", None),
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
|
||||
def _run(ssh: SSHClient, cmd: str, *, what: str, timeout: int = _CMD_TIMEOUT) -> str:
|
||||
output, exit_code = ssh.execute(cmd, return_exit_code=True, timeout=timeout)
|
||||
if exit_code == -1:
|
||||
raise ScriptExecError(f"{what}: таймаут (>{timeout}с) или обрыв SSH")
|
||||
if exit_code != 0:
|
||||
raise ScriptExecError(f"{what}: exit={exit_code}: {(output or '').strip()[:2000]}")
|
||||
return output or ""
|
||||
|
||||
|
||||
def run_on_node(server: ProxmoxServer, client: ProxmoxClient, script: str,
|
||||
interpreter: str, timeout: int) -> ExecResult:
|
||||
"""Выполнить скрипт на хосте Proxmox (root@node)."""
|
||||
ssh = _node_ssh(server, client)
|
||||
if not ssh.connect():
|
||||
return ExecResult(success=False, output="", exit_code=-1,
|
||||
error=f"Не удалось подключиться по SSH к {server.name}")
|
||||
|
||||
b64 = base64.b64encode(script.encode("utf-8")).decode("ascii")
|
||||
tmp = f"/tmp/pve_script_{abs(hash(script)) % 100000}_{int(time.time())}"
|
||||
try:
|
||||
_run(ssh, f"printf '%s' '{b64}' | base64 -d > {tmp} && chmod +x {tmp}",
|
||||
what="write script on node")
|
||||
output, exit_code = ssh.execute(f"{interpreter} {tmp}", return_exit_code=True, timeout=timeout)
|
||||
return ExecResult(success=exit_code == 0, output=output or "", exit_code=exit_code)
|
||||
except ScriptExecError as e:
|
||||
return ExecResult(success=False, output="", exit_code=-1, error=str(e))
|
||||
finally:
|
||||
try:
|
||||
ssh.execute(f"rm -f {tmp}", timeout=10)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def run_on_lxc(server: ProxmoxServer, client: ProxmoxClient, node: str, vmid: int,
|
||||
script: str, interpreter: str, timeout: int) -> ExecResult:
|
||||
"""Выполнить скрипт внутри LXC через `pct exec` (SSH ноды, нет guest agent для LXC)."""
|
||||
ssh = _node_ssh(server, client)
|
||||
if not ssh.connect():
|
||||
return ExecResult(success=False, output="", exit_code=-1,
|
||||
error=f"Не удалось подключиться по SSH к {server.name}")
|
||||
|
||||
b64 = base64.b64encode(script.encode("utf-8")).decode("ascii")
|
||||
tmp_node = f"/tmp/pve_script_{vmid}_{int(time.time())}"
|
||||
tmp_ct = f"/tmp/pve_script_{vmid}.sh"
|
||||
try:
|
||||
_run(ssh, f"printf '%s' '{b64}' | base64 -d > {tmp_node}",
|
||||
what="write script on node")
|
||||
_run(ssh, f"pct push {vmid} {tmp_node} {tmp_ct}", what="pct push script")
|
||||
output, exit_code = ssh.execute(
|
||||
f"pct exec {vmid} -- {interpreter} {tmp_ct}",
|
||||
return_exit_code=True, timeout=timeout,
|
||||
)
|
||||
return ExecResult(success=exit_code == 0, output=output or "", exit_code=exit_code)
|
||||
except ScriptExecError as e:
|
||||
return ExecResult(success=False, output="", exit_code=-1, error=str(e))
|
||||
finally:
|
||||
try:
|
||||
ssh.execute(f"rm -f {tmp_node}", timeout=10)
|
||||
ssh.execute(f"pct exec {vmid} -- rm -f {tmp_ct}", timeout=10)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def run_on_qemu(client: ProxmoxClient, node: str, vmid: int, script: str,
|
||||
interpreter: str, timeout: int) -> ExecResult:
|
||||
"""Выполнить скрипт внутри VM через QEMU guest agent."""
|
||||
result = client.execute_script(node, vmid, script, interpreter=interpreter, timeout=timeout)
|
||||
if not result.get("success"):
|
||||
return ExecResult(
|
||||
success=False, output=result.get("stdout", "") or "",
|
||||
exit_code=result.get("exit_code", -1),
|
||||
error=result.get("error") or result.get("stderr"),
|
||||
)
|
||||
return ExecResult(
|
||||
success=result.get("exit_code", 0) == 0,
|
||||
output=result.get("stdout", "") or "",
|
||||
exit_code=result.get("exit_code", 0),
|
||||
error=result.get("stderr") or None,
|
||||
)
|
||||
|
||||
|
||||
def execute(server: ProxmoxServer, *, target_type: str, node: Optional[str],
|
||||
vmid: Optional[int], vm_type: Optional[str], script: str,
|
||||
interpreter: str, timeout: int) -> ExecResult:
|
||||
"""Точка входа: выполнить скрипт на нужной цели.
|
||||
|
||||
target_type: "node" (хост Proxmox) | "guest" (VM/LXC).
|
||||
vm_type (только для guest): "qemu" | "lxc".
|
||||
"""
|
||||
try:
|
||||
client = ProxmoxClient.from_server(server)
|
||||
except Exception as e:
|
||||
return ExecResult(success=False, output="", exit_code=-1,
|
||||
error=f"Не удалось создать Proxmox-клиент: {e}")
|
||||
|
||||
try:
|
||||
if target_type == "node":
|
||||
return run_on_node(server, client, script, interpreter, timeout)
|
||||
if target_type == "guest":
|
||||
if vmid is None or not node:
|
||||
return ExecResult(success=False, output="", exit_code=-1,
|
||||
error="Для guest-скрипта нужны node и vmid")
|
||||
if vm_type == "lxc":
|
||||
return run_on_lxc(server, client, node, vmid, script, interpreter, timeout)
|
||||
return run_on_qemu(client, node, vmid, script, interpreter, timeout)
|
||||
return ExecResult(success=False, output="", exit_code=-1,
|
||||
error=f"Неизвестный target_type: {target_type}")
|
||||
except Exception as e:
|
||||
logger.error(f"[script_engine] execute failed: {e}")
|
||||
return ExecResult(success=False, output="", exit_code=-1, error=str(e))
|
||||
Reference in New Issue
Block a user