fix(appstore): DNS, per-server golden template, bind-mount perms, delete race
App Store install/update pipeline reliability fixes: - explicit nameserver (APPSTORE_NAMESERVER) on App Store LXCs and the golden template build CT, instead of inheriting a node resolver that may be unreachable from the container network (e.g. Tailscale-only DNS) - golden template storage/resolution moved from one global setting to per-server_id (migration 37: app_operations.server_id) — building it on one Proxmox server no longer overwrites the template configured for another - golden template automated build fixed: vzdump export step no longer fails on "unable to parse directory volume name 'vztmpl/probe'" - bind-mount host directories are pre-created with permissive ownership before `docker compose up`, fixing Permission denied for non-root containers (e.g. MariaDB) writing to Docker-auto-created root-owned dirs - delete/teardown now waits for Proxmox to actually confirm the destroy task finished (was silently proceeding after a short timeout, letting a new install reuse the VMID while the node was still wiping the old disk) - pct create retries a few times on transient "got lock" config errors - failed pipeline steps now report the tail of command output (4000 chars) instead of the head, so the real error isn't buried under pull/progress noise - install error box in the UI wraps long text and scrolls instead of stretching the dialog Also carries forward in-progress script catalog / instances / RBAC changes that were already uncommitted in the working tree before this session. Bump to v1.9.1, update WIKI.md/docs/CHANGELOG accordingly. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -147,10 +147,22 @@ def build_env(app: CatalogApp, form_answers: dict) -> tuple[dict, dict]:
|
||||
_GOLDEN_SETTING_KEY = "appstore_golden_template"
|
||||
|
||||
|
||||
def _resolve_golden_template(db, ostemplate: Optional[str] = None) -> Optional[str]:
|
||||
"""Определить golden vztmpl: явный override → сохранённый в БД → env-дефолт."""
|
||||
def _golden_key(server_id: int) -> str:
|
||||
return f"{_GOLDEN_SETTING_KEY}:{server_id}"
|
||||
|
||||
|
||||
def _resolve_golden_template(db, server_id: int, ostemplate: Optional[str] = None) -> Optional[str]:
|
||||
"""Определить golden vztmpl для конкретного сервера.
|
||||
|
||||
Приоритет: явный override → сохранённый для ЭТОГО server_id → старый общий
|
||||
ключ (обратная совместимость с настройкой до per-server хранения) →
|
||||
env-дефолт. vztmpl — файл на storage конкретного Proxmox-сервера, поэтому
|
||||
шаблон, собранный на сервере A, не существует на сервере B — нельзя просто
|
||||
отдавать один и тот же сохранённый volid для всех серверов.
|
||||
"""
|
||||
return (
|
||||
ostemplate
|
||||
or get_setting(db, _golden_key(server_id))
|
||||
or get_setting(db, _GOLDEN_SETTING_KEY)
|
||||
or settings.APPSTORE_GOLDEN_TEMPLATE
|
||||
)
|
||||
@@ -165,7 +177,7 @@ def prepare_golden_template(db, user, *, server_id: int, node: Optional[str] = N
|
||||
if not server:
|
||||
raise EngineError("Proxmox сервер не найден")
|
||||
|
||||
op = _new_operation(db, None, "golden_template", user.id)
|
||||
op = _new_operation(db, None, "golden_template", user.id, server_id=server_id)
|
||||
_engine_executor.submit(
|
||||
_run_golden_template, op.id, user.id, server_id, node,
|
||||
template_storage, rootfs_storage, bridge, force,
|
||||
@@ -186,10 +198,11 @@ def _run_golden_template(operation_id, user_id, server_id, node,
|
||||
)
|
||||
result = build_golden_template(db, spec, on_step)
|
||||
|
||||
# Сохраняем volid в БД — install() будет предпочитать его env-дефолту.
|
||||
# Сохраняем volid ПОД ЭТИМ СЕРВЕРОМ — install() на других серверах не
|
||||
# должен получить чужой (недоступный на их storage) шаблон.
|
||||
try:
|
||||
set_setting(db, _GOLDEN_SETTING_KEY, result.volid,
|
||||
description="App Store: собранный золотой LXC-шаблон")
|
||||
set_setting(db, _golden_key(server_id), result.volid,
|
||||
description=f"App Store: золотой LXC-шаблон сервера #{server_id}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[appstore-engine] save golden template setting: {e}")
|
||||
|
||||
@@ -197,7 +210,7 @@ def _run_golden_template(operation_id, user_id, server_id, node,
|
||||
try:
|
||||
broadcast_task_update(user_id, "appstore_golden_template_done",
|
||||
{"volid": result.volid, "node": result.node,
|
||||
"status": result.status})
|
||||
"status": result.status, "server_id": server_id})
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
@@ -207,18 +220,18 @@ def _run_golden_template(operation_id, user_id, server_id, node,
|
||||
db.close()
|
||||
|
||||
|
||||
def golden_template_status(db) -> dict:
|
||||
"""Текущий шаблон (из БД/env) + последняя операция сборки."""
|
||||
def golden_template_status(db, server_id: int) -> dict:
|
||||
"""Текущий шаблон конкретного сервера (БД/env) + последняя операция сборки на нём."""
|
||||
op = (
|
||||
db.query(AppOperation)
|
||||
.filter(AppOperation.type == "golden_template")
|
||||
.filter(AppOperation.type == "golden_template", AppOperation.server_id == server_id)
|
||||
.order_by(AppOperation.started_at.desc())
|
||||
.first()
|
||||
)
|
||||
return {
|
||||
"configured_template": _resolve_golden_template(db),
|
||||
"configured_template": _resolve_golden_template(db, server_id),
|
||||
"env_template": settings.APPSTORE_GOLDEN_TEMPLATE,
|
||||
"saved_template": get_setting(db, _GOLDEN_SETTING_KEY),
|
||||
"saved_template": get_setting(db, _golden_key(server_id)),
|
||||
"last_operation": op.to_dict() if op else None,
|
||||
}
|
||||
|
||||
@@ -273,7 +286,7 @@ def install(db, user, *, app_id: str, name: str, form_answers: dict,
|
||||
if not _NAME_RE.match(name or ""):
|
||||
raise EngineError("Недопустимое имя приложения (a-z, 0-9, дефис, 1..63)")
|
||||
|
||||
golden = _resolve_golden_template(db, ostemplate)
|
||||
golden = _resolve_golden_template(db, server_id, ostemplate)
|
||||
if not golden:
|
||||
raise EngineError("Не настроен золотой шаблон LXC — подготовьте его "
|
||||
"(App Store → золотой шаблон) или задайте APPSTORE_GOLDEN_TEMPLATE")
|
||||
@@ -325,9 +338,10 @@ def install(db, user, *, app_id: str, name: str, form_answers: dict,
|
||||
return {"installed_app_id": ia.id, "operation_id": op.id, "vmid": vmid, "secrets": secrets_shown}
|
||||
|
||||
|
||||
def _new_operation(db, installed_app_id: int, op_type: str, user_id: int) -> AppOperation:
|
||||
def _new_operation(db, installed_app_id: int, op_type: str, user_id: int,
|
||||
server_id: Optional[int] = None) -> AppOperation:
|
||||
op = AppOperation(
|
||||
installed_app_id=installed_app_id, type=op_type,
|
||||
installed_app_id=installed_app_id, type=op_type, server_id=server_id,
|
||||
status="running", progress=0, steps_log=[], user_id=user_id,
|
||||
)
|
||||
db.add(op)
|
||||
@@ -401,7 +415,7 @@ def retry_install(db, user, installed_app_id: int) -> dict:
|
||||
compose = app.compose_yaml if app else None
|
||||
if not compose:
|
||||
raise EngineError("compose приложения недоступен для повтора")
|
||||
golden = _resolve_golden_template(db)
|
||||
golden = _resolve_golden_template(db, ia.server_id)
|
||||
if not golden:
|
||||
raise EngineError("Не настроен золотой шаблон LXC — подготовьте его "
|
||||
"(App Store → золотой шаблон) или задайте APPSTORE_GOLDEN_TEMPLATE")
|
||||
@@ -444,10 +458,12 @@ def _run_delete(installed_app_id, operation_id, user_id, server_id, vmid, node):
|
||||
_record_step(operation_id, user_id, step, progress)
|
||||
|
||||
if vmid and server_id:
|
||||
try:
|
||||
poc_teardown(db, server_id, vmid, node, on_step)
|
||||
except Exception as e:
|
||||
logger.warning(f"[appstore-engine] teardown vmid={vmid}: {e}")
|
||||
# Не глотаем ошибку teardown: если Proxmox не подтвердил реальное
|
||||
# завершение удаления (см. poc_teardown/_TEARDOWN_WAIT_TIMEOUT),
|
||||
# ресурсы ноды могут быть ещё заняты — пробрасываем наверх, чтобы
|
||||
# НЕ помечать установку удалённой раньше времени (иначе следующая
|
||||
# установка того же приложения словит гонку блокировки VMID).
|
||||
poc_teardown(db, server_id, vmid, node, on_step)
|
||||
# Освобождаем IP в IPAM (no-op, если приложение ставилось по DHCP).
|
||||
try:
|
||||
IPAMService(db).release_ip_by_vmid(
|
||||
@@ -476,6 +492,12 @@ def _run_delete(installed_app_id, operation_id, user_id, server_id, vmid, node):
|
||||
except Exception as e:
|
||||
logger.error(f"[appstore-engine] delete #{installed_app_id} failed: {e}")
|
||||
_finish_op(operation_id, user_id, "failed", error=str(e))
|
||||
# Оставляем InstalledApp на месте (ресурсы ноды не подтверждены
|
||||
# освобождёнными) — статус "error" позволяет повторить удаление позже.
|
||||
ia = db.get(InstalledApp, installed_app_id)
|
||||
if ia:
|
||||
ia.status = "error"
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@@ -35,6 +35,9 @@ 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)
|
||||
|
||||
_CS_APP_RE = re.compile(r'^APP="([^"]+)"')
|
||||
_CS_VAR_RE = re.compile(r'^(var_\w+)="\$\{var_\w+:-([^}]*)\}"$')
|
||||
|
||||
|
||||
def _parse_script_metadata(text: str, fallback_name: str) -> dict:
|
||||
name = fallback_name
|
||||
@@ -85,6 +88,46 @@ def _parse_script_metadata(text: str, fallback_name: str) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _parse_community_scripts_metadata(text: str, fallback_name: str) -> dict:
|
||||
"""Метаданные ct/*.sh из community-scripts/ProxmoxVE: APP="..." + var_X="${var_X:-default}".
|
||||
|
||||
В самих ct-скриптах нет полей name/description в привычном виде: имя
|
||||
приложения берётся из `APP=`, а параметры — из строк `var_X="${var_X:-DEF}"`
|
||||
(тот самый bash-паттерн "переменная окружения с дефолтом", который upstream
|
||||
читает при headless-запуске). Эти var_X переносятся в params_schema один в
|
||||
один по имени, чтобы существующий execute-движок (export VAR=value перед
|
||||
телом скрипта) сработал без изменений.
|
||||
"""
|
||||
name = fallback_name
|
||||
params: List[dict] = []
|
||||
|
||||
for line in text.splitlines():
|
||||
stripped = line.strip()
|
||||
m = _CS_APP_RE.match(stripped)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
continue
|
||||
pm = _CS_VAR_RE.match(stripped)
|
||||
if pm:
|
||||
p_name, default = pm.group(1), pm.group(2)
|
||||
label = p_name.removeprefix("var_").replace("_", " ").capitalize()
|
||||
params.append({
|
||||
"name": p_name,
|
||||
"label": label,
|
||||
"type": "number" if default.lstrip("-").isdigit() else "string",
|
||||
"required": False,
|
||||
"default": default,
|
||||
})
|
||||
|
||||
return {
|
||||
"name": name,
|
||||
"description": f"Community-Scripts LXC installer: {name}",
|
||||
"target_type": "node",
|
||||
"category": "LXC (community-scripts)",
|
||||
"params_schema": params,
|
||||
}
|
||||
|
||||
|
||||
def _clone_repo(repo: ScriptGitRepo, dest: str) -> None:
|
||||
subprocess.run(
|
||||
["git", "clone", "--depth", "1", "--branch", repo.branch, repo.url, dest],
|
||||
@@ -112,6 +155,9 @@ def sync_git_repo(db: Session, repo: ScriptGitRepo) -> dict:
|
||||
pattern = os.path.join(tmp_dir, repo.path_glob)
|
||||
files = _glob.glob(pattern, recursive=True)
|
||||
|
||||
is_community_scripts = repo.metadata_format == "community-scripts-ct"
|
||||
record_source = "community-scripts" if is_community_scripts else "git"
|
||||
|
||||
seen_slugs: List[str] = []
|
||||
for path in files:
|
||||
rel_path = os.path.relpath(path, tmp_dir)
|
||||
@@ -124,7 +170,10 @@ def sync_git_repo(db: Session, repo: ScriptGitRepo) -> dict:
|
||||
logger.warning(f"[script-sync] read {rel_path} failed: {e}")
|
||||
continue
|
||||
|
||||
meta = _parse_script_metadata(content, fallback_name=os.path.basename(rel_path))
|
||||
if is_community_scripts:
|
||||
meta = _parse_community_scripts_metadata(content, fallback_name=os.path.basename(rel_path))
|
||||
else:
|
||||
meta = _parse_script_metadata(content, fallback_name=os.path.basename(rel_path))
|
||||
|
||||
existing = db.query(ScriptCatalog).filter(ScriptCatalog.slug == slug).first()
|
||||
if existing:
|
||||
@@ -135,13 +184,14 @@ def sync_git_repo(db: Session, repo: ScriptGitRepo) -> dict:
|
||||
existing.params_schema = meta["params_schema"]
|
||||
existing.content = content
|
||||
existing.git_path = rel_path
|
||||
existing.source = record_source
|
||||
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,
|
||||
source=record_source, git_repo_id=repo.id, git_path=rel_path,
|
||||
))
|
||||
created += 1
|
||||
seen_slugs.append(slug)
|
||||
|
||||
Reference in New Issue
Block a user